commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
52
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
fuzzy_diff
stringlengths
16
3.18k
01cc82642273af950caedba471ed4cc9e788b615
alapage/urls.py
alapage/urls.py
from django.conf.urls import url from alapage.views import HomepageView, PageView, PagesmapView urlpatterns = [] urlpatterns.append( url(r'^sitemap/$', PagesmapView.as_view(), name="alapage-map")) #urlpatterns.append(url(r'^alapage/wizard/$', PageWizardView.as_view(), name="alapage-wizard")) #urlpatterns.append(url(r'^alapage/wizard/post/$', AddPagePostView.as_view(), name="alapage-wizard-post")) urlpatterns.append( url(r'^(?P<url>.*?)$', PageView.as_view(), name="page-view")) urlpatterns.append(url(r'^', HomepageView.as_view(), name="home-view"))
from django.conf.urls import url from alapage.views import HomepageView, PageView, PagesmapView urlpatterns = [ url(r'^sitemap/?$', PagesmapView.as_view(), name="alapage-map"), url(r'^(?P<url>.*?)?$', PageView.as_view(), name="page-view"), url(r'^', HomepageView.as_view(), name="home-view"), ]
Fix url regex for no trailing slash
Fix url regex for no trailing slash
Python
mit
synw/django-alapage,synw/django-alapage,synw/django-alapage
- from django.conf.urls import url from alapage.views import HomepageView, PageView, PagesmapView - urlpatterns = [] + urlpatterns = [ + url(r'^sitemap/?$', PagesmapView.as_view(), name="alapage-map"), + url(r'^(?P<url>.*?)?$', PageView.as_view(), name="page-view"), + url(r'^', HomepageView.as_view(), name="home-view"), + ] - urlpatterns.append( - url(r'^sitemap/$', PagesmapView.as_view(), name="alapage-map")) - #urlpatterns.append(url(r'^alapage/wizard/$', PageWizardView.as_view(), name="alapage-wizard")) - #urlpatterns.append(url(r'^alapage/wizard/post/$', AddPagePostView.as_view(), name="alapage-wizard-post")) - urlpatterns.append( - url(r'^(?P<url>.*?)$', PageView.as_view(), name="page-view")) - urlpatterns.append(url(r'^', HomepageView.as_view(), name="home-view")) -
Fix url regex for no trailing slash
## Code Before: from django.conf.urls import url from alapage.views import HomepageView, PageView, PagesmapView urlpatterns = [] urlpatterns.append( url(r'^sitemap/$', PagesmapView.as_view(), name="alapage-map")) #urlpatterns.append(url(r'^alapage/wizard/$', PageWizardView.as_view(), name="alapage-wizard")) #urlpatterns.append(url(r'^alapage/wizard/post/$', AddPagePostView.as_view(), name="alapage-wizard-post")) urlpatterns.append( url(r'^(?P<url>.*?)$', PageView.as_view(), name="page-view")) urlpatterns.append(url(r'^', HomepageView.as_view(), name="home-view")) ## Instruction: Fix url regex for no trailing slash ## Code After: from django.conf.urls import url from alapage.views import HomepageView, PageView, PagesmapView urlpatterns = [ url(r'^sitemap/?$', PagesmapView.as_view(), name="alapage-map"), url(r'^(?P<url>.*?)?$', PageView.as_view(), name="page-view"), url(r'^', HomepageView.as_view(), name="home-view"), ]
# ... existing code ... from django.conf.urls import url # ... modified code ... urlpatterns = [ url(r'^sitemap/?$', PagesmapView.as_view(), name="alapage-map"), url(r'^(?P<url>.*?)?$', PageView.as_view(), name="page-view"), url(r'^', HomepageView.as_view(), name="home-view"), ] # ... rest of the code ...
f1af343bf48843c8298ef6f07227402be1f4e511
angr/engines/soot/values/thisref.py
angr/engines/soot/values/thisref.py
from .base import SimSootValue from .local import SimSootValue_Local class SimSootValue_ThisRef(SimSootValue): __slots__ = [ 'id', 'type', 'heap_alloc_id' ] def __init__(self, heap_alloc_id, type_): self.id = self._create_unique_id(heap_alloc_id, type_) self.heap_alloc_id = heap_alloc_id self.type = type_ @staticmethod def _create_unique_id(heap_alloc_id, class_name): return "%s.%s.this" % (heap_alloc_id, class_name) @classmethod def from_sootvalue(cls, soot_value, state): local = SimSootValue_Local("%s.this" % soot_value.type, soot_value.type) return state.memory.load(local) def __repr__(self): return self.id
from .base import SimSootValue from .local import SimSootValue_Local class SimSootValue_ThisRef(SimSootValue): __slots__ = [ 'id', 'type', 'heap_alloc_id' ] def __init__(self, heap_alloc_id, type_): self.id = self._create_unique_id(heap_alloc_id, type_) self.heap_alloc_id = heap_alloc_id self.type = type_ @staticmethod def _create_unique_id(heap_alloc_id, class_name): return "%s.%s.this" % (heap_alloc_id, class_name) @classmethod def from_sootvalue(cls, soot_value, state): local = SimSootValue_Local("this", soot_value.type) return state.memory.load(local) def __repr__(self): return self.id
Fix naming of 'this' reference
Fix naming of 'this' reference
Python
bsd-2-clause
schieb/angr,schieb/angr,angr/angr,angr/angr,iamahuman/angr,iamahuman/angr,schieb/angr,angr/angr,iamahuman/angr
from .base import SimSootValue from .local import SimSootValue_Local class SimSootValue_ThisRef(SimSootValue): __slots__ = [ 'id', 'type', 'heap_alloc_id' ] def __init__(self, heap_alloc_id, type_): self.id = self._create_unique_id(heap_alloc_id, type_) self.heap_alloc_id = heap_alloc_id self.type = type_ @staticmethod def _create_unique_id(heap_alloc_id, class_name): return "%s.%s.this" % (heap_alloc_id, class_name) @classmethod def from_sootvalue(cls, soot_value, state): - local = SimSootValue_Local("%s.this" % soot_value.type, soot_value.type) + local = SimSootValue_Local("this", soot_value.type) return state.memory.load(local) def __repr__(self): return self.id
Fix naming of 'this' reference
## Code Before: from .base import SimSootValue from .local import SimSootValue_Local class SimSootValue_ThisRef(SimSootValue): __slots__ = [ 'id', 'type', 'heap_alloc_id' ] def __init__(self, heap_alloc_id, type_): self.id = self._create_unique_id(heap_alloc_id, type_) self.heap_alloc_id = heap_alloc_id self.type = type_ @staticmethod def _create_unique_id(heap_alloc_id, class_name): return "%s.%s.this" % (heap_alloc_id, class_name) @classmethod def from_sootvalue(cls, soot_value, state): local = SimSootValue_Local("%s.this" % soot_value.type, soot_value.type) return state.memory.load(local) def __repr__(self): return self.id ## Instruction: Fix naming of 'this' reference ## Code After: from .base import SimSootValue from .local import SimSootValue_Local class SimSootValue_ThisRef(SimSootValue): __slots__ = [ 'id', 'type', 'heap_alloc_id' ] def __init__(self, heap_alloc_id, type_): self.id = self._create_unique_id(heap_alloc_id, type_) self.heap_alloc_id = heap_alloc_id self.type = type_ @staticmethod def _create_unique_id(heap_alloc_id, class_name): return "%s.%s.this" % (heap_alloc_id, class_name) @classmethod def from_sootvalue(cls, soot_value, state): local = SimSootValue_Local("this", soot_value.type) return state.memory.load(local) def __repr__(self): return self.id
... def from_sootvalue(cls, soot_value, state): local = SimSootValue_Local("this", soot_value.type) return state.memory.load(local) ...
7d2d94d69797586860f7bb8c21a0b0e217fbc394
components/mgmtworker/scripts/start.py
components/mgmtworker/scripts/start.py
from os.path import join, dirname from cloudify import ctx ctx.download_resource( join('components', 'utils.py'), join(dirname(__file__), 'utils.py')) import utils # NOQA MGMT_WORKER_SERVICE_NAME = 'mgmtworker' CELERY_PATH = '/opt/mgmtworker/env/bin/celery' # also hardcoded in create @utils.retry(ValueError) def check_worker_running(amqp_url): """Use `celery status` to check if the worker is running.""" result = utils.sudo([ CELERY_PATH, '-b', celery_amqp_url, '--app=cloudify_agent.app.app', 'status' ], ignore_failures=True) if result.returncode != 0: raise ValueError('celery status: worker not running') ctx.logger.info('Starting Management Worker Service...') utils.start_service(MGMT_WORKER_SERVICE_NAME) utils.systemd.verify_alive(MGMT_WORKER_SERVICE_NAME) celery_amqp_url = ('amqp://{rabbitmq_username}:{rabbitmq_password}@' '{rabbitmq_endpoint_ip}:{broker_port}//').format( **ctx.instance.runtime_properties) try: check_worker_running(celery_amqp_url) except ValueError: ctx.abort_operation('Celery worker failed to start')
from os.path import join, dirname from cloudify import ctx ctx.download_resource( join('components', 'utils.py'), join(dirname(__file__), 'utils.py')) import utils # NOQA MGMT_WORKER_SERVICE_NAME = 'mgmtworker' CELERY_PATH = '/opt/mgmtworker/env/bin/celery' # also hardcoded in create @utils.retry(ValueError) def check_worker_running(): """Use `celery status` to check if the worker is running.""" result = utils.sudo([ 'CELERY_WORK_DIR=/opt/mgmtworker/work', CELERY_PATH, '--config=cloudify.broker_config', 'status' ], ignore_failures=True) if result.returncode != 0: raise ValueError('celery status: worker not running') ctx.logger.info('Starting Management Worker Service...') utils.start_service(MGMT_WORKER_SERVICE_NAME) utils.systemd.verify_alive(MGMT_WORKER_SERVICE_NAME) try: check_worker_running() except ValueError: ctx.abort_operation('Celery worker failed to start')
Use the stored broker_config instead of working it out ourselves
Use the stored broker_config instead of working it out ourselves Fixes SSL Means we're verifying the config is written properly too
Python
apache-2.0
isaac-s/cloudify-manager-blueprints,Cloudify-PS/cloudify-manager-blueprints,cloudify-cosmo/cloudify-manager-blueprints,cloudify-cosmo/cloudify-manager-blueprints,isaac-s/cloudify-manager-blueprints,Cloudify-PS/cloudify-manager-blueprints
from os.path import join, dirname from cloudify import ctx ctx.download_resource( join('components', 'utils.py'), join(dirname(__file__), 'utils.py')) import utils # NOQA MGMT_WORKER_SERVICE_NAME = 'mgmtworker' CELERY_PATH = '/opt/mgmtworker/env/bin/celery' # also hardcoded in create @utils.retry(ValueError) - def check_worker_running(amqp_url): + def check_worker_running(): """Use `celery status` to check if the worker is running.""" result = utils.sudo([ + 'CELERY_WORK_DIR=/opt/mgmtworker/work', CELERY_PATH, + '--config=cloudify.broker_config', - '-b', celery_amqp_url, - '--app=cloudify_agent.app.app', 'status' ], ignore_failures=True) if result.returncode != 0: raise ValueError('celery status: worker not running') ctx.logger.info('Starting Management Worker Service...') utils.start_service(MGMT_WORKER_SERVICE_NAME) utils.systemd.verify_alive(MGMT_WORKER_SERVICE_NAME) - celery_amqp_url = ('amqp://{rabbitmq_username}:{rabbitmq_password}@' - '{rabbitmq_endpoint_ip}:{broker_port}//').format( - **ctx.instance.runtime_properties) try: - check_worker_running(celery_amqp_url) + check_worker_running() except ValueError: ctx.abort_operation('Celery worker failed to start')
Use the stored broker_config instead of working it out ourselves
## Code Before: from os.path import join, dirname from cloudify import ctx ctx.download_resource( join('components', 'utils.py'), join(dirname(__file__), 'utils.py')) import utils # NOQA MGMT_WORKER_SERVICE_NAME = 'mgmtworker' CELERY_PATH = '/opt/mgmtworker/env/bin/celery' # also hardcoded in create @utils.retry(ValueError) def check_worker_running(amqp_url): """Use `celery status` to check if the worker is running.""" result = utils.sudo([ CELERY_PATH, '-b', celery_amqp_url, '--app=cloudify_agent.app.app', 'status' ], ignore_failures=True) if result.returncode != 0: raise ValueError('celery status: worker not running') ctx.logger.info('Starting Management Worker Service...') utils.start_service(MGMT_WORKER_SERVICE_NAME) utils.systemd.verify_alive(MGMT_WORKER_SERVICE_NAME) celery_amqp_url = ('amqp://{rabbitmq_username}:{rabbitmq_password}@' '{rabbitmq_endpoint_ip}:{broker_port}//').format( **ctx.instance.runtime_properties) try: check_worker_running(celery_amqp_url) except ValueError: ctx.abort_operation('Celery worker failed to start') ## Instruction: Use the stored broker_config instead of working it out ourselves ## Code After: from os.path import join, dirname from cloudify import ctx ctx.download_resource( join('components', 'utils.py'), join(dirname(__file__), 'utils.py')) import utils # NOQA MGMT_WORKER_SERVICE_NAME = 'mgmtworker' CELERY_PATH = '/opt/mgmtworker/env/bin/celery' # also hardcoded in create @utils.retry(ValueError) def check_worker_running(): """Use `celery status` to check if the worker is running.""" result = utils.sudo([ 'CELERY_WORK_DIR=/opt/mgmtworker/work', CELERY_PATH, '--config=cloudify.broker_config', 'status' ], ignore_failures=True) if result.returncode != 0: raise ValueError('celery status: worker not running') ctx.logger.info('Starting Management Worker Service...') utils.start_service(MGMT_WORKER_SERVICE_NAME) utils.systemd.verify_alive(MGMT_WORKER_SERVICE_NAME) try: check_worker_running() except ValueError: ctx.abort_operation('Celery worker failed to start')
# ... existing code ... @utils.retry(ValueError) def check_worker_running(): """Use `celery status` to check if the worker is running.""" # ... modified code ... result = utils.sudo([ 'CELERY_WORK_DIR=/opt/mgmtworker/work', CELERY_PATH, '--config=cloudify.broker_config', 'status' ... utils.systemd.verify_alive(MGMT_WORKER_SERVICE_NAME) ... try: check_worker_running() except ValueError: # ... rest of the code ...
f48554bcc5ac1161314592cb43ba65701d387289
tests/test_check_endpoint.py
tests/test_check_endpoint.py
import pytest def test_get_connection(): assert False def test_verify_hostname_with_valid_hostname(): assert False def test_verify_hostname_with_valid_altname(): assert False def test_verify_hostname_with_invalid_hostname(): assert False def test_expiring_certificate_with_good_cert(): assert False def test_expiring_certificate_with_bad_cert(): assert false def test_send_email(): assert False
import pytest # We're going to fake a connection for purposes of testing. # So far all we use is getpeercert method, so that's all we need to fake class fake_connection(object): def __init__(self): pass def getpeercert(self): cert_details = {'notAfter': 'Dec 31 00:00:00 2015 GMT', 'subjectAltName': (('DNS', 'www.fake.com'),), 'subject': ((('countryName', u'US'),), (('stateOrProvinceName', u'Oregon'),), (('localityName', u'Springfield'),), (('organizationName', u'FakeCompany'),), (('commonName', u'fake.com'),))} return cert_details def test_get_connection(): assert False def test_verify_hostname_with_valid_hostname(): assert False def test_verify_hostname_with_valid_altname(): assert False def test_verify_hostname_with_invalid_hostname(): assert False def test_expiring_certificate_with_good_cert(): assert False def test_expiring_certificate_with_bad_cert(): assert False def test_send_email(): assert False
Add fake connection class, PEP8 changes
Add fake connection class, PEP8 changes Also had a bad assert in there
Python
mit
twirrim/checkendpoint
import pytest + + # We're going to fake a connection for purposes of testing. + # So far all we use is getpeercert method, so that's all we need to fake + class fake_connection(object): + def __init__(self): + pass + + def getpeercert(self): + cert_details = {'notAfter': 'Dec 31 00:00:00 2015 GMT', + 'subjectAltName': (('DNS', 'www.fake.com'),), + 'subject': ((('countryName', u'US'),), + (('stateOrProvinceName', u'Oregon'),), + (('localityName', u'Springfield'),), + (('organizationName', u'FakeCompany'),), + (('commonName', u'fake.com'),))} + return cert_details + def test_get_connection(): assert False + def test_verify_hostname_with_valid_hostname(): assert False + def test_verify_hostname_with_valid_altname(): assert False + def test_verify_hostname_with_invalid_hostname(): assert False + def test_expiring_certificate_with_good_cert(): assert False + def test_expiring_certificate_with_bad_cert(): - assert false + assert False + def test_send_email(): assert False +
Add fake connection class, PEP8 changes
## Code Before: import pytest def test_get_connection(): assert False def test_verify_hostname_with_valid_hostname(): assert False def test_verify_hostname_with_valid_altname(): assert False def test_verify_hostname_with_invalid_hostname(): assert False def test_expiring_certificate_with_good_cert(): assert False def test_expiring_certificate_with_bad_cert(): assert false def test_send_email(): assert False ## Instruction: Add fake connection class, PEP8 changes ## Code After: import pytest # We're going to fake a connection for purposes of testing. # So far all we use is getpeercert method, so that's all we need to fake class fake_connection(object): def __init__(self): pass def getpeercert(self): cert_details = {'notAfter': 'Dec 31 00:00:00 2015 GMT', 'subjectAltName': (('DNS', 'www.fake.com'),), 'subject': ((('countryName', u'US'),), (('stateOrProvinceName', u'Oregon'),), (('localityName', u'Springfield'),), (('organizationName', u'FakeCompany'),), (('commonName', u'fake.com'),))} return cert_details def test_get_connection(): assert False def test_verify_hostname_with_valid_hostname(): assert False def test_verify_hostname_with_valid_altname(): assert False def test_verify_hostname_with_invalid_hostname(): assert False def test_expiring_certificate_with_good_cert(): assert False def test_expiring_certificate_with_bad_cert(): assert False def test_send_email(): assert False
// ... existing code ... import pytest # We're going to fake a connection for purposes of testing. # So far all we use is getpeercert method, so that's all we need to fake class fake_connection(object): def __init__(self): pass def getpeercert(self): cert_details = {'notAfter': 'Dec 31 00:00:00 2015 GMT', 'subjectAltName': (('DNS', 'www.fake.com'),), 'subject': ((('countryName', u'US'),), (('stateOrProvinceName', u'Oregon'),), (('localityName', u'Springfield'),), (('organizationName', u'FakeCompany'),), (('commonName', u'fake.com'),))} return cert_details // ... modified code ... def test_verify_hostname_with_valid_hostname(): ... assert False ... def test_verify_hostname_with_invalid_hostname(): ... assert False ... def test_expiring_certificate_with_bad_cert(): assert False // ... rest of the code ...
85d684369e72aa2968f9ffbd0632f84558e1b44e
tests/test_vector2_dot.py
tests/test_vector2_dot.py
from ppb_vector import Vector2 from math import isclose, sqrt import pytest # type: ignore from hypothesis import assume, given, note from utils import floats, vectors @given(x=vectors(), y=vectors()) def test_dot_commutes(x: Vector2, y: Vector2): assert x * y == y * x MAGNITUDE=1e10 @given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE), y=vectors(max_magnitude=sqrt(MAGNITUDE)), scalar=floats(max_magnitude=sqrt(MAGNITUDE))) def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float): """Test that x · (λ y + z) = λ x·y + x·z""" inner, outer = x * (scalar * y + z), scalar * x * y + x * z note(f"inner: {inner}") note(f"outer: {outer}") assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
from ppb_vector import Vector2 from math import isclose, sqrt import pytest # type: ignore from hypothesis import assume, given, note from utils import floats, vectors @given(x=vectors(), y=vectors()) def test_dot_commutes(x: Vector2, y: Vector2): assert x * y == y * x @given(x=vectors()) def test_dot_length(x: Vector2): assert isclose(x * x, x.length * x.length) MAGNITUDE=1e10 @given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE), y=vectors(max_magnitude=sqrt(MAGNITUDE)), scalar=floats(max_magnitude=sqrt(MAGNITUDE))) def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float): """Test that x · (λ y + z) = λ x·y + x·z""" inner, outer = x * (scalar * y + z), scalar * x * y + x * z note(f"inner: {inner}") note(f"outer: {outer}") assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
Test that x² == |x|²
tests/dot: Test that x² == |x|²
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
from ppb_vector import Vector2 from math import isclose, sqrt import pytest # type: ignore from hypothesis import assume, given, note from utils import floats, vectors @given(x=vectors(), y=vectors()) def test_dot_commutes(x: Vector2, y: Vector2): assert x * y == y * x + + @given(x=vectors()) + def test_dot_length(x: Vector2): + assert isclose(x * x, x.length * x.length) MAGNITUDE=1e10 @given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE), y=vectors(max_magnitude=sqrt(MAGNITUDE)), scalar=floats(max_magnitude=sqrt(MAGNITUDE))) def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float): """Test that x · (λ y + z) = λ x·y + x·z""" inner, outer = x * (scalar * y + z), scalar * x * y + x * z note(f"inner: {inner}") note(f"outer: {outer}") assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
Test that x² == |x|²
## Code Before: from ppb_vector import Vector2 from math import isclose, sqrt import pytest # type: ignore from hypothesis import assume, given, note from utils import floats, vectors @given(x=vectors(), y=vectors()) def test_dot_commutes(x: Vector2, y: Vector2): assert x * y == y * x MAGNITUDE=1e10 @given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE), y=vectors(max_magnitude=sqrt(MAGNITUDE)), scalar=floats(max_magnitude=sqrt(MAGNITUDE))) def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float): """Test that x · (λ y + z) = λ x·y + x·z""" inner, outer = x * (scalar * y + z), scalar * x * y + x * z note(f"inner: {inner}") note(f"outer: {outer}") assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5) ## Instruction: Test that x² == |x|² ## Code After: from ppb_vector import Vector2 from math import isclose, sqrt import pytest # type: ignore from hypothesis import assume, given, note from utils import floats, vectors @given(x=vectors(), y=vectors()) def test_dot_commutes(x: Vector2, y: Vector2): assert x * y == y * x @given(x=vectors()) def test_dot_length(x: Vector2): assert isclose(x * x, x.length * x.length) MAGNITUDE=1e10 @given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE), y=vectors(max_magnitude=sqrt(MAGNITUDE)), scalar=floats(max_magnitude=sqrt(MAGNITUDE))) def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float): """Test that x · (λ y + z) = λ x·y + x·z""" inner, outer = x * (scalar * y + z), scalar * x * y + x * z note(f"inner: {inner}") note(f"outer: {outer}") assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
// ... existing code ... @given(x=vectors()) def test_dot_length(x: Vector2): assert isclose(x * x, x.length * x.length) // ... rest of the code ...
78b62cd865b5c31a17c982b78dc91127ebf54525
erpnext/patches/may_2012/same_purchase_rate_patch.py
erpnext/patches/may_2012/same_purchase_rate_patch.py
def execute(): import webnotes gd = webnotes.model.code.get_obj('Global Defaults') gd.doc.maintain_same_rate = 1 gd.doc.save() gd.on_update()
def execute(): import webnotes from webnotes.model.code import get_obj gd = get_obj('Global Defaults') gd.doc.maintain_same_rate = 1 gd.doc.save() gd.on_update()
Maintain same rate throughout pur cycle: in global defaults, by default set true
Maintain same rate throughout pur cycle: in global defaults, by default set true
Python
agpl-3.0
rohitwaghchaure/digitales_erpnext,gangadhar-kadam/smrterp,pombredanne/erpnext,saurabh6790/test-med-app,gangadharkadam/johnerp,indictranstech/erpnext,hernad/erpnext,gangadhar-kadam/helpdesk-erpnext,gangadhar-kadam/mic-erpnext,mbauskar/Das_Erpnext,hernad/erpnext,Tejal011089/huntercamp_erpnext,saurabh6790/ON-RISAPP,mbauskar/phrerp,gangadhar-kadam/laganerp,gangadhar-kadam/hrerp,pombredanne/erpnext,pawaranand/phrerp,gangadharkadam/contributionerp,mbauskar/phrerp,dieface/erpnext,indictranstech/Das_Erpnext,suyashphadtare/sajil-erp,njmube/erpnext,indictranstech/fbd_erpnext,indictranstech/phrerp,gangadhar-kadam/powapp,njmube/erpnext,saurabh6790/aimobilize-app-backup,gangadhar-kadam/latestchurcherp,Drooids/erpnext,indictranstech/biggift-erpnext,geekroot/erpnext,suyashphadtare/sajil-erp,suyashphadtare/sajil-final-erp,indictranstech/Das_Erpnext,indictranstech/biggift-erpnext,indictranstech/phrerp,gangadhar-kadam/verve_erp,mbauskar/internal-hr,gangadhar-kadam/church-erpnext,gmarke/erpnext,Tejal011089/Medsyn2_app,indictranstech/buyback-erp,gangadhar-kadam/smrterp,Tejal011089/digitales_erpnext,Tejal011089/trufil-erpnext,indictranstech/vestasi-erpnext,gmarke/erpnext,netfirms/erpnext,hatwar/buyback-erpnext,dieface/erpnext,shitolepriya/test-erp,gangadharkadam/contributionerp,mbauskar/sapphire-erpnext,SPKian/Testing2,suyashphadtare/test,sheafferusa/erpnext,fuhongliang/erpnext,gangadharkadam/verveerp,indictranstech/tele-erpnext,saurabh6790/omnisys-app,Tejal011089/paypal_erpnext,mbauskar/omnitech-erpnext,shitolepriya/test-erp,gangadhar-kadam/verve-erp,mbauskar/phrerp,gangadhar-kadam/adb-erp,saurabh6790/omnit-app,MartinEnder/erpnext-de,SPKian/Testing,rohitwaghchaure/GenieManager-erpnext,indictranstech/Das_Erpnext,geekroot/erpnext,gangadharkadam/tailorerp,suyashphadtare/vestasi-erp-jan-end,hanselke/erpnext-1,mahabuber/erpnext,gangadhar-kadam/helpdesk-erpnext,hatwar/Das_erpnext,aruizramon/alec_erpnext,saurabh6790/medsyn-app1,saurabh6790/test_final_med_app,gangadharkadam/v4_erp,indictranstech/trufil-erpnext,anandpdoshi/erpnext,SPKian/Testing2,rohitwaghchaure/New_Theme_Erp,indictranstech/buyback-erp,gsnbng/erpnext,saurabh6790/medsyn-app,saurabh6790/omn-app,sagar30051991/ozsmart-erp,gangadhar-kadam/latestchurcherp,sagar30051991/ozsmart-erp,gangadhar-kadam/mtn-erpnext,Tejal011089/paypal_erpnext,gangadharkadam/office_erp,saurabh6790/med_new_app,netfirms/erpnext,BhupeshGupta/erpnext,Suninus/erpnext,gsnbng/erpnext,gangadhar-kadam/latestchurcherp,Tejal011089/osmosis_erpnext,shitolepriya/test-erp,rohitwaghchaure/digitales_erpnext,gangadhar-kadam/verve_live_erp,ThiagoGarciaAlves/erpnext,ThiagoGarciaAlves/erpnext,gangadharkadam/v5_erp,ShashaQin/erpnext,SPKian/Testing,indictranstech/focal-erpnext,indictranstech/osmosis-erpnext,indictranstech/focal-erpnext,Suninus/erpnext,gangadharkadam/saloon_erp_install,Tejal011089/med2-app,mbauskar/omnitech-demo-erpnext,rohitwaghchaure/New_Theme_Erp,suyashphadtare/gd-erp,meisterkleister/erpnext,saurabh6790/test-med-app,mbauskar/alec_frappe5_erpnext,MartinEnder/erpnext-de,suyashphadtare/vestasi-erp-jan-end,gangadharkadam/v6_erp,gangadhar-kadam/powapp,gangadharkadam/sher,saurabh6790/alert-med-app,mbauskar/Das_Erpnext,BhupeshGupta/erpnext,indictranstech/reciphergroup-erpnext,Tejal011089/osmosis_erpnext,anandpdoshi/erpnext,gangadhar-kadam/verve_test_erp,gangadharkadam/v5_erp,shft117/SteckerApp,rohitwaghchaure/erpnext_smart,gangadhar-kadam/prjapp,geekroot/erpnext,saurabh6790/ON-RISAPP,indictranstech/buyback-erp,gangadharkadam/sterp,tmimori/erpnext,fuhongliang/erpnext,mbauskar/Das_Erpnext,Tejal011089/huntercamp_erpnext,gangadharkadam/saloon_erp,ThiagoGarciaAlves/erpnext,indictranstech/trufil-erpnext,saurabh6790/medapp,suyashphadtare/vestasi-erp-jan-end,saurabh6790/test-erp,indictranstech/fbd_erpnext,gangadharkadam/saloon_erp_install,gangadhar-kadam/laganerp,Tejal011089/digitales_erpnext,fuhongliang/erpnext,SPKian/Testing2,saurabh6790/aimobilize,meisterkleister/erpnext,indictranstech/focal-erpnext,gangadharkadam/saloon_erp,SPKian/Testing,rohitwaghchaure/erpnext-receipher,gangadharkadam/smrterp,gangadharkadam/v5_erp,gangadhar-kadam/sms-erpnext,gangadharkadam/office_erp,hernad/erpnext,mbauskar/sapphire-erpnext,gangadharkadam/saloon_erp_install,saurabh6790/OFF-RISAPP,suyashphadtare/vestasi-update-erp,ShashaQin/erpnext,gangadhar-kadam/laganerp,Tejal011089/osmosis_erpnext,treejames/erpnext,gangadhar-kadam/sms-erpnext,BhupeshGupta/erpnext,mbauskar/omnitech-demo-erpnext,tmimori/erpnext,saurabh6790/medsynaptic1-app,gangadharkadam/vlinkerp,sagar30051991/ozsmart-erp,Tejal011089/trufil-erpnext,rohitwaghchaure/erpnext-receipher,gangadharkadam/sterp,indictranstech/fbd_erpnext,saurabh6790/trufil_app,rohitwaghchaure/GenieManager-erpnext,sheafferusa/erpnext,saurabh6790/med_new_app,indictranstech/phrerp,suyashphadtare/gd-erp,njmube/erpnext,mbauskar/internal-hr,gangadhar-kadam/sapphire_app,Tejal011089/trufil-erpnext,gangadharkadam/vlinkerp,gangadharkadam/tailorerp,indictranstech/tele-erpnext,susuchina/ERPNEXT,Tejal011089/digitales_erpnext,suyashphadtare/sajil-final-erp,gangadharkadam/saloon_erp,MartinEnder/erpnext-de,gangadharkadam/vlinkerp,saurabh6790/med_app_rels,SPKian/Testing,rohitwaghchaure/erpnext_smart,saurabh6790/medsynaptic1-app,gangadhar-kadam/verve_test_erp,rohitwaghchaure/GenieManager-erpnext,gangadharkadam/contributionerp,4commerce-technologies-AG/erpnext,saurabh6790/omnitech-apps,indictranstech/tele-erpnext,hatwar/buyback-erpnext,saurabh6790/medsynaptic-app,susuchina/ERPNEXT,gangadharkadam/v6_erp,indictranstech/osmosis-erpnext,saurabh6790/omnitech-apps,rohitwaghchaure/erpnext_smart,rohitwaghchaure/New_Theme_Erp,saurabh6790/trufil_app,indictranstech/vestasi-erpnext,mbauskar/sapphire-erpnext,hatwar/focal-erpnext,pombredanne/erpnext,gangadharkadam/smrterp,saurabh6790/pow-app,mbauskar/omnitech-erpnext,treejames/erpnext,gangadharkadam/office_erp,dieface/erpnext,indictranstech/trufil-erpnext,hatwar/buyback-erpnext,indictranstech/vestasi-erpnext,saurabh6790/medsyn-app1,gangadharkadam/v4_erp,mbauskar/alec_frappe5_erpnext,netfirms/erpnext,suyashphadtare/vestasi-erp-final,gangadhar-kadam/verve_erp,suyashphadtare/vestasi-update-erp,suyashphadtare/vestasi-erp-final,mahabuber/erpnext,gangadharkadam/letzerp,susuchina/ERPNEXT,suyashphadtare/sajil-final-erp,indictranstech/osmosis-erpnext,treejames/erpnext,hatwar/Das_erpnext,gangadhar-kadam/verve_erp,mahabuber/erpnext,saurabh6790/pow-app,shft117/SteckerApp,indictranstech/phrerp,gangadhar-kadam/verve_erp,mbauskar/sapphire-erpnext,saurabh6790/omnisys-app,suyashphadtare/vestasi-update-erp,gangadhar-kadam/helpdesk-erpnext,Yellowen/Owrang,saurabh6790/aimobilize,gangadhar-kadam/powapp,hatwar/focal-erpnext,saurabh6790/omnit-app,fuhongliang/erpnext,ThiagoGarciaAlves/erpnext,saurabh6790/test-erp,Tejal011089/trufil-erpnext,hernad/erpnext,suyashphadtare/vestasi-erp-1,sheafferusa/erpnext,indictranstech/internal-erpnext,mbauskar/Das_Erpnext,mbauskar/helpdesk-erpnext,gangadhar-kadam/hrerp,Tejal011089/fbd_erpnext,hanselke/erpnext-1,gangadhar-kadam/helpdesk-erpnext,saurabh6790/tru_app_back,indictranstech/tele-erpnext,gsnbng/erpnext,rohitwaghchaure/erpnext-receipher,sheafferusa/erpnext,gangadharkadam/verveerp,suyashphadtare/gd-erp,gangadhar-kadam/nassimapp,gangadhar-kadam/nassimapp,shft117/SteckerApp,gangadhar-kadam/verve_test_erp,rohitwaghchaure/erpnext-receipher,gmarke/erpnext,saurabh6790/OFF-RISAPP,4commerce-technologies-AG/erpnext,indictranstech/erpnext,meisterkleister/erpnext,Tejal011089/med2-app,Tejal011089/Medsyn2_app,suyashphadtare/vestasi-erp-final,mbauskar/omnitech-erpnext,ShashaQin/erpnext,gangadharkadam/v4_erp,mbauskar/phrerp,sagar30051991/ozsmart-erp,indictranstech/erpnext,indictranstech/internal-erpnext,suyashphadtare/vestasi-erp-jan-end,hatwar/focal-erpnext,indictranstech/internal-erpnext,SPKian/Testing2,Drooids/erpnext,hatwar/Das_erpnext,gangadhar-kadam/prjapp,gangadharkadam/sher,Tejal011089/paypal_erpnext,gangadharkadam/vlinkerp,suyashphadtare/vestasi-erp-1,gangadhar-kadam/church-erpnext,indictranstech/erpnext,geekroot/erpnext,Tejal011089/osmosis_erpnext,gangadhar-kadam/verve_live_erp,gangadharkadam/v5_erp,hatwar/buyback-erpnext,suyashphadtare/test,mbauskar/alec_frappe5_erpnext,saurabh6790/alert-med-app,Suninus/erpnext,saurabh6790/med_app_rels,gangadhar-kadam/latestchurcherp,Tejal011089/digitales_erpnext,rohitwaghchaure/digitales_erpnext,gangadhar-kadam/mic-erpnext,indictranstech/reciphergroup-erpnext,indictranstech/trufil-erpnext,gangadhar-kadam/sapphire_app,aruizramon/alec_erpnext,gangadharkadam/saloon_erp_install,saurabh6790/omn-app,indictranstech/Das_Erpnext,anandpdoshi/erpnext,rohitwaghchaure/New_Theme_Erp,meisterkleister/erpnext,mbauskar/omnitech-erpnext,mbauskar/omnitech-demo-erpnext,Aptitudetech/ERPNext,mbauskar/helpdesk-erpnext,gangadhar-kadam/verve_live_erp,suyashphadtare/sajil-erp,shitolepriya/test-erp,mbauskar/helpdesk-erpnext,Tejal011089/fbd_erpnext,hanselke/erpnext-1,saurabh6790/test-erp,gangadharkadam/letzerp,Tejal011089/fbd_erpnext,gangadharkadam/v6_erp,saurabh6790/medsyn-app,gangadhar-kadam/verve-erp,gangadharkadam/verveerp,gangadharkadam/contributionerp,gangadhar-kadam/verve-erp,treejames/erpnext,gsnbng/erpnext,pombredanne/erpnext,gangadharkadam/saloon_erp,indictranstech/fbd_erpnext,indictranstech/biggift-erpnext,gangadhar-kadam/verve_test_erp,aruizramon/alec_erpnext,suyashphadtare/test,mbauskar/helpdesk-erpnext,4commerce-technologies-AG/erpnext,Drooids/erpnext,saurabh6790/test_final_med_app,shft117/SteckerApp,netfirms/erpnext,gangadharkadam/letzerp,mbauskar/internal-hr,saurabh6790/omni-apps,tmimori/erpnext,pawaranand/phrerp,hanselke/erpnext-1,indictranstech/osmosis-erpnext,njmube/erpnext,gmarke/erpnext,Tejal011089/fbd_erpnext,saurabh6790/test-erp,BhupeshGupta/erpnext,gangadhar-kadam/sapphire_app,Yellowen/Owrang,susuchina/ERPNEXT,indictranstech/internal-erpnext,hatwar/focal-erpnext,gangadharkadam/johnerp,indictranstech/biggift-erpnext,gangadharkadam/v6_erp,saurabh6790/aimobilize-app-backup,gangadharkadam/letzerp,Tejal011089/huntercamp_erpnext,saurabh6790/tru_app_back,saurabh6790/omni-apps,Drooids/erpnext,indictranstech/vestasi-erpnext,suyashphadtare/gd-erp,pawaranand/phrerp,Tejal011089/huntercamp_erpnext,dieface/erpnext,Suninus/erpnext,Tejal011089/paypal_erpnext,tmimori/erpnext,saurabh6790/medapp,indictranstech/buyback-erp,ShashaQin/erpnext,pawaranand/phrerp,indictranstech/focal-erpnext,indictranstech/reciphergroup-erpnext,indictranstech/reciphergroup-erpnext,hatwar/Das_erpnext,mbauskar/omnitech-demo-erpnext,gangadharkadam/v4_erp,MartinEnder/erpnext-de,anandpdoshi/erpnext,suyashphadtare/vestasi-erp-1,rohitwaghchaure/GenieManager-erpnext,mahabuber/erpnext,gangadhar-kadam/adb-erp,gangadhar-kadam/mtn-erpnext,gangadhar-kadam/verve_live_erp,aruizramon/alec_erpnext,gangadharkadam/verveerp,mbauskar/alec_frappe5_erpnext,rohitwaghchaure/digitales_erpnext,saurabh6790/medsynaptic-app
def execute(): import webnotes + from webnotes.model.code import get_obj - gd = webnotes.model.code.get_obj('Global Defaults') + gd = get_obj('Global Defaults') gd.doc.maintain_same_rate = 1 gd.doc.save() gd.on_update()
Maintain same rate throughout pur cycle: in global defaults, by default set true
## Code Before: def execute(): import webnotes gd = webnotes.model.code.get_obj('Global Defaults') gd.doc.maintain_same_rate = 1 gd.doc.save() gd.on_update() ## Instruction: Maintain same rate throughout pur cycle: in global defaults, by default set true ## Code After: def execute(): import webnotes from webnotes.model.code import get_obj gd = get_obj('Global Defaults') gd.doc.maintain_same_rate = 1 gd.doc.save() gd.on_update()
... import webnotes from webnotes.model.code import get_obj gd = get_obj('Global Defaults') gd.doc.maintain_same_rate = 1 ...
607ba7481abc7556c247e140b963dfc9d5bd2161
examples/strings.py
examples/strings.py
import collections import collections.abc def strings_have_format_map_method(): """ As of Python 3.2 you can use the .format_map() method on a string object to use mapping objects (not just builtin dictionaries) when formatting a string. """ class Default(dict): def __missing__(self, key): return key print("This prints the keys: {a} {key2}".format_map(Default(a="key1"))) mapping = collections.defaultdict(int, a=2) print("This prints the value 2000: {a}{b}{c}{d}".format_map(mapping)) class MyMapping(collections.abc.Mapping): def __init__(self): self._data = {'a': 'A', 'b': 'B', 'c': 'C'} def __getitem__(self, key): return self._data[key] def __len__(self): return len(self._data) def __iter__(self): for item in self._data: yield item mapping = MyMapping() print("This prints ABC: {a}{b}{c}".format_map(mapping))
import collections import collections.abc def strings_have_format_map_method(): """ As of Python 3.2 you can use the .format_map() method on a string object to use mapping objects (not just builtin dictionaries) when formatting a string. """ class Default(dict): def __missing__(self, key): return key print("This prints key1 and key2: {key1} and {key2}".format_map(Default(key1="key1"))) mapping = collections.defaultdict(int, a=2) print("This prints the value 2000: {a}{b}{c}{d}".format_map(mapping)) class MyMapping(collections.abc.Mapping): def __init__(self): self._data = {'a': 'A', 'b': 'B', 'c': 'C'} def __getitem__(self, key): return self._data[key] def __len__(self): return len(self._data) def __iter__(self): for item in self._data: yield item mapping = MyMapping() print("This prints ABC: {a}{b}{c}".format_map(mapping))
Make string example a bit less confusing
Make string example a bit less confusing
Python
mit
svisser/python-3-examples
import collections import collections.abc def strings_have_format_map_method(): """ As of Python 3.2 you can use the .format_map() method on a string object to use mapping objects (not just builtin dictionaries) when formatting a string. """ class Default(dict): def __missing__(self, key): return key - print("This prints the keys: {a} {key2}".format_map(Default(a="key1"))) + print("This prints key1 and key2: {key1} and {key2}".format_map(Default(key1="key1"))) mapping = collections.defaultdict(int, a=2) print("This prints the value 2000: {a}{b}{c}{d}".format_map(mapping)) class MyMapping(collections.abc.Mapping): def __init__(self): self._data = {'a': 'A', 'b': 'B', 'c': 'C'} def __getitem__(self, key): return self._data[key] def __len__(self): return len(self._data) def __iter__(self): for item in self._data: yield item mapping = MyMapping() print("This prints ABC: {a}{b}{c}".format_map(mapping))
Make string example a bit less confusing
## Code Before: import collections import collections.abc def strings_have_format_map_method(): """ As of Python 3.2 you can use the .format_map() method on a string object to use mapping objects (not just builtin dictionaries) when formatting a string. """ class Default(dict): def __missing__(self, key): return key print("This prints the keys: {a} {key2}".format_map(Default(a="key1"))) mapping = collections.defaultdict(int, a=2) print("This prints the value 2000: {a}{b}{c}{d}".format_map(mapping)) class MyMapping(collections.abc.Mapping): def __init__(self): self._data = {'a': 'A', 'b': 'B', 'c': 'C'} def __getitem__(self, key): return self._data[key] def __len__(self): return len(self._data) def __iter__(self): for item in self._data: yield item mapping = MyMapping() print("This prints ABC: {a}{b}{c}".format_map(mapping)) ## Instruction: Make string example a bit less confusing ## Code After: import collections import collections.abc def strings_have_format_map_method(): """ As of Python 3.2 you can use the .format_map() method on a string object to use mapping objects (not just builtin dictionaries) when formatting a string. """ class Default(dict): def __missing__(self, key): return key print("This prints key1 and key2: {key1} and {key2}".format_map(Default(key1="key1"))) mapping = collections.defaultdict(int, a=2) print("This prints the value 2000: {a}{b}{c}{d}".format_map(mapping)) class MyMapping(collections.abc.Mapping): def __init__(self): self._data = {'a': 'A', 'b': 'B', 'c': 'C'} def __getitem__(self, key): return self._data[key] def __len__(self): return len(self._data) def __iter__(self): for item in self._data: yield item mapping = MyMapping() print("This prints ABC: {a}{b}{c}".format_map(mapping))
# ... existing code ... print("This prints key1 and key2: {key1} and {key2}".format_map(Default(key1="key1"))) # ... rest of the code ...
ccfe12391050d598ec32861ed146b66f4e907943
noodles/entities.py
noodles/entities.py
import re norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): return ['ABC Inc', 'Joost Ltd.'] class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text))
COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv' import re import csv norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): rows = csv.reader(open(COMPANY_SOURCE_FILE, 'r')) names = [normalize(row[0]) for row in rows] return names class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text))
Use big company list for regex entity extraction
Use big company list for regex entity extraction
Python
mit
uf6/noodles,uf6/noodles
+ COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv' import re + import csv norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): - return ['ABC Inc', 'Joost Ltd.'] + rows = csv.reader(open(COMPANY_SOURCE_FILE, 'r')) + names = [normalize(row[0]) for row in rows] + return names class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text))
Use big company list for regex entity extraction
## Code Before: import re norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): return ['ABC Inc', 'Joost Ltd.'] class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text)) ## Instruction: Use big company list for regex entity extraction ## Code After: COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv' import re import csv norm_reqs = ( ('ltd.', 'limited'), (' bv ', 'b.v.'), ) def normalize(text): text = text.lower() for (rgx, replacement) in norm_reqs: text = re.sub(rgx, replacement, text) return text def get_company_names(): rows = csv.reader(open(COMPANY_SOURCE_FILE, 'r')) names = [normalize(row[0]) for row in rows] return names class EntityExtractor(object): def __init__(self): normed = [re.escape(normalize(x)) for x in get_company_names()] joined = '|'.join(normed) self.regex = re.compile('(' + joined + ')') def entities_from_text(self, text): return self.regex.findall(normalize(text))
... COMPANY_SOURCE_FILE = '/tmp/companies_dev.csv' ... import re import csv ... def get_company_names(): rows = csv.reader(open(COMPANY_SOURCE_FILE, 'r')) names = [normalize(row[0]) for row in rows] return names ...
f38eb25fe13320297baad173c8e6d6ac7cfb9542
spacy/tests/tokens/test_vec.py
spacy/tests/tokens/test_vec.py
from __future__ import unicode_literals from spacy.en import English import pytest @pytest.mark.models def test_vec(EN): hype = EN.vocab['hype'] assert hype.orth_ == 'hype' assert 0.08 >= hype.vector[0] > 0.07 @pytest.mark.models def test_capitalized(EN): hype = EN.vocab['Hype'] assert hype.orth_ == 'Hype' assert 0.08 >= hype.vector[0] > 0.07
from __future__ import unicode_literals from spacy.en import English import pytest @pytest.mark.models def test_vec(EN): hype = EN.vocab['hype'] assert hype.orth_ == 'hype' assert -0.7 >= hype.vector[0] > -0.8 @pytest.mark.models def test_capitalized(EN): hype = EN.vocab['Hype'] assert hype.orth_ == 'Hype' assert -0.7 >= hype.vector[0] > -0.8
Fix test for word vector
Fix test for word vector
Python
mit
oroszgy/spaCy.hu,recognai/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,banglakit/spaCy,explosion/spaCy,explosion/spaCy,raphael0202/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,recognai/spaCy,Gregory-Howard/spaCy,recognai/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,honnibal/spaCy,recognai/spaCy,banglakit/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,recognai/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,explosion/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,honnibal/spaCy,honnibal/spaCy,raphael0202/spaCy,explosion/spaCy,raphael0202/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,banglakit/spaCy,raphael0202/spaCy,banglakit/spaCy,honnibal/spaCy,aikramer2/spaCy,spacy-io/spaCy,raphael0202/spaCy,spacy-io/spaCy,spacy-io/spaCy
from __future__ import unicode_literals from spacy.en import English import pytest @pytest.mark.models def test_vec(EN): hype = EN.vocab['hype'] assert hype.orth_ == 'hype' - assert 0.08 >= hype.vector[0] > 0.07 + assert -0.7 >= hype.vector[0] > -0.8 @pytest.mark.models def test_capitalized(EN): hype = EN.vocab['Hype'] assert hype.orth_ == 'Hype' - assert 0.08 >= hype.vector[0] > 0.07 + assert -0.7 >= hype.vector[0] > -0.8
Fix test for word vector
## Code Before: from __future__ import unicode_literals from spacy.en import English import pytest @pytest.mark.models def test_vec(EN): hype = EN.vocab['hype'] assert hype.orth_ == 'hype' assert 0.08 >= hype.vector[0] > 0.07 @pytest.mark.models def test_capitalized(EN): hype = EN.vocab['Hype'] assert hype.orth_ == 'Hype' assert 0.08 >= hype.vector[0] > 0.07 ## Instruction: Fix test for word vector ## Code After: from __future__ import unicode_literals from spacy.en import English import pytest @pytest.mark.models def test_vec(EN): hype = EN.vocab['hype'] assert hype.orth_ == 'hype' assert -0.7 >= hype.vector[0] > -0.8 @pytest.mark.models def test_capitalized(EN): hype = EN.vocab['Hype'] assert hype.orth_ == 'Hype' assert -0.7 >= hype.vector[0] > -0.8
# ... existing code ... assert hype.orth_ == 'hype' assert -0.7 >= hype.vector[0] > -0.8 # ... modified code ... assert hype.orth_ == 'Hype' assert -0.7 >= hype.vector[0] > -0.8 # ... rest of the code ...
e4e8c4e3b98e122e5cf4c9c349c4fb2abfe00ab1
api/bioguide/models.py
api/bioguide/models.py
from django.db import models class Legislator(models.Model): """Model representing a legislator in a session of congress. """ bioguide_id = models.CharField(max_length=7, db_index=True) prefix = models.CharField(max_length=16) first = models.CharField(max_length=64) last = models.CharField(max_length=64) suffix = models.CharField(max_length=16) birth_death = models.CharField(max_length=16) position = models.CharField(max_length=24) party = models.CharField(max_length=32) state = models.CharField(max_length=2) congress = models.CharField(max_length=3) class Meta: unique_together = (('bioguide_id', 'congress', )) def __unicode__(self): return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
from django.db import models class Legislator(models.Model): """Model representing a legislator in a session of congress. """ bioguide_id = models.CharField(max_length=7, db_index=True) prefix = models.CharField(max_length=16) first = models.CharField(max_length=64) last = models.CharField(max_length=64) suffix = models.CharField(max_length=16) birth_death = models.CharField(max_length=16) position = models.CharField(max_length=24) party = models.CharField(max_length=32) state = models.CharField(max_length=2) congress = models.CharField(max_length=3) class Meta: unique_together = (('bioguide_id', 'congress', 'position', )) def __unicode__(self): return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis)
Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis)
Python
bsd-3-clause
propublica/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,sunlightlabs/Capitol-Words
from django.db import models class Legislator(models.Model): """Model representing a legislator in a session of congress. """ bioguide_id = models.CharField(max_length=7, db_index=True) prefix = models.CharField(max_length=16) first = models.CharField(max_length=64) last = models.CharField(max_length=64) suffix = models.CharField(max_length=16) birth_death = models.CharField(max_length=16) position = models.CharField(max_length=24) party = models.CharField(max_length=32) state = models.CharField(max_length=2) congress = models.CharField(max_length=3) class Meta: - unique_together = (('bioguide_id', 'congress', )) + unique_together = (('bioguide_id', 'congress', 'position', )) def __unicode__(self): return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis)
## Code Before: from django.db import models class Legislator(models.Model): """Model representing a legislator in a session of congress. """ bioguide_id = models.CharField(max_length=7, db_index=True) prefix = models.CharField(max_length=16) first = models.CharField(max_length=64) last = models.CharField(max_length=64) suffix = models.CharField(max_length=16) birth_death = models.CharField(max_length=16) position = models.CharField(max_length=24) party = models.CharField(max_length=32) state = models.CharField(max_length=2) congress = models.CharField(max_length=3) class Meta: unique_together = (('bioguide_id', 'congress', )) def __unicode__(self): return ' '.join([self.prefix, self.first, self.last, self.suffix, ]) ## Instruction: Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis) ## Code After: from django.db import models class Legislator(models.Model): """Model representing a legislator in a session of congress. """ bioguide_id = models.CharField(max_length=7, db_index=True) prefix = models.CharField(max_length=16) first = models.CharField(max_length=64) last = models.CharField(max_length=64) suffix = models.CharField(max_length=16) birth_death = models.CharField(max_length=16) position = models.CharField(max_length=24) party = models.CharField(max_length=32) state = models.CharField(max_length=2) congress = models.CharField(max_length=3) class Meta: unique_together = (('bioguide_id', 'congress', 'position', )) def __unicode__(self): return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
# ... existing code ... class Meta: unique_together = (('bioguide_id', 'congress', 'position', )) # ... rest of the code ...
79ff39c4d6a5ad91a32cfdc7b59a89fa5461d244
MongoHN/forms.py
MongoHN/forms.py
""" MongoHN.forms - WTForms used by MongoHN """ from MongoHN.models import User from flask.ext.wtf import Form from wtforms import SubmitField, TextField, BooleanField, PasswordField from wtforms.validators import Required, DataRequired class LoginForm(Form): username = TextField('Username', validators = [ Required() ]) password = PasswordField('Password', validators = [ Required() ]) remember_me = BooleanField('remember_me', default = False) submit = SubmitField('Login') def validate(self): rv = Form.validate(self) if not rv: return False user = User.objects(username=self.username.data).first() if user is None: self.username.errors.append('Unknown username') return False if not user.check_password(self.password.data): self.password.errors.append('Invalid password') return False self.user = user return True class RegistrationForm(Form): username = TextField('Username', validators=[ DataRequired() ]) password = PasswordField('Password', validators=[ DataRequired() ]) email = TextField('Email', validators=[ DataRequired() ]) submit = SubmitField('Register', validators=[ Required() ]) def validate_username(form, field): if User.objects(username=field.data).first(): raise ValueError("Username already exists.") def create_user(self): user = User() user.username = self.username.data user.password = self.password.data user.email = self.email.data user.save() self.user = user #
""" MongoHN.forms - WTForms used by MongoHN """ from MongoHN.models import User from flask.ext.wtf import Form from wtforms import SubmitField, TextField, BooleanField, PasswordField from wtforms.validators import Required, DataRequired, ValidationError class LoginForm(Form): username = TextField('Username', validators = [ Required() ]) password = PasswordField('Password', validators = [ Required() ]) remember_me = BooleanField('remember_me', default = False) submit = SubmitField('Login') def validate(self): rv = Form.validate(self) if not rv: return False user = User.objects(username=self.username.data).first() if user is None: self.username.errors.append('Unknown username') return False if not user.check_password(self.password.data): self.password.errors.append('Invalid password') return False self.user = user return True class RegistrationForm(Form): username = TextField('Username', validators=[ DataRequired() ]) password = PasswordField('Password', validators=[ DataRequired() ]) email = TextField('Email', validators=[ DataRequired() ]) submit = SubmitField('Register', validators=[ Required() ]) def validate_username(form, field): if User.objects(username=field.data).first(): raise ValidationError("Username already exists.") def create_user(self): user = User() user.username = self.username.data user.password = self.password.data user.email = self.email.data user.save() self.user = user #
Use ValidationError rather than ValueError
Use ValidationError rather than ValueError
Python
mit
bsandrow/MongoHN,bsandrow/MongoHN
""" MongoHN.forms - WTForms used by MongoHN """ from MongoHN.models import User from flask.ext.wtf import Form from wtforms import SubmitField, TextField, BooleanField, PasswordField - from wtforms.validators import Required, DataRequired + from wtforms.validators import Required, DataRequired, ValidationError class LoginForm(Form): username = TextField('Username', validators = [ Required() ]) password = PasswordField('Password', validators = [ Required() ]) remember_me = BooleanField('remember_me', default = False) submit = SubmitField('Login') def validate(self): rv = Form.validate(self) if not rv: return False user = User.objects(username=self.username.data).first() if user is None: self.username.errors.append('Unknown username') return False if not user.check_password(self.password.data): self.password.errors.append('Invalid password') return False self.user = user return True class RegistrationForm(Form): username = TextField('Username', validators=[ DataRequired() ]) password = PasswordField('Password', validators=[ DataRequired() ]) email = TextField('Email', validators=[ DataRequired() ]) submit = SubmitField('Register', validators=[ Required() ]) def validate_username(form, field): if User.objects(username=field.data).first(): - raise ValueError("Username already exists.") + raise ValidationError("Username already exists.") def create_user(self): user = User() user.username = self.username.data user.password = self.password.data user.email = self.email.data user.save() self.user = user #
Use ValidationError rather than ValueError
## Code Before: """ MongoHN.forms - WTForms used by MongoHN """ from MongoHN.models import User from flask.ext.wtf import Form from wtforms import SubmitField, TextField, BooleanField, PasswordField from wtforms.validators import Required, DataRequired class LoginForm(Form): username = TextField('Username', validators = [ Required() ]) password = PasswordField('Password', validators = [ Required() ]) remember_me = BooleanField('remember_me', default = False) submit = SubmitField('Login') def validate(self): rv = Form.validate(self) if not rv: return False user = User.objects(username=self.username.data).first() if user is None: self.username.errors.append('Unknown username') return False if not user.check_password(self.password.data): self.password.errors.append('Invalid password') return False self.user = user return True class RegistrationForm(Form): username = TextField('Username', validators=[ DataRequired() ]) password = PasswordField('Password', validators=[ DataRequired() ]) email = TextField('Email', validators=[ DataRequired() ]) submit = SubmitField('Register', validators=[ Required() ]) def validate_username(form, field): if User.objects(username=field.data).first(): raise ValueError("Username already exists.") def create_user(self): user = User() user.username = self.username.data user.password = self.password.data user.email = self.email.data user.save() self.user = user # ## Instruction: Use ValidationError rather than ValueError ## Code After: """ MongoHN.forms - WTForms used by MongoHN """ from MongoHN.models import User from flask.ext.wtf import Form from wtforms import SubmitField, TextField, BooleanField, PasswordField from wtforms.validators import Required, DataRequired, ValidationError class LoginForm(Form): username = TextField('Username', validators = [ Required() ]) password = PasswordField('Password', validators = [ Required() ]) remember_me = BooleanField('remember_me', default = False) submit = SubmitField('Login') def validate(self): rv = Form.validate(self) if not rv: return False user = User.objects(username=self.username.data).first() if user is None: self.username.errors.append('Unknown username') return False if not user.check_password(self.password.data): self.password.errors.append('Invalid password') return False self.user = user return True class RegistrationForm(Form): username = TextField('Username', validators=[ DataRequired() ]) password = PasswordField('Password', validators=[ DataRequired() ]) email = TextField('Email', validators=[ DataRequired() ]) submit = SubmitField('Register', validators=[ Required() ]) def validate_username(form, field): if User.objects(username=field.data).first(): raise ValidationError("Username already exists.") def create_user(self): user = User() user.username = self.username.data user.password = self.password.data user.email = self.email.data user.save() self.user = user #
// ... existing code ... from wtforms import SubmitField, TextField, BooleanField, PasswordField from wtforms.validators import Required, DataRequired, ValidationError // ... modified code ... if User.objects(username=field.data).first(): raise ValidationError("Username already exists.") // ... rest of the code ...
60daa277d5c3f1d9ab07ff5beccdaa323996068b
feincmstools/templatetags/feincmstools_tags.py
feincmstools/templatetags/feincmstools_tags.py
import os from django import template register = template.Library() @register.filter def is_parent_of(page1, page2): """ Determines whether a given page is the parent of another page Example: {% if page|is_parent_of:feincms_page %} ... {% endif %} """ if page1 is None: return False return (page1.tree_id == page2.tree_id and page1.lft < page2.lft and page1.rght > page2.rght) @register.filter def is_equal_or_parent_of(page1, page2): return (page1.tree_id == page2.tree_id and page1.lft <= page2.lft and page1.rght >= page2.rght) @register.filter def is_sibling_of(page1, page2): """ Determines whether a given page is a sibling of another page {% if page|is_sibling_of:feincms_page %} ... {% endif %} """ if page1 is None or page2 is None: return False return (page1.parent_id == page2.parent_id) @register.filter def get_extension(filename): """ Return the extension from a file name """ return os.path.splitext(filename)[1][1:]
import os from django import template from feincms.templatetags.feincms_tags import feincms_render_content register = template.Library() @register.filter def is_parent_of(page1, page2): """ Determines whether a given page is the parent of another page Example: {% if page|is_parent_of:feincms_page %} ... {% endif %} """ if page1 is None: return False return (page1.tree_id == page2.tree_id and page1.lft < page2.lft and page1.rght > page2.rght) @register.filter def is_equal_or_parent_of(page1, page2): return (page1.tree_id == page2.tree_id and page1.lft <= page2.lft and page1.rght >= page2.rght) @register.filter def is_sibling_of(page1, page2): """ Determines whether a given page is a sibling of another page {% if page|is_sibling_of:feincms_page %} ... {% endif %} """ if page1 is None or page2 is None: return False return (page1.parent_id == page2.parent_id) @register.filter def get_extension(filename): """ Return the extension from a file name """ return os.path.splitext(filename)[1][1:] @register.assignment_tag(takes_context=True) def feincms_render_content_as(context, content, request=None): return feincms_render_content(context, content, request)
Add assignment tag util for rendering chunks to tpl context
Add assignment tag util for rendering chunks to tpl context
Python
bsd-3-clause
ixc/glamkit-feincmstools,ixc/glamkit-feincmstools
import os from django import template + + from feincms.templatetags.feincms_tags import feincms_render_content + register = template.Library() @register.filter def is_parent_of(page1, page2): """ Determines whether a given page is the parent of another page Example: {% if page|is_parent_of:feincms_page %} ... {% endif %} """ if page1 is None: return False return (page1.tree_id == page2.tree_id and page1.lft < page2.lft and page1.rght > page2.rght) @register.filter def is_equal_or_parent_of(page1, page2): return (page1.tree_id == page2.tree_id and page1.lft <= page2.lft and page1.rght >= page2.rght) @register.filter def is_sibling_of(page1, page2): """ Determines whether a given page is a sibling of another page {% if page|is_sibling_of:feincms_page %} ... {% endif %} """ if page1 is None or page2 is None: return False return (page1.parent_id == page2.parent_id) @register.filter def get_extension(filename): """ Return the extension from a file name """ return os.path.splitext(filename)[1][1:] + + @register.assignment_tag(takes_context=True) + def feincms_render_content_as(context, content, request=None): + return feincms_render_content(context, content, request) +
Add assignment tag util for rendering chunks to tpl context
## Code Before: import os from django import template register = template.Library() @register.filter def is_parent_of(page1, page2): """ Determines whether a given page is the parent of another page Example: {% if page|is_parent_of:feincms_page %} ... {% endif %} """ if page1 is None: return False return (page1.tree_id == page2.tree_id and page1.lft < page2.lft and page1.rght > page2.rght) @register.filter def is_equal_or_parent_of(page1, page2): return (page1.tree_id == page2.tree_id and page1.lft <= page2.lft and page1.rght >= page2.rght) @register.filter def is_sibling_of(page1, page2): """ Determines whether a given page is a sibling of another page {% if page|is_sibling_of:feincms_page %} ... {% endif %} """ if page1 is None or page2 is None: return False return (page1.parent_id == page2.parent_id) @register.filter def get_extension(filename): """ Return the extension from a file name """ return os.path.splitext(filename)[1][1:] ## Instruction: Add assignment tag util for rendering chunks to tpl context ## Code After: import os from django import template from feincms.templatetags.feincms_tags import feincms_render_content register = template.Library() @register.filter def is_parent_of(page1, page2): """ Determines whether a given page is the parent of another page Example: {% if page|is_parent_of:feincms_page %} ... {% endif %} """ if page1 is None: return False return (page1.tree_id == page2.tree_id and page1.lft < page2.lft and page1.rght > page2.rght) @register.filter def is_equal_or_parent_of(page1, page2): return (page1.tree_id == page2.tree_id and page1.lft <= page2.lft and page1.rght >= page2.rght) @register.filter def is_sibling_of(page1, page2): """ Determines whether a given page is a sibling of another page {% if page|is_sibling_of:feincms_page %} ... {% endif %} """ if page1 is None or page2 is None: return False return (page1.parent_id == page2.parent_id) @register.filter def get_extension(filename): """ Return the extension from a file name """ return os.path.splitext(filename)[1][1:] @register.assignment_tag(takes_context=True) def feincms_render_content_as(context, content, request=None): return feincms_render_content(context, content, request)
... from django import template from feincms.templatetags.feincms_tags import feincms_render_content register = template.Library() ... return os.path.splitext(filename)[1][1:] @register.assignment_tag(takes_context=True) def feincms_render_content_as(context, content, request=None): return feincms_render_content(context, content, request) ...
189847ffdca0264ddd6248faa9974ba35eaea373
tests/test_aur.py
tests/test_aur.py
from flaky import flaky import pytest pytestmark = pytest.mark.asyncio @flaky(max_runs=5) async def test_aur(get_version): assert await get_version("asciidoc-fake", {"aur": None}) == "1.0-1" @flaky(max_runs=5) async def test_aur_strip_release(get_version): assert await get_version("asciidoc-fake", {"aur": None, "strip-release": 1}) == "1.0"
from flaky import flaky import pytest pytestmark = pytest.mark.asyncio @flaky async def test_aur(get_version): assert await get_version("asciidoc-fake", {"aur": None}) == "1.0-1" @flaky async def test_aur_strip_release(get_version): assert await get_version("asciidoc-fake", {"aur": None, "strip-release": 1}) == "1.0"
Revert "make AUR tests more flaky"
Revert "make AUR tests more flaky" This reverts commit 61df628bd8bc97acbed40a4af67b124c47584f5f. It doesn't help :-(
Python
mit
lilydjwg/nvchecker
from flaky import flaky import pytest pytestmark = pytest.mark.asyncio - @flaky(max_runs=5) + @flaky async def test_aur(get_version): assert await get_version("asciidoc-fake", {"aur": None}) == "1.0-1" - @flaky(max_runs=5) + @flaky async def test_aur_strip_release(get_version): assert await get_version("asciidoc-fake", {"aur": None, "strip-release": 1}) == "1.0"
Revert "make AUR tests more flaky"
## Code Before: from flaky import flaky import pytest pytestmark = pytest.mark.asyncio @flaky(max_runs=5) async def test_aur(get_version): assert await get_version("asciidoc-fake", {"aur": None}) == "1.0-1" @flaky(max_runs=5) async def test_aur_strip_release(get_version): assert await get_version("asciidoc-fake", {"aur": None, "strip-release": 1}) == "1.0" ## Instruction: Revert "make AUR tests more flaky" ## Code After: from flaky import flaky import pytest pytestmark = pytest.mark.asyncio @flaky async def test_aur(get_version): assert await get_version("asciidoc-fake", {"aur": None}) == "1.0-1" @flaky async def test_aur_strip_release(get_version): assert await get_version("asciidoc-fake", {"aur": None, "strip-release": 1}) == "1.0"
// ... existing code ... @flaky async def test_aur(get_version): // ... modified code ... @flaky async def test_aur_strip_release(get_version): // ... rest of the code ...
52a4a10d54374b08c5835d02077fd1edcdc547ac
tests/test_union_energy_grids/results.py
tests/test_union_energy_grids/results.py
import sys # import statepoint sys.path.insert(0, '../../src/utils') import statepoint # read in statepoint file if len(sys.argv) > 1: sp = statepoint.StatePoint(sys.argv[1]) else: sp = statepoint.StatePoint('statepoint.10.binary') sp.read_results() # set up output string outstr = '' # write out k-combined outstr += 'k-combined:\n' outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1]) # write results to file with open('results_test.dat','w') as fh: fh.write(outstr)
import sys sys.path.insert(0, '../../src/utils') from openmc.statepoint import StatePoint # read in statepoint file if len(sys.argv) > 1: print(sys.argv) sp = StatePoint(sys.argv[1]) else: sp = StatePoint('statepoint.10.binary') sp.read_results() # set up output string outstr = '' # write out k-combined outstr += 'k-combined:\n' outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1]) # write results to file with open('results_test.dat','w') as fh: fh.write(outstr)
Fix import for statepoint for test_union_energy_grids
Fix import for statepoint for test_union_energy_grids
Python
mit
smharper/openmc,paulromano/openmc,mit-crpg/openmc,bhermanmit/openmc,wbinventor/openmc,paulromano/openmc,samuelshaner/openmc,mit-crpg/openmc,smharper/openmc,samuelshaner/openmc,johnnyliu27/openmc,mit-crpg/openmc,lilulu/openmc,walshjon/openmc,shikhar413/openmc,liangjg/openmc,shikhar413/openmc,walshjon/openmc,paulromano/openmc,amandalund/openmc,lilulu/openmc,samuelshaner/openmc,kellyrowland/openmc,kellyrowland/openmc,wbinventor/openmc,smharper/openmc,shikhar413/openmc,johnnyliu27/openmc,smharper/openmc,wbinventor/openmc,wbinventor/openmc,walshjon/openmc,lilulu/openmc,amandalund/openmc,johnnyliu27/openmc,mjlong/openmc,liangjg/openmc,mit-crpg/openmc,paulromano/openmc,shikhar413/openmc,bhermanmit/openmc,samuelshaner/openmc,johnnyliu27/openmc,liangjg/openmc,walshjon/openmc,amandalund/openmc,amandalund/openmc,liangjg/openmc,mjlong/openmc
import sys - # import statepoint sys.path.insert(0, '../../src/utils') - import statepoint + from openmc.statepoint import StatePoint # read in statepoint file if len(sys.argv) > 1: + print(sys.argv) - sp = statepoint.StatePoint(sys.argv[1]) + sp = StatePoint(sys.argv[1]) else: - sp = statepoint.StatePoint('statepoint.10.binary') + sp = StatePoint('statepoint.10.binary') sp.read_results() # set up output string outstr = '' - + # write out k-combined outstr += 'k-combined:\n' outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1]) # write results to file with open('results_test.dat','w') as fh: fh.write(outstr)
Fix import for statepoint for test_union_energy_grids
## Code Before: import sys # import statepoint sys.path.insert(0, '../../src/utils') import statepoint # read in statepoint file if len(sys.argv) > 1: sp = statepoint.StatePoint(sys.argv[1]) else: sp = statepoint.StatePoint('statepoint.10.binary') sp.read_results() # set up output string outstr = '' # write out k-combined outstr += 'k-combined:\n' outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1]) # write results to file with open('results_test.dat','w') as fh: fh.write(outstr) ## Instruction: Fix import for statepoint for test_union_energy_grids ## Code After: import sys sys.path.insert(0, '../../src/utils') from openmc.statepoint import StatePoint # read in statepoint file if len(sys.argv) > 1: print(sys.argv) sp = StatePoint(sys.argv[1]) else: sp = StatePoint('statepoint.10.binary') sp.read_results() # set up output string outstr = '' # write out k-combined outstr += 'k-combined:\n' outstr += "{0:12.6E} {1:12.6E}\n".format(sp.k_combined[0], sp.k_combined[1]) # write results to file with open('results_test.dat','w') as fh: fh.write(outstr)
... sys.path.insert(0, '../../src/utils') from openmc.statepoint import StatePoint ... if len(sys.argv) > 1: print(sys.argv) sp = StatePoint(sys.argv[1]) else: sp = StatePoint('statepoint.10.binary') sp.read_results() ... outstr = '' # write out k-combined ...
a75a725af141762b25a77522b43d6e241643baa6
medical_insurance/models/medical_patient.py
medical_insurance/models/medical_patient.py
from openerp import fields, models class MedicalPatient(models.Model): _inherit = 'medical.patient' insurance_plan_ids = fields.Many2many( string='Insurance Plans', comodel_name='medical.insurance.plan', help='Past & Present Insurance Plans', )
from openerp import fields, models class MedicalPatient(models.Model): _inherit = 'medical.patient' insurance_plan_ids = fields.One2many( string='Insurance Plans', comodel_name='medical.insurance.plan', inverse_name='patient_id', help='Past & Present Insurance Plans', )
Fix incorrect relation in medical_insurance
Fix incorrect relation in medical_insurance
Python
agpl-3.0
laslabs/vertical-medical,laslabs/vertical-medical
from openerp import fields, models class MedicalPatient(models.Model): _inherit = 'medical.patient' - insurance_plan_ids = fields.Many2many( + insurance_plan_ids = fields.One2many( string='Insurance Plans', comodel_name='medical.insurance.plan', + inverse_name='patient_id', help='Past & Present Insurance Plans', )
Fix incorrect relation in medical_insurance
## Code Before: from openerp import fields, models class MedicalPatient(models.Model): _inherit = 'medical.patient' insurance_plan_ids = fields.Many2many( string='Insurance Plans', comodel_name='medical.insurance.plan', help='Past & Present Insurance Plans', ) ## Instruction: Fix incorrect relation in medical_insurance ## Code After: from openerp import fields, models class MedicalPatient(models.Model): _inherit = 'medical.patient' insurance_plan_ids = fields.One2many( string='Insurance Plans', comodel_name='medical.insurance.plan', inverse_name='patient_id', help='Past & Present Insurance Plans', )
# ... existing code ... _inherit = 'medical.patient' insurance_plan_ids = fields.One2many( string='Insurance Plans', # ... modified code ... comodel_name='medical.insurance.plan', inverse_name='patient_id', help='Past & Present Insurance Plans', # ... rest of the code ...
9af4f3bc2ddc07e47f311ae51e20e3f99733ea35
Orange/tests/test_regression.py
Orange/tests/test_regression.py
import unittest import inspect import pkgutil import Orange from Orange.data import Table from Orange.regression import Learner class RegressionLearnersTest(unittest.TestCase): def all_learners(self): regression_modules = pkgutil.walk_packages( path=Orange.regression.__path__, prefix="Orange.regression.", onerror=lambda x: None) for importer, modname, ispkg in regression_modules: try: module = pkgutil.importlib.import_module(modname) except ImportError: continue for name, class_ in inspect.getmembers(module, inspect.isclass): if issubclass(class_, Learner) and 'base' not in class_.__module__: yield class_ def test_adequacy_all_learners(self): for learner in self.all_learners(): learner = learner() table = Table("iris") self.assertRaises(ValueError, learner, table)
import unittest import inspect import pkgutil import traceback import Orange from Orange.data import Table from Orange.regression import Learner class RegressionLearnersTest(unittest.TestCase): def all_learners(self): regression_modules = pkgutil.walk_packages( path=Orange.regression.__path__, prefix="Orange.regression.", onerror=lambda x: None) for importer, modname, ispkg in regression_modules: try: module = pkgutil.importlib.import_module(modname) except ImportError: continue for name, class_ in inspect.getmembers(module, inspect.isclass): if issubclass(class_, Learner) and 'base' not in class_.__module__: yield class_ def test_adequacy_all_learners(self): for learner in self.all_learners(): try: learner = learner() table = Table("iris") self.assertRaises(ValueError, learner, table) except TypeError as err: traceback.print_exc() continue
Handle TypeError while testing all regression learners
Handle TypeError while testing all regression learners
Python
bsd-2-clause
qPCR4vir/orange3,marinkaz/orange3,cheral/orange3,kwikadi/orange3,kwikadi/orange3,kwikadi/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,marinkaz/orange3,cheral/orange3,marinkaz/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,qPCR4vir/orange3,cheral/orange3,cheral/orange3,qPCR4vir/orange3,marinkaz/orange3,kwikadi/orange3
import unittest import inspect import pkgutil + import traceback import Orange from Orange.data import Table from Orange.regression import Learner class RegressionLearnersTest(unittest.TestCase): def all_learners(self): regression_modules = pkgutil.walk_packages( path=Orange.regression.__path__, prefix="Orange.regression.", onerror=lambda x: None) for importer, modname, ispkg in regression_modules: try: module = pkgutil.importlib.import_module(modname) except ImportError: continue for name, class_ in inspect.getmembers(module, inspect.isclass): if issubclass(class_, Learner) and 'base' not in class_.__module__: yield class_ def test_adequacy_all_learners(self): for learner in self.all_learners(): + try: - learner = learner() + learner = learner() - table = Table("iris") + table = Table("iris") - self.assertRaises(ValueError, learner, table) + self.assertRaises(ValueError, learner, table) + except TypeError as err: + traceback.print_exc() + continue
Handle TypeError while testing all regression learners
## Code Before: import unittest import inspect import pkgutil import Orange from Orange.data import Table from Orange.regression import Learner class RegressionLearnersTest(unittest.TestCase): def all_learners(self): regression_modules = pkgutil.walk_packages( path=Orange.regression.__path__, prefix="Orange.regression.", onerror=lambda x: None) for importer, modname, ispkg in regression_modules: try: module = pkgutil.importlib.import_module(modname) except ImportError: continue for name, class_ in inspect.getmembers(module, inspect.isclass): if issubclass(class_, Learner) and 'base' not in class_.__module__: yield class_ def test_adequacy_all_learners(self): for learner in self.all_learners(): learner = learner() table = Table("iris") self.assertRaises(ValueError, learner, table) ## Instruction: Handle TypeError while testing all regression learners ## Code After: import unittest import inspect import pkgutil import traceback import Orange from Orange.data import Table from Orange.regression import Learner class RegressionLearnersTest(unittest.TestCase): def all_learners(self): regression_modules = pkgutil.walk_packages( path=Orange.regression.__path__, prefix="Orange.regression.", onerror=lambda x: None) for importer, modname, ispkg in regression_modules: try: module = pkgutil.importlib.import_module(modname) except ImportError: continue for name, class_ in inspect.getmembers(module, inspect.isclass): if issubclass(class_, Learner) and 'base' not in class_.__module__: yield class_ def test_adequacy_all_learners(self): for learner in self.all_learners(): try: learner = learner() table = Table("iris") self.assertRaises(ValueError, learner, table) except TypeError as err: traceback.print_exc() continue
# ... existing code ... import pkgutil import traceback # ... modified code ... for learner in self.all_learners(): try: learner = learner() table = Table("iris") self.assertRaises(ValueError, learner, table) except TypeError as err: traceback.print_exc() continue # ... rest of the code ...
8b3d73ce9bbdcf39e7babd5637fcff9d1ad1dbf9
smartcard/Synchronization.py
smartcard/Synchronization.py
from threading import RLock def synchronized(method): def f(*args): self = args[0] self.mutex.acquire() # print method.__name__, 'acquired' try: return apply(method, args) finally: self.mutex.release() # print method.__name__, 'released' return f def synchronize(klass, names=None): """Synchronize methods in the given class. Only synchronize the methods whose names are given, or all methods if names=None.""" if type(names) == type(''): names = names.split() for (name, val) in klass.__dict__.items(): if callable(val) and name != '__init__' and \ (names == None or name in names): # print "synchronizing", name klass.__dict__[name] = synchronized(val) class Synchronization: # You can create your own self.mutex, or inherit from this class: def __init__(self): self.mutex = RLock()
from threading import RLock def synchronized(method): def f(*args): self = args[0] self.mutex.acquire() # print method.__name__, 'acquired' try: return apply(method, args) finally: self.mutex.release() # print method.__name__, 'released' return f def synchronize(klass, names=None): """Synchronize methods in the given class. Only synchronize the methods whose names are given, or all methods if names=None.""" if type(names) == type(''): names = names.split() for (name, val) in klass.__dict__.items(): if callable(val) and name != '__init__' and \ (names == None or name in names): # print "synchronizing", name setattr(klass, name, synchronized(val)) class Synchronization(object): # You can create your own self.mutex, or inherit from this class: def __init__(self): self.mutex = RLock()
Use setattr() instead of a direct access to __dict__
Use setattr() instead of a direct access to __dict__ Closes Feature Request 3110077 "new style classes" https://sourceforge.net/tracker/?func=detail&aid=3110077&group_id=196342&atid=957075
Python
lgpl-2.1
moreati/pyscard,moreati/pyscard,LudovicRousseau/pyscard,moreati/pyscard,LudovicRousseau/pyscard,LudovicRousseau/pyscard
from threading import RLock def synchronized(method): def f(*args): self = args[0] self.mutex.acquire() # print method.__name__, 'acquired' try: return apply(method, args) finally: self.mutex.release() # print method.__name__, 'released' return f def synchronize(klass, names=None): """Synchronize methods in the given class. Only synchronize the methods whose names are given, or all methods if names=None.""" if type(names) == type(''): names = names.split() for (name, val) in klass.__dict__.items(): if callable(val) and name != '__init__' and \ (names == None or name in names): # print "synchronizing", name - klass.__dict__[name] = synchronized(val) + setattr(klass, name, synchronized(val)) - class Synchronization: + class Synchronization(object): # You can create your own self.mutex, or inherit from this class: def __init__(self): self.mutex = RLock()
Use setattr() instead of a direct access to __dict__
## Code Before: from threading import RLock def synchronized(method): def f(*args): self = args[0] self.mutex.acquire() # print method.__name__, 'acquired' try: return apply(method, args) finally: self.mutex.release() # print method.__name__, 'released' return f def synchronize(klass, names=None): """Synchronize methods in the given class. Only synchronize the methods whose names are given, or all methods if names=None.""" if type(names) == type(''): names = names.split() for (name, val) in klass.__dict__.items(): if callable(val) and name != '__init__' and \ (names == None or name in names): # print "synchronizing", name klass.__dict__[name] = synchronized(val) class Synchronization: # You can create your own self.mutex, or inherit from this class: def __init__(self): self.mutex = RLock() ## Instruction: Use setattr() instead of a direct access to __dict__ ## Code After: from threading import RLock def synchronized(method): def f(*args): self = args[0] self.mutex.acquire() # print method.__name__, 'acquired' try: return apply(method, args) finally: self.mutex.release() # print method.__name__, 'released' return f def synchronize(klass, names=None): """Synchronize methods in the given class. Only synchronize the methods whose names are given, or all methods if names=None.""" if type(names) == type(''): names = names.split() for (name, val) in klass.__dict__.items(): if callable(val) and name != '__init__' and \ (names == None or name in names): # print "synchronizing", name setattr(klass, name, synchronized(val)) class Synchronization(object): # You can create your own self.mutex, or inherit from this class: def __init__(self): self.mutex = RLock()
... # print "synchronizing", name setattr(klass, name, synchronized(val)) ... class Synchronization(object): # You can create your own self.mutex, or inherit from this class: ...
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/?')
... def test_get_absolute_url_return_path_with_faces_s_face_page(self): self.assertRegexpMatches(self.face.get_absolute_url(),'/categories/faces/s/lokesh/?') ...
a04a8c7d8e1087df39025d6e798d83438ac35f77
setup.py
setup.py
from distutils.core import setup setup(name='hpswitch', version='0.1', description="A library for interacting with HP Networking switches", packages=['hpswitch', ], url='https://github.com/leonhandreke/hpswitch', license="MIT License", )
from distutils.core import setup setup(name='hpswitch', version='0.1', description="A library for interacting with HP Networking switches", packages=['hpswitch', ], url='https://github.com/leonhandreke/hpswitch', license="MIT License", requires=['pysnmp'] )
Add pysnmp as a dependency
Add pysnmp as a dependency
Python
mit
leonhandreke/hpswitch,thechristschn/hpswitch
from distutils.core import setup setup(name='hpswitch', version='0.1', description="A library for interacting with HP Networking switches", packages=['hpswitch', ], url='https://github.com/leonhandreke/hpswitch', license="MIT License", + requires=['pysnmp'] )
Add pysnmp as a dependency
## Code Before: from distutils.core import setup setup(name='hpswitch', version='0.1', description="A library for interacting with HP Networking switches", packages=['hpswitch', ], url='https://github.com/leonhandreke/hpswitch', license="MIT License", ) ## Instruction: Add pysnmp as a dependency ## Code After: from distutils.core import setup setup(name='hpswitch', version='0.1', description="A library for interacting with HP Networking switches", packages=['hpswitch', ], url='https://github.com/leonhandreke/hpswitch', license="MIT License", requires=['pysnmp'] )
... license="MIT License", requires=['pysnmp'] ) ...
9feb84c39c6988ff31f3d7cb38852a457870111b
bin/readability_to_dr.py
bin/readability_to_dr.py
import hashlib import json import os import sys print(sys.path) from gigacluster import Doc, dr, Tokenizer tok = Tokenizer() for root, dirs, files in os.walk(sys.argv[1]): dirs.sort() files = set(files) cluster_dr = os.path.join(root, 'cluster.dr') with open(cluster_dr, 'wb') as f_dr: writer = dr.Writer(f_dr, Doc) for filename in sorted(f for f in files if f.endswith('.readability')): dr_filename = filename.replace('.readability', '.dr') if not dr_filename in files: path = os.path.join(root, filename) with open(path) as f: try: data = json.load(f) except Exception: pass else: if not ('url' in data and 'title' in data and 'content' in data): continue id = hashlib.md5(data['url'].encode('utf8')).hexdigest() title = data.get('title', '') text = data.get('content', '') doc = Doc(id=id) title = title.encode('utf8') tok.tokenize(title, doc, 0, is_headline=True) tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) print(doc) writer.write(doc)
from collections import defaultdict import hashlib import json import os import sys from gigacluster import Doc, dr, Tokenizer tok = Tokenizer() stats = defaultdict(int) for root, dirs, files in os.walk(sys.argv[1]): dirs.sort() files = set(files) cluster_dr = os.path.join(root, 'cluster.dr') with open(cluster_dr, 'wb') as f_dr: writer = dr.Writer(f_dr, Doc) written = 0 for filename in sorted(f for f in files if f.endswith('.readability')): path = os.path.join(root, filename) with open(path) as f: try: data = json.load(f) except Exception: stats['bad json'] += 1 pass else: if not ('url' in data and 'title' in data and 'content' in data): stats['no url/title/content'] += 1 continue id = hashlib.md5(data['url'].encode('utf8')).hexdigest() title = data.get('title', '') text = data.get('content', '') doc = Doc(id=id) title = title.encode('utf8') tok.tokenize(title, doc, 0, is_headline=True) tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) writer.write(doc) stats['ok'] += 1 written += 1 if not written: print('No docs written for {}'.format(cluster_dr)) os.remove(cluster_dr) print('Stats\t{}'.format(dict(stats)))
Check for empty cluster dr files.
Check for empty cluster dr files.
Python
mit
schwa-lab/gigacluster,schwa-lab/gigacluster
- + from collections import defaultdict import hashlib import json import os import sys - print(sys.path) from gigacluster import Doc, dr, Tokenizer tok = Tokenizer() + stats = defaultdict(int) for root, dirs, files in os.walk(sys.argv[1]): dirs.sort() files = set(files) cluster_dr = os.path.join(root, 'cluster.dr') with open(cluster_dr, 'wb') as f_dr: writer = dr.Writer(f_dr, Doc) + written = 0 for filename in sorted(f for f in files if f.endswith('.readability')): - dr_filename = filename.replace('.readability', '.dr') - if not dr_filename in files: - path = os.path.join(root, filename) + path = os.path.join(root, filename) - with open(path) as f: + with open(path) as f: - try: + try: - data = json.load(f) + data = json.load(f) - except Exception: + except Exception: + stats['bad json'] += 1 - pass + pass - else: + else: - if not ('url' in data and 'title' in data and 'content' in data): + if not ('url' in data and 'title' in data and 'content' in data): + stats['no url/title/content'] += 1 - continue + continue - id = hashlib.md5(data['url'].encode('utf8')).hexdigest() + id = hashlib.md5(data['url'].encode('utf8')).hexdigest() - title = data.get('title', '') + title = data.get('title', '') - text = data.get('content', '') + text = data.get('content', '') - doc = Doc(id=id) + doc = Doc(id=id) - title = title.encode('utf8') + title = title.encode('utf8') - tok.tokenize(title, doc, 0, is_headline=True) + tok.tokenize(title, doc, 0, is_headline=True) - tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) + tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) - print(doc) - writer.write(doc) + writer.write(doc) + stats['ok'] += 1 + written += 1 + if not written: + print('No docs written for {}'.format(cluster_dr)) + os.remove(cluster_dr) + print('Stats\t{}'.format(dict(stats)))
Check for empty cluster dr files.
## Code Before: import hashlib import json import os import sys print(sys.path) from gigacluster import Doc, dr, Tokenizer tok = Tokenizer() for root, dirs, files in os.walk(sys.argv[1]): dirs.sort() files = set(files) cluster_dr = os.path.join(root, 'cluster.dr') with open(cluster_dr, 'wb') as f_dr: writer = dr.Writer(f_dr, Doc) for filename in sorted(f for f in files if f.endswith('.readability')): dr_filename = filename.replace('.readability', '.dr') if not dr_filename in files: path = os.path.join(root, filename) with open(path) as f: try: data = json.load(f) except Exception: pass else: if not ('url' in data and 'title' in data and 'content' in data): continue id = hashlib.md5(data['url'].encode('utf8')).hexdigest() title = data.get('title', '') text = data.get('content', '') doc = Doc(id=id) title = title.encode('utf8') tok.tokenize(title, doc, 0, is_headline=True) tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) print(doc) writer.write(doc) ## Instruction: Check for empty cluster dr files. ## Code After: from collections import defaultdict import hashlib import json import os import sys from gigacluster import Doc, dr, Tokenizer tok = Tokenizer() stats = defaultdict(int) for root, dirs, files in os.walk(sys.argv[1]): dirs.sort() files = set(files) cluster_dr = os.path.join(root, 'cluster.dr') with open(cluster_dr, 'wb') as f_dr: writer = dr.Writer(f_dr, Doc) written = 0 for filename in sorted(f for f in files if f.endswith('.readability')): path = os.path.join(root, filename) with open(path) as f: try: data = json.load(f) except Exception: stats['bad json'] += 1 pass else: if not ('url' in data and 'title' in data and 'content' in data): stats['no url/title/content'] += 1 continue id = hashlib.md5(data['url'].encode('utf8')).hexdigest() title = data.get('title', '') text = data.get('content', '') doc = Doc(id=id) title = title.encode('utf8') tok.tokenize(title, doc, 0, is_headline=True) tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) writer.write(doc) stats['ok'] += 1 written += 1 if not written: print('No docs written for {}'.format(cluster_dr)) os.remove(cluster_dr) print('Stats\t{}'.format(dict(stats)))
... from collections import defaultdict import hashlib ... import sys from gigacluster import Doc, dr, Tokenizer ... tok = Tokenizer() stats = defaultdict(int) for root, dirs, files in os.walk(sys.argv[1]): ... writer = dr.Writer(f_dr, Doc) written = 0 for filename in sorted(f for f in files if f.endswith('.readability')): path = os.path.join(root, filename) with open(path) as f: try: data = json.load(f) except Exception: stats['bad json'] += 1 pass else: if not ('url' in data and 'title' in data and 'content' in data): stats['no url/title/content'] += 1 continue id = hashlib.md5(data['url'].encode('utf8')).hexdigest() title = data.get('title', '') text = data.get('content', '') doc = Doc(id=id) title = title.encode('utf8') tok.tokenize(title, doc, 0, is_headline=True) tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) writer.write(doc) stats['ok'] += 1 written += 1 if not written: print('No docs written for {}'.format(cluster_dr)) os.remove(cluster_dr) print('Stats\t{}'.format(dict(stats))) ...
b466e0c41629575e0661aff1ba37c7056a732e0a
magicbot/__init__.py
magicbot/__init__.py
from .magicrobot import MagicRobot from .magic_tunable import tunable from .magic_reset import will_reset_to from .state_machine import AutonomousStateMachine, StateMachine, state, timed_state
from .magicrobot import MagicRobot from .magic_tunable import tunable from .magic_reset import will_reset_to from .state_machine import AutonomousStateMachine, StateMachine, default_state, state, timed_state
Add default_state to the magicbot exports
Add default_state to the magicbot exports
Python
bsd-3-clause
Twinters007/robotpy-wpilib-utilities,Twinters007/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities
from .magicrobot import MagicRobot from .magic_tunable import tunable from .magic_reset import will_reset_to - from .state_machine import AutonomousStateMachine, StateMachine, state, timed_state + from .state_machine import AutonomousStateMachine, StateMachine, default_state, state, timed_state
Add default_state to the magicbot exports
## Code Before: from .magicrobot import MagicRobot from .magic_tunable import tunable from .magic_reset import will_reset_to from .state_machine import AutonomousStateMachine, StateMachine, state, timed_state ## Instruction: Add default_state to the magicbot exports ## Code After: from .magicrobot import MagicRobot from .magic_tunable import tunable from .magic_reset import will_reset_to from .state_machine import AutonomousStateMachine, StateMachine, default_state, state, timed_state
# ... existing code ... from .state_machine import AutonomousStateMachine, StateMachine, default_state, state, timed_state # ... rest of the code ...
e6d7181ababaa9f08602c48e03d6557ddb6a4deb
tests/test_gio.py
tests/test_gio.py
import os import unittest from common import gio, gobject class TestInputStream(unittest.TestCase): def setUp(self): f = open("inputstream.txt", "w") f.write("testing") self._f = open("inputstream.txt", "r") self.stream = gio.unix.InputStream(self._f.fileno(), False) def tearDown(self): self._f.close() os.unlink("inputstream.txt") def testWrite(self): self.assertEquals(self.stream.read(), "testing") class TestOutputStream(unittest.TestCase): def setUp(self): self._f = open("outputstream.txt", "w") self.stream = gio.unix.OutputStream(self._f.fileno(), False) def tearDown(self): self._f.close() os.unlink("outputstream.txt") def testWrite(self): self.stream.write("testing") self.stream.close() self.failUnless(os.path.exists("outputstream.txt")) self.assertEquals(open("outputstream.txt").read(), "testing") def testWriteAsync(self): def callback(stream, result): loop.quit() f = gio.file_new_for_path("outputstream.txt") stream = f.read() stream.read_async(10240, 0, None, callback) loop = gobject.MainLoop() loop.run()
import os import unittest from common import gio, gobject class TestInputStream(unittest.TestCase): def setUp(self): f = open("inputstream.txt", "w") f.write("testing") self._f = open("inputstream.txt", "r") self.stream = gio.unix.InputStream(self._f.fileno(), False) def tearDown(self): self._f.close() os.unlink("inputstream.txt") def testRead(self): self.assertEquals(self.stream.read(), "testing") def testReadAsync(self): def callback(stream, result): self.assertEquals(stream.read_finish(result), len("testing")) loop.quit() self.stream.read_async(10240, 0, None, callback) loop = gobject.MainLoop() loop.run() class TestOutputStream(unittest.TestCase): def setUp(self): self._f = open("outputstream.txt", "w") self.stream = gio.unix.OutputStream(self._f.fileno(), False) self._f.flush() def tearDown(self): self._f.close() os.unlink("outputstream.txt") def testWrite(self): self.stream.write("testing") self.stream.close() self.failUnless(os.path.exists("outputstream.txt")) self.assertEquals(open("outputstream.txt").read(), "testing")
Reorganize tests and make them test more useful things
Reorganize tests and make them test more useful things svn path=/trunk/; revision=738
Python
lgpl-2.1
pexip/pygobject,GNOME/pygobject,davibe/pygobject,alexef/pygobject,davidmalcolm/pygobject,MathieuDuponchelle/pygobject,davidmalcolm/pygobject,Distrotech/pygobject,choeger/pygobject-cmake,sfeltman/pygobject,Distrotech/pygobject,MathieuDuponchelle/pygobject,GNOME/pygobject,thiblahute/pygobject,jdahlin/pygobject,atizo/pygobject,alexef/pygobject,jdahlin/pygobject,choeger/pygobject-cmake,thiblahute/pygobject,GNOME/pygobject,nzjrs/pygobject,Distrotech/pygobject,pexip/pygobject,pexip/pygobject,atizo/pygobject,davibe/pygobject,choeger/pygobject-cmake,alexef/pygobject,davibe/pygobject,davibe/pygobject,MathieuDuponchelle/pygobject,Distrotech/pygobject,jdahlin/pygobject,sfeltman/pygobject,nzjrs/pygobject,thiblahute/pygobject,atizo/pygobject,nzjrs/pygobject,davidmalcolm/pygobject,sfeltman/pygobject
import os import unittest from common import gio, gobject class TestInputStream(unittest.TestCase): def setUp(self): f = open("inputstream.txt", "w") f.write("testing") self._f = open("inputstream.txt", "r") self.stream = gio.unix.InputStream(self._f.fileno(), False) def tearDown(self): self._f.close() os.unlink("inputstream.txt") - def testWrite(self): + def testRead(self): self.assertEquals(self.stream.read(), "testing") + + def testReadAsync(self): + def callback(stream, result): + self.assertEquals(stream.read_finish(result), len("testing")) + loop.quit() + + self.stream.read_async(10240, 0, None, callback) + + loop = gobject.MainLoop() + loop.run() class TestOutputStream(unittest.TestCase): def setUp(self): self._f = open("outputstream.txt", "w") self.stream = gio.unix.OutputStream(self._f.fileno(), False) + self._f.flush() def tearDown(self): self._f.close() os.unlink("outputstream.txt") def testWrite(self): self.stream.write("testing") self.stream.close() self.failUnless(os.path.exists("outputstream.txt")) self.assertEquals(open("outputstream.txt").read(), "testing") - def testWriteAsync(self): - def callback(stream, result): - loop.quit() - f = gio.file_new_for_path("outputstream.txt") - stream = f.read() - stream.read_async(10240, 0, None, callback) - - loop = gobject.MainLoop() - loop.run() -
Reorganize tests and make them test more useful things
## Code Before: import os import unittest from common import gio, gobject class TestInputStream(unittest.TestCase): def setUp(self): f = open("inputstream.txt", "w") f.write("testing") self._f = open("inputstream.txt", "r") self.stream = gio.unix.InputStream(self._f.fileno(), False) def tearDown(self): self._f.close() os.unlink("inputstream.txt") def testWrite(self): self.assertEquals(self.stream.read(), "testing") class TestOutputStream(unittest.TestCase): def setUp(self): self._f = open("outputstream.txt", "w") self.stream = gio.unix.OutputStream(self._f.fileno(), False) def tearDown(self): self._f.close() os.unlink("outputstream.txt") def testWrite(self): self.stream.write("testing") self.stream.close() self.failUnless(os.path.exists("outputstream.txt")) self.assertEquals(open("outputstream.txt").read(), "testing") def testWriteAsync(self): def callback(stream, result): loop.quit() f = gio.file_new_for_path("outputstream.txt") stream = f.read() stream.read_async(10240, 0, None, callback) loop = gobject.MainLoop() loop.run() ## Instruction: Reorganize tests and make them test more useful things ## Code After: import os import unittest from common import gio, gobject class TestInputStream(unittest.TestCase): def setUp(self): f = open("inputstream.txt", "w") f.write("testing") self._f = open("inputstream.txt", "r") self.stream = gio.unix.InputStream(self._f.fileno(), False) def tearDown(self): self._f.close() os.unlink("inputstream.txt") def testRead(self): self.assertEquals(self.stream.read(), "testing") def testReadAsync(self): def callback(stream, result): self.assertEquals(stream.read_finish(result), len("testing")) loop.quit() self.stream.read_async(10240, 0, None, callback) loop = gobject.MainLoop() loop.run() class TestOutputStream(unittest.TestCase): def setUp(self): self._f = open("outputstream.txt", "w") self.stream = gio.unix.OutputStream(self._f.fileno(), False) self._f.flush() def tearDown(self): self._f.close() os.unlink("outputstream.txt") def testWrite(self): self.stream.write("testing") self.stream.close() self.failUnless(os.path.exists("outputstream.txt")) self.assertEquals(open("outputstream.txt").read(), "testing")
... def testRead(self): self.assertEquals(self.stream.read(), "testing") def testReadAsync(self): def callback(stream, result): self.assertEquals(stream.read_finish(result), len("testing")) loop.quit() self.stream.read_async(10240, 0, None, callback) loop = gobject.MainLoop() loop.run() ... self.stream = gio.unix.OutputStream(self._f.fileno(), False) self._f.flush() ... ...
f21da23d45c328acffaba69a6f2fbf2056ca326b
datapipe/denoising/__init__.py
datapipe/denoising/__init__.py
__all__ = ['abstract_cleaning_algorithm', 'fft', 'null', 'null_ref', 'tailcut', 'tailcut_jd', 'wavelets_mrfilter', 'wavelets_mrtransform']
__all__ = ['abstract_cleaning_algorithm', 'fft', 'null', 'null_ref', 'tailcut', 'tailcut_jd', 'wavelets_mrfilter', 'wavelets_mrtransform', 'inverse_transform_sampling']
Add a module to the __all__ list.
Add a module to the __all__ list.
Python
mit
jdhp-sap/sap-cta-data-pipeline,jdhp-sap/sap-cta-data-pipeline,jdhp-sap/data-pipeline-standalone-scripts,jdhp-sap/data-pipeline-standalone-scripts
__all__ = ['abstract_cleaning_algorithm', 'fft', 'null', 'null_ref', 'tailcut', 'tailcut_jd', 'wavelets_mrfilter', - 'wavelets_mrtransform'] + 'wavelets_mrtransform', + 'inverse_transform_sampling']
Add a module to the __all__ list.
## Code Before: __all__ = ['abstract_cleaning_algorithm', 'fft', 'null', 'null_ref', 'tailcut', 'tailcut_jd', 'wavelets_mrfilter', 'wavelets_mrtransform'] ## Instruction: Add a module to the __all__ list. ## Code After: __all__ = ['abstract_cleaning_algorithm', 'fft', 'null', 'null_ref', 'tailcut', 'tailcut_jd', 'wavelets_mrfilter', 'wavelets_mrtransform', 'inverse_transform_sampling']
# ... existing code ... 'wavelets_mrfilter', 'wavelets_mrtransform', 'inverse_transform_sampling'] # ... rest of the code ...
7c3a3283b3da0c01da012bb823d781036d1847b6
packages/syft/src/syft/core/node/common/node_table/node_route.py
packages/syft/src/syft/core/node/common/node_table/node_route.py
from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String # relative from . import Base class NodeRoute(Base): __tablename__ = "node_route" id = Column(Integer(), primary_key=True, autoincrement=True) node_id = Column(Integer, ForeignKey("node.id")) host_or_ip = Column(String(255)) is_vpn = Column(Boolean(), default=False)
from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String # relative from . import Base class NodeRoute(Base): __tablename__ = "node_route" id = Column(Integer(), primary_key=True, autoincrement=True) node_id = Column(Integer, ForeignKey("node.id")) host_or_ip = Column(String(255), default="") is_vpn = Column(Boolean(), default=False) vpn_endpoint = Column(String(255), default="") vpn_key = Column(String(255), default="")
ADD vpn_endpoint and vpn_key columns
ADD vpn_endpoint and vpn_key columns
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String # relative from . import Base class NodeRoute(Base): __tablename__ = "node_route" id = Column(Integer(), primary_key=True, autoincrement=True) node_id = Column(Integer, ForeignKey("node.id")) - host_or_ip = Column(String(255)) + host_or_ip = Column(String(255), default="") is_vpn = Column(Boolean(), default=False) + vpn_endpoint = Column(String(255), default="") + vpn_key = Column(String(255), default="")
ADD vpn_endpoint and vpn_key columns
## Code Before: from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String # relative from . import Base class NodeRoute(Base): __tablename__ = "node_route" id = Column(Integer(), primary_key=True, autoincrement=True) node_id = Column(Integer, ForeignKey("node.id")) host_or_ip = Column(String(255)) is_vpn = Column(Boolean(), default=False) ## Instruction: ADD vpn_endpoint and vpn_key columns ## Code After: from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String # relative from . import Base class NodeRoute(Base): __tablename__ = "node_route" id = Column(Integer(), primary_key=True, autoincrement=True) node_id = Column(Integer, ForeignKey("node.id")) host_or_ip = Column(String(255), default="") is_vpn = Column(Boolean(), default=False) vpn_endpoint = Column(String(255), default="") vpn_key = Column(String(255), default="")
# ... existing code ... node_id = Column(Integer, ForeignKey("node.id")) host_or_ip = Column(String(255), default="") is_vpn = Column(Boolean(), default=False) vpn_endpoint = Column(String(255), default="") vpn_key = Column(String(255), default="") # ... rest of the code ...
a1746483da4e84c004e55ea4d33693a764ac5807
githubsetupircnotifications.py
githubsetupircnotifications.py
import github3
import argparse import github3 def main(): parser = argparse.ArgumentParser() parser.add_argument('--username'), parser.add_argument('--password'), args = parser.parse_args()
Add username and password args
Add username and password args
Python
mit
kragniz/github-setup-irc-notifications
+ + import argparse import github3 + + def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--username'), + parser.add_argument('--password'), + args = parser.parse_args() +
Add username and password args
## Code Before: import github3 ## Instruction: Add username and password args ## Code After: import argparse import github3 def main(): parser = argparse.ArgumentParser() parser.add_argument('--username'), parser.add_argument('--password'), args = parser.parse_args()
# ... existing code ... import argparse # ... modified code ... import github3 def main(): parser = argparse.ArgumentParser() parser.add_argument('--username'), parser.add_argument('--password'), args = parser.parse_args() # ... rest of the code ...
0a9601c4ee085c38f660e6d40c98256098576a92
setup.py
setup.py
from distutils.core import setup from pip.req import parse_requirements install_reqs = parse_requirements("./requirements.txt") reqs = [str(ir.req) for ir in install_reqs] setup( name='url-matchers', version='0.0.1', modules=['url_matchers'], install_requires=reqs, author="Alex Good", author_email="[email protected]", url="https://github.com/alexjg/url-matchers", )
from distutils.core import setup from os import path from pip.req import parse_requirements requirements_location = path.join(path.dirname(__file__), "requirements.txt") install_reqs = parse_requirements(requirements_location) reqs = [str(ir.req) for ir in install_reqs] setup( name='url-matchers', version='0.0.1', modules=['url_matchers'], install_requires=reqs, author="Alex Good", author_email="[email protected]", url="https://github.com/alexjg/url-matchers", )
Use absolute path for requirements file
Use absolute path for requirements file
Python
mit
alexjg/url-matchers
from distutils.core import setup + from os import path from pip.req import parse_requirements + requirements_location = path.join(path.dirname(__file__), "requirements.txt") - install_reqs = parse_requirements("./requirements.txt") + install_reqs = parse_requirements(requirements_location) reqs = [str(ir.req) for ir in install_reqs] setup( name='url-matchers', version='0.0.1', modules=['url_matchers'], install_requires=reqs, author="Alex Good", author_email="[email protected]", url="https://github.com/alexjg/url-matchers", )
Use absolute path for requirements file
## Code Before: from distutils.core import setup from pip.req import parse_requirements install_reqs = parse_requirements("./requirements.txt") reqs = [str(ir.req) for ir in install_reqs] setup( name='url-matchers', version='0.0.1', modules=['url_matchers'], install_requires=reqs, author="Alex Good", author_email="[email protected]", url="https://github.com/alexjg/url-matchers", ) ## Instruction: Use absolute path for requirements file ## Code After: from distutils.core import setup from os import path from pip.req import parse_requirements requirements_location = path.join(path.dirname(__file__), "requirements.txt") install_reqs = parse_requirements(requirements_location) reqs = [str(ir.req) for ir in install_reqs] setup( name='url-matchers', version='0.0.1', modules=['url_matchers'], install_requires=reqs, author="Alex Good", author_email="[email protected]", url="https://github.com/alexjg/url-matchers", )
# ... existing code ... from distutils.core import setup from os import path from pip.req import parse_requirements # ... modified code ... requirements_location = path.join(path.dirname(__file__), "requirements.txt") install_reqs = parse_requirements(requirements_location) reqs = [str(ir.req) for ir in install_reqs] # ... rest of the code ...
1212d33d849155f8c1cdc6a610e893318937e7c5
silk/webdoc/html/v5.py
silk/webdoc/html/v5.py
from .common import * del ACRONYM del APPLET del BASEFONT del BIG del CENTER del DIR del FONT del FRAME del FRAMESET del NOFRAMES del STRIKE del TT del U
from .common import ( # flake8: noqa A, ABBR, # ACRONYM, ADDRESS, # APPLET, AREA, B, BASE, # BASEFONT, BDO, # BIG, BLOCKQUOTE, BODY, BR, BUTTON, Body, CAPTION, CAT, # CENTER, CITE, CODE, COL, COLGROUP, COMMENT, CONDITIONAL_COMMENT, DD, DEL, DFN, # DIR, DIV, DL, DT, EM, FIELDSET, # FONT, FORM, # FRAME, # FRAMESET, Form, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, HTMLDoc, Hyper, I, IFRAME, IMG, INPUT, INS, Image, Javascript, KBD, LABEL, LEGEND, LI, LINK, MAP, MENU, META, NBSP, # NOFRAMES, NOSCRIPT, OBJECT, OL, OPTGROUP, OPTION, P, PARAM, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, # STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, # TT, # U, UL, VAR, XML, XMLEntity, XMLNode, XMP, xmlescape, xmlunescape )
Replace import * with explicit names
Replace import * with explicit names
Python
bsd-3-clause
orbnauticus/silk
- from .common import * + from .common import ( # flake8: noqa + A, + ABBR, + # ACRONYM, + ADDRESS, + # APPLET, + AREA, + B, + BASE, + # BASEFONT, + BDO, + # BIG, + BLOCKQUOTE, + BODY, + BR, + BUTTON, + Body, + CAPTION, + CAT, + # CENTER, + CITE, + CODE, + COL, + COLGROUP, + COMMENT, + CONDITIONAL_COMMENT, + DD, + DEL, + DFN, + # DIR, + DIV, + DL, + DT, + EM, + FIELDSET, + # FONT, + FORM, + # FRAME, + # FRAMESET, + Form, + H1, + H2, + H3, + H4, + H5, + H6, + HEAD, + HR, + HTML, + HTMLDoc, + Hyper, + I, + IFRAME, + IMG, + INPUT, + INS, + Image, + Javascript, + KBD, + LABEL, + LEGEND, + LI, + LINK, + MAP, + MENU, + META, + NBSP, + # NOFRAMES, + NOSCRIPT, + OBJECT, + OL, + OPTGROUP, + OPTION, + P, + PARAM, + PRE, + Q, + S, + SAMP, + SCRIPT, + SELECT, + SMALL, + SPAN, + # STRIKE, + STRONG, + STYLE, + SUB, + SUP, + TABLE, + TBODY, + TD, + TEXTAREA, + TFOOT, + TH, + THEAD, + TITLE, + TR, + # TT, + # U, + UL, + VAR, + XML, + XMLEntity, + XMLNode, + XMP, + xmlescape, + xmlunescape + ) - del ACRONYM - del APPLET - del BASEFONT - del BIG - del CENTER - del DIR - del FONT - del FRAME - del FRAMESET - del NOFRAMES - del STRIKE - del TT - del U -
Replace import * with explicit names
## Code Before: from .common import * del ACRONYM del APPLET del BASEFONT del BIG del CENTER del DIR del FONT del FRAME del FRAMESET del NOFRAMES del STRIKE del TT del U ## Instruction: Replace import * with explicit names ## Code After: from .common import ( # flake8: noqa A, ABBR, # ACRONYM, ADDRESS, # APPLET, AREA, B, BASE, # BASEFONT, BDO, # BIG, BLOCKQUOTE, BODY, BR, BUTTON, Body, CAPTION, CAT, # CENTER, CITE, CODE, COL, COLGROUP, COMMENT, CONDITIONAL_COMMENT, DD, DEL, DFN, # DIR, DIV, DL, DT, EM, FIELDSET, # FONT, FORM, # FRAME, # FRAMESET, Form, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, HTMLDoc, Hyper, I, IFRAME, IMG, INPUT, INS, Image, Javascript, KBD, LABEL, LEGEND, LI, LINK, MAP, MENU, META, NBSP, # NOFRAMES, NOSCRIPT, OBJECT, OL, OPTGROUP, OPTION, P, PARAM, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, # STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, # TT, # U, UL, VAR, XML, XMLEntity, XMLNode, XMP, xmlescape, xmlunescape )
# ... existing code ... from .common import ( # flake8: noqa A, ABBR, # ACRONYM, ADDRESS, # APPLET, AREA, B, BASE, # BASEFONT, BDO, # BIG, BLOCKQUOTE, BODY, BR, BUTTON, Body, CAPTION, CAT, # CENTER, CITE, CODE, COL, COLGROUP, COMMENT, CONDITIONAL_COMMENT, DD, DEL, DFN, # DIR, DIV, DL, DT, EM, FIELDSET, # FONT, FORM, # FRAME, # FRAMESET, Form, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, HTMLDoc, Hyper, I, IFRAME, IMG, INPUT, INS, Image, Javascript, KBD, LABEL, LEGEND, LI, LINK, MAP, MENU, META, NBSP, # NOFRAMES, NOSCRIPT, OBJECT, OL, OPTGROUP, OPTION, P, PARAM, PRE, Q, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, # STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TITLE, TR, # TT, # U, UL, VAR, XML, XMLEntity, XMLNode, XMP, xmlescape, xmlunescape ) # ... rest of the code ...
f800d11aa5a198fcb2193773b30e4e066a226321
code/handle-output.py
code/handle-output.py
import synthetic_data_experiments as sde import logging if __name__ == "__main__": args = sde.get_integrous_arguments_values()
import synthetic_data_experiments as sde import logging if __name__ == "__main__": args = sde.get_integrous_arguments_values() for repeat_idx in xrange(args.num_repeats) : resu_dir = "%s/repeat_%d" % (args.resu_dir, repeat_idx) data_dir = '%s/repeat_%d' % (args.data_dir, repeat_idx)
Set resu dir and data dir
Set resu dir and data dir
Python
mit
chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan
import synthetic_data_experiments as sde import logging if __name__ == "__main__": args = sde.get_integrous_arguments_values() + for repeat_idx in xrange(args.num_repeats) : + + resu_dir = "%s/repeat_%d" % (args.resu_dir, repeat_idx) + data_dir = '%s/repeat_%d' % (args.data_dir, repeat_idx) + +
Set resu dir and data dir
## Code Before: import synthetic_data_experiments as sde import logging if __name__ == "__main__": args = sde.get_integrous_arguments_values() ## Instruction: Set resu dir and data dir ## Code After: import synthetic_data_experiments as sde import logging if __name__ == "__main__": args = sde.get_integrous_arguments_values() for repeat_idx in xrange(args.num_repeats) : resu_dir = "%s/repeat_%d" % (args.resu_dir, repeat_idx) data_dir = '%s/repeat_%d' % (args.data_dir, repeat_idx)
... for repeat_idx in xrange(args.num_repeats) : resu_dir = "%s/repeat_%d" % (args.resu_dir, repeat_idx) data_dir = '%s/repeat_%d' % (args.data_dir, repeat_idx) ...
10d0b7c452c8d9d5893cfe612e0beaa738f61628
easy_pjax/__init__.py
easy_pjax/__init__.py
from __future__ import absolute_import, division, print_function, unicode_literals __version__ = "1.2.0" try: from django.template import add_to_builtins except ImportError: # import path changed in 1.8 from django.template.base import add_to_builtins add_to_builtins("easy_pjax.templatetags.pjax_tags")
from __future__ import absolute_import, division, print_function, unicode_literals __version__ = "1.2.0" has_add_to_builtins = True try: from django.template import add_to_builtins except ImportError: try: # import path changed in 1.8 from django.template.base import add_to_builtins except ImportError: has_add_to_builtins = False if has_add_to_builtins: add_to_builtins("easy_pjax.templatetags.pjax_tags")
Add to template builtins only if add_to_buitlins is available (Django <= 1.8)
Add to template builtins only if add_to_buitlins is available (Django <= 1.8)
Python
bsd-3-clause
nigma/django-easy-pjax,nigma/django-easy-pjax,nigma/django-easy-pjax
from __future__ import absolute_import, division, print_function, unicode_literals __version__ = "1.2.0" - + has_add_to_builtins = True try: from django.template import add_to_builtins except ImportError: + try: - # import path changed in 1.8 + # import path changed in 1.8 - from django.template.base import add_to_builtins + from django.template.base import add_to_builtins + except ImportError: + has_add_to_builtins = False + if has_add_to_builtins: - add_to_builtins("easy_pjax.templatetags.pjax_tags") + add_to_builtins("easy_pjax.templatetags.pjax_tags")
Add to template builtins only if add_to_buitlins is available (Django <= 1.8)
## Code Before: from __future__ import absolute_import, division, print_function, unicode_literals __version__ = "1.2.0" try: from django.template import add_to_builtins except ImportError: # import path changed in 1.8 from django.template.base import add_to_builtins add_to_builtins("easy_pjax.templatetags.pjax_tags") ## Instruction: Add to template builtins only if add_to_buitlins is available (Django <= 1.8) ## Code After: from __future__ import absolute_import, division, print_function, unicode_literals __version__ = "1.2.0" has_add_to_builtins = True try: from django.template import add_to_builtins except ImportError: try: # import path changed in 1.8 from django.template.base import add_to_builtins except ImportError: has_add_to_builtins = False if has_add_to_builtins: add_to_builtins("easy_pjax.templatetags.pjax_tags")
# ... existing code ... has_add_to_builtins = True try: # ... modified code ... except ImportError: try: # import path changed in 1.8 from django.template.base import add_to_builtins except ImportError: has_add_to_builtins = False if has_add_to_builtins: add_to_builtins("easy_pjax.templatetags.pjax_tags") # ... rest of the code ...
edec252d9a050ead0084280f9772f05a2a3d7608
preferences/forms.py
preferences/forms.py
from registration.forms import RegistrationFormUniqueEmail class RegistrationUserForm(RegistrationFormUniqueEmail): class Meta: model = User fields = ("email")
from django import forms from registration.forms import RegistrationFormUniqueEmail from preferences.models import Preferences # from django.forms import ModelForm # class RegistrationUserForm(RegistrationFormUniqueEmail): # class Meta: # model = User # fields = ("email") class PreferencesForm(forms.ModelForm): class Meta: model = Preferences fields = ['representitive', 'senator', 'street_line1', 'street_line2', 'zipcode', 'city', 'state']
Add preferences form built off model
Add preferences form built off model
Python
mit
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
+ from django import forms from registration.forms import RegistrationFormUniqueEmail - class RegistrationUserForm(RegistrationFormUniqueEmail): + from preferences.models import Preferences + # from django.forms import ModelForm + + # class RegistrationUserForm(RegistrationFormUniqueEmail): + + # class Meta: + # model = User + # fields = ("email") + + + class PreferencesForm(forms.ModelForm): class Meta: - model = User + model = Preferences - fields = ("email") + fields = ['representitive', 'senator', 'street_line1', 'street_line2', + 'zipcode', 'city', 'state']
Add preferences form built off model
## Code Before: from registration.forms import RegistrationFormUniqueEmail class RegistrationUserForm(RegistrationFormUniqueEmail): class Meta: model = User fields = ("email") ## Instruction: Add preferences form built off model ## Code After: from django import forms from registration.forms import RegistrationFormUniqueEmail from preferences.models import Preferences # from django.forms import ModelForm # class RegistrationUserForm(RegistrationFormUniqueEmail): # class Meta: # model = User # fields = ("email") class PreferencesForm(forms.ModelForm): class Meta: model = Preferences fields = ['representitive', 'senator', 'street_line1', 'street_line2', 'zipcode', 'city', 'state']
// ... existing code ... from django import forms from registration.forms import RegistrationFormUniqueEmail // ... modified code ... from preferences.models import Preferences # from django.forms import ModelForm # class RegistrationUserForm(RegistrationFormUniqueEmail): # class Meta: # model = User # fields = ("email") class PreferencesForm(forms.ModelForm): class Meta: model = Preferences fields = ['representitive', 'senator', 'street_line1', 'street_line2', 'zipcode', 'city', 'state'] // ... rest of the code ...
3c95ba7e4eda0762d735503b718119e361eb7295
tests/basics/try-finally-return.py
tests/basics/try-finally-return.py
def func1(): try: return "it worked" finally: print("finally 1") print(func1())
def func1(): try: return "it worked" finally: print("finally 1") print(func1()) def func2(): try: return "it worked" finally: print("finally 2") def func3(): try: s = func2() return s + ", did this work?" finally: print("finally 3") print(func3())
Add additional testcase for finally/return.
Add additional testcase for finally/return.
Python
mit
heisewangluo/micropython,noahchense/micropython,henriknelson/micropython,alex-robbins/micropython,aethaniel/micropython,pramasoul/micropython,jlillest/micropython,noahwilliamsson/micropython,henriknelson/micropython,warner83/micropython,ruffy91/micropython,adafruit/circuitpython,mianos/micropython,dhylands/micropython,tralamazza/micropython,swegener/micropython,tralamazza/micropython,oopy/micropython,toolmacher/micropython,paul-xxx/micropython,orionrobots/micropython,oopy/micropython,ceramos/micropython,matthewelse/micropython,hosaka/micropython,EcmaXp/micropython,alex-robbins/micropython,xyb/micropython,galenhz/micropython,neilh10/micropython,drrk/micropython,cloudformdesign/micropython,Peetz0r/micropython-esp32,Timmenem/micropython,jimkmc/micropython,swegener/micropython,skybird6672/micropython,pfalcon/micropython,warner83/micropython,drrk/micropython,danicampora/micropython,lowRISC/micropython,ernesto-g/micropython,kostyll/micropython,HenrikSolver/micropython,cwyark/micropython,methoxid/micropystat,vriera/micropython,Timmenem/micropython,vitiral/micropython,supergis/micropython,MrSurly/micropython-esp32,stonegithubs/micropython,omtinez/micropython,martinribelotta/micropython,firstval/micropython,heisewangluo/micropython,supergis/micropython,emfcamp/micropython,utopiaprince/micropython,noahwilliamsson/micropython,KISSMonX/micropython,rubencabrera/micropython,hiway/micropython,hiway/micropython,chrisdearman/micropython,torwag/micropython,methoxid/micropystat,SungEun-Steve-Kim/test-mp,TDAbboud/micropython,mgyenik/micropython,neilh10/micropython,infinnovation/micropython,praemdonck/micropython,supergis/micropython,adamkh/micropython,mpalomer/micropython,PappaPeppar/micropython,dhylands/micropython,TDAbboud/micropython,turbinenreiter/micropython,rubencabrera/micropython,dinau/micropython,Vogtinator/micropython,EcmaXp/micropython,bvernoux/micropython,ChuckM/micropython,PappaPeppar/micropython,redbear/micropython,turbinenreiter/micropython,torwag/micropython,infinnovation/micropython,PappaPeppar/micropython,mianos/micropython,SHA2017-badge/micropython-esp32,AriZuu/micropython,hosaka/micropython,supergis/micropython,turbinenreiter/micropython,torwag/micropython,ahotam/micropython,drrk/micropython,deshipu/micropython,methoxid/micropystat,alex-march/micropython,hosaka/micropython,praemdonck/micropython,stonegithubs/micropython,xuxiaoxin/micropython,slzatz/micropython,selste/micropython,swegener/micropython,adafruit/micropython,jimkmc/micropython,Vogtinator/micropython,toolmacher/micropython,stonegithubs/micropython,toolmacher/micropython,galenhz/micropython,adafruit/micropython,mianos/micropython,alex-robbins/micropython,matthewelse/micropython,HenrikSolver/micropython,tuc-osg/micropython,praemdonck/micropython,firstval/micropython,blazewicz/micropython,feilongfl/micropython,pramasoul/micropython,dxxb/micropython,cwyark/micropython,martinribelotta/micropython,adafruit/circuitpython,TDAbboud/micropython,blazewicz/micropython,ceramos/micropython,adamkh/micropython,utopiaprince/micropython,tdautc19841202/micropython,dinau/micropython,lbattraw/micropython,xhat/micropython,MrSurly/micropython-esp32,ahotam/micropython,galenhz/micropython,dinau/micropython,jmarcelino/pycom-micropython,ryannathans/micropython,SungEun-Steve-Kim/test-mp,ChuckM/micropython,mhoffma/micropython,ruffy91/micropython,micropython/micropython-esp32,dxxb/micropython,martinribelotta/micropython,rubencabrera/micropython,ericsnowcurrently/micropython,vriera/micropython,danicampora/micropython,xuxiaoxin/micropython,vriera/micropython,kostyll/micropython,firstval/micropython,dhylands/micropython,pfalcon/micropython,supergis/micropython,redbear/micropython,pfalcon/micropython,MrSurly/micropython,alex-robbins/micropython,jlillest/micropython,pramasoul/micropython,cnoviello/micropython,pozetroninc/micropython,ryannathans/micropython,adafruit/circuitpython,galenhz/micropython,bvernoux/micropython,Timmenem/micropython,tdautc19841202/micropython,danicampora/micropython,noahchense/micropython,suda/micropython,cnoviello/micropython,hosaka/micropython,torwag/micropython,SHA2017-badge/micropython-esp32,tobbad/micropython,blmorris/micropython,xyb/micropython,noahchense/micropython,kerneltask/micropython,ruffy91/micropython,deshipu/micropython,cloudformdesign/micropython,firstval/micropython,SungEun-Steve-Kim/test-mp,orionrobots/micropython,dinau/micropython,warner83/micropython,aethaniel/micropython,jlillest/micropython,blazewicz/micropython,jimkmc/micropython,neilh10/micropython,stonegithubs/micropython,KISSMonX/micropython,pfalcon/micropython,ceramos/micropython,TDAbboud/micropython,deshipu/micropython,feilongfl/micropython,SHA2017-badge/micropython-esp32,cnoviello/micropython,mianos/micropython,trezor/micropython,swegener/micropython,blazewicz/micropython,alex-robbins/micropython,skybird6672/micropython,blmorris/micropython,Peetz0r/micropython-esp32,KISSMonX/micropython,aitjcize/micropython,dinau/micropython,mianos/micropython,chrisdearman/micropython,warner83/micropython,micropython/micropython-esp32,ruffy91/micropython,kerneltask/micropython,orionrobots/micropython,jlillest/micropython,MrSurly/micropython,infinnovation/micropython,bvernoux/micropython,adafruit/micropython,danicampora/micropython,ganshun666/micropython,tobbad/micropython,trezor/micropython,omtinez/micropython,misterdanb/micropython,mhoffma/micropython,ChuckM/micropython,adafruit/circuitpython,tdautc19841202/micropython,vriera/micropython,cnoviello/micropython,lbattraw/micropython,xhat/micropython,cwyark/micropython,tdautc19841202/micropython,mhoffma/micropython,pramasoul/micropython,mhoffma/micropython,ceramos/micropython,adafruit/micropython,misterdanb/micropython,infinnovation/micropython,vriera/micropython,PappaPeppar/micropython,ryannathans/micropython,swegener/micropython,kostyll/micropython,pfalcon/micropython,AriZuu/micropython,toolmacher/micropython,trezor/micropython,micropython/micropython-esp32,xyb/micropython,selste/micropython,rubencabrera/micropython,vitiral/micropython,toolmacher/micropython,blmorris/micropython,kostyll/micropython,martinribelotta/micropython,redbear/micropython,dmazzella/micropython,ruffy91/micropython,tdautc19841202/micropython,xuxiaoxin/micropython,praemdonck/micropython,tralamazza/micropython,emfcamp/micropython,drrk/micropython,vitiral/micropython,emfcamp/micropython,ernesto-g/micropython,emfcamp/micropython,misterdanb/micropython,skybird6672/micropython,noahchense/micropython,misterdanb/micropython,MrSurly/micropython-esp32,mpalomer/micropython,henriknelson/micropython,omtinez/micropython,pozetroninc/micropython,redbear/micropython,jimkmc/micropython,cloudformdesign/micropython,ganshun666/micropython,methoxid/micropystat,alex-march/micropython,micropython/micropython-esp32,xyb/micropython,noahwilliamsson/micropython,Timmenem/micropython,SHA2017-badge/micropython-esp32,feilongfl/micropython,selste/micropython,pozetroninc/micropython,xhat/micropython,lowRISC/micropython,TDAbboud/micropython,skybird6672/micropython,hiway/micropython,selste/micropython,slzatz/micropython,pramasoul/micropython,tuc-osg/micropython,mpalomer/micropython,ganshun666/micropython,paul-xxx/micropython,utopiaprince/micropython,matthewelse/micropython,hosaka/micropython,oopy/micropython,jimkmc/micropython,puuu/micropython,xyb/micropython,galenhz/micropython,adamkh/micropython,lbattraw/micropython,feilongfl/micropython,ahotam/micropython,mgyenik/micropython,matthewelse/micropython,paul-xxx/micropython,cnoviello/micropython,ChuckM/micropython,MrSurly/micropython,bvernoux/micropython,Vogtinator/micropython,trezor/micropython,Peetz0r/micropython-esp32,alex-march/micropython,utopiaprince/micropython,lowRISC/micropython,adamkh/micropython,suda/micropython,noahwilliamsson/micropython,chrisdearman/micropython,SHA2017-badge/micropython-esp32,slzatz/micropython,chrisdearman/micropython,Timmenem/micropython,vitiral/micropython,lbattraw/micropython,matthewelse/micropython,utopiaprince/micropython,jlillest/micropython,lowRISC/micropython,adamkh/micropython,mgyenik/micropython,ryannathans/micropython,KISSMonX/micropython,emfcamp/micropython,MrSurly/micropython,aethaniel/micropython,xhat/micropython,skybird6672/micropython,noahwilliamsson/micropython,EcmaXp/micropython,danicampora/micropython,redbear/micropython,Vogtinator/micropython,AriZuu/micropython,dhylands/micropython,tobbad/micropython,blmorris/micropython,dmazzella/micropython,SungEun-Steve-Kim/test-mp,ChuckM/micropython,drrk/micropython,HenrikSolver/micropython,trezor/micropython,jmarcelino/pycom-micropython,cwyark/micropython,oopy/micropython,EcmaXp/micropython,blazewicz/micropython,ericsnowcurrently/micropython,lowRISC/micropython,SungEun-Steve-Kim/test-mp,ahotam/micropython,orionrobots/micropython,adafruit/micropython,MrSurly/micropython-esp32,cloudformdesign/micropython,mhoffma/micropython,oopy/micropython,dmazzella/micropython,vitiral/micropython,tralamazza/micropython,Peetz0r/micropython-esp32,chrisdearman/micropython,slzatz/micropython,PappaPeppar/micropython,suda/micropython,tuc-osg/micropython,tobbad/micropython,aitjcize/micropython,mpalomer/micropython,pozetroninc/micropython,ahotam/micropython,micropython/micropython-esp32,misterdanb/micropython,AriZuu/micropython,ganshun666/micropython,kerneltask/micropython,deshipu/micropython,warner83/micropython,ceramos/micropython,dxxb/micropython,KISSMonX/micropython,ericsnowcurrently/micropython,jmarcelino/pycom-micropython,tobbad/micropython,omtinez/micropython,kerneltask/micropython,kerneltask/micropython,adafruit/circuitpython,HenrikSolver/micropython,blmorris/micropython,henriknelson/micropython,EcmaXp/micropython,xuxiaoxin/micropython,tuc-osg/micropython,bvernoux/micropython,turbinenreiter/micropython,pozetroninc/micropython,feilongfl/micropython,firstval/micropython,jmarcelino/pycom-micropython,martinribelotta/micropython,ernesto-g/micropython,jmarcelino/pycom-micropython,aitjcize/micropython,adafruit/circuitpython,suda/micropython,omtinez/micropython,tuc-osg/micropython,aitjcize/micropython,aethaniel/micropython,puuu/micropython,methoxid/micropystat,Vogtinator/micropython,paul-xxx/micropython,ericsnowcurrently/micropython,ernesto-g/micropython,paul-xxx/micropython,ericsnowcurrently/micropython,dxxb/micropython,ryannathans/micropython,AriZuu/micropython,HenrikSolver/micropython,praemdonck/micropython,suda/micropython,heisewangluo/micropython,slzatz/micropython,puuu/micropython,puuu/micropython,noahchense/micropython,cwyark/micropython,mgyenik/micropython,neilh10/micropython,torwag/micropython,rubencabrera/micropython,matthewelse/micropython,aethaniel/micropython,puuu/micropython,dhylands/micropython,dxxb/micropython,MrSurly/micropython-esp32,turbinenreiter/micropython,hiway/micropython,xhat/micropython,alex-march/micropython,cloudformdesign/micropython,deshipu/micropython,xuxiaoxin/micropython,stonegithubs/micropython,infinnovation/micropython,lbattraw/micropython,heisewangluo/micropython,mgyenik/micropython,alex-march/micropython,ernesto-g/micropython,henriknelson/micropython,orionrobots/micropython,Peetz0r/micropython-esp32,ganshun666/micropython,heisewangluo/micropython,selste/micropython,mpalomer/micropython,dmazzella/micropython,hiway/micropython,kostyll/micropython,neilh10/micropython,MrSurly/micropython
def func1(): try: return "it worked" finally: print("finally 1") print(func1()) + + def func2(): + try: + return "it worked" + finally: + print("finally 2") + + def func3(): + try: + s = func2() + return s + ", did this work?" + finally: + print("finally 3") + + print(func3()) +
Add additional testcase for finally/return.
## Code Before: def func1(): try: return "it worked" finally: print("finally 1") print(func1()) ## Instruction: Add additional testcase for finally/return. ## Code After: def func1(): try: return "it worked" finally: print("finally 1") print(func1()) def func2(): try: return "it worked" finally: print("finally 2") def func3(): try: s = func2() return s + ", did this work?" finally: print("finally 3") print(func3())
// ... existing code ... print(func1()) def func2(): try: return "it worked" finally: print("finally 2") def func3(): try: s = func2() return s + ", did this work?" finally: print("finally 3") print(func3()) // ... rest of the code ...
83bf2da38eb67abab9005495289eb97b58c3856a
ec2_instance_change_type.py
ec2_instance_change_type.py
import sys import click from aws_util import Ec2Util @click.command() @click.option('-p', '--profile', default='default', help='Profile name to use.') @click.argument('id_or_tag', required=True) @click.argument('new_instance_type', required=True) def cli(profile, id_or_tag, new_instance_type): ec2 = Ec2Util(profile) instance = ec2.get_instance(id_or_tag) if instance: old_instance_state = instance.state['Name'] old_instance_type = instance.instance_type print('Current instance type is %s' % old_instance_type) if new_instance_type != instance.instance_type: ec2.change_instance_type(id_or_tag, new_instance_type) instance.reload() print('Instance type changed to %s successfully' % instance.instance_type) else: print('Error. Cannot find instance') if __name__ == '__main__': cli()
import sys import click from aws_util import Ec2Util @click.command() @click.option('-p', '--profile', default='default', help='Profile name to use.') @click.argument('id_or_tag', required=True) @click.argument('new_instance_type', required=True) def cli(profile, id_or_tag, new_instance_type): ec2 = Ec2Util(profile) instance = ec2.get_instance(id_or_tag) if instance: old_instance_state = instance.state['Name'] old_instance_type = instance.instance_type print('Current instance type is %s' % old_instance_type) if new_instance_type != instance.instance_type: ec2.change_instance_type(id_or_tag, new_instance_type) instance.reload() print('Instance type changed to %s successfully' % instance.instance_type) else: print('Current instance type is the same as new type. No need to do anything.') else: print('Error. Cannot find instance') if __name__ == '__main__': cli()
Change message that detects instance type
Change message that detects instance type
Python
mit
thinhpham/aws-tools
import sys import click from aws_util import Ec2Util @click.command() @click.option('-p', '--profile', default='default', help='Profile name to use.') @click.argument('id_or_tag', required=True) @click.argument('new_instance_type', required=True) def cli(profile, id_or_tag, new_instance_type): ec2 = Ec2Util(profile) instance = ec2.get_instance(id_or_tag) if instance: old_instance_state = instance.state['Name'] old_instance_type = instance.instance_type print('Current instance type is %s' % old_instance_type) if new_instance_type != instance.instance_type: ec2.change_instance_type(id_or_tag, new_instance_type) instance.reload() - print('Instance type changed to %s successfully' % instance.instance_type) + print('Instance type changed to %s successfully' % instance.instance_type) + else: + print('Current instance type is the same as new type. No need to do anything.') else: print('Error. Cannot find instance') if __name__ == '__main__': cli()
Change message that detects instance type
## Code Before: import sys import click from aws_util import Ec2Util @click.command() @click.option('-p', '--profile', default='default', help='Profile name to use.') @click.argument('id_or_tag', required=True) @click.argument('new_instance_type', required=True) def cli(profile, id_or_tag, new_instance_type): ec2 = Ec2Util(profile) instance = ec2.get_instance(id_or_tag) if instance: old_instance_state = instance.state['Name'] old_instance_type = instance.instance_type print('Current instance type is %s' % old_instance_type) if new_instance_type != instance.instance_type: ec2.change_instance_type(id_or_tag, new_instance_type) instance.reload() print('Instance type changed to %s successfully' % instance.instance_type) else: print('Error. Cannot find instance') if __name__ == '__main__': cli() ## Instruction: Change message that detects instance type ## Code After: import sys import click from aws_util import Ec2Util @click.command() @click.option('-p', '--profile', default='default', help='Profile name to use.') @click.argument('id_or_tag', required=True) @click.argument('new_instance_type', required=True) def cli(profile, id_or_tag, new_instance_type): ec2 = Ec2Util(profile) instance = ec2.get_instance(id_or_tag) if instance: old_instance_state = instance.state['Name'] old_instance_type = instance.instance_type print('Current instance type is %s' % old_instance_type) if new_instance_type != instance.instance_type: ec2.change_instance_type(id_or_tag, new_instance_type) instance.reload() print('Instance type changed to %s successfully' % instance.instance_type) else: print('Current instance type is the same as new type. No need to do anything.') else: print('Error. Cannot find instance') if __name__ == '__main__': cli()
# ... existing code ... instance.reload() print('Instance type changed to %s successfully' % instance.instance_type) else: print('Current instance type is the same as new type. No need to do anything.') else: # ... rest of the code ...
14c41706d6437247bbe69e0e574c03863fbe5bda
api/v2/views/maintenance_record.py
api/v2/views/maintenance_record.py
from rest_framework.serializers import ValidationError from core.models import MaintenanceRecord from api.permissions import CanEditOrReadOnly from api.v2.serializers.details import MaintenanceRecordSerializer from api.v2.views.base import AuthOptionalViewSet class MaintenanceRecordViewSet(AuthOptionalViewSet): """ API endpoint that allows records to be viewed or edited. """ http_method_names = ['get', 'post', 'put', 'patch', 'head', 'options', 'trace'] queryset = MaintenanceRecord.objects.order_by('-start_date') permission_classes = (CanEditOrReadOnly,) serializer_class = MaintenanceRecordSerializer
import django_filters from rest_framework import filters from rest_framework.serializers import ValidationError from core.models import AtmosphereUser, MaintenanceRecord from core.query import only_current from api.permissions import CanEditOrReadOnly from api.v2.serializers.details import MaintenanceRecordSerializer from api.v2.views.base import AuthOptionalViewSet class MaintenanceRecordFilterBackend(filters.BaseFilterBackend): """ Filter MaintenanceRecords using the request_user and 'query_params' """ def filter_queryset(self, request, queryset, view): request_params = request.query_params active = request_params.get('active') if isinstance(active, basestring) and active.lower() == 'true'\ or isinstance(active, bool) and active: queryset = MaintenanceRecord.active() return queryset class MaintenanceRecordViewSet(AuthOptionalViewSet): """ API endpoint that allows records to be viewed or edited. """ http_method_names = ['get', 'post', 'put', 'patch', 'head', 'options', 'trace'] queryset = MaintenanceRecord.objects.order_by('-start_date') permission_classes = (CanEditOrReadOnly,) serializer_class = MaintenanceRecordSerializer filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, MaintenanceRecordFilterBackend)
Add '?active=' filter for Maintenance Record
[ATMO-1200] Add '?active=' filter for Maintenance Record
Python
apache-2.0
CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend
+ import django_filters + + from rest_framework import filters from rest_framework.serializers import ValidationError - from core.models import MaintenanceRecord + from core.models import AtmosphereUser, MaintenanceRecord + from core.query import only_current from api.permissions import CanEditOrReadOnly from api.v2.serializers.details import MaintenanceRecordSerializer from api.v2.views.base import AuthOptionalViewSet + + class MaintenanceRecordFilterBackend(filters.BaseFilterBackend): + """ + Filter MaintenanceRecords using the request_user and 'query_params' + """ + def filter_queryset(self, request, queryset, view): + request_params = request.query_params + active = request_params.get('active') + if isinstance(active, basestring) and active.lower() == 'true'\ + or isinstance(active, bool) and active: + queryset = MaintenanceRecord.active() + return queryset class MaintenanceRecordViewSet(AuthOptionalViewSet): """ API endpoint that allows records to be viewed or edited. """ http_method_names = ['get', 'post', 'put', 'patch', 'head', 'options', 'trace'] queryset = MaintenanceRecord.objects.order_by('-start_date') permission_classes = (CanEditOrReadOnly,) serializer_class = MaintenanceRecordSerializer + filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, MaintenanceRecordFilterBackend)
Add '?active=' filter for Maintenance Record
## Code Before: from rest_framework.serializers import ValidationError from core.models import MaintenanceRecord from api.permissions import CanEditOrReadOnly from api.v2.serializers.details import MaintenanceRecordSerializer from api.v2.views.base import AuthOptionalViewSet class MaintenanceRecordViewSet(AuthOptionalViewSet): """ API endpoint that allows records to be viewed or edited. """ http_method_names = ['get', 'post', 'put', 'patch', 'head', 'options', 'trace'] queryset = MaintenanceRecord.objects.order_by('-start_date') permission_classes = (CanEditOrReadOnly,) serializer_class = MaintenanceRecordSerializer ## Instruction: Add '?active=' filter for Maintenance Record ## Code After: import django_filters from rest_framework import filters from rest_framework.serializers import ValidationError from core.models import AtmosphereUser, MaintenanceRecord from core.query import only_current from api.permissions import CanEditOrReadOnly from api.v2.serializers.details import MaintenanceRecordSerializer from api.v2.views.base import AuthOptionalViewSet class MaintenanceRecordFilterBackend(filters.BaseFilterBackend): """ Filter MaintenanceRecords using the request_user and 'query_params' """ def filter_queryset(self, request, queryset, view): request_params = request.query_params active = request_params.get('active') if isinstance(active, basestring) and active.lower() == 'true'\ or isinstance(active, bool) and active: queryset = MaintenanceRecord.active() return queryset class MaintenanceRecordViewSet(AuthOptionalViewSet): """ API endpoint that allows records to be viewed or edited. """ http_method_names = ['get', 'post', 'put', 'patch', 'head', 'options', 'trace'] queryset = MaintenanceRecord.objects.order_by('-start_date') permission_classes = (CanEditOrReadOnly,) serializer_class = MaintenanceRecordSerializer filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, MaintenanceRecordFilterBackend)
# ... existing code ... import django_filters from rest_framework import filters from rest_framework.serializers import ValidationError # ... modified code ... from core.models import AtmosphereUser, MaintenanceRecord from core.query import only_current ... class MaintenanceRecordFilterBackend(filters.BaseFilterBackend): """ Filter MaintenanceRecords using the request_user and 'query_params' """ def filter_queryset(self, request, queryset, view): request_params = request.query_params active = request_params.get('active') if isinstance(active, basestring) and active.lower() == 'true'\ or isinstance(active, bool) and active: queryset = MaintenanceRecord.active() return queryset ... serializer_class = MaintenanceRecordSerializer filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, MaintenanceRecordFilterBackend) # ... rest of the code ...
5ac8e4619473275f2f0b26b8a9b64049d793a4ed
rmqid/__init__.py
rmqid/__init__.py
__version__ = '0.3.0' from rmqid.connection import Connection from rmqid.exchange import Exchange from rmqid.message import Message from rmqid.queue import Queue from rmqid.tx import Tx from rmqid.simple import consumer from rmqid.simple import get from rmqid.simple import publish
__version__ = '0.3.0' from rmqid.connection import Connection from rmqid.exchange import Exchange from rmqid.message import Message from rmqid.queue import Queue from rmqid.tx import Tx from rmqid.simple import consumer from rmqid.simple import get from rmqid.simple import publish import logging try: from logging import NullHandler except ImportError: # Python 2.6 does not have a NullHandler class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger().addHandler(NullHandler())
Add a NullHandler so logging warnings are not emitted if no logger is setup
Add a NullHandler so logging warnings are not emitted if no logger is setup
Python
bsd-3-clause
jonahbull/rabbitpy,gmr/rabbitpy,gmr/rabbitpy
__version__ = '0.3.0' from rmqid.connection import Connection from rmqid.exchange import Exchange from rmqid.message import Message from rmqid.queue import Queue from rmqid.tx import Tx from rmqid.simple import consumer from rmqid.simple import get from rmqid.simple import publish + import logging + + try: + from logging import NullHandler + except ImportError: + # Python 2.6 does not have a NullHandler + class NullHandler(logging.Handler): + def emit(self, record): + pass + + logging.getLogger().addHandler(NullHandler()) +
Add a NullHandler so logging warnings are not emitted if no logger is setup
## Code Before: __version__ = '0.3.0' from rmqid.connection import Connection from rmqid.exchange import Exchange from rmqid.message import Message from rmqid.queue import Queue from rmqid.tx import Tx from rmqid.simple import consumer from rmqid.simple import get from rmqid.simple import publish ## Instruction: Add a NullHandler so logging warnings are not emitted if no logger is setup ## Code After: __version__ = '0.3.0' from rmqid.connection import Connection from rmqid.exchange import Exchange from rmqid.message import Message from rmqid.queue import Queue from rmqid.tx import Tx from rmqid.simple import consumer from rmqid.simple import get from rmqid.simple import publish import logging try: from logging import NullHandler except ImportError: # Python 2.6 does not have a NullHandler class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger().addHandler(NullHandler())
// ... existing code ... from rmqid.simple import publish import logging try: from logging import NullHandler except ImportError: # Python 2.6 does not have a NullHandler class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger().addHandler(NullHandler()) // ... rest of the code ...
0c56e276aa1963ec35d744f61cecbb9368f115be
admin_tools/theming/templatetags/theming_tags.py
admin_tools/theming/templatetags/theming_tags.py
from django import template from django.conf import settings from admin_tools.utils import get_media_url register = template.Library() def render_theming_css(): """ Template tag that renders the needed css files for the theming app. """ css = getattr(settings, 'ADMIN_TOOLS_THEMING_CSS', False) if css: css = '/'.join([get_media_url(), css]) else: css = '/'.join([get_media_url(), 'admin_tools', 'css', 'theming.css']) return '<link rel="stylesheet" type="text/css" media="screen" href="%s" />' % css register.simple_tag(render_theming_css)
from django import template from django.conf import settings from admin_tools.utils import get_media_url register = template.Library() def render_theming_css(): """ Template tag that renders the needed css files for the theming app. If ADMIN_TOOLS_THEMING_CSS is explicitely defined to None, don't render anything. """ rval = '' try: css_path = getattr(settings, 'ADMIN_TOOLS_THEMING_CSS') except AttributeError: css_path = 'admin_tools/css/theming.css' if css_path is not None: css_url = '%s/%s' % (get_media_url(), css_path) rval = '<link rel="stylesheet" type="text/css" media="screen" href="%s" />' % css_url return rval register.simple_tag(render_theming_css)
Enable not loading theming CSS by explicitely setting ADMIN_TOOLS_THEMING_CSS to None
Enable not loading theming CSS by explicitely setting ADMIN_TOOLS_THEMING_CSS to None
Python
mit
liberation/django-admin-tools,liberation/django-admin-tools,liberation/django-admin-tools,liberation/django-admin-tools
from django import template from django.conf import settings from admin_tools.utils import get_media_url register = template.Library() def render_theming_css(): """ Template tag that renders the needed css files for the theming app. + + If ADMIN_TOOLS_THEMING_CSS is explicitely defined to None, don't render + anything. """ + rval = '' + try: - css = getattr(settings, 'ADMIN_TOOLS_THEMING_CSS', False) + css_path = getattr(settings, 'ADMIN_TOOLS_THEMING_CSS') - if css: + except AttributeError: + css_path = 'admin_tools/css/theming.css' + + if css_path is not None: - css = '/'.join([get_media_url(), css]) + css_url = '%s/%s' % (get_media_url(), css_path) - else: - css = '/'.join([get_media_url(), 'admin_tools', 'css', 'theming.css']) - return '<link rel="stylesheet" type="text/css" media="screen" href="%s" />' % css + rval = '<link rel="stylesheet" type="text/css" media="screen" href="%s" />' % css_url + + return rval + register.simple_tag(render_theming_css)
Enable not loading theming CSS by explicitely setting ADMIN_TOOLS_THEMING_CSS to None
## Code Before: from django import template from django.conf import settings from admin_tools.utils import get_media_url register = template.Library() def render_theming_css(): """ Template tag that renders the needed css files for the theming app. """ css = getattr(settings, 'ADMIN_TOOLS_THEMING_CSS', False) if css: css = '/'.join([get_media_url(), css]) else: css = '/'.join([get_media_url(), 'admin_tools', 'css', 'theming.css']) return '<link rel="stylesheet" type="text/css" media="screen" href="%s" />' % css register.simple_tag(render_theming_css) ## Instruction: Enable not loading theming CSS by explicitely setting ADMIN_TOOLS_THEMING_CSS to None ## Code After: from django import template from django.conf import settings from admin_tools.utils import get_media_url register = template.Library() def render_theming_css(): """ Template tag that renders the needed css files for the theming app. If ADMIN_TOOLS_THEMING_CSS is explicitely defined to None, don't render anything. """ rval = '' try: css_path = getattr(settings, 'ADMIN_TOOLS_THEMING_CSS') except AttributeError: css_path = 'admin_tools/css/theming.css' if css_path is not None: css_url = '%s/%s' % (get_media_url(), css_path) rval = '<link rel="stylesheet" type="text/css" media="screen" href="%s" />' % css_url return rval register.simple_tag(render_theming_css)
// ... existing code ... Template tag that renders the needed css files for the theming app. If ADMIN_TOOLS_THEMING_CSS is explicitely defined to None, don't render anything. """ rval = '' try: css_path = getattr(settings, 'ADMIN_TOOLS_THEMING_CSS') except AttributeError: css_path = 'admin_tools/css/theming.css' if css_path is not None: css_url = '%s/%s' % (get_media_url(), css_path) rval = '<link rel="stylesheet" type="text/css" media="screen" href="%s" />' % css_url return rval register.simple_tag(render_theming_css) // ... rest of the code ...
325fed2ef774e708e96d1b123672e1be238d7d21
nailgun/nailgun/models.py
nailgun/nailgun/models.py
from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes') name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes')
from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes', null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes')
Allow nodes not to have related environment
Allow nodes not to have related environment
Python
apache-2.0
SmartInfrastructures/fuel-main-dev,nebril/fuel-web,dancn/fuel-main-dev,SergK/fuel-main,zhaochao/fuel-main,nebril/fuel-web,prmtl/fuel-web,zhaochao/fuel-main,eayunstack/fuel-web,nebril/fuel-web,SmartInfrastructures/fuel-main-dev,SmartInfrastructures/fuel-main-dev,teselkin/fuel-main,Fiware/ops.Fuel-main-dev,teselkin/fuel-main,zhaochao/fuel-web,dancn/fuel-main-dev,eayunstack/fuel-web,stackforge/fuel-web,huntxu/fuel-web,SmartInfrastructures/fuel-web-dev,prmtl/fuel-web,eayunstack/fuel-web,zhaochao/fuel-main,teselkin/fuel-main,SmartInfrastructures/fuel-web-dev,SmartInfrastructures/fuel-web-dev,stackforge/fuel-web,Fiware/ops.Fuel-main-dev,AnselZhangGit/fuel-main,nebril/fuel-web,SmartInfrastructures/fuel-web-dev,eayunstack/fuel-web,dancn/fuel-main-dev,zhaochao/fuel-web,dancn/fuel-main-dev,koder-ua/nailgun-fcert,zhaochao/fuel-main,AnselZhangGit/fuel-main,teselkin/fuel-main,prmtl/fuel-web,huntxu/fuel-web,koder-ua/nailgun-fcert,SergK/fuel-main,huntxu/fuel-main,koder-ua/nailgun-fcert,huntxu/fuel-main,huntxu/fuel-main,stackforge/fuel-main,eayunstack/fuel-main,SmartInfrastructures/fuel-main-dev,ddepaoli3/fuel-main-dev,Fiware/ops.Fuel-main-dev,AnselZhangGit/fuel-main,stackforge/fuel-web,SergK/fuel-main,zhaochao/fuel-web,ddepaoli3/fuel-main-dev,SmartInfrastructures/fuel-web-dev,ddepaoli3/fuel-main-dev,AnselZhangGit/fuel-main,huntxu/fuel-web,nebril/fuel-web,prmtl/fuel-web,huntxu/fuel-web,eayunstack/fuel-main,huntxu/fuel-web,zhaochao/fuel-main,zhaochao/fuel-web,stackforge/fuel-main,ddepaoli3/fuel-main-dev,prmtl/fuel-web,zhaochao/fuel-web,stackforge/fuel-main,koder-ua/nailgun-fcert,eayunstack/fuel-web,eayunstack/fuel-main,Fiware/ops.Fuel-main-dev
from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) - environment = models.ForeignKey(Environment, related_name='nodes') + environment = models.ForeignKey(Environment, related_name='nodes', + null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes')
Allow nodes not to have related environment
## Code Before: from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes') name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes') ## Instruction: Allow nodes not to have related environment ## Code After: from django.db import models from django.contrib.auth.models import User from jsonfield import JSONField class Environment(models.Model): #user = models.ForeignKey(User, related_name='environments') name = models.CharField(max_length=100) class Role(models.Model): id = models.CharField(max_length=30, primary_key=True) name = models.CharField(max_length=50) class Node(models.Model): NODE_STATUSES = ( ('online', 'online'), ('offline', 'offline'), ('busy', 'busy'), ) environment = models.ForeignKey(Environment, related_name='nodes', null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=100, primary_key=True) status = models.CharField(max_length=30, choices=NODE_STATUSES, default='online') metadata = JSONField() roles = models.ManyToManyField(Role, related_name='nodes')
// ... existing code ... ) environment = models.ForeignKey(Environment, related_name='nodes', null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=100, primary_key=True) // ... rest of the code ...
257b186eb64638d6638be93633d4db02ce14d390
docker_log_es/storage.py
docker_log_es/storage.py
import socket from os import environ as env from tornado.netutil import Resolver from tornado import gen from tornado.httpclient import AsyncHTTPClient class UnixResolver(Resolver): def initialize(self, resolver): self.resolver = resolver def close(self): self.resolver.close() @gen.coroutine def resolve(self, host, port, *args, **kwargs): scheme, path = Storage.DOCKER.split('://') if host == 'docker': if scheme == 'unix': raise gen.Return([(socket.AF_UNIX, path)]) elif scheme == 'tcp' or scheme == 'http': t = path.split(":") if len(t) > 1: host, port = t port = int(port) else: host, port = t[0], 80 result = yield self.resolver.resolve(host, port, *args, **kwargs) raise gen.Return(result) AsyncHTTPClient.configure( None, resolver=UnixResolver(resolver=Resolver()), max_clients=20000 ) class Storage(object): CONTAINERS = set([]) DOCKER = env.get('DOCKER_HOST', 'unix:///var/run/docker.sock') ELASTICSEARCH = env.get('ELASTICSEARCH', 'http://127.0.0.1:9200') http = AsyncHTTPClient()
import socket from os import environ as env from tornado.netutil import Resolver from tornado import gen from tornado.httpclient import AsyncHTTPClient class UnixResolver(Resolver): def initialize(self, resolver): self.resolver = resolver def close(self): self.resolver.close() @gen.coroutine def resolve(self, host, port, *args, **kwargs): scheme, path = Storage.DOCKER.split('://') if host == 'docker': if scheme == 'unix': raise gen.Return([(socket.AF_UNIX, path)]) elif scheme == 'tcp' or scheme == 'http': t = path.split(":") if len(t) > 1: host, port = t port = int(port) else: host, port = t[0], 80 result = yield self.resolver.resolve(host, port, *args, **kwargs) raise gen.Return(result) AsyncHTTPClient.configure( None, resolver=UnixResolver(resolver=Resolver()), max_clients=20000 ) class Storage(object): CONTAINERS = set([]) DOCKER = env.get('DOCKER_HOST', 'unix:///var/run/docker.sock') ELASTICSEARCH = env.get('ELASTICSEARCH', 'http://elasticsearch:9200') http = AsyncHTTPClient()
Connect to the "elasticsearch" host by default
Connect to the "elasticsearch" host by default
Python
mit
ei-grad/docker-log-es
import socket from os import environ as env from tornado.netutil import Resolver from tornado import gen from tornado.httpclient import AsyncHTTPClient class UnixResolver(Resolver): def initialize(self, resolver): self.resolver = resolver def close(self): self.resolver.close() @gen.coroutine def resolve(self, host, port, *args, **kwargs): scheme, path = Storage.DOCKER.split('://') if host == 'docker': if scheme == 'unix': raise gen.Return([(socket.AF_UNIX, path)]) elif scheme == 'tcp' or scheme == 'http': t = path.split(":") if len(t) > 1: host, port = t port = int(port) else: host, port = t[0], 80 result = yield self.resolver.resolve(host, port, *args, **kwargs) raise gen.Return(result) AsyncHTTPClient.configure( None, resolver=UnixResolver(resolver=Resolver()), max_clients=20000 ) class Storage(object): CONTAINERS = set([]) DOCKER = env.get('DOCKER_HOST', 'unix:///var/run/docker.sock') - ELASTICSEARCH = env.get('ELASTICSEARCH', 'http://127.0.0.1:9200') + ELASTICSEARCH = env.get('ELASTICSEARCH', 'http://elasticsearch:9200') http = AsyncHTTPClient()
Connect to the "elasticsearch" host by default
## Code Before: import socket from os import environ as env from tornado.netutil import Resolver from tornado import gen from tornado.httpclient import AsyncHTTPClient class UnixResolver(Resolver): def initialize(self, resolver): self.resolver = resolver def close(self): self.resolver.close() @gen.coroutine def resolve(self, host, port, *args, **kwargs): scheme, path = Storage.DOCKER.split('://') if host == 'docker': if scheme == 'unix': raise gen.Return([(socket.AF_UNIX, path)]) elif scheme == 'tcp' or scheme == 'http': t = path.split(":") if len(t) > 1: host, port = t port = int(port) else: host, port = t[0], 80 result = yield self.resolver.resolve(host, port, *args, **kwargs) raise gen.Return(result) AsyncHTTPClient.configure( None, resolver=UnixResolver(resolver=Resolver()), max_clients=20000 ) class Storage(object): CONTAINERS = set([]) DOCKER = env.get('DOCKER_HOST', 'unix:///var/run/docker.sock') ELASTICSEARCH = env.get('ELASTICSEARCH', 'http://127.0.0.1:9200') http = AsyncHTTPClient() ## Instruction: Connect to the "elasticsearch" host by default ## Code After: import socket from os import environ as env from tornado.netutil import Resolver from tornado import gen from tornado.httpclient import AsyncHTTPClient class UnixResolver(Resolver): def initialize(self, resolver): self.resolver = resolver def close(self): self.resolver.close() @gen.coroutine def resolve(self, host, port, *args, **kwargs): scheme, path = Storage.DOCKER.split('://') if host == 'docker': if scheme == 'unix': raise gen.Return([(socket.AF_UNIX, path)]) elif scheme == 'tcp' or scheme == 'http': t = path.split(":") if len(t) > 1: host, port = t port = int(port) else: host, port = t[0], 80 result = yield self.resolver.resolve(host, port, *args, **kwargs) raise gen.Return(result) AsyncHTTPClient.configure( None, resolver=UnixResolver(resolver=Resolver()), max_clients=20000 ) class Storage(object): CONTAINERS = set([]) DOCKER = env.get('DOCKER_HOST', 'unix:///var/run/docker.sock') ELASTICSEARCH = env.get('ELASTICSEARCH', 'http://elasticsearch:9200') http = AsyncHTTPClient()
// ... existing code ... DOCKER = env.get('DOCKER_HOST', 'unix:///var/run/docker.sock') ELASTICSEARCH = env.get('ELASTICSEARCH', 'http://elasticsearch:9200') http = AsyncHTTPClient() // ... rest of the code ...
21c60fdd99e37436228cfe8e59f1b8788ea2b58b
platformio/builder/tools/pioar.py
platformio/builder/tools/pioar.py
import atexit from os import remove from tempfile import mkstemp MAX_SOURCES_LENGTH = 8000 # Windows CLI has limit with command length to 8192 def _remove_tmpfile(path): try: remove(path) except WindowsError: pass def _huge_sources_hook(sources): if len(str(sources)) < MAX_SOURCES_LENGTH: return sources _, tmp_file = mkstemp() with open(tmp_file, "w") as f: f.write(str(sources).replace("\\", "/")) atexit.register(_remove_tmpfile, tmp_file) return "@%s" % tmp_file def exists(_): return True def generate(env): env.Replace( _huge_sources_hook=_huge_sources_hook, ARCOM=env.get("ARCOM", "").replace( "$SOURCES", "${_huge_sources_hook(SOURCES)}")) return env
import atexit from os import remove from tempfile import mkstemp MAX_SOURCES_LENGTH = 8000 # Windows CLI has limit with command length to 8192 def _remove_tmpfile(path): try: remove(path) except WindowsError: # pylint: disable=E0602 pass def _huge_sources_hook(sources): if len(str(sources)) < MAX_SOURCES_LENGTH: return sources _, tmp_file = mkstemp() with open(tmp_file, "w") as f: f.write(str(sources).replace("\\", "/")) atexit.register(_remove_tmpfile, tmp_file) return "@%s" % tmp_file def exists(_): return True def generate(env): env.Replace( _huge_sources_hook=_huge_sources_hook, ARCOM=env.get("ARCOM", "").replace( "$SOURCES", "${_huge_sources_hook(SOURCES)}")) return env
Hide PyLint warning with undefined WindowsError exception
Hide PyLint warning with undefined WindowsError exception
Python
apache-2.0
dkuku/platformio,mseroczynski/platformio,jrobeson/platformio,bkudria/platformio,awong1900/platformio,TimJay/platformio,TimJay/platformio,jrobeson/platformio,awong1900/platformio,awong1900/platformio,mcanthony/platformio,TimJay/platformio,ZachMassia/platformio,platformio/platformio-core,TimJay/platformio,platformio/platformio-core,jrobeson/platformio,platformio/platformio,valeros/platformio,jrobeson/platformio,bkudria/platformio,TimJay/platformio,bkudria/platformio,mplewis/platformio,bkudria/platformio,eiginn/platformio,atyenoria/platformio
import atexit from os import remove from tempfile import mkstemp MAX_SOURCES_LENGTH = 8000 # Windows CLI has limit with command length to 8192 def _remove_tmpfile(path): try: remove(path) - except WindowsError: + except WindowsError: # pylint: disable=E0602 pass def _huge_sources_hook(sources): if len(str(sources)) < MAX_SOURCES_LENGTH: return sources _, tmp_file = mkstemp() with open(tmp_file, "w") as f: f.write(str(sources).replace("\\", "/")) atexit.register(_remove_tmpfile, tmp_file) return "@%s" % tmp_file def exists(_): return True def generate(env): env.Replace( _huge_sources_hook=_huge_sources_hook, ARCOM=env.get("ARCOM", "").replace( "$SOURCES", "${_huge_sources_hook(SOURCES)}")) return env
Hide PyLint warning with undefined WindowsError exception
## Code Before: import atexit from os import remove from tempfile import mkstemp MAX_SOURCES_LENGTH = 8000 # Windows CLI has limit with command length to 8192 def _remove_tmpfile(path): try: remove(path) except WindowsError: pass def _huge_sources_hook(sources): if len(str(sources)) < MAX_SOURCES_LENGTH: return sources _, tmp_file = mkstemp() with open(tmp_file, "w") as f: f.write(str(sources).replace("\\", "/")) atexit.register(_remove_tmpfile, tmp_file) return "@%s" % tmp_file def exists(_): return True def generate(env): env.Replace( _huge_sources_hook=_huge_sources_hook, ARCOM=env.get("ARCOM", "").replace( "$SOURCES", "${_huge_sources_hook(SOURCES)}")) return env ## Instruction: Hide PyLint warning with undefined WindowsError exception ## Code After: import atexit from os import remove from tempfile import mkstemp MAX_SOURCES_LENGTH = 8000 # Windows CLI has limit with command length to 8192 def _remove_tmpfile(path): try: remove(path) except WindowsError: # pylint: disable=E0602 pass def _huge_sources_hook(sources): if len(str(sources)) < MAX_SOURCES_LENGTH: return sources _, tmp_file = mkstemp() with open(tmp_file, "w") as f: f.write(str(sources).replace("\\", "/")) atexit.register(_remove_tmpfile, tmp_file) return "@%s" % tmp_file def exists(_): return True def generate(env): env.Replace( _huge_sources_hook=_huge_sources_hook, ARCOM=env.get("ARCOM", "").replace( "$SOURCES", "${_huge_sources_hook(SOURCES)}")) return env
... remove(path) except WindowsError: # pylint: disable=E0602 pass ...
a16889f353873e3d08a24440b9aa83177ffd001f
engine.py
engine.py
import json import sys import os # For os.path and the like class DictWrapper(object): def __init__(self, d): self.__dict__ = d def eval_script(self): return eval(self.script) # With self as context d = json.load(sys.stdin) dw = DictWrapper(d) json.dump(dw.eval_script(), sys.stdout)
import json import sys import os # For os.path and the like class DictWrapper(object): def __init__(self, d): self.__dict__ = d def eval_script(self): return eval(self.script) # With self as context def __getattr__(self, attr): return None if __name__ == '__main__': input_dict = json.load(sys.stdin) dw = DictWrapper(input_dict) json.dump(dw.eval_script(), sys.stdout)
Implement __getattr__ to handle KeyErrors
Implement __getattr__ to handle KeyErrors
Python
mit
dleehr/py-expr-engine
import json import sys - import os # For os.path and the like + import os # For os.path and the like + class DictWrapper(object): def __init__(self, d): self.__dict__ = d + def eval_script(self): - return eval(self.script) # With self as context + return eval(self.script) # With self as context + + def __getattr__(self, attr): + return None + if __name__ == '__main__': - d = json.load(sys.stdin) + input_dict = json.load(sys.stdin) - dw = DictWrapper(d) + dw = DictWrapper(input_dict) - json.dump(dw.eval_script(), sys.stdout) + json.dump(dw.eval_script(), sys.stdout)
Implement __getattr__ to handle KeyErrors
## Code Before: import json import sys import os # For os.path and the like class DictWrapper(object): def __init__(self, d): self.__dict__ = d def eval_script(self): return eval(self.script) # With self as context d = json.load(sys.stdin) dw = DictWrapper(d) json.dump(dw.eval_script(), sys.stdout) ## Instruction: Implement __getattr__ to handle KeyErrors ## Code After: import json import sys import os # For os.path and the like class DictWrapper(object): def __init__(self, d): self.__dict__ = d def eval_script(self): return eval(self.script) # With self as context def __getattr__(self, attr): return None if __name__ == '__main__': input_dict = json.load(sys.stdin) dw = DictWrapper(input_dict) json.dump(dw.eval_script(), sys.stdout)
# ... existing code ... import sys import os # For os.path and the like # ... modified code ... self.__dict__ = d def eval_script(self): return eval(self.script) # With self as context def __getattr__(self, attr): return None ... if __name__ == '__main__': input_dict = json.load(sys.stdin) dw = DictWrapper(input_dict) json.dump(dw.eval_script(), sys.stdout) # ... rest of the code ...
b3f91806b525ddef50d541f937bed539f9bae20a
mezzanine/project_template/deploy/live_settings.py
mezzanine/project_template/deploy/live_settings.py
DATABASES = { "default": { # Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.postgresql_psycopg2", # DB name or path to database file if using sqlite3. "NAME": "%(proj_name)s", # Not used with sqlite3. "USER": "%(proj_name)s", # Not used with sqlite3. "PASSWORD": "%(db_pass)s", # Set to empty string for localhost. Not used with sqlite3. "HOST": "127.0.0.1", # Set to empty string for default. Not used with sqlite3. "PORT": "", } } SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https") CACHE_MIDDLEWARE_SECONDS = 60 CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "127.0.0.1:11211", } }
DATABASES = { "default": { # Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.postgresql_psycopg2", # DB name or path to database file if using sqlite3. "NAME": "%(proj_name)s", # Not used with sqlite3. "USER": "%(proj_name)s", # Not used with sqlite3. "PASSWORD": "%(db_pass)s", # Set to empty string for localhost. Not used with sqlite3. "HOST": "127.0.0.1", # Set to empty string for default. Not used with sqlite3. "PORT": "", } } SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https") CACHE_MIDDLEWARE_SECONDS = 60 CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "127.0.0.1:11211", } } SESSION_ENGINE = "django.contrib.sessions.backends.cache"
Use cache backend for sessions in deployed settings.
Use cache backend for sessions in deployed settings.
Python
bsd-2-clause
Kniyl/mezzanine,webounty/mezzanine,spookylukey/mezzanine,theclanks/mezzanine,batpad/mezzanine,sjdines/mezzanine,dovydas/mezzanine,readevalprint/mezzanine,eino-makitalo/mezzanine,industrydive/mezzanine,joshcartme/mezzanine,Cajoline/mezzanine,frankier/mezzanine,PegasusWang/mezzanine,biomassives/mezzanine,Skytorn86/mezzanine,adrian-the-git/mezzanine,agepoly/mezzanine,saintbird/mezzanine,damnfine/mezzanine,stbarnabas/mezzanine,dsanders11/mezzanine,biomassives/mezzanine,gradel/mezzanine,joshcartme/mezzanine,vladir/mezzanine,geodesign/mezzanine,molokov/mezzanine,geodesign/mezzanine,geodesign/mezzanine,sjuxax/mezzanine,orlenko/sfpirg,SoLoHiC/mezzanine,orlenko/sfpirg,wyzex/mezzanine,vladir/mezzanine,wyzex/mezzanine,douglaskastle/mezzanine,Cicero-Zhao/mezzanine,nikolas/mezzanine,theclanks/mezzanine,scarcry/snm-mezzanine,wyzex/mezzanine,frankchin/mezzanine,dekomote/mezzanine-modeltranslation-backport,dekomote/mezzanine-modeltranslation-backport,readevalprint/mezzanine,dsanders11/mezzanine,gbosh/mezzanine,saintbird/mezzanine,damnfine/mezzanine,molokov/mezzanine,scarcry/snm-mezzanine,SoLoHiC/mezzanine,christianwgd/mezzanine,sjuxax/mezzanine,stephenmcd/mezzanine,ZeroXn/mezzanine,vladir/mezzanine,batpad/mezzanine,nikolas/mezzanine,Kniyl/mezzanine,wrwrwr/mezzanine,biomassives/mezzanine,promil23/mezzanine,dekomote/mezzanine-modeltranslation-backport,Skytorn86/mezzanine,jerivas/mezzanine,cccs-web/mezzanine,AlexHill/mezzanine,Cajoline/mezzanine,mush42/mezzanine,fusionbox/mezzanine,agepoly/mezzanine,orlenko/sfpirg,dsanders11/mezzanine,wbtuomela/mezzanine,guibernardino/mezzanine,wbtuomela/mezzanine,viaregio/mezzanine,orlenko/plei,emile2016/mezzanine,dustinrb/mezzanine,webounty/mezzanine,douglaskastle/mezzanine,orlenko/plei,promil23/mezzanine,gradel/mezzanine,frankier/mezzanine,emile2016/mezzanine,Skytorn86/mezzanine,mush42/mezzanine,cccs-web/mezzanine,SoLoHiC/mezzanine,damnfine/mezzanine,douglaskastle/mezzanine,nikolas/mezzanine,PegasusWang/mezzanine,industrydive/mezzanine,spookylukey/mezzanine,Cicero-Zhao/mezzanine,PegasusWang/mezzanine,adrian-the-git/mezzanine,viaregio/mezzanine,fusionbox/mezzanine,eino-makitalo/mezzanine,jerivas/mezzanine,ryneeverett/mezzanine,dovydas/mezzanine,gbosh/mezzanine,emile2016/mezzanine,frankchin/mezzanine,dovydas/mezzanine,saintbird/mezzanine,ZeroXn/mezzanine,webounty/mezzanine,ryneeverett/mezzanine,jerivas/mezzanine,agepoly/mezzanine,stephenmcd/mezzanine,readevalprint/mezzanine,wrwrwr/mezzanine,gradel/mezzanine,theclanks/mezzanine,joshcartme/mezzanine,dustinrb/mezzanine,frankchin/mezzanine,Kniyl/mezzanine,tuxinhang1989/mezzanine,christianwgd/mezzanine,molokov/mezzanine,ryneeverett/mezzanine,stbarnabas/mezzanine,tuxinhang1989/mezzanine,sjdines/mezzanine,ZeroXn/mezzanine,viaregio/mezzanine,jjz/mezzanine,jjz/mezzanine,guibernardino/mezzanine,Cajoline/mezzanine,industrydive/mezzanine,sjuxax/mezzanine,tuxinhang1989/mezzanine,eino-makitalo/mezzanine,orlenko/plei,jjz/mezzanine,sjdines/mezzanine,gbosh/mezzanine,mush42/mezzanine,dustinrb/mezzanine,scarcry/snm-mezzanine,christianwgd/mezzanine,adrian-the-git/mezzanine,stephenmcd/mezzanine,promil23/mezzanine,spookylukey/mezzanine,wbtuomela/mezzanine,frankier/mezzanine,AlexHill/mezzanine
DATABASES = { "default": { # Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.postgresql_psycopg2", # DB name or path to database file if using sqlite3. "NAME": "%(proj_name)s", # Not used with sqlite3. "USER": "%(proj_name)s", # Not used with sqlite3. "PASSWORD": "%(db_pass)s", # Set to empty string for localhost. Not used with sqlite3. "HOST": "127.0.0.1", # Set to empty string for default. Not used with sqlite3. "PORT": "", } } SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https") CACHE_MIDDLEWARE_SECONDS = 60 CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "127.0.0.1:11211", } } + SESSION_ENGINE = "django.contrib.sessions.backends.cache" +
Use cache backend for sessions in deployed settings.
## Code Before: DATABASES = { "default": { # Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.postgresql_psycopg2", # DB name or path to database file if using sqlite3. "NAME": "%(proj_name)s", # Not used with sqlite3. "USER": "%(proj_name)s", # Not used with sqlite3. "PASSWORD": "%(db_pass)s", # Set to empty string for localhost. Not used with sqlite3. "HOST": "127.0.0.1", # Set to empty string for default. Not used with sqlite3. "PORT": "", } } SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https") CACHE_MIDDLEWARE_SECONDS = 60 CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "127.0.0.1:11211", } } ## Instruction: Use cache backend for sessions in deployed settings. ## Code After: DATABASES = { "default": { # Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.postgresql_psycopg2", # DB name or path to database file if using sqlite3. "NAME": "%(proj_name)s", # Not used with sqlite3. "USER": "%(proj_name)s", # Not used with sqlite3. "PASSWORD": "%(db_pass)s", # Set to empty string for localhost. Not used with sqlite3. "HOST": "127.0.0.1", # Set to empty string for default. Not used with sqlite3. "PORT": "", } } SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https") CACHE_MIDDLEWARE_SECONDS = 60 CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "127.0.0.1:11211", } } SESSION_ENGINE = "django.contrib.sessions.backends.cache"
# ... existing code ... } SESSION_ENGINE = "django.contrib.sessions.backends.cache" # ... rest of the code ...
fcf52a1d427d2e89031480f747374860f64c45ff
constant_listener/pyspeechTest.py
constant_listener/pyspeechTest.py
from pyspeech import best_speech_result import unittest from pyaudio import PyAudio import Queue class PyspeechTest(unittest.TestCase): def setUp(self): self.p = PyAudio() def test_google_stt(self): good_morning = open('example_wavs/good_morning.wav', 'rb') output = best_speech_result(self.p, good_morning.read(), {}, "google") self.assertEqual(output, "good morning") hello_world = open('example_wavs/hello_world.wav', 'rb') output = best_speech_result(self.p, hello_world.read(), {}, "google") self.assertEqual(output, "hello world") if __name__ == "__main__": unittest.main()
from pyspeech import best_speech_result import unittest from pyaudio import PyAudio import Queue class PyspeechTest(unittest.TestCase): def setUp(self): self.p = PyAudio() def test_google_stt(self): good_morning = open('example_wavs/good_morning.wav', 'rb') output = best_speech_result(self.p, good_morning.read(), {}, "google") self.assertEqual(output, "good morning") hello_world = open('example_wavs/hello_world.wav', 'rb') output = best_speech_result(self.p, hello_world.read(), {}, "google") self.assertEqual(output, "hello world") # This will fail without a valid wit_token in profile.yml def test_wit_stt(self): import yaml profile = yaml.load(open("profile.yml").read()) good_morning = open('example_wavs/good_morning.wav', 'rb') output = best_speech_result(self.p, good_morning.read(), profile, "wit") self.assertEqual(output, "good morning") hello_world = open('example_wavs/hello_world.wav', 'rb') output = best_speech_result(self.p, hello_world.read(), profile, "wit") self.assertEqual(output, "hello world") if __name__ == "__main__": unittest.main()
Add tests for Wit STT
Add tests for Wit STT
Python
mit
MattWis/constant_listener
from pyspeech import best_speech_result import unittest from pyaudio import PyAudio import Queue class PyspeechTest(unittest.TestCase): def setUp(self): self.p = PyAudio() def test_google_stt(self): good_morning = open('example_wavs/good_morning.wav', 'rb') output = best_speech_result(self.p, good_morning.read(), {}, "google") self.assertEqual(output, "good morning") hello_world = open('example_wavs/hello_world.wav', 'rb') output = best_speech_result(self.p, hello_world.read(), {}, "google") self.assertEqual(output, "hello world") + # This will fail without a valid wit_token in profile.yml + def test_wit_stt(self): + import yaml + profile = yaml.load(open("profile.yml").read()) + good_morning = open('example_wavs/good_morning.wav', 'rb') + output = best_speech_result(self.p, good_morning.read(), profile, "wit") + self.assertEqual(output, "good morning") + + hello_world = open('example_wavs/hello_world.wav', 'rb') + output = best_speech_result(self.p, hello_world.read(), profile, "wit") + self.assertEqual(output, "hello world") + if __name__ == "__main__": unittest.main()
Add tests for Wit STT
## Code Before: from pyspeech import best_speech_result import unittest from pyaudio import PyAudio import Queue class PyspeechTest(unittest.TestCase): def setUp(self): self.p = PyAudio() def test_google_stt(self): good_morning = open('example_wavs/good_morning.wav', 'rb') output = best_speech_result(self.p, good_morning.read(), {}, "google") self.assertEqual(output, "good morning") hello_world = open('example_wavs/hello_world.wav', 'rb') output = best_speech_result(self.p, hello_world.read(), {}, "google") self.assertEqual(output, "hello world") if __name__ == "__main__": unittest.main() ## Instruction: Add tests for Wit STT ## Code After: from pyspeech import best_speech_result import unittest from pyaudio import PyAudio import Queue class PyspeechTest(unittest.TestCase): def setUp(self): self.p = PyAudio() def test_google_stt(self): good_morning = open('example_wavs/good_morning.wav', 'rb') output = best_speech_result(self.p, good_morning.read(), {}, "google") self.assertEqual(output, "good morning") hello_world = open('example_wavs/hello_world.wav', 'rb') output = best_speech_result(self.p, hello_world.read(), {}, "google") self.assertEqual(output, "hello world") # This will fail without a valid wit_token in profile.yml def test_wit_stt(self): import yaml profile = yaml.load(open("profile.yml").read()) good_morning = open('example_wavs/good_morning.wav', 'rb') output = best_speech_result(self.p, good_morning.read(), profile, "wit") self.assertEqual(output, "good morning") hello_world = open('example_wavs/hello_world.wav', 'rb') output = best_speech_result(self.p, hello_world.read(), profile, "wit") self.assertEqual(output, "hello world") if __name__ == "__main__": unittest.main()
// ... existing code ... # This will fail without a valid wit_token in profile.yml def test_wit_stt(self): import yaml profile = yaml.load(open("profile.yml").read()) good_morning = open('example_wavs/good_morning.wav', 'rb') output = best_speech_result(self.p, good_morning.read(), profile, "wit") self.assertEqual(output, "good morning") hello_world = open('example_wavs/hello_world.wav', 'rb') output = best_speech_result(self.p, hello_world.read(), profile, "wit") self.assertEqual(output, "hello world") if __name__ == "__main__": // ... rest of the code ...
89c906fc0ff6490de07543292c6e1e738652e2ef
pelicanconf.py
pelicanconf.py
from __future__ import unicode_literals AUTHOR = u'Leonardo Zhou' SITENAME = u'\u4e91\u7ffc\u56fe\u5357' SITEURL = '' TIMEZONE = 'Asia/Shanghai' DEFAULT_LANG = u'zh' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('Python.org', 'http://python.org/'), ('Jinja2', 'http://jinja.pocoo.org/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing RELATIVE_URLS = True STATIC_PATHS = ['images', 'extra/CNAME'] EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},}
from __future__ import unicode_literals AUTHOR = u'Leonardo Zhou' SITENAME = u'\u4e91\u7ffc\u56fe\u5357' SITEURL = '' TIMEZONE = 'Asia/Shanghai' DEFAULT_LANG = u'zh' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('Python.org', 'http://python.org/'), ('Jinja2', 'http://jinja.pocoo.org/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing RELATIVE_URLS = True STATIC_PATHS = ['images', 'extra/CNAME'] EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},} THEME = 'themes/BT3-Flat-4zha' ARTICLE_URL = '{slug}/' ARTICLE_SAVE_AS = '{slug}/index.html'
Change custom theme settings and url pattern
Change custom theme settings and url pattern
Python
cc0-1.0
glasslion/zha,glasslion/zha-beta,glasslion/zha,glasslion/zha-beta,glasslion/zha-beta,glasslion/zha
from __future__ import unicode_literals AUTHOR = u'Leonardo Zhou' SITENAME = u'\u4e91\u7ffc\u56fe\u5357' SITEURL = '' TIMEZONE = 'Asia/Shanghai' DEFAULT_LANG = u'zh' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('Python.org', 'http://python.org/'), ('Jinja2', 'http://jinja.pocoo.org/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing RELATIVE_URLS = True STATIC_PATHS = ['images', 'extra/CNAME'] EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},} + THEME = 'themes/BT3-Flat-4zha' + + ARTICLE_URL = '{slug}/' + ARTICLE_SAVE_AS = '{slug}/index.html'
Change custom theme settings and url pattern
## Code Before: from __future__ import unicode_literals AUTHOR = u'Leonardo Zhou' SITENAME = u'\u4e91\u7ffc\u56fe\u5357' SITEURL = '' TIMEZONE = 'Asia/Shanghai' DEFAULT_LANG = u'zh' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('Python.org', 'http://python.org/'), ('Jinja2', 'http://jinja.pocoo.org/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing RELATIVE_URLS = True STATIC_PATHS = ['images', 'extra/CNAME'] EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},} ## Instruction: Change custom theme settings and url pattern ## Code After: from __future__ import unicode_literals AUTHOR = u'Leonardo Zhou' SITENAME = u'\u4e91\u7ffc\u56fe\u5357' SITEURL = '' TIMEZONE = 'Asia/Shanghai' DEFAULT_LANG = u'zh' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('Python.org', 'http://python.org/'), ('Jinja2', 'http://jinja.pocoo.org/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing RELATIVE_URLS = True STATIC_PATHS = ['images', 'extra/CNAME'] EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},} THEME = 'themes/BT3-Flat-4zha' ARTICLE_URL = '{slug}/' ARTICLE_SAVE_AS = '{slug}/index.html'
// ... existing code ... EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},} THEME = 'themes/BT3-Flat-4zha' ARTICLE_URL = '{slug}/' ARTICLE_SAVE_AS = '{slug}/index.html' // ... rest of the code ...
d2ac548441523e2ed4d0ac824e5972ae48be3b19
packages/Python/lldbsuite/test/lang/swift/closure_shortcuts/TestClosureShortcuts.py
packages/Python/lldbsuite/test/lang/swift/closure_shortcuts/TestClosureShortcuts.py
import lldbsuite.test.lldbinline as lldbinline from lldbsuite.test.decorators import * lldbinline.MakeInlineTest(__file__, globals(), decorators=[swiftTest,skipUnlessDarwin])
import lldbsuite.test.lldbinline as lldbinline from lldbsuite.test.decorators import * lldbinline.MakeInlineTest(__file__, globals(), decorators=[swiftTest])
Fix typo and run everywhere.
Fix typo and run everywhere.
Python
apache-2.0
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb
import lldbsuite.test.lldbinline as lldbinline from lldbsuite.test.decorators import * lldbinline.MakeInlineTest(__file__, globals(), - decorators=[swiftTest,skipUnlessDarwin]) + decorators=[swiftTest])
Fix typo and run everywhere.
## Code Before: import lldbsuite.test.lldbinline as lldbinline from lldbsuite.test.decorators import * lldbinline.MakeInlineTest(__file__, globals(), decorators=[swiftTest,skipUnlessDarwin]) ## Instruction: Fix typo and run everywhere. ## Code After: import lldbsuite.test.lldbinline as lldbinline from lldbsuite.test.decorators import * lldbinline.MakeInlineTest(__file__, globals(), decorators=[swiftTest])
# ... existing code ... lldbinline.MakeInlineTest(__file__, globals(), decorators=[swiftTest]) # ... rest of the code ...
b652da4dda3ed5c0a37f2d32a07b9afaf6267e53
organization/network/migrations/0118_team_slug.py
organization/network/migrations/0118_team_slug.py
from __future__ import unicode_literals from django.db import migrations, models from organization.network.models import Team def generate_slugs(apps, schema_editor): teams = Team.objects.all() for team in teams: team.save() class Migration(migrations.Migration): dependencies = [ ('organization-network', '0117_merge_20181204_1801'), ] operations = [ migrations.AddField( model_name='team', name='slug', field=models.CharField(blank=True, help_text='Leave blank to have the URL auto-generated from the name.', max_length=2000, null=True, verbose_name='URL'), ), migrations.RunPython(generate_slugs), ]
from __future__ import unicode_literals from django.db import migrations, models from organization.network.models import Team # def generate_slugs(apps, schema_editor): # teams = Team.objects.all() # for team in teams: # team.save() class Migration(migrations.Migration): dependencies = [ ('organization-network', '0117_merge_20181204_1801'), ] operations = [ migrations.AddField( model_name='team', name='slug', field=models.CharField(blank=True, help_text='Leave blank to have the URL auto-generated from the name.', max_length=2000, null=True, verbose_name='URL'), ), # migrations.RunPython(generate_slugs), ]
Fix migration when no existing team.user field at fresh start
Fix migration when no existing team.user field at fresh start
Python
agpl-3.0
Ircam-Web/mezzanine-organization,Ircam-Web/mezzanine-organization
from __future__ import unicode_literals from django.db import migrations, models from organization.network.models import Team - def generate_slugs(apps, schema_editor): + # def generate_slugs(apps, schema_editor): - teams = Team.objects.all() + # teams = Team.objects.all() - for team in teams: + # for team in teams: - team.save() + # team.save() class Migration(migrations.Migration): dependencies = [ ('organization-network', '0117_merge_20181204_1801'), ] operations = [ migrations.AddField( model_name='team', name='slug', field=models.CharField(blank=True, help_text='Leave blank to have the URL auto-generated from the name.', max_length=2000, null=True, verbose_name='URL'), ), - migrations.RunPython(generate_slugs), + # migrations.RunPython(generate_slugs), ]
Fix migration when no existing team.user field at fresh start
## Code Before: from __future__ import unicode_literals from django.db import migrations, models from organization.network.models import Team def generate_slugs(apps, schema_editor): teams = Team.objects.all() for team in teams: team.save() class Migration(migrations.Migration): dependencies = [ ('organization-network', '0117_merge_20181204_1801'), ] operations = [ migrations.AddField( model_name='team', name='slug', field=models.CharField(blank=True, help_text='Leave blank to have the URL auto-generated from the name.', max_length=2000, null=True, verbose_name='URL'), ), migrations.RunPython(generate_slugs), ] ## Instruction: Fix migration when no existing team.user field at fresh start ## Code After: from __future__ import unicode_literals from django.db import migrations, models from organization.network.models import Team # def generate_slugs(apps, schema_editor): # teams = Team.objects.all() # for team in teams: # team.save() class Migration(migrations.Migration): dependencies = [ ('organization-network', '0117_merge_20181204_1801'), ] operations = [ migrations.AddField( model_name='team', name='slug', field=models.CharField(blank=True, help_text='Leave blank to have the URL auto-generated from the name.', max_length=2000, null=True, verbose_name='URL'), ), # migrations.RunPython(generate_slugs), ]
// ... existing code ... # def generate_slugs(apps, schema_editor): # teams = Team.objects.all() # for team in teams: # team.save() // ... modified code ... ), # migrations.RunPython(generate_slugs), ] // ... rest of the code ...
06ef0b92b1c8e6cc2916f4d68ec3b4ae513c9085
july/people/views.py
july/people/views.py
from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template.context import RequestContext #from google.appengine.ext import db from july.people.models import Commit from gae_django.auth.models import User from django.http import Http404 from forms import EditUserForm def user_profile(request, username): user = User.all().filter("username", username).get() if user == None: raise Http404("User not found") commits = Commit.all().ancestor(request.user.key()) expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()]) return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request)) @login_required def edit_profile(request, username, template_name='people/edit.html'): user = request.user #CONSIDER FILES with no POST? Can that happen? form = EditUserForm(request.POST or None, request.FILES or None) if form.is_valid(): for key in form.cleaned_data: setattr(user,key,form.cleaned_data.get(key)) user.put() if user == None: raise Http404("User not found") expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()]) return render_to_response(template_name, {'form':form, }, RequestContext(request))
from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template.context import RequestContext #from google.appengine.ext import db from july.people.models import Commit from gae_django.auth.models import User from django.http import Http404 def user_profile(request, username): user = User.all().filter("username", username).get() if user == None: raise Http404("User not found") commits = Commit.all().ancestor(request.user.key()) expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()]) return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request)) @login_required def edit_profile(request, username, template_name='people/edit.html'): from forms import EditUserForm user = request.user #CONSIDER FILES with no POST? Can that happen? form = EditUserForm(request.POST or None, request.FILES or None) if form.is_valid(): for key in form.cleaned_data: setattr(user,key,form.cleaned_data.get(key)) user.put() if user == None: raise Http404("User not found") expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()]) return render_to_response(template_name, {'form':form, }, RequestContext(request))
Fix typo and move missing import into edit view
Fix typo and move missing import into edit view
Python
mit
julython/julython.org,julython/julython.org,ChimeraCoder/GOctober,julython/julython.org,ChimeraCoder/GOctober,julython/julython.org,ChimeraCoder/GOctober
from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template.context import RequestContext #from google.appengine.ext import db from july.people.models import Commit from gae_django.auth.models import User from django.http import Http404 - from forms import EditUserForm def user_profile(request, username): user = User.all().filter("username", username).get() if user == None: raise Http404("User not found") commits = Commit.all().ancestor(request.user.key()) expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()]) return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request)) @login_required def edit_profile(request, username, template_name='people/edit.html'): + from forms import EditUserForm user = request.user #CONSIDER FILES with no POST? Can that happen? form = EditUserForm(request.POST or None, request.FILES or None) if form.is_valid(): for key in form.cleaned_data: - setattr(user,key,form.cleaned_data.get(key)) + setattr(user,key,form.cleaned_data.get(key)) user.put() if user == None: raise Http404("User not found") expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()]) return render_to_response(template_name, {'form':form, }, RequestContext(request))
Fix typo and move missing import into edit view
## Code Before: from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template.context import RequestContext #from google.appengine.ext import db from july.people.models import Commit from gae_django.auth.models import User from django.http import Http404 from forms import EditUserForm def user_profile(request, username): user = User.all().filter("username", username).get() if user == None: raise Http404("User not found") commits = Commit.all().ancestor(request.user.key()) expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()]) return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request)) @login_required def edit_profile(request, username, template_name='people/edit.html'): user = request.user #CONSIDER FILES with no POST? Can that happen? form = EditUserForm(request.POST or None, request.FILES or None) if form.is_valid(): for key in form.cleaned_data: setattr(user,key,form.cleaned_data.get(key)) user.put() if user == None: raise Http404("User not found") expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()]) return render_to_response(template_name, {'form':form, }, RequestContext(request)) ## Instruction: Fix typo and move missing import into edit view ## Code After: from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template.context import RequestContext #from google.appengine.ext import db from july.people.models import Commit from gae_django.auth.models import User from django.http import Http404 def user_profile(request, username): user = User.all().filter("username", username).get() if user == None: raise Http404("User not found") commits = Commit.all().ancestor(request.user.key()) expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()]) return render_to_response('people/profile.html', {"expandos": expandos, "commits":commits}, RequestContext(request)) @login_required def edit_profile(request, username, template_name='people/edit.html'): from forms import EditUserForm user = request.user #CONSIDER FILES with no POST? Can that happen? form = EditUserForm(request.POST or None, request.FILES or None) if form.is_valid(): for key in form.cleaned_data: setattr(user,key,form.cleaned_data.get(key)) user.put() if user == None: raise Http404("User not found") expandos = dict([(key, getattr(user, key, None)) for key in user.dynamic_properties()]) return render_to_response(template_name, {'form':form, }, RequestContext(request))
# ... existing code ... from django.http import Http404 # ... modified code ... def edit_profile(request, username, template_name='people/edit.html'): from forms import EditUserForm user = request.user ... for key in form.cleaned_data: setattr(user,key,form.cleaned_data.get(key)) user.put() # ... rest of the code ...
19c2f919c6deb11331e927ad3f794424905fc4f3
self-post-stream/stream.py
self-post-stream/stream.py
import praw import argparse parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.') parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')') parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', type=int) args = parser.parse_args() r = praw.Reddit(user_agent='stream only self posts from a sub by /u/km97') posts = [post for post in r.get_subreddit(args.sub).get_hot(limit=args.limit) if post.is_self] for post in posts: print("Title:", post.title) print("Score: {} | Comments: {}".format(post.score, post.num_comments)) print() print(post.selftext.replace('**', '').replace('*', '')) print() print("Link:", post.permalink) print('=' * 30)
import praw import argparse parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.') parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')') parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', type=int) args = parser.parse_args() args.limit = 1000 if args.limit > 1000 else args.limit r = praw.Reddit(user_agent='stream only self posts from a sub by /u/km97') posts = [post for post in r.get_subreddit(args.sub).get_hot(limit=args.limit) if post.is_self] for post in posts: print("Title:", post.title) print("Score: {} | Comments: {}".format(post.score, post.num_comments)) print() print(post.selftext.replace('**', '').replace('*', '')) print() print("Link:", post.permalink) print('=' * 30)
Add value check for -limit
Add value check for -limit
Python
mit
kshvmdn/reddit-bots
import praw import argparse parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.') parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')') parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', type=int) + args = parser.parse_args() + args.limit = 1000 if args.limit > 1000 else args.limit r = praw.Reddit(user_agent='stream only self posts from a sub by /u/km97') posts = [post for post in r.get_subreddit(args.sub).get_hot(limit=args.limit) if post.is_self] for post in posts: print("Title:", post.title) print("Score: {} | Comments: {}".format(post.score, post.num_comments)) print() print(post.selftext.replace('**', '').replace('*', '')) print() print("Link:", post.permalink) print('=' * 30)
Add value check for -limit
## Code Before: import praw import argparse parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.') parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')') parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', type=int) args = parser.parse_args() r = praw.Reddit(user_agent='stream only self posts from a sub by /u/km97') posts = [post for post in r.get_subreddit(args.sub).get_hot(limit=args.limit) if post.is_self] for post in posts: print("Title:", post.title) print("Score: {} | Comments: {}".format(post.score, post.num_comments)) print() print(post.selftext.replace('**', '').replace('*', '')) print() print("Link:", post.permalink) print('=' * 30) ## Instruction: Add value check for -limit ## Code After: import praw import argparse parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.') parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')') parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', type=int) args = parser.parse_args() args.limit = 1000 if args.limit > 1000 else args.limit r = praw.Reddit(user_agent='stream only self posts from a sub by /u/km97') posts = [post for post in r.get_subreddit(args.sub).get_hot(limit=args.limit) if post.is_self] for post in posts: print("Title:", post.title) print("Score: {} | Comments: {}".format(post.score, post.num_comments)) print() print(post.selftext.replace('**', '').replace('*', '')) print() print("Link:", post.permalink) print('=' * 30)
// ... existing code ... parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', type=int) args = parser.parse_args() args.limit = 1000 if args.limit > 1000 else args.limit // ... rest of the code ...
c84728b57d1c8923cdadec10f132953de4c1dd21
tests/integration/conftest.py
tests/integration/conftest.py
import pytest @pytest.fixture def coinbase(): return '0xdc544d1aa88ff8bbd2f2aec754b1f1e99e1812fd' @pytest.fixture def private_key(): return '0x58d23b55bc9cdce1f18c2500f40ff4ab7245df9a89505e9b1fa4851f623d241d' KEYFILE = '{"address":"dc544d1aa88ff8bbd2f2aec754b1f1e99e1812fd","crypto":{"cipher":"aes-128-ctr","ciphertext":"52e06bc9397ea9fa2f0dae8de2b3e8116e92a2ecca9ad5ff0061d1c449704e98","cipherparams":{"iv":"aa5d0a5370ef65395c1a6607af857124"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"9fdf0764eb3645ffc184e166537f6fe70516bf0e34dc7311dea21f100f0c9263"},"mac":"4e0b51f42b865c15c485f4faefdd1f01a38637e5247f8c75ffe6a8c0eba856f6"},"id":"5a6124e0-10f1-4c1c-ae3e-d903eacb740a","version":3}' # noqa: E501
import pytest from web3.utils.module_testing.math_contract import ( MATH_BYTECODE, MATH_ABI, ) from web3.utils.module_testing.emitter_contract import ( EMITTER_BYTECODE, EMITTER_ABI, ) @pytest.fixture(scope="session") def math_contract_factory(web3): contract_factory = web3.eth.contract(abi=MATH_ABI, bytecode=MATH_BYTECODE) return contract_factory @pytest.fixture(scope="session") def emitter_contract_factory(web3): contract_factory = web3.eth.contract(abi=EMITTER_ABI, bytecode=EMITTER_BYTECODE) return contract_factory
Add common factory fixtures to be shared across integration tests
Add common factory fixtures to be shared across integration tests
Python
mit
pipermerriam/web3.py
import pytest - - @pytest.fixture - def coinbase(): - return '0xdc544d1aa88ff8bbd2f2aec754b1f1e99e1812fd' + from web3.utils.module_testing.math_contract import ( + MATH_BYTECODE, + MATH_ABI, + ) + from web3.utils.module_testing.emitter_contract import ( + EMITTER_BYTECODE, + EMITTER_ABI, + ) - @pytest.fixture - def private_key(): - return '0x58d23b55bc9cdce1f18c2500f40ff4ab7245df9a89505e9b1fa4851f623d241d' + @pytest.fixture(scope="session") + def math_contract_factory(web3): + contract_factory = web3.eth.contract(abi=MATH_ABI, bytecode=MATH_BYTECODE) + return contract_factory - KEYFILE = '{"address":"dc544d1aa88ff8bbd2f2aec754b1f1e99e1812fd","crypto":{"cipher":"aes-128-ctr","ciphertext":"52e06bc9397ea9fa2f0dae8de2b3e8116e92a2ecca9ad5ff0061d1c449704e98","cipherparams":{"iv":"aa5d0a5370ef65395c1a6607af857124"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"9fdf0764eb3645ffc184e166537f6fe70516bf0e34dc7311dea21f100f0c9263"},"mac":"4e0b51f42b865c15c485f4faefdd1f01a38637e5247f8c75ffe6a8c0eba856f6"},"id":"5a6124e0-10f1-4c1c-ae3e-d903eacb740a","version":3}' # noqa: E501 + @pytest.fixture(scope="session") + def emitter_contract_factory(web3): + contract_factory = web3.eth.contract(abi=EMITTER_ABI, bytecode=EMITTER_BYTECODE) + return contract_factory
Add common factory fixtures to be shared across integration tests
## Code Before: import pytest @pytest.fixture def coinbase(): return '0xdc544d1aa88ff8bbd2f2aec754b1f1e99e1812fd' @pytest.fixture def private_key(): return '0x58d23b55bc9cdce1f18c2500f40ff4ab7245df9a89505e9b1fa4851f623d241d' KEYFILE = '{"address":"dc544d1aa88ff8bbd2f2aec754b1f1e99e1812fd","crypto":{"cipher":"aes-128-ctr","ciphertext":"52e06bc9397ea9fa2f0dae8de2b3e8116e92a2ecca9ad5ff0061d1c449704e98","cipherparams":{"iv":"aa5d0a5370ef65395c1a6607af857124"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"9fdf0764eb3645ffc184e166537f6fe70516bf0e34dc7311dea21f100f0c9263"},"mac":"4e0b51f42b865c15c485f4faefdd1f01a38637e5247f8c75ffe6a8c0eba856f6"},"id":"5a6124e0-10f1-4c1c-ae3e-d903eacb740a","version":3}' # noqa: E501 ## Instruction: Add common factory fixtures to be shared across integration tests ## Code After: import pytest from web3.utils.module_testing.math_contract import ( MATH_BYTECODE, MATH_ABI, ) from web3.utils.module_testing.emitter_contract import ( EMITTER_BYTECODE, EMITTER_ABI, ) @pytest.fixture(scope="session") def math_contract_factory(web3): contract_factory = web3.eth.contract(abi=MATH_ABI, bytecode=MATH_BYTECODE) return contract_factory @pytest.fixture(scope="session") def emitter_contract_factory(web3): contract_factory = web3.eth.contract(abi=EMITTER_ABI, bytecode=EMITTER_BYTECODE) return contract_factory
# ... existing code ... from web3.utils.module_testing.math_contract import ( MATH_BYTECODE, MATH_ABI, ) from web3.utils.module_testing.emitter_contract import ( EMITTER_BYTECODE, EMITTER_ABI, ) # ... modified code ... @pytest.fixture(scope="session") def math_contract_factory(web3): contract_factory = web3.eth.contract(abi=MATH_ABI, bytecode=MATH_BYTECODE) return contract_factory ... @pytest.fixture(scope="session") def emitter_contract_factory(web3): contract_factory = web3.eth.contract(abi=EMITTER_ABI, bytecode=EMITTER_BYTECODE) return contract_factory # ... rest of the code ...
029df34ce4a69adf5321531b229503d66169c9a6
tests/optimizers/test_conjugate_gradient.py
tests/optimizers/test_conjugate_gradient.py
from pymanopt.optimizers import ConjugateGradient from .._test import TestCase class TestConjugateGradient(TestCase): def test_beta_type(self): with self.assertRaises(ValueError): ConjugateGradient(beta_rule="SomeUnknownBetaRule")
import numpy as np import numpy.testing as np_testing from nose2.tools import params import pymanopt from pymanopt.optimizers import ConjugateGradient from .._test import TestCase class TestConjugateGradient(TestCase): def setUp(self): n = 32 matrix = np.random.normal(size=(n, n)) matrix = 0.5 * (matrix + matrix.T) eigenvalues, eigenvectors = np.linalg.eig(matrix) self.dominant_eigenvector = eigenvectors[:, np.argmax(eigenvalues)] self.manifold = manifold = pymanopt.manifolds.Sphere(n) @pymanopt.function.autograd(manifold) def cost(point): return -point.T @ matrix @ point self.problem = pymanopt.Problem(manifold, cost) @params( "FletcherReeves", "HagerZhang", "HestenesStiefel", "PolakRibiere", ) def test_beta_rules(self, beta_rule): optimizer = ConjugateGradient(beta_rule=beta_rule, verbosity=0) result = optimizer.run(self.problem) estimated_dominant_eigenvector = result.point if np.sign(self.dominant_eigenvector[0]) != np.sign( estimated_dominant_eigenvector[0] ): estimated_dominant_eigenvector = -estimated_dominant_eigenvector np_testing.assert_allclose( self.dominant_eigenvector, estimated_dominant_eigenvector, atol=1e-6, ) def test_beta_invalid_rule(self): with self.assertRaises(ValueError): ConjugateGradient(beta_rule="SomeUnknownBetaRule")
Add simple end-to-end test case for beta rules
Add simple end-to-end test case for beta rules Signed-off-by: Niklas Koep <[email protected]>
Python
bsd-3-clause
pymanopt/pymanopt,pymanopt/pymanopt
+ import numpy as np + import numpy.testing as np_testing + from nose2.tools import params + + import pymanopt from pymanopt.optimizers import ConjugateGradient from .._test import TestCase class TestConjugateGradient(TestCase): + def setUp(self): + n = 32 + matrix = np.random.normal(size=(n, n)) + matrix = 0.5 * (matrix + matrix.T) + + eigenvalues, eigenvectors = np.linalg.eig(matrix) + self.dominant_eigenvector = eigenvectors[:, np.argmax(eigenvalues)] + + self.manifold = manifold = pymanopt.manifolds.Sphere(n) + + @pymanopt.function.autograd(manifold) + def cost(point): + return -point.T @ matrix @ point + + self.problem = pymanopt.Problem(manifold, cost) + + @params( + "FletcherReeves", + "HagerZhang", + "HestenesStiefel", + "PolakRibiere", + ) + def test_beta_rules(self, beta_rule): + optimizer = ConjugateGradient(beta_rule=beta_rule, verbosity=0) + result = optimizer.run(self.problem) + estimated_dominant_eigenvector = result.point + if np.sign(self.dominant_eigenvector[0]) != np.sign( + estimated_dominant_eigenvector[0] + ): + estimated_dominant_eigenvector = -estimated_dominant_eigenvector + np_testing.assert_allclose( + self.dominant_eigenvector, + estimated_dominant_eigenvector, + atol=1e-6, + ) + - def test_beta_type(self): + def test_beta_invalid_rule(self): with self.assertRaises(ValueError): ConjugateGradient(beta_rule="SomeUnknownBetaRule")
Add simple end-to-end test case for beta rules
## Code Before: from pymanopt.optimizers import ConjugateGradient from .._test import TestCase class TestConjugateGradient(TestCase): def test_beta_type(self): with self.assertRaises(ValueError): ConjugateGradient(beta_rule="SomeUnknownBetaRule") ## Instruction: Add simple end-to-end test case for beta rules ## Code After: import numpy as np import numpy.testing as np_testing from nose2.tools import params import pymanopt from pymanopt.optimizers import ConjugateGradient from .._test import TestCase class TestConjugateGradient(TestCase): def setUp(self): n = 32 matrix = np.random.normal(size=(n, n)) matrix = 0.5 * (matrix + matrix.T) eigenvalues, eigenvectors = np.linalg.eig(matrix) self.dominant_eigenvector = eigenvectors[:, np.argmax(eigenvalues)] self.manifold = manifold = pymanopt.manifolds.Sphere(n) @pymanopt.function.autograd(manifold) def cost(point): return -point.T @ matrix @ point self.problem = pymanopt.Problem(manifold, cost) @params( "FletcherReeves", "HagerZhang", "HestenesStiefel", "PolakRibiere", ) def test_beta_rules(self, beta_rule): optimizer = ConjugateGradient(beta_rule=beta_rule, verbosity=0) result = optimizer.run(self.problem) estimated_dominant_eigenvector = result.point if np.sign(self.dominant_eigenvector[0]) != np.sign( estimated_dominant_eigenvector[0] ): estimated_dominant_eigenvector = -estimated_dominant_eigenvector np_testing.assert_allclose( self.dominant_eigenvector, estimated_dominant_eigenvector, atol=1e-6, ) def test_beta_invalid_rule(self): with self.assertRaises(ValueError): ConjugateGradient(beta_rule="SomeUnknownBetaRule")
# ... existing code ... import numpy as np import numpy.testing as np_testing from nose2.tools import params import pymanopt from pymanopt.optimizers import ConjugateGradient # ... modified code ... class TestConjugateGradient(TestCase): def setUp(self): n = 32 matrix = np.random.normal(size=(n, n)) matrix = 0.5 * (matrix + matrix.T) eigenvalues, eigenvectors = np.linalg.eig(matrix) self.dominant_eigenvector = eigenvectors[:, np.argmax(eigenvalues)] self.manifold = manifold = pymanopt.manifolds.Sphere(n) @pymanopt.function.autograd(manifold) def cost(point): return -point.T @ matrix @ point self.problem = pymanopt.Problem(manifold, cost) @params( "FletcherReeves", "HagerZhang", "HestenesStiefel", "PolakRibiere", ) def test_beta_rules(self, beta_rule): optimizer = ConjugateGradient(beta_rule=beta_rule, verbosity=0) result = optimizer.run(self.problem) estimated_dominant_eigenvector = result.point if np.sign(self.dominant_eigenvector[0]) != np.sign( estimated_dominant_eigenvector[0] ): estimated_dominant_eigenvector = -estimated_dominant_eigenvector np_testing.assert_allclose( self.dominant_eigenvector, estimated_dominant_eigenvector, atol=1e-6, ) def test_beta_invalid_rule(self): with self.assertRaises(ValueError): # ... rest of the code ...
52c8ee184cc0071187c1915c4f3e6f287f3faa81
config/__init__.py
config/__init__.py
import os BASE_PATH = os.path.abspath(os.path.dirname(__file__)) PRO_CONF_PATH = '/etc/skylines/production.py' DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py') TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py') def to_envvar(path=None): """ Loads the application configuration from a file. Returns the configuration or None if no configuration could be found. """ if path: path = os.path.abspath(path) if not os.path.exists(path): return elif os.path.exists(PRO_CONF_PATH): path = PRO_CONF_PATH elif os.path.exists(DEV_CONF_PATH): path = DEV_CONF_PATH else: return os.environ['SKYLINES_CONFIG'] = path return True def use_testing(): os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH
import os BASE_PATH = os.path.abspath(os.path.dirname(__file__)) PRO_CONF_PATH = '/etc/skylines/production.py' DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py') TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py') def to_envvar(path=None): """ Loads the application configuration from a file. Returns the configuration or None if no configuration could be found. """ if path: path = os.path.abspath(path) if not os.path.exists(path): return elif os.path.exists(PRO_CONF_PATH): path = PRO_CONF_PATH elif os.path.exists(DEV_CONF_PATH): path = DEV_CONF_PATH else: return os.environ['SKYLINES_CONFIG'] = path return True def use_testing(): os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH # Make sure use_testing() is not detected as a unit test by nose use_testing.__test__ = False
Make sure use_testing() is not detected as a unit test by nose
config: Make sure use_testing() is not detected as a unit test by nose
Python
agpl-3.0
shadowoneau/skylines,kerel-fs/skylines,Turbo87/skylines,kerel-fs/skylines,snip/skylines,Harry-R/skylines,snip/skylines,RBE-Avionik/skylines,Harry-R/skylines,Turbo87/skylines,RBE-Avionik/skylines,TobiasLohner/SkyLines,skylines-project/skylines,Turbo87/skylines,Harry-R/skylines,skylines-project/skylines,skylines-project/skylines,Harry-R/skylines,TobiasLohner/SkyLines,shadowoneau/skylines,kerel-fs/skylines,RBE-Avionik/skylines,TobiasLohner/SkyLines,shadowoneau/skylines,RBE-Avionik/skylines,shadowoneau/skylines,skylines-project/skylines,Turbo87/skylines,snip/skylines
import os BASE_PATH = os.path.abspath(os.path.dirname(__file__)) PRO_CONF_PATH = '/etc/skylines/production.py' DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py') TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py') def to_envvar(path=None): """ Loads the application configuration from a file. Returns the configuration or None if no configuration could be found. """ if path: path = os.path.abspath(path) if not os.path.exists(path): return elif os.path.exists(PRO_CONF_PATH): path = PRO_CONF_PATH elif os.path.exists(DEV_CONF_PATH): path = DEV_CONF_PATH else: return os.environ['SKYLINES_CONFIG'] = path return True def use_testing(): os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH + # Make sure use_testing() is not detected as a unit test by nose + use_testing.__test__ = False +
Make sure use_testing() is not detected as a unit test by nose
## Code Before: import os BASE_PATH = os.path.abspath(os.path.dirname(__file__)) PRO_CONF_PATH = '/etc/skylines/production.py' DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py') TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py') def to_envvar(path=None): """ Loads the application configuration from a file. Returns the configuration or None if no configuration could be found. """ if path: path = os.path.abspath(path) if not os.path.exists(path): return elif os.path.exists(PRO_CONF_PATH): path = PRO_CONF_PATH elif os.path.exists(DEV_CONF_PATH): path = DEV_CONF_PATH else: return os.environ['SKYLINES_CONFIG'] = path return True def use_testing(): os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH ## Instruction: Make sure use_testing() is not detected as a unit test by nose ## Code After: import os BASE_PATH = os.path.abspath(os.path.dirname(__file__)) PRO_CONF_PATH = '/etc/skylines/production.py' DEV_CONF_PATH = os.path.join(BASE_PATH, 'default.py') TESTING_CONF_PATH = os.path.join(BASE_PATH, 'testing.py') def to_envvar(path=None): """ Loads the application configuration from a file. Returns the configuration or None if no configuration could be found. """ if path: path = os.path.abspath(path) if not os.path.exists(path): return elif os.path.exists(PRO_CONF_PATH): path = PRO_CONF_PATH elif os.path.exists(DEV_CONF_PATH): path = DEV_CONF_PATH else: return os.environ['SKYLINES_CONFIG'] = path return True def use_testing(): os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH # Make sure use_testing() is not detected as a unit test by nose use_testing.__test__ = False
... os.environ['SKYLINES_CONFIG'] = TESTING_CONF_PATH # Make sure use_testing() is not detected as a unit test by nose use_testing.__test__ = False ...
7418079606a6e24cb0dccfa148b47c3f736e985f
zou/app/blueprints/persons/resources.py
zou/app/blueprints/persons/resources.py
from flask import abort from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from zou.app.services import persons_service from zou.app.utils import auth, permissions class NewPersonResource(Resource): @jwt_required def post(self): permissions.check_admin_permissions() data = self.get_arguments() person = persons_service.create_person( data["email"], auth.encrypt_password("default"), data["first_name"], data["last_name"], data["phone"] ) return person, 201 def get_arguments(self): parser = reqparse.RequestParser() parser.add_argument( "email", help="The email is required.", required=True ) parser.add_argument( "first_name", help="The first name is required.", required=True ) parser.add_argument( "last_name", help="The last name is required.", required=True ) parser.add_argument("phone", default="") args = parser.parse_args() return args
from flask import abort from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from zou.app.services import persons_service from zou.app.utils import auth, permissions class NewPersonResource(Resource): @jwt_required def post(self): permissions.check_admin_permissions() data = self.get_arguments() person = persons_service.create_person( data["email"], auth.encrypt_password("default"), data["first_name"], data["last_name"], data["phone"], role=data["role"] ) return person, 201 def get_arguments(self): parser = reqparse.RequestParser() parser.add_argument( "email", help="The email is required.", required=True ) parser.add_argument( "first_name", help="The first name is required.", required=True ) parser.add_argument( "last_name", help="The last name is required.", required=True ) parser.add_argument("phone", default="") parser.add_argument("role", default="user") args = parser.parse_args() return args
Allow to set role while creating a person
Allow to set role while creating a person
Python
agpl-3.0
cgwire/zou
from flask import abort from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from zou.app.services import persons_service from zou.app.utils import auth, permissions class NewPersonResource(Resource): @jwt_required def post(self): permissions.check_admin_permissions() data = self.get_arguments() person = persons_service.create_person( data["email"], auth.encrypt_password("default"), data["first_name"], data["last_name"], - data["phone"] + data["phone"], + role=data["role"] ) return person, 201 def get_arguments(self): parser = reqparse.RequestParser() parser.add_argument( "email", help="The email is required.", required=True ) parser.add_argument( "first_name", help="The first name is required.", required=True ) parser.add_argument( "last_name", help="The last name is required.", required=True ) parser.add_argument("phone", default="") + parser.add_argument("role", default="user") args = parser.parse_args() return args
Allow to set role while creating a person
## Code Before: from flask import abort from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from zou.app.services import persons_service from zou.app.utils import auth, permissions class NewPersonResource(Resource): @jwt_required def post(self): permissions.check_admin_permissions() data = self.get_arguments() person = persons_service.create_person( data["email"], auth.encrypt_password("default"), data["first_name"], data["last_name"], data["phone"] ) return person, 201 def get_arguments(self): parser = reqparse.RequestParser() parser.add_argument( "email", help="The email is required.", required=True ) parser.add_argument( "first_name", help="The first name is required.", required=True ) parser.add_argument( "last_name", help="The last name is required.", required=True ) parser.add_argument("phone", default="") args = parser.parse_args() return args ## Instruction: Allow to set role while creating a person ## Code After: from flask import abort from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from zou.app.services import persons_service from zou.app.utils import auth, permissions class NewPersonResource(Resource): @jwt_required def post(self): permissions.check_admin_permissions() data = self.get_arguments() person = persons_service.create_person( data["email"], auth.encrypt_password("default"), data["first_name"], data["last_name"], data["phone"], role=data["role"] ) return person, 201 def get_arguments(self): parser = reqparse.RequestParser() parser.add_argument( "email", help="The email is required.", required=True ) parser.add_argument( "first_name", help="The first name is required.", required=True ) parser.add_argument( "last_name", help="The last name is required.", required=True ) parser.add_argument("phone", default="") parser.add_argument("role", default="user") args = parser.parse_args() return args
# ... existing code ... data["last_name"], data["phone"], role=data["role"] ) # ... modified code ... parser.add_argument("phone", default="") parser.add_argument("role", default="user") args = parser.parse_args() # ... rest of the code ...
58b5a991d91101b9149014def8e93fe70852ae32
measurement/views.py
measurement/views.py
from .models import Measurement from rest_framework import viewsets from graph.serializers import MeasurementGraphSeriesSerializer from rest_framework.exceptions import ParseError from api.permissions import IsPatient from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from django.core.exceptions import PermissionDenied from rest_framework.response import Response class CurrentPatientMeasurements(APIView): permission_classes = (IsAuthenticated, IsPatient,) def get(self, request, format=None): type = self.request.QUERY_PARAMS.get('type', None) if type is None: raise ParseError(detail="Query string 'type' is not specified") if not type in ['A', 'O', 'P', 'T']: raise ParseError(detail="type must be one of the following values: 'A', 'O', 'P', 'T'") patient = request.user.patient if 'A' == type and not patient.activity_access: raise PermissionDenied() if 'O' == type and not patient.o2_access: raise PermissionDenied() if 'P' == type and not patient.pulse_access: raise PermissionDenied() if 'T' == type and not patient.temperature_access: raise PermissionDenied() queryset = Measurement.objects.filter(patient__id=patient.id, type=type) serializer = MeasurementGraphSeriesSerializer(queryset, many=True) return Response(serializer.data)
from .models import Measurement from rest_framework import viewsets from graph.serializers import MeasurementGraphSeriesSerializer from rest_framework.exceptions import ParseError from api.permissions import IsPatient from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from django.core.exceptions import PermissionDenied from rest_framework.response import Response from patient.serializers import PatientGraphSeriesSerializer class CurrentPatientMeasurements(APIView): permission_classes = (IsAuthenticated, IsPatient,) def get(self, request, format=None): type = self.request.QUERY_PARAMS.get('type', None) if type is None: raise ParseError(detail="Query string 'type' is not specified") if not type in ['A', 'O', 'P', 'T']: raise ParseError(detail="type must be one of the following values: 'A', 'O', 'P', 'T'") patient = request.user.patient if 'A' == type and not patient.activity_access: raise PermissionDenied() if 'O' == type and not patient.o2_access: raise PermissionDenied() if 'P' == type and not patient.pulse_access: raise PermissionDenied() if 'T' == type and not patient.temperature_access: raise PermissionDenied() serializer = PatientGraphSeriesSerializer(instance=patient, context={'type': type}) return Response(serializer.data)
Update measurements endpoint of current patient
Update measurements endpoint of current patient
Python
mit
sigurdsa/angelika-api
from .models import Measurement from rest_framework import viewsets from graph.serializers import MeasurementGraphSeriesSerializer from rest_framework.exceptions import ParseError from api.permissions import IsPatient from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from django.core.exceptions import PermissionDenied from rest_framework.response import Response + from patient.serializers import PatientGraphSeriesSerializer class CurrentPatientMeasurements(APIView): permission_classes = (IsAuthenticated, IsPatient,) def get(self, request, format=None): type = self.request.QUERY_PARAMS.get('type', None) if type is None: raise ParseError(detail="Query string 'type' is not specified") if not type in ['A', 'O', 'P', 'T']: raise ParseError(detail="type must be one of the following values: 'A', 'O', 'P', 'T'") patient = request.user.patient if 'A' == type and not patient.activity_access: raise PermissionDenied() if 'O' == type and not patient.o2_access: raise PermissionDenied() if 'P' == type and not patient.pulse_access: raise PermissionDenied() if 'T' == type and not patient.temperature_access: raise PermissionDenied() + serializer = PatientGraphSeriesSerializer(instance=patient, context={'type': type}) - queryset = Measurement.objects.filter(patient__id=patient.id, type=type) - serializer = MeasurementGraphSeriesSerializer(queryset, many=True) return Response(serializer.data)
Update measurements endpoint of current patient
## Code Before: from .models import Measurement from rest_framework import viewsets from graph.serializers import MeasurementGraphSeriesSerializer from rest_framework.exceptions import ParseError from api.permissions import IsPatient from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from django.core.exceptions import PermissionDenied from rest_framework.response import Response class CurrentPatientMeasurements(APIView): permission_classes = (IsAuthenticated, IsPatient,) def get(self, request, format=None): type = self.request.QUERY_PARAMS.get('type', None) if type is None: raise ParseError(detail="Query string 'type' is not specified") if not type in ['A', 'O', 'P', 'T']: raise ParseError(detail="type must be one of the following values: 'A', 'O', 'P', 'T'") patient = request.user.patient if 'A' == type and not patient.activity_access: raise PermissionDenied() if 'O' == type and not patient.o2_access: raise PermissionDenied() if 'P' == type and not patient.pulse_access: raise PermissionDenied() if 'T' == type and not patient.temperature_access: raise PermissionDenied() queryset = Measurement.objects.filter(patient__id=patient.id, type=type) serializer = MeasurementGraphSeriesSerializer(queryset, many=True) return Response(serializer.data) ## Instruction: Update measurements endpoint of current patient ## Code After: from .models import Measurement from rest_framework import viewsets from graph.serializers import MeasurementGraphSeriesSerializer from rest_framework.exceptions import ParseError from api.permissions import IsPatient from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from django.core.exceptions import PermissionDenied from rest_framework.response import Response from patient.serializers import PatientGraphSeriesSerializer class CurrentPatientMeasurements(APIView): permission_classes = (IsAuthenticated, IsPatient,) def get(self, request, format=None): type = self.request.QUERY_PARAMS.get('type', None) if type is None: raise ParseError(detail="Query string 'type' is not specified") if not type in ['A', 'O', 'P', 'T']: raise ParseError(detail="type must be one of the following values: 'A', 'O', 'P', 'T'") patient = request.user.patient if 'A' == type and not patient.activity_access: raise PermissionDenied() if 'O' == type and not patient.o2_access: raise PermissionDenied() if 'P' == type and not patient.pulse_access: raise PermissionDenied() if 'T' == type and not patient.temperature_access: raise PermissionDenied() serializer = PatientGraphSeriesSerializer(instance=patient, context={'type': type}) return Response(serializer.data)
// ... existing code ... from rest_framework.response import Response from patient.serializers import PatientGraphSeriesSerializer // ... modified code ... serializer = PatientGraphSeriesSerializer(instance=patient, context={'type': type}) return Response(serializer.data) // ... rest of the code ...
c96e82caaa3fd560263c54db71772b44e9cd78d7
examples/upgrade_local_charm_k8s.py
examples/upgrade_local_charm_k8s.py
from juju import jasyncio from juju.model import Model async def main(): model = Model() print('Connecting to model') # Connect to current model with current user, per Juju CLI await model.connect() try: print('Deploying bundle') applications = await model.deploy( './examples/k8s-local-bundle/bundle.yaml', ) print('Waiting for active') await model.wait_for_idle(status='active') print("Successfully deployed!") await applications[0].upgrade_charm(path='./examples/charms/onos.charm') await model.wait_for_idle(status='active') print('Removing bundle') for application in applications: await application.remove() finally: print('Disconnecting from model') await model.disconnect() print("Success") if __name__ == '__main__': jasyncio.run(main())
from juju import jasyncio from juju.model import Model async def main(): model = Model() print('Connecting to model') # Connect to current model with current user, per Juju CLI await model.connect() try: print('Deploying bundle') applications = await model.deploy( './examples/k8s-local-bundle/bundle.yaml', ) print('Waiting for active') await model.wait_for_idle(status='active') print("Successfully deployed!") local_path = './examples/charms/onos.charm' print('Upgrading charm with %s' % local_path) await applications[0].upgrade_charm(path=local_path) await model.wait_for_idle(status='active') print('Removing bundle') for application in applications: await application.remove() finally: print('Disconnecting from model') await model.disconnect() print("Success") if __name__ == '__main__': jasyncio.run(main())
Make the example more informative
Make the example more informative
Python
apache-2.0
juju/python-libjuju,juju/python-libjuju
from juju import jasyncio from juju.model import Model async def main(): model = Model() print('Connecting to model') # Connect to current model with current user, per Juju CLI await model.connect() try: print('Deploying bundle') applications = await model.deploy( './examples/k8s-local-bundle/bundle.yaml', ) print('Waiting for active') await model.wait_for_idle(status='active') print("Successfully deployed!") + local_path = './examples/charms/onos.charm' + print('Upgrading charm with %s' % local_path) - await applications[0].upgrade_charm(path='./examples/charms/onos.charm') + await applications[0].upgrade_charm(path=local_path) await model.wait_for_idle(status='active') print('Removing bundle') for application in applications: await application.remove() finally: print('Disconnecting from model') await model.disconnect() print("Success") if __name__ == '__main__': jasyncio.run(main())
Make the example more informative
## Code Before: from juju import jasyncio from juju.model import Model async def main(): model = Model() print('Connecting to model') # Connect to current model with current user, per Juju CLI await model.connect() try: print('Deploying bundle') applications = await model.deploy( './examples/k8s-local-bundle/bundle.yaml', ) print('Waiting for active') await model.wait_for_idle(status='active') print("Successfully deployed!") await applications[0].upgrade_charm(path='./examples/charms/onos.charm') await model.wait_for_idle(status='active') print('Removing bundle') for application in applications: await application.remove() finally: print('Disconnecting from model') await model.disconnect() print("Success") if __name__ == '__main__': jasyncio.run(main()) ## Instruction: Make the example more informative ## Code After: from juju import jasyncio from juju.model import Model async def main(): model = Model() print('Connecting to model') # Connect to current model with current user, per Juju CLI await model.connect() try: print('Deploying bundle') applications = await model.deploy( './examples/k8s-local-bundle/bundle.yaml', ) print('Waiting for active') await model.wait_for_idle(status='active') print("Successfully deployed!") local_path = './examples/charms/onos.charm' print('Upgrading charm with %s' % local_path) await applications[0].upgrade_charm(path=local_path) await model.wait_for_idle(status='active') print('Removing bundle') for application in applications: await application.remove() finally: print('Disconnecting from model') await model.disconnect() print("Success") if __name__ == '__main__': jasyncio.run(main())
# ... existing code ... local_path = './examples/charms/onos.charm' print('Upgrading charm with %s' % local_path) await applications[0].upgrade_charm(path=local_path) # ... rest of the code ...
d7a347b0cee650d7b5cb6a0eca613da543e0e305
tests/conftest.py
tests/conftest.py
import pytest from flask import Flask, jsonify @pytest.fixture def app(): app = Flask(__name__) app.config['SECRET_KEY'] = '42' @app.route('/') def index(): return app.response_class('OK') @app.route('/ping') def ping(): return jsonify(ping='pong') return app
import pytest from textwrap import dedent from flask import Flask, jsonify pytest_plugins = 'pytester' @pytest.fixture def app(): app = Flask(__name__) app.config['SECRET_KEY'] = '42' @app.route('/') def index(): return app.response_class('OK') @app.route('/ping') def ping(): return jsonify(ping='pong') return app @pytest.fixture def appdir(testdir): app_root = testdir.tmpdir test_root = app_root.mkdir('tests') def create_test_module(code, filename='test_app.py'): f = test_root.join(filename) f.write(dedent(code), ensure=True) return f testdir.create_test_module = create_test_module testdir.create_test_module(''' import pytest from flask import Flask @pytest.fixture def app(): app = Flask(__name__) return app ''', filename='conftest.py') return testdir
Add `appdir` fixture to simplify testing
Add `appdir` fixture to simplify testing
Python
mit
amateja/pytest-flask
import pytest + from textwrap import dedent from flask import Flask, jsonify + + + pytest_plugins = 'pytester' @pytest.fixture def app(): app = Flask(__name__) app.config['SECRET_KEY'] = '42' @app.route('/') def index(): return app.response_class('OK') @app.route('/ping') def ping(): return jsonify(ping='pong') return app + + @pytest.fixture + def appdir(testdir): + app_root = testdir.tmpdir + test_root = app_root.mkdir('tests') + + def create_test_module(code, filename='test_app.py'): + f = test_root.join(filename) + f.write(dedent(code), ensure=True) + return f + + testdir.create_test_module = create_test_module + + testdir.create_test_module(''' + import pytest + + from flask import Flask + + @pytest.fixture + def app(): + app = Flask(__name__) + return app + ''', filename='conftest.py') + return testdir +
Add `appdir` fixture to simplify testing
## Code Before: import pytest from flask import Flask, jsonify @pytest.fixture def app(): app = Flask(__name__) app.config['SECRET_KEY'] = '42' @app.route('/') def index(): return app.response_class('OK') @app.route('/ping') def ping(): return jsonify(ping='pong') return app ## Instruction: Add `appdir` fixture to simplify testing ## Code After: import pytest from textwrap import dedent from flask import Flask, jsonify pytest_plugins = 'pytester' @pytest.fixture def app(): app = Flask(__name__) app.config['SECRET_KEY'] = '42' @app.route('/') def index(): return app.response_class('OK') @app.route('/ping') def ping(): return jsonify(ping='pong') return app @pytest.fixture def appdir(testdir): app_root = testdir.tmpdir test_root = app_root.mkdir('tests') def create_test_module(code, filename='test_app.py'): f = test_root.join(filename) f.write(dedent(code), ensure=True) return f testdir.create_test_module = create_test_module testdir.create_test_module(''' import pytest from flask import Flask @pytest.fixture def app(): app = Flask(__name__) return app ''', filename='conftest.py') return testdir
... from textwrap import dedent from flask import Flask, jsonify pytest_plugins = 'pytester' ... return app @pytest.fixture def appdir(testdir): app_root = testdir.tmpdir test_root = app_root.mkdir('tests') def create_test_module(code, filename='test_app.py'): f = test_root.join(filename) f.write(dedent(code), ensure=True) return f testdir.create_test_module = create_test_module testdir.create_test_module(''' import pytest from flask import Flask @pytest.fixture def app(): app = Flask(__name__) return app ''', filename='conftest.py') return testdir ...
b66171d0b3d8cdf361f4341976d7eb0830fb38ce
dribdat/boxout/dribdat.py
dribdat/boxout/dribdat.py
"""Boxout module for Dribdat projects.""" import pystache TEMPLATE_PROJECT = r""" <div class="onebox honeycomb"> <a href="{{link}}" class="hexagon {{#is_challenge}}challenge{{/is_challenge}} {{^is_challenge}}project stage-{{progress}}{{/is_challenge}}"> <div class="hexagontent"> {{#image_url}} <div class="hexaicon" style="background-image:url('{{image_url}}')"></div> {{/image_url}} </div> </a> <a href="{{link}}" class="title">{{name}}</a> <div class="event-detail"> <span>{{event_name}}</span> <i class="phase">{{phase}}</i> </div> <p>{{summary}}</p> </div> """ def box_project(url): """Create a OneBox for local projects.""" project_id = url.split('/')[-1] if not project_id: return None from ..user.models import Project project = Project.query.filter_by(id=int(project_id)).first() if not project: return None pd = project.data # project.url returns a relative path pd['link'] = url return pystache.render(TEMPLATE_PROJECT, pd)
"""Boxout module for Dribdat projects.""" import pystache TEMPLATE_PROJECT = r""" <div class="onebox honeycomb"> <a href="{{link}}" class="hexagon {{#is_challenge}}challenge{{/is_challenge}} {{^is_challenge}}project stage-{{progress}}{{/is_challenge}}"> <div class="hexagontent"> {{#image_url}} <div class="hexaicon" style="background-image:url('{{image_url}}')"></div> {{/image_url}} </div> </a> <a href="{{link}}" class="title">{{name}}</a> <div class="event-detail"> <span>{{event_name}}</span> <i class="phase">{{phase}}</i> </div> <p>{{summary}}</p> </div> """ def box_project(url): """Create a OneBox for local projects.""" project_id = url.split('/')[-1].split('#')[0] if not project_id or not project_id.isnumeric(): return None from ..user.models import Project project = Project.query.filter_by(id=int(project_id)).first() if not project: return None pd = project.data # project.url returns a relative path pd['link'] = url return pystache.render(TEMPLATE_PROJECT, pd)
Fix project links broken by anchor
Fix project links broken by anchor
Python
mit
loleg/dribdat,loleg/dribdat,loleg/dribdat,loleg/dribdat
"""Boxout module for Dribdat projects.""" import pystache TEMPLATE_PROJECT = r""" <div class="onebox honeycomb"> <a href="{{link}}" class="hexagon {{#is_challenge}}challenge{{/is_challenge}} {{^is_challenge}}project stage-{{progress}}{{/is_challenge}}"> <div class="hexagontent"> {{#image_url}} <div class="hexaicon" style="background-image:url('{{image_url}}')"></div> {{/image_url}} </div> </a> <a href="{{link}}" class="title">{{name}}</a> <div class="event-detail"> <span>{{event_name}}</span> <i class="phase">{{phase}}</i> </div> <p>{{summary}}</p> </div> """ def box_project(url): """Create a OneBox for local projects.""" - project_id = url.split('/')[-1] + project_id = url.split('/')[-1].split('#')[0] - if not project_id: + if not project_id or not project_id.isnumeric(): return None from ..user.models import Project project = Project.query.filter_by(id=int(project_id)).first() if not project: return None pd = project.data # project.url returns a relative path pd['link'] = url return pystache.render(TEMPLATE_PROJECT, pd)
Fix project links broken by anchor
## Code Before: """Boxout module for Dribdat projects.""" import pystache TEMPLATE_PROJECT = r""" <div class="onebox honeycomb"> <a href="{{link}}" class="hexagon {{#is_challenge}}challenge{{/is_challenge}} {{^is_challenge}}project stage-{{progress}}{{/is_challenge}}"> <div class="hexagontent"> {{#image_url}} <div class="hexaicon" style="background-image:url('{{image_url}}')"></div> {{/image_url}} </div> </a> <a href="{{link}}" class="title">{{name}}</a> <div class="event-detail"> <span>{{event_name}}</span> <i class="phase">{{phase}}</i> </div> <p>{{summary}}</p> </div> """ def box_project(url): """Create a OneBox for local projects.""" project_id = url.split('/')[-1] if not project_id: return None from ..user.models import Project project = Project.query.filter_by(id=int(project_id)).first() if not project: return None pd = project.data # project.url returns a relative path pd['link'] = url return pystache.render(TEMPLATE_PROJECT, pd) ## Instruction: Fix project links broken by anchor ## Code After: """Boxout module for Dribdat projects.""" import pystache TEMPLATE_PROJECT = r""" <div class="onebox honeycomb"> <a href="{{link}}" class="hexagon {{#is_challenge}}challenge{{/is_challenge}} {{^is_challenge}}project stage-{{progress}}{{/is_challenge}}"> <div class="hexagontent"> {{#image_url}} <div class="hexaicon" style="background-image:url('{{image_url}}')"></div> {{/image_url}} </div> </a> <a href="{{link}}" class="title">{{name}}</a> <div class="event-detail"> <span>{{event_name}}</span> <i class="phase">{{phase}}</i> </div> <p>{{summary}}</p> </div> """ def box_project(url): """Create a OneBox for local projects.""" project_id = url.split('/')[-1].split('#')[0] if not project_id or not project_id.isnumeric(): return None from ..user.models import Project project = Project.query.filter_by(id=int(project_id)).first() if not project: return None pd = project.data # project.url returns a relative path pd['link'] = url return pystache.render(TEMPLATE_PROJECT, pd)
// ... existing code ... """Create a OneBox for local projects.""" project_id = url.split('/')[-1].split('#')[0] if not project_id or not project_id.isnumeric(): return None // ... rest of the code ...
dd9dfa86fe0f7cb8d95b580ff9ae62753fb19026
gefion/checks/base.py
gefion/checks/base.py
"""Base classes.""" import time class Result(object): """Provides results of a Check. Attributes: availability (bool): Availability, usually reflects outcome of a check. runtime (float): Time consumed running the check, in seconds. message (string): Additional explainations for the result. timestamp (int): UTC timestamp of the check. """ def __init__(self, availability, runtime, message, timestamp=time.time()): """Initialise Result. Args: See class attributes. """ self.availability = availability self.runtime = runtime self.message = message self.timestamp = timestamp @property def api_serialised(self): """Return serialisable data for API monitor assignments.""" return {'availability': self.availability, 'runtime': self.runtime, 'message': self.message, 'timestamp': self.timestamp} class Check(object): """Performs checks for availability of resources. This should be inherited by checking implementations. """ def __init__(self, **kwargs): """Initialise Check.""" pass def check(self): """Check if specified resource is availability. Called without arguments. Returns: gefion.checkers.Result """ raise NotImplementedError
"""Base classes.""" import time class Result(object): """Provides results of a Check. Attributes: availability (bool): Availability, usually reflects outcome of a check. runtime (float): Time consumed running the check, in seconds. message (string): Additional explainations for the result. timestamp (int): UTC timestamp of the check. """ def __init__(self, availability, runtime, message, timestamp=time.time()): """Initialise Result. Args: See class attributes. """ self.availability = availability self.runtime = runtime self.message = message self.timestamp = timestamp @property def api_serialised(self): """Return serialisable data for API result submissions.""" return {'availability': self.availability, 'runtime': self.runtime, 'message': self.message, 'timestamp': self.timestamp} class Check(object): """Performs checks for availability of resources. This should be inherited by checking implementations. """ def __init__(self, **kwargs): """Initialise Check.""" pass def check(self): """Check if specified resource is availabile. Called without arguments. Returns: gefion.checkers.Result """ raise NotImplementedError
Fix typos in Result and Check docstrings
Fix typos in Result and Check docstrings
Python
bsd-3-clause
dargasea/gefion
"""Base classes.""" import time class Result(object): """Provides results of a Check. Attributes: availability (bool): Availability, usually reflects outcome of a check. runtime (float): Time consumed running the check, in seconds. message (string): Additional explainations for the result. timestamp (int): UTC timestamp of the check. """ def __init__(self, availability, runtime, message, timestamp=time.time()): """Initialise Result. Args: See class attributes. """ self.availability = availability self.runtime = runtime self.message = message self.timestamp = timestamp @property def api_serialised(self): - """Return serialisable data for API monitor assignments.""" + """Return serialisable data for API result submissions.""" return {'availability': self.availability, 'runtime': self.runtime, 'message': self.message, 'timestamp': self.timestamp} class Check(object): """Performs checks for availability of resources. This should be inherited by checking implementations. """ def __init__(self, **kwargs): """Initialise Check.""" pass def check(self): - """Check if specified resource is availability. + """Check if specified resource is availabile. Called without arguments. Returns: gefion.checkers.Result """ raise NotImplementedError
Fix typos in Result and Check docstrings
## Code Before: """Base classes.""" import time class Result(object): """Provides results of a Check. Attributes: availability (bool): Availability, usually reflects outcome of a check. runtime (float): Time consumed running the check, in seconds. message (string): Additional explainations for the result. timestamp (int): UTC timestamp of the check. """ def __init__(self, availability, runtime, message, timestamp=time.time()): """Initialise Result. Args: See class attributes. """ self.availability = availability self.runtime = runtime self.message = message self.timestamp = timestamp @property def api_serialised(self): """Return serialisable data for API monitor assignments.""" return {'availability': self.availability, 'runtime': self.runtime, 'message': self.message, 'timestamp': self.timestamp} class Check(object): """Performs checks for availability of resources. This should be inherited by checking implementations. """ def __init__(self, **kwargs): """Initialise Check.""" pass def check(self): """Check if specified resource is availability. Called without arguments. Returns: gefion.checkers.Result """ raise NotImplementedError ## Instruction: Fix typos in Result and Check docstrings ## Code After: """Base classes.""" import time class Result(object): """Provides results of a Check. Attributes: availability (bool): Availability, usually reflects outcome of a check. runtime (float): Time consumed running the check, in seconds. message (string): Additional explainations for the result. timestamp (int): UTC timestamp of the check. """ def __init__(self, availability, runtime, message, timestamp=time.time()): """Initialise Result. Args: See class attributes. """ self.availability = availability self.runtime = runtime self.message = message self.timestamp = timestamp @property def api_serialised(self): """Return serialisable data for API result submissions.""" return {'availability': self.availability, 'runtime': self.runtime, 'message': self.message, 'timestamp': self.timestamp} class Check(object): """Performs checks for availability of resources. This should be inherited by checking implementations. """ def __init__(self, **kwargs): """Initialise Check.""" pass def check(self): """Check if specified resource is availabile. Called without arguments. Returns: gefion.checkers.Result """ raise NotImplementedError
... def api_serialised(self): """Return serialisable data for API result submissions.""" return {'availability': self.availability, ... def check(self): """Check if specified resource is availabile. ...
a4a5ca393ffc553202b266bdea790768a119f8f8
django_pin_auth/auth_backend.py
django_pin_auth/auth_backend.py
from django.contrib.auth import get_user_model from .models import SingleUseToken class PinBackend(object): """Authentication backend based on pin value.""" def authenticate(self, request, email=None, pin=None): """Authenticate user based on valid pin.""" user_model = get_user_model() kwargs = { user_model.USERNAME_FIELD: email } try: user = user_model.objects.get(**kwargs) except user_model.DoesNotExist: return None # Now that we have the user, check that we have a token try: token = self._get_token(user, pin) except SingleUseToken.DoesNotExist: return None if token.is_valid(): # Read token (delete it) token.read() return user def _get_token(self, user, pin): """Get the token for corresponding user and pin.""" return SingleUseToken.objects.get(user=user, token=pin)
from django.contrib.auth import get_user_model from .models import SingleUseToken class PinBackend(object): """Authentication backend based on pin value.""" def authenticate(self, request, email=None, pin=None): """Authenticate user based on valid pin.""" try: token = self._get_token(email, pin) except SingleUseToken.DoesNotExist: return None if token.is_valid(): # Read token (delete it) token.read() return token.user def _get_token(self, email, pin): """Get the token for corresponding user and pin.""" user_model = get_user_model() kwargs = { 'user__%s' % user_model.USERNAME_FIELD: email, 'token': pin } return SingleUseToken.objects.get(**kwargs) def get_user(self, user_id): """Get user from id.""" user_model = get_user_model() try: return user_model.objects.get(pk=user_id) except user_model.DoesNotExist: return None
Refactor to query straight for user
refactor(verification): Refactor to query straight for user - Implement get_user - Change to make a single query to find the token, using a join to the user's email
Python
mit
redapesolutions/django-pin-auth,redapesolutions/django-pin-auth,redapesolutions/django-pin-auth
from django.contrib.auth import get_user_model from .models import SingleUseToken class PinBackend(object): """Authentication backend based on pin value.""" def authenticate(self, request, email=None, pin=None): """Authenticate user based on valid pin.""" - user_model = get_user_model() - kwargs = { - user_model.USERNAME_FIELD: email - } try: - user = user_model.objects.get(**kwargs) - except user_model.DoesNotExist: - return None - - # Now that we have the user, check that we have a token - try: - token = self._get_token(user, pin) + token = self._get_token(email, pin) except SingleUseToken.DoesNotExist: return None if token.is_valid(): # Read token (delete it) token.read() - return user + return token.user - def _get_token(self, user, pin): + def _get_token(self, email, pin): """Get the token for corresponding user and pin.""" + user_model = get_user_model() + kwargs = { + 'user__%s' % user_model.USERNAME_FIELD: email, + 'token': pin + } - return SingleUseToken.objects.get(user=user, token=pin) + return SingleUseToken.objects.get(**kwargs) + def get_user(self, user_id): + """Get user from id.""" + user_model = get_user_model() + try: + return user_model.objects.get(pk=user_id) + except user_model.DoesNotExist: + return None +
Refactor to query straight for user
## Code Before: from django.contrib.auth import get_user_model from .models import SingleUseToken class PinBackend(object): """Authentication backend based on pin value.""" def authenticate(self, request, email=None, pin=None): """Authenticate user based on valid pin.""" user_model = get_user_model() kwargs = { user_model.USERNAME_FIELD: email } try: user = user_model.objects.get(**kwargs) except user_model.DoesNotExist: return None # Now that we have the user, check that we have a token try: token = self._get_token(user, pin) except SingleUseToken.DoesNotExist: return None if token.is_valid(): # Read token (delete it) token.read() return user def _get_token(self, user, pin): """Get the token for corresponding user and pin.""" return SingleUseToken.objects.get(user=user, token=pin) ## Instruction: Refactor to query straight for user ## Code After: from django.contrib.auth import get_user_model from .models import SingleUseToken class PinBackend(object): """Authentication backend based on pin value.""" def authenticate(self, request, email=None, pin=None): """Authenticate user based on valid pin.""" try: token = self._get_token(email, pin) except SingleUseToken.DoesNotExist: return None if token.is_valid(): # Read token (delete it) token.read() return token.user def _get_token(self, email, pin): """Get the token for corresponding user and pin.""" user_model = get_user_model() kwargs = { 'user__%s' % user_model.USERNAME_FIELD: email, 'token': pin } return SingleUseToken.objects.get(**kwargs) def get_user(self, user_id): """Get user from id.""" user_model = get_user_model() try: return user_model.objects.get(pk=user_id) except user_model.DoesNotExist: return None
... """Authenticate user based on valid pin.""" try: token = self._get_token(email, pin) except SingleUseToken.DoesNotExist: ... token.read() return token.user def _get_token(self, email, pin): """Get the token for corresponding user and pin.""" user_model = get_user_model() kwargs = { 'user__%s' % user_model.USERNAME_FIELD: email, 'token': pin } return SingleUseToken.objects.get(**kwargs) def get_user(self, user_id): """Get user from id.""" user_model = get_user_model() try: return user_model.objects.get(pk=user_id) except user_model.DoesNotExist: return None ...
f684692a013e80d0c4d07b1c0eba204bd94d2314
config.py
config.py
HOST = "0.0.0.0" # Port to listen on PORT = 8000 # File to store the JSON server list data in. FILENAME = "list.json" # Ammount of time, is seconds, after which servers are removed from the list # if they haven't updated their listings. Note: By default Minetest servers # only announce once every 5 minutes, so this should be more than 300. PURGE_TIME = 350 # List of banned IP addresses. BANLIST = [] # Creates server entries if a server sends an 'update' and there is no entry yet # This should only be used to populate the server list after list.json was deleted. ALLOW_UPDATE_WITHOUT_OLD = False
HOST = "0.0.0.0" # Port to listen on PORT = 8000 # File to store the JSON server list data in. FILENAME = "list.json" # Ammount of time, is seconds, after which servers are removed from the list # if they haven't updated their listings. Note: By default Minetest servers # only announce once every 5 minutes, so this should be more than 300. PURGE_TIME = 350 # List of banned IP addresses. BANLIST = [] # Creates server entries if a server sends an 'update' and there is no entry yet # This should only be used to populate the server list after list.json was deleted. # This WILL cause problems such as mapgen, mods and privilege information missing from the list ALLOW_UPDATE_WITHOUT_OLD = False
Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems
Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems
Python
lgpl-2.1
minetest/master-server,minetest/master-server,minetest/master-server
HOST = "0.0.0.0" # Port to listen on PORT = 8000 # File to store the JSON server list data in. FILENAME = "list.json" # Ammount of time, is seconds, after which servers are removed from the list # if they haven't updated their listings. Note: By default Minetest servers # only announce once every 5 minutes, so this should be more than 300. PURGE_TIME = 350 # List of banned IP addresses. BANLIST = [] # Creates server entries if a server sends an 'update' and there is no entry yet # This should only be used to populate the server list after list.json was deleted. + # This WILL cause problems such as mapgen, mods and privilege information missing from the list ALLOW_UPDATE_WITHOUT_OLD = False
Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems
## Code Before: HOST = "0.0.0.0" # Port to listen on PORT = 8000 # File to store the JSON server list data in. FILENAME = "list.json" # Ammount of time, is seconds, after which servers are removed from the list # if they haven't updated their listings. Note: By default Minetest servers # only announce once every 5 minutes, so this should be more than 300. PURGE_TIME = 350 # List of banned IP addresses. BANLIST = [] # Creates server entries if a server sends an 'update' and there is no entry yet # This should only be used to populate the server list after list.json was deleted. ALLOW_UPDATE_WITHOUT_OLD = False ## Instruction: Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems ## Code After: HOST = "0.0.0.0" # Port to listen on PORT = 8000 # File to store the JSON server list data in. FILENAME = "list.json" # Ammount of time, is seconds, after which servers are removed from the list # if they haven't updated their listings. Note: By default Minetest servers # only announce once every 5 minutes, so this should be more than 300. PURGE_TIME = 350 # List of banned IP addresses. BANLIST = [] # Creates server entries if a server sends an 'update' and there is no entry yet # This should only be used to populate the server list after list.json was deleted. # This WILL cause problems such as mapgen, mods and privilege information missing from the list ALLOW_UPDATE_WITHOUT_OLD = False
// ... existing code ... # This should only be used to populate the server list after list.json was deleted. # This WILL cause problems such as mapgen, mods and privilege information missing from the list ALLOW_UPDATE_WITHOUT_OLD = False // ... rest of the code ...
764f8d9d7818076555cde5fcad29f3052b523771
company/autocomplete_light_registry.py
company/autocomplete_light_registry.py
import autocomplete_light from .models import Company class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['^name'] model = Company autocomplete_light.register(CompanyAutocomplete)
import autocomplete_light from .models import Company class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['name', 'official_name', 'common_name'] model = Company autocomplete_light.register(CompanyAutocomplete)
Add more search fields to autocomplete
Add more search fields to autocomplete
Python
bsd-3-clause
KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend
import autocomplete_light from .models import Company class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase): - search_fields = ['^name'] + search_fields = ['name', 'official_name', 'common_name'] model = Company autocomplete_light.register(CompanyAutocomplete)
Add more search fields to autocomplete
## Code Before: import autocomplete_light from .models import Company class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['^name'] model = Company autocomplete_light.register(CompanyAutocomplete) ## Instruction: Add more search fields to autocomplete ## Code After: import autocomplete_light from .models import Company class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['name', 'official_name', 'common_name'] model = Company autocomplete_light.register(CompanyAutocomplete)
// ... existing code ... class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['name', 'official_name', 'common_name'] model = Company // ... rest of the code ...
505f7f6b243502cb4d6053ac7d54e0ecad15c557
functional_tests/test_question_page.py
functional_tests/test_question_page.py
from selenium import webdriver import unittest from django.test import TestCase from functional_tests import SERVER_URL class AskQuestion(TestCase): """Users can ask questions.""" def setUp(self): """Selenium browser.""" self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): """Cleanup browser.""" self.browser.quit() def test_typical_question(self): """When the user does it right, it should work.""" self.browser.get(SERVER_URL+"/question") submit_button = self.browser.find_element_by_css_selector("input[type=submit]") question_input = self.browser.find_element_by_tag_name("textarea") if __name__ == '__main__': unittest.main()
from selenium import webdriver from hamcrest import * import unittest from django.test import TestCase from functional_tests import SERVER_URL class AskQuestion(TestCase): """Users can ask questions.""" def setUp(self): """Selenium browser.""" self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): """Cleanup browser.""" self.browser.quit() def test_typical_question(self): """When the user does it right, it should work.""" self.browser.get(SERVER_URL+"/question") submit_button = self.browser.find_element_by_css_selector("input[type=submit]") question_input = self.browser.find_element_by_tag_name("textarea") question_input.send_keys(LONG_QUESTION) submit_button.click() displayed_question = self.browser.find_element_by_class_name("question") assert_that(displayed_question.text, equal_to(LONG_QUESTION), "Questions should be shown after they are submitted") LONG_QUESTION = """Centuries ago there lived-- "A king!" my little readers will say immediately. No, children, you are mistaken. Once upon a time there was a piece of wood. It was not an expensive piece of wood. Far from it. Just a common block of firewood, one of those thick, solid logs that are put on the fire in winter to make cold rooms cozy and warm. I do not know how this really happened, yet the fact remains that one fine day this piece of wood found itself in the shop of an old carpenter. His real name was Mastro Antonio, but everyone called him Mastro Cherry, for the tip of his nose was so round and red and shiny that it looked like a ripe cherry. """ if __name__ == '__main__': unittest.main()
Test for submitting and viewing questions.
Test for submitting and viewing questions.
Python
agpl-3.0
bjaress/shortanswer
from selenium import webdriver + from hamcrest import * import unittest from django.test import TestCase from functional_tests import SERVER_URL class AskQuestion(TestCase): """Users can ask questions.""" def setUp(self): """Selenium browser.""" self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): """Cleanup browser.""" self.browser.quit() def test_typical_question(self): """When the user does it right, it should work.""" self.browser.get(SERVER_URL+"/question") submit_button = self.browser.find_element_by_css_selector("input[type=submit]") question_input = self.browser.find_element_by_tag_name("textarea") + question_input.send_keys(LONG_QUESTION) + submit_button.click() + displayed_question = self.browser.find_element_by_class_name("question") + assert_that(displayed_question.text, equal_to(LONG_QUESTION), + "Questions should be shown after they are submitted") + + + LONG_QUESTION = """Centuries ago there lived-- + + "A king!" my little readers will say immediately. + + No, children, you are mistaken. Once upon a time there was a piece of + wood. It was not an expensive piece of wood. Far from it. Just a common + block of firewood, one of those thick, solid logs that are put on the + fire in winter to make cold rooms cozy and warm. + + I do not know how this really happened, yet the fact remains that one + fine day this piece of wood found itself in the shop of an old + carpenter. His real name was Mastro Antonio, but everyone called him + Mastro Cherry, for the tip of his nose was so round and red and shiny + that it looked like a ripe cherry. + """ + if __name__ == '__main__': unittest.main()
Test for submitting and viewing questions.
## Code Before: from selenium import webdriver import unittest from django.test import TestCase from functional_tests import SERVER_URL class AskQuestion(TestCase): """Users can ask questions.""" def setUp(self): """Selenium browser.""" self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): """Cleanup browser.""" self.browser.quit() def test_typical_question(self): """When the user does it right, it should work.""" self.browser.get(SERVER_URL+"/question") submit_button = self.browser.find_element_by_css_selector("input[type=submit]") question_input = self.browser.find_element_by_tag_name("textarea") if __name__ == '__main__': unittest.main() ## Instruction: Test for submitting and viewing questions. ## Code After: from selenium import webdriver from hamcrest import * import unittest from django.test import TestCase from functional_tests import SERVER_URL class AskQuestion(TestCase): """Users can ask questions.""" def setUp(self): """Selenium browser.""" self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): """Cleanup browser.""" self.browser.quit() def test_typical_question(self): """When the user does it right, it should work.""" self.browser.get(SERVER_URL+"/question") submit_button = self.browser.find_element_by_css_selector("input[type=submit]") question_input = self.browser.find_element_by_tag_name("textarea") question_input.send_keys(LONG_QUESTION) submit_button.click() displayed_question = self.browser.find_element_by_class_name("question") assert_that(displayed_question.text, equal_to(LONG_QUESTION), "Questions should be shown after they are submitted") LONG_QUESTION = """Centuries ago there lived-- "A king!" my little readers will say immediately. No, children, you are mistaken. Once upon a time there was a piece of wood. It was not an expensive piece of wood. Far from it. Just a common block of firewood, one of those thick, solid logs that are put on the fire in winter to make cold rooms cozy and warm. I do not know how this really happened, yet the fact remains that one fine day this piece of wood found itself in the shop of an old carpenter. His real name was Mastro Antonio, but everyone called him Mastro Cherry, for the tip of his nose was so round and red and shiny that it looked like a ripe cherry. """ if __name__ == '__main__': unittest.main()
// ... existing code ... from selenium import webdriver from hamcrest import * import unittest // ... modified code ... question_input = self.browser.find_element_by_tag_name("textarea") question_input.send_keys(LONG_QUESTION) submit_button.click() displayed_question = self.browser.find_element_by_class_name("question") assert_that(displayed_question.text, equal_to(LONG_QUESTION), "Questions should be shown after they are submitted") LONG_QUESTION = """Centuries ago there lived-- "A king!" my little readers will say immediately. No, children, you are mistaken. Once upon a time there was a piece of wood. It was not an expensive piece of wood. Far from it. Just a common block of firewood, one of those thick, solid logs that are put on the fire in winter to make cold rooms cozy and warm. I do not know how this really happened, yet the fact remains that one fine day this piece of wood found itself in the shop of an old carpenter. His real name was Mastro Antonio, but everyone called him Mastro Cherry, for the tip of his nose was so round and red and shiny that it looked like a ripe cherry. """ // ... rest of the code ...
4095b95930a57e78e35592dba413a776959adcde
logistic_order/model/sale_order.py
logistic_order/model/sale_order.py
from openerp.osv import orm, fields class sale_order(orm.Model): _inherit = 'sale.order' _columns = { # override only to change the 'string' argument # from 'Customer' to 'Requesting Entity' 'partner_id': fields.many2one( 'res.partner', 'Requesting Entity', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, required=True, change_default=True, select=True, track_visibility='always'), 'consignee_id': fields.many2one( 'res.partner', string='Consignee', required=True), 'incoterm_address': fields.char( 'Incoterm Place', help="Incoterm Place of Delivery. " "International Commercial Terms are a series of " "predefined commercial terms used in " "international transactions."), 'requested_by': fields.text('Requested By'), }
from openerp.osv import orm, fields class sale_order(orm.Model): _inherit = 'sale.order' _columns = { # override only to change the 'string' argument # from 'Customer' to 'Requesting Entity' 'partner_id': fields.many2one( 'res.partner', 'Requesting Entity', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, required=True, change_default=True, select=True, track_visibility='always'), 'consignee_id': fields.many2one( 'res.partner', string='Consignee', required=True), 'incoterm_address': fields.char( 'Incoterm Place', help="Incoterm Place of Delivery. " "International Commercial Terms are a series of " "predefined commercial terms used in " "international transactions."), 'requested_by': fields.text('Requested By'), 'state': fields.selection([ ('draft', 'Draft Cost Estimate'), ('sent', 'Cost Estimate Sent'), ('cancel', 'Cancelled'), ('waiting_date', 'Waiting Schedule'), ('progress', 'Logistic Order'), ('manual', 'Logistic Order to Invoice'), ('invoice_except', 'Invoice Exception'), ('done', 'Done'), ], 'Status', readonly=True, track_visibility='onchange', help="Gives the status of the cost estimate or logistic order. \nThe exception status is automatically set when a cancel operation occurs in the processing of a document linked to the logistic order. \nThe 'Waiting Schedule' status is set when the invoice is confirmed but waiting for the scheduler to run on the order date.", select=True), }
Rename state of SO according to LO and Cost Estimate
[IMP] Rename state of SO according to LO and Cost Estimate
Python
agpl-3.0
yvaucher/vertical-ngo,mdietrichc2c/vertical-ngo,jorsea/vertical-ngo,gurneyalex/vertical-ngo,jorsea/vertical-ngo,jgrandguillaume/vertical-ngo
from openerp.osv import orm, fields class sale_order(orm.Model): _inherit = 'sale.order' _columns = { # override only to change the 'string' argument # from 'Customer' to 'Requesting Entity' 'partner_id': fields.many2one( 'res.partner', 'Requesting Entity', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, required=True, change_default=True, select=True, track_visibility='always'), 'consignee_id': fields.many2one( 'res.partner', string='Consignee', required=True), 'incoterm_address': fields.char( 'Incoterm Place', help="Incoterm Place of Delivery. " "International Commercial Terms are a series of " "predefined commercial terms used in " "international transactions."), 'requested_by': fields.text('Requested By'), + 'state': fields.selection([ + ('draft', 'Draft Cost Estimate'), + ('sent', 'Cost Estimate Sent'), + ('cancel', 'Cancelled'), + ('waiting_date', 'Waiting Schedule'), + ('progress', 'Logistic Order'), + ('manual', 'Logistic Order to Invoice'), + ('invoice_except', 'Invoice Exception'), + ('done', 'Done'), + ], 'Status', readonly=True, track_visibility='onchange', + help="Gives the status of the cost estimate or logistic order. \nThe exception status is automatically set when a cancel operation occurs in the processing of a document linked to the logistic order. \nThe 'Waiting Schedule' status is set when the invoice is confirmed but waiting for the scheduler to run on the order date.", select=True), + }
Rename state of SO according to LO and Cost Estimate
## Code Before: from openerp.osv import orm, fields class sale_order(orm.Model): _inherit = 'sale.order' _columns = { # override only to change the 'string' argument # from 'Customer' to 'Requesting Entity' 'partner_id': fields.many2one( 'res.partner', 'Requesting Entity', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, required=True, change_default=True, select=True, track_visibility='always'), 'consignee_id': fields.many2one( 'res.partner', string='Consignee', required=True), 'incoterm_address': fields.char( 'Incoterm Place', help="Incoterm Place of Delivery. " "International Commercial Terms are a series of " "predefined commercial terms used in " "international transactions."), 'requested_by': fields.text('Requested By'), } ## Instruction: Rename state of SO according to LO and Cost Estimate ## Code After: from openerp.osv import orm, fields class sale_order(orm.Model): _inherit = 'sale.order' _columns = { # override only to change the 'string' argument # from 'Customer' to 'Requesting Entity' 'partner_id': fields.many2one( 'res.partner', 'Requesting Entity', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, required=True, change_default=True, select=True, track_visibility='always'), 'consignee_id': fields.many2one( 'res.partner', string='Consignee', required=True), 'incoterm_address': fields.char( 'Incoterm Place', help="Incoterm Place of Delivery. " "International Commercial Terms are a series of " "predefined commercial terms used in " "international transactions."), 'requested_by': fields.text('Requested By'), 'state': fields.selection([ ('draft', 'Draft Cost Estimate'), ('sent', 'Cost Estimate Sent'), ('cancel', 'Cancelled'), ('waiting_date', 'Waiting Schedule'), ('progress', 'Logistic Order'), ('manual', 'Logistic Order to Invoice'), ('invoice_except', 'Invoice Exception'), ('done', 'Done'), ], 'Status', readonly=True, track_visibility='onchange', help="Gives the status of the cost estimate or logistic order. \nThe exception status is automatically set when a cancel operation occurs in the processing of a document linked to the logistic order. \nThe 'Waiting Schedule' status is set when the invoice is confirmed but waiting for the scheduler to run on the order date.", select=True), }
# ... existing code ... 'requested_by': fields.text('Requested By'), 'state': fields.selection([ ('draft', 'Draft Cost Estimate'), ('sent', 'Cost Estimate Sent'), ('cancel', 'Cancelled'), ('waiting_date', 'Waiting Schedule'), ('progress', 'Logistic Order'), ('manual', 'Logistic Order to Invoice'), ('invoice_except', 'Invoice Exception'), ('done', 'Done'), ], 'Status', readonly=True, track_visibility='onchange', help="Gives the status of the cost estimate or logistic order. \nThe exception status is automatically set when a cancel operation occurs in the processing of a document linked to the logistic order. \nThe 'Waiting Schedule' status is set when the invoice is confirmed but waiting for the scheduler to run on the order date.", select=True), } # ... rest of the code ...
aaaa857642fa4ce2631fb47f3c929d3197037231
falcom/generate_pageview.py
falcom/generate_pageview.py
class Pagetags: default_confidence = 100 def generate_pageview (self): return "" def add_raw_tags (self, tag_data): pass
class Pagetags: def __init__ (self): self.default_confidence = 100 @property def default_confidence (self): return self.__default_confid @default_confidence.setter def default_confidence (self, value): self.__default_confid = value def generate_pageview (self): return "" def add_raw_tags (self, tag_data): pass
Make default_confidence into a @property
:muscle: Make default_confidence into a @property
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
class Pagetags: + def __init__ (self): - default_confidence = 100 + self.default_confidence = 100 + + @property + def default_confidence (self): + return self.__default_confid + + @default_confidence.setter + def default_confidence (self, value): + self.__default_confid = value def generate_pageview (self): return "" def add_raw_tags (self, tag_data): pass
Make default_confidence into a @property
## Code Before: class Pagetags: default_confidence = 100 def generate_pageview (self): return "" def add_raw_tags (self, tag_data): pass ## Instruction: Make default_confidence into a @property ## Code After: class Pagetags: def __init__ (self): self.default_confidence = 100 @property def default_confidence (self): return self.__default_confid @default_confidence.setter def default_confidence (self, value): self.__default_confid = value def generate_pageview (self): return "" def add_raw_tags (self, tag_data): pass
// ... existing code ... def __init__ (self): self.default_confidence = 100 @property def default_confidence (self): return self.__default_confid @default_confidence.setter def default_confidence (self, value): self.__default_confid = value // ... rest of the code ...
c5a617db987fda0302cf5963bbc41e8d0887347d
tests/conftest.py
tests/conftest.py
import pytest @pytest.fixture def observe(monkeypatch): def patch(module, func): original_func = getattr(module, func) def wrapper(*args, **kwargs): result = original_func(*args, **kwargs) self.calls[self.last_call] = (args, kwargs, result) self.last_call += 1 return result self = wrapper self.calls = {} self.last_call = 0 monkeypatch.setattr(module, func, wrapper) return wrapper return patch
import pytest @pytest.fixture def observe(monkeypatch): """ Wrap a function so its call history can be inspected. Example: # foo.py def func(bar): return 2 * bar # test.py import pytest import foo def test_func(observe): observer = observe(foo, "func") assert foo.func(3) == 6 assert foo.func(-5) == -10 assert len(observer.calls) == 2 """ class ObserverFactory: def __init__(self, module, func): self.original_func = getattr(module, func) self.calls = [] monkeypatch.setattr(module, func, self) def __call__(self, *args, **kwargs): result = self.original_func(*args, **kwargs) self.calls.append((args, kwargs, result)) return result return ObserverFactory
Clean up test helper, add example
Clean up test helper, add example
Python
mit
numberoverzero/pyservice
import pytest @pytest.fixture def observe(monkeypatch): - def patch(module, func): - original_func = getattr(module, func) + """ + Wrap a function so its call history can be inspected. + Example: + + # foo.py + def func(bar): + return 2 * bar + + # test.py + import pytest + import foo + + def test_func(observe): + observer = observe(foo, "func") + assert foo.func(3) == 6 + assert foo.func(-5) == -10 + assert len(observer.calls) == 2 + """ + class ObserverFactory: + def __init__(self, module, func): + self.original_func = getattr(module, func) + self.calls = [] + monkeypatch.setattr(module, func, self) + - def wrapper(*args, **kwargs): + def __call__(self, *args, **kwargs): - result = original_func(*args, **kwargs) + result = self.original_func(*args, **kwargs) - self.calls[self.last_call] = (args, kwargs, result) + self.calls.append((args, kwargs, result)) - self.last_call += 1 return result + return ObserverFactory - self = wrapper - self.calls = {} - self.last_call = 0 - monkeypatch.setattr(module, func, wrapper) - return wrapper - return patch -
Clean up test helper, add example
## Code Before: import pytest @pytest.fixture def observe(monkeypatch): def patch(module, func): original_func = getattr(module, func) def wrapper(*args, **kwargs): result = original_func(*args, **kwargs) self.calls[self.last_call] = (args, kwargs, result) self.last_call += 1 return result self = wrapper self.calls = {} self.last_call = 0 monkeypatch.setattr(module, func, wrapper) return wrapper return patch ## Instruction: Clean up test helper, add example ## Code After: import pytest @pytest.fixture def observe(monkeypatch): """ Wrap a function so its call history can be inspected. Example: # foo.py def func(bar): return 2 * bar # test.py import pytest import foo def test_func(observe): observer = observe(foo, "func") assert foo.func(3) == 6 assert foo.func(-5) == -10 assert len(observer.calls) == 2 """ class ObserverFactory: def __init__(self, module, func): self.original_func = getattr(module, func) self.calls = [] monkeypatch.setattr(module, func, self) def __call__(self, *args, **kwargs): result = self.original_func(*args, **kwargs) self.calls.append((args, kwargs, result)) return result return ObserverFactory
... def observe(monkeypatch): """ Wrap a function so its call history can be inspected. Example: # foo.py def func(bar): return 2 * bar # test.py import pytest import foo def test_func(observe): observer = observe(foo, "func") assert foo.func(3) == 6 assert foo.func(-5) == -10 assert len(observer.calls) == 2 """ class ObserverFactory: def __init__(self, module, func): self.original_func = getattr(module, func) self.calls = [] monkeypatch.setattr(module, func, self) def __call__(self, *args, **kwargs): result = self.original_func(*args, **kwargs) self.calls.append((args, kwargs, result)) return result return ObserverFactory ...
01331f37c629f0738c5517527a6e78be55334e04
democracy/views/utils.py
democracy/views/utils.py
from functools import lru_cache from rest_framework import serializers class AbstractFieldSerializer(serializers.RelatedField): parent_serializer_class = serializers.ModelSerializer def to_representation(self, image): return self.parent_serializer_class(image, context=self.context).data class AbstractSerializerMixin(object): @classmethod @lru_cache() def get_field_serializer_class(cls): return type('%sFieldSerializer' % cls.Meta.model, (AbstractFieldSerializer,), { "parent_serializer_class": cls }) @classmethod def get_field_serializer(cls, **kwargs): return cls.get_field_serializer_class()(**kwargs)
from functools import lru_cache from rest_framework import serializers from rest_framework.relations import ManyRelatedField, MANY_RELATION_KWARGS class AbstractFieldSerializer(serializers.RelatedField): parent_serializer_class = serializers.ModelSerializer many_field_class = ManyRelatedField def to_representation(self, image): return self.parent_serializer_class(image, context=self.context).data @classmethod def many_init(cls, *args, **kwargs): list_kwargs = {'child_relation': cls(*args, **kwargs)} for key in kwargs.keys(): if key in MANY_RELATION_KWARGS: list_kwargs[key] = kwargs[key] return cls.many_field_class(**list_kwargs) class AbstractSerializerMixin(object): @classmethod @lru_cache() def get_field_serializer_class(cls, many_field_class=ManyRelatedField): return type('%sFieldSerializer' % cls.Meta.model, (AbstractFieldSerializer,), { "parent_serializer_class": cls, "many_field_class": many_field_class, }) @classmethod def get_field_serializer(cls, **kwargs): many_field_class = kwargs.pop("many_field_class", ManyRelatedField) return cls.get_field_serializer_class(many_field_class=many_field_class)(**kwargs)
Allow overriding the ManyRelatedField for image fields
Allow overriding the ManyRelatedField for image fields
Python
mit
City-of-Helsinki/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,stephawe/kerrokantasi,vikoivun/kerrokantasi,vikoivun/kerrokantasi,vikoivun/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi
from functools import lru_cache from rest_framework import serializers + from rest_framework.relations import ManyRelatedField, MANY_RELATION_KWARGS class AbstractFieldSerializer(serializers.RelatedField): parent_serializer_class = serializers.ModelSerializer + many_field_class = ManyRelatedField def to_representation(self, image): return self.parent_serializer_class(image, context=self.context).data + + @classmethod + def many_init(cls, *args, **kwargs): + list_kwargs = {'child_relation': cls(*args, **kwargs)} + for key in kwargs.keys(): + if key in MANY_RELATION_KWARGS: + list_kwargs[key] = kwargs[key] + return cls.many_field_class(**list_kwargs) class AbstractSerializerMixin(object): @classmethod @lru_cache() - def get_field_serializer_class(cls): + def get_field_serializer_class(cls, many_field_class=ManyRelatedField): return type('%sFieldSerializer' % cls.Meta.model, (AbstractFieldSerializer,), { - "parent_serializer_class": cls + "parent_serializer_class": cls, + "many_field_class": many_field_class, }) @classmethod def get_field_serializer(cls, **kwargs): + many_field_class = kwargs.pop("many_field_class", ManyRelatedField) - return cls.get_field_serializer_class()(**kwargs) + return cls.get_field_serializer_class(many_field_class=many_field_class)(**kwargs)
Allow overriding the ManyRelatedField for image fields
## Code Before: from functools import lru_cache from rest_framework import serializers class AbstractFieldSerializer(serializers.RelatedField): parent_serializer_class = serializers.ModelSerializer def to_representation(self, image): return self.parent_serializer_class(image, context=self.context).data class AbstractSerializerMixin(object): @classmethod @lru_cache() def get_field_serializer_class(cls): return type('%sFieldSerializer' % cls.Meta.model, (AbstractFieldSerializer,), { "parent_serializer_class": cls }) @classmethod def get_field_serializer(cls, **kwargs): return cls.get_field_serializer_class()(**kwargs) ## Instruction: Allow overriding the ManyRelatedField for image fields ## Code After: from functools import lru_cache from rest_framework import serializers from rest_framework.relations import ManyRelatedField, MANY_RELATION_KWARGS class AbstractFieldSerializer(serializers.RelatedField): parent_serializer_class = serializers.ModelSerializer many_field_class = ManyRelatedField def to_representation(self, image): return self.parent_serializer_class(image, context=self.context).data @classmethod def many_init(cls, *args, **kwargs): list_kwargs = {'child_relation': cls(*args, **kwargs)} for key in kwargs.keys(): if key in MANY_RELATION_KWARGS: list_kwargs[key] = kwargs[key] return cls.many_field_class(**list_kwargs) class AbstractSerializerMixin(object): @classmethod @lru_cache() def get_field_serializer_class(cls, many_field_class=ManyRelatedField): return type('%sFieldSerializer' % cls.Meta.model, (AbstractFieldSerializer,), { "parent_serializer_class": cls, "many_field_class": many_field_class, }) @classmethod def get_field_serializer(cls, **kwargs): many_field_class = kwargs.pop("many_field_class", ManyRelatedField) return cls.get_field_serializer_class(many_field_class=many_field_class)(**kwargs)
... from rest_framework import serializers from rest_framework.relations import ManyRelatedField, MANY_RELATION_KWARGS ... parent_serializer_class = serializers.ModelSerializer many_field_class = ManyRelatedField ... return self.parent_serializer_class(image, context=self.context).data @classmethod def many_init(cls, *args, **kwargs): list_kwargs = {'child_relation': cls(*args, **kwargs)} for key in kwargs.keys(): if key in MANY_RELATION_KWARGS: list_kwargs[key] = kwargs[key] return cls.many_field_class(**list_kwargs) ... @lru_cache() def get_field_serializer_class(cls, many_field_class=ManyRelatedField): return type('%sFieldSerializer' % cls.Meta.model, (AbstractFieldSerializer,), { "parent_serializer_class": cls, "many_field_class": many_field_class, }) ... def get_field_serializer(cls, **kwargs): many_field_class = kwargs.pop("many_field_class", ManyRelatedField) return cls.get_field_serializer_class(many_field_class=many_field_class)(**kwargs) ...
1231c5e2c9fd4edc033e6021372950ca9b89c2f1
ansible/module_utils/dcos.py
ansible/module_utils/dcos.py
import requests def dcos_api(method, endpoint, body=None, params=None): url = "{url}acs/api/v1{endpoint}".format( url=params['dcos_credentials']['url'], endpoint=endpoint) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, }
import requests import urlparse def dcos_api(method, endpoint, body=None, params=None): result = urlparse.urlsplit(params['dcos_credentials']['url']) netloc = result.netloc.split('@')[-1] result = result._replace(netloc=netloc) path = "acs/api/v1{endpoint}".format(endpoint=endpoint) result = result._replace(path=path) url = urlparse.urlunsplit(result) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, }
Fix for urls with user/pass
Fix for urls with user/pass
Python
mit
TerryHowe/ansible-modules-dcos,TerryHowe/ansible-modules-dcos
import requests + import urlparse def dcos_api(method, endpoint, body=None, params=None): - url = "{url}acs/api/v1{endpoint}".format( - url=params['dcos_credentials']['url'], - endpoint=endpoint) + result = urlparse.urlsplit(params['dcos_credentials']['url']) + netloc = result.netloc.split('@')[-1] + result = result._replace(netloc=netloc) + path = "acs/api/v1{endpoint}".format(endpoint=endpoint) + result = result._replace(path=path) + url = urlparse.urlunsplit(result) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, }
Fix for urls with user/pass
## Code Before: import requests def dcos_api(method, endpoint, body=None, params=None): url = "{url}acs/api/v1{endpoint}".format( url=params['dcos_credentials']['url'], endpoint=endpoint) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, } ## Instruction: Fix for urls with user/pass ## Code After: import requests import urlparse def dcos_api(method, endpoint, body=None, params=None): result = urlparse.urlsplit(params['dcos_credentials']['url']) netloc = result.netloc.split('@')[-1] result = result._replace(netloc=netloc) path = "acs/api/v1{endpoint}".format(endpoint=endpoint) result = result._replace(path=path) url = urlparse.urlunsplit(result) headers = { 'Content-Type': 'application/json', 'Authorization': "token={}".format(params['dcos_credentials']['token']), } verify = params.get('ssl_verify', True) if method == 'GET': response = requests.get(url, headers=headers, verify=verify) elif method == 'PUT': response = requests.put(url, json=body, headers=headers, verify=verify) elif method == 'PATCH': response = requests.patch(url, json=body, headers=headers, verify=verify) elif method == 'DELETE': response = requests.delete(url, headers=headers, verify=verify) try: response_json = response.json() except: response_json = {} return { 'url': url, 'status_code': response.status_code, 'text': response.text, 'json': response_json, 'request_body': body, 'request_headers': headers, }
... import requests import urlparse ... def dcos_api(method, endpoint, body=None, params=None): result = urlparse.urlsplit(params['dcos_credentials']['url']) netloc = result.netloc.split('@')[-1] result = result._replace(netloc=netloc) path = "acs/api/v1{endpoint}".format(endpoint=endpoint) result = result._replace(path=path) url = urlparse.urlunsplit(result) headers = { ...
00c28d76d93331d7a501f0006cbadcaef48e499f
d1lod/tests/conftest.py
d1lod/tests/conftest.py
import pytest from d1lod import sesame @pytest.fixture(scope="module") def store(): return sesame.Store('localhost', 8080) @pytest.fixture(scope="module") def repo(store): return sesame.Repository(store, 'test') @pytest.fixture(scope="module") def interface(repo): return sesame.Interface(repo)
import pytest from d1lod import sesame @pytest.fixture(scope="module") def store(): return sesame.Store('localhost', 8080) @pytest.fixture(scope="module") def repo(store): 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/', "prov": "http://www.w3.org/ns/prov#" } repository = sesame.Repository(store, 'test', ns=namespaces) return repository @pytest.fixture(scope="module") def interface(repo): return sesame.Interface(repo)
Add default set of namespaces to test repository instance
Add default set of namespaces to test repository instance
Python
apache-2.0
ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod
import pytest from d1lod import sesame @pytest.fixture(scope="module") def store(): return sesame.Store('localhost', 8080) @pytest.fixture(scope="module") def repo(store): + 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/', + "prov": "http://www.w3.org/ns/prov#" + } + - return sesame.Repository(store, 'test') + repository = sesame.Repository(store, 'test', ns=namespaces) + + return repository @pytest.fixture(scope="module") def interface(repo): return sesame.Interface(repo)
Add default set of namespaces to test repository instance
## Code Before: import pytest from d1lod import sesame @pytest.fixture(scope="module") def store(): return sesame.Store('localhost', 8080) @pytest.fixture(scope="module") def repo(store): return sesame.Repository(store, 'test') @pytest.fixture(scope="module") def interface(repo): return sesame.Interface(repo) ## Instruction: Add default set of namespaces to test repository instance ## Code After: import pytest from d1lod import sesame @pytest.fixture(scope="module") def store(): return sesame.Store('localhost', 8080) @pytest.fixture(scope="module") def repo(store): 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/', "prov": "http://www.w3.org/ns/prov#" } repository = sesame.Repository(store, 'test', ns=namespaces) return repository @pytest.fixture(scope="module") def interface(repo): return sesame.Interface(repo)
# ... existing code ... def repo(store): 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/', "prov": "http://www.w3.org/ns/prov#" } repository = sesame.Repository(store, 'test', ns=namespaces) return repository # ... rest of the code ...
e8d5732e94d14a3a72999bd270af1fd3f3a2e09f
fileutil_posix.py
fileutil_posix.py
import sys, os, subprocess def run(args, workdir=None): p = subprocess.Popen(args, close_fds=True, cwd=workdir) return p.wait() if sys.platform == "darwin": shell_open_command = "open" else: shell_open_command = "xdg-open" def shell_open(path, workdir=None): return run([shell_open_command, path], workdir=workdir) == 0 def get_user_config_dir(name=""): path = os.environ.get("HOME", "") if name: path = os.path.join(path, "." + name) return os.path.realpath(path) __all__ = ( "shell_open", "get_user_config_dir", )
import sys, os, subprocess def run(args, workdir=None): p = subprocess.Popen(args, close_fds=True, cwd=workdir) return p.wait() if sys.platform == "darwin": shell_open_command = "open" else: shell_open_command = "xdg-open" def shell_open(path, workdir=None): return run([shell_open_command, path], workdir=workdir) == 0 def get_user_config_dir(name=""): path = os.environ.get("XDG_CONFIG_HOME") if not path: path = os.path.join(os.environ.get("HOME", "/"), ".config") if name: path = os.path.join(path, name) return os.path.realpath(path) __all__ = ( "shell_open", "get_user_config_dir", )
Use XDG_CONFIG_HOME for configuration directory.
Use XDG_CONFIG_HOME for configuration directory.
Python
mit
shaurz/devo
import sys, os, subprocess def run(args, workdir=None): p = subprocess.Popen(args, close_fds=True, cwd=workdir) return p.wait() if sys.platform == "darwin": shell_open_command = "open" else: shell_open_command = "xdg-open" def shell_open(path, workdir=None): return run([shell_open_command, path], workdir=workdir) == 0 def get_user_config_dir(name=""): - path = os.environ.get("HOME", "") + path = os.environ.get("XDG_CONFIG_HOME") + if not path: + path = os.path.join(os.environ.get("HOME", "/"), ".config") if name: - path = os.path.join(path, "." + name) + path = os.path.join(path, name) return os.path.realpath(path) __all__ = ( "shell_open", "get_user_config_dir", )
Use XDG_CONFIG_HOME for configuration directory.
## Code Before: import sys, os, subprocess def run(args, workdir=None): p = subprocess.Popen(args, close_fds=True, cwd=workdir) return p.wait() if sys.platform == "darwin": shell_open_command = "open" else: shell_open_command = "xdg-open" def shell_open(path, workdir=None): return run([shell_open_command, path], workdir=workdir) == 0 def get_user_config_dir(name=""): path = os.environ.get("HOME", "") if name: path = os.path.join(path, "." + name) return os.path.realpath(path) __all__ = ( "shell_open", "get_user_config_dir", ) ## Instruction: Use XDG_CONFIG_HOME for configuration directory. ## Code After: import sys, os, subprocess def run(args, workdir=None): p = subprocess.Popen(args, close_fds=True, cwd=workdir) return p.wait() if sys.platform == "darwin": shell_open_command = "open" else: shell_open_command = "xdg-open" def shell_open(path, workdir=None): return run([shell_open_command, path], workdir=workdir) == 0 def get_user_config_dir(name=""): path = os.environ.get("XDG_CONFIG_HOME") if not path: path = os.path.join(os.environ.get("HOME", "/"), ".config") if name: path = os.path.join(path, name) return os.path.realpath(path) __all__ = ( "shell_open", "get_user_config_dir", )
// ... existing code ... def get_user_config_dir(name=""): path = os.environ.get("XDG_CONFIG_HOME") if not path: path = os.path.join(os.environ.get("HOME", "/"), ".config") if name: path = os.path.join(path, name) return os.path.realpath(path) // ... rest of the code ...
4625a1ed4115b85ce7d96a0d0ba486e589e9fe6c
runtests.py
runtests.py
import sys from optparse import OptionParser from os.path import abspath, dirname from django.test.simple import DjangoTestSuiteRunner def runtests(*test_args, **kwargs): parent = dirname(abspath(__file__)) sys.path.insert(0, parent) test_runner = DjangoTestSuiteRunner( verbosity=kwargs.get('verbosity', 1), interactive=kwargs.get('interactive', False), failfast=kwargs.get('failfast') ) failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': parser = OptionParser() parser.add_option('--failfast', action='store_true', default=False, dest='failfast') (options, args) = parser.parse_args() runtests(failfast=options.failfast, *args)
import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' from django.test.utils import get_runner from django.conf import settings import django if django.VERSION >= (1, 7): django.setup() def runtests(): TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) failures = test_runner.run_tests(['tests']) sys.exit(bool(failures)) if __name__ == '__main__': runtests()
Make test runner only run basis tests
Make test runner only run basis tests and not dependecies tests
Python
mit
frecar/django-basis
+ import os import sys - from optparse import OptionParser - from os.path import abspath, dirname - from django.test.simple import DjangoTestSuiteRunner + + os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' + + from django.test.utils import get_runner + from django.conf import settings + import django + + if django.VERSION >= (1, 7): + django.setup() + def runtests(): + TestRunner = get_runner(settings) + test_runner = TestRunner(verbosity=1, interactive=True) - def runtests(*test_args, **kwargs): - parent = dirname(abspath(__file__)) - sys.path.insert(0, parent) - test_runner = DjangoTestSuiteRunner( - verbosity=kwargs.get('verbosity', 1), - interactive=kwargs.get('interactive', False), - failfast=kwargs.get('failfast') - ) - failures = test_runner.run_tests(test_args) + failures = test_runner.run_tests(['tests']) - sys.exit(failures) + sys.exit(bool(failures)) + if __name__ == '__main__': + runtests() - parser = OptionParser() - parser.add_option('--failfast', action='store_true', default=False, dest='failfast') - (options, args) = parser.parse_args() - - runtests(failfast=options.failfast, *args)
Make test runner only run basis tests
## Code Before: import sys from optparse import OptionParser from os.path import abspath, dirname from django.test.simple import DjangoTestSuiteRunner def runtests(*test_args, **kwargs): parent = dirname(abspath(__file__)) sys.path.insert(0, parent) test_runner = DjangoTestSuiteRunner( verbosity=kwargs.get('verbosity', 1), interactive=kwargs.get('interactive', False), failfast=kwargs.get('failfast') ) failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': parser = OptionParser() parser.add_option('--failfast', action='store_true', default=False, dest='failfast') (options, args) = parser.parse_args() runtests(failfast=options.failfast, *args) ## Instruction: Make test runner only run basis tests ## Code After: import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' from django.test.utils import get_runner from django.conf import settings import django if django.VERSION >= (1, 7): django.setup() def runtests(): TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) failures = test_runner.run_tests(['tests']) sys.exit(bool(failures)) if __name__ == '__main__': runtests()
// ... existing code ... import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' from django.test.utils import get_runner from django.conf import settings import django if django.VERSION >= (1, 7): django.setup() // ... modified code ... def runtests(): TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) failures = test_runner.run_tests(['tests']) sys.exit(bool(failures)) ... if __name__ == '__main__': runtests() // ... rest of the code ...
87881f594836b7cf92ffce69dbb643ee05df88d1
utils/config_utils.py
utils/config_utils.py
import sys import yaml def job_config(args): try: config_file = './config/{0}.yml'.format(args[0]) except IndexError: sys.exit("Job name is a required argument. Example: chicago_cta") try: with open(config_file, 'r') as file: config = yaml.safe_load(file) except IOError: sys.exit("Missing config file for job: '{0}'".format(config_file)) return config, config_file
import sys import yaml def main_config(): config_file = './config/.main.yml' try: with open(config_file, 'r') as file: config = yaml.safe_load(file) except IOError: sys.exit("Missing main config file: '{0}'".format(config_file)) return config, config_file def job_config(args): try: config_file = './config/{0}.yml'.format(args[0]) except IndexError: sys.exit("Job name is a required argument. Example: chicago_cta") try: with open(config_file, 'r') as file: config = yaml.safe_load(file) except IOError: sys.exit("Missing config file for job: '{0}'".format(config_file)) return config, config_file
Add util for loading main config
Add util for loading main config
Python
mit
projectweekend/Transit-Stop-Collector
import sys import yaml + + + def main_config(): + config_file = './config/.main.yml' + + try: + with open(config_file, 'r') as file: + config = yaml.safe_load(file) + except IOError: + sys.exit("Missing main config file: '{0}'".format(config_file)) + + return config, config_file def job_config(args): try: config_file = './config/{0}.yml'.format(args[0]) except IndexError: sys.exit("Job name is a required argument. Example: chicago_cta") try: with open(config_file, 'r') as file: config = yaml.safe_load(file) except IOError: sys.exit("Missing config file for job: '{0}'".format(config_file)) return config, config_file
Add util for loading main config
## Code Before: import sys import yaml def job_config(args): try: config_file = './config/{0}.yml'.format(args[0]) except IndexError: sys.exit("Job name is a required argument. Example: chicago_cta") try: with open(config_file, 'r') as file: config = yaml.safe_load(file) except IOError: sys.exit("Missing config file for job: '{0}'".format(config_file)) return config, config_file ## Instruction: Add util for loading main config ## Code After: import sys import yaml def main_config(): config_file = './config/.main.yml' try: with open(config_file, 'r') as file: config = yaml.safe_load(file) except IOError: sys.exit("Missing main config file: '{0}'".format(config_file)) return config, config_file def job_config(args): try: config_file = './config/{0}.yml'.format(args[0]) except IndexError: sys.exit("Job name is a required argument. Example: chicago_cta") try: with open(config_file, 'r') as file: config = yaml.safe_load(file) except IOError: sys.exit("Missing config file for job: '{0}'".format(config_file)) return config, config_file
// ... existing code ... import yaml def main_config(): config_file = './config/.main.yml' try: with open(config_file, 'r') as file: config = yaml.safe_load(file) except IOError: sys.exit("Missing main config file: '{0}'".format(config_file)) return config, config_file // ... rest of the code ...
5812aae9059ede1a3cb19be9033ebc435d5ebb94
scripts/create_user.py
scripts/create_user.py
import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=config['mysql_root_pass']) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") # Close connection and database cursor.close() cnx.close()
import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") cnx.commit() # Close connection and database cursor.close() cnx.close()
Fix MySQL command executing (MySQL commit).
scripts: Fix MySQL command executing (MySQL commit).
Python
mit
alberand/tserver,alberand/tserver,alberand/tserver,alberand/tserver
import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', - password=config['mysql_root_pass']) + password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") - + cnx.commit() # Close connection and database cursor.close() cnx.close()
Fix MySQL command executing (MySQL commit).
## Code Before: import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=config['mysql_root_pass']) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") # Close connection and database cursor.close() cnx.close() ## Instruction: Fix MySQL command executing (MySQL commit). ## Code After: import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") cnx.commit() # Close connection and database cursor.close() cnx.close()
... user='root', password=sys.argv[2]) cursor = cnx.cursor() ... cnx.commit() ...
eac0b6cb28e86b43d6459d631f10fd3d7a7b2287
cli/hdfs.py
cli/hdfs.py
__author__ = 'Dongjoon Hyun ([email protected])' __license__ = 'Apache License' __version__ = '0.2' from fabric.api import * @task def ls(inpath='/'): """ fab hdfs.ls:/sample """ cmd = '/usr/bin/hadoop fs -ls %(inpath)s 2> /dev/null' % locals() run(cmd) @task def count(inpath): """ fab hdfs.count:/data/text/newsgroup """ cmd = '/usr/bin/hadoop fs -count %(inpath)s 2> /dev/null' % locals() run(cmd) @task def du(inpath): """ fab hdfs.du:/sample """ cmd = '/usr/bin/hadoop fs -du -h %(inpath)s 2> /dev/null' % locals() run(cmd) @task def text(inpath, count=5): """ fab hdfs.text:/sample/hani_news.head.txt.gz,5 """ cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null | head -n %(count)s' % locals() run(cmd)
__author__ = 'Dongjoon Hyun ([email protected])' __license__ = 'Apache License' __version__ = '0.2' from fabric.api import * @task def ls(inpath='/'): """ fab hdfs.ls:/sample """ cmd = '/usr/bin/hadoop fs -ls %(inpath)s 2> /dev/null' % locals() run(cmd) @task def count(inpath): """ fab hdfs.count:/data/text/newsgroup """ cmd = '/usr/bin/hadoop fs -count %(inpath)s 2> /dev/null' % locals() run(cmd) @task def du(inpath): """ fab hdfs.du:/sample """ cmd = '/usr/bin/hadoop fs -du -h %(inpath)s 2> /dev/null' % locals() run(cmd) @task def text(inpath, count=0): """ fab hdfs.text:/sample/hani_news.head.txt.gz,5 """ if count == 0: cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null' % locals() else: cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null | head -n %(count)s' % locals() run(cmd)
Change default value for line number
Change default value for line number
Python
apache-2.0
dongjoon-hyun/tools,dongjoon-hyun/tools,dongjoon-hyun/tools,dongjoon-hyun/tools,dongjoon-hyun/tools
__author__ = 'Dongjoon Hyun ([email protected])' __license__ = 'Apache License' __version__ = '0.2' from fabric.api import * @task def ls(inpath='/'): """ fab hdfs.ls:/sample """ cmd = '/usr/bin/hadoop fs -ls %(inpath)s 2> /dev/null' % locals() run(cmd) @task def count(inpath): """ fab hdfs.count:/data/text/newsgroup """ cmd = '/usr/bin/hadoop fs -count %(inpath)s 2> /dev/null' % locals() run(cmd) @task def du(inpath): """ fab hdfs.du:/sample """ cmd = '/usr/bin/hadoop fs -du -h %(inpath)s 2> /dev/null' % locals() run(cmd) @task - def text(inpath, count=5): + def text(inpath, count=0): """ fab hdfs.text:/sample/hani_news.head.txt.gz,5 """ + if count == 0: + cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null' % locals() + else: - cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null | head -n %(count)s' % locals() + cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null | head -n %(count)s' % locals() run(cmd)
Change default value for line number
## Code Before: __author__ = 'Dongjoon Hyun ([email protected])' __license__ = 'Apache License' __version__ = '0.2' from fabric.api import * @task def ls(inpath='/'): """ fab hdfs.ls:/sample """ cmd = '/usr/bin/hadoop fs -ls %(inpath)s 2> /dev/null' % locals() run(cmd) @task def count(inpath): """ fab hdfs.count:/data/text/newsgroup """ cmd = '/usr/bin/hadoop fs -count %(inpath)s 2> /dev/null' % locals() run(cmd) @task def du(inpath): """ fab hdfs.du:/sample """ cmd = '/usr/bin/hadoop fs -du -h %(inpath)s 2> /dev/null' % locals() run(cmd) @task def text(inpath, count=5): """ fab hdfs.text:/sample/hani_news.head.txt.gz,5 """ cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null | head -n %(count)s' % locals() run(cmd) ## Instruction: Change default value for line number ## Code After: __author__ = 'Dongjoon Hyun ([email protected])' __license__ = 'Apache License' __version__ = '0.2' from fabric.api import * @task def ls(inpath='/'): """ fab hdfs.ls:/sample """ cmd = '/usr/bin/hadoop fs -ls %(inpath)s 2> /dev/null' % locals() run(cmd) @task def count(inpath): """ fab hdfs.count:/data/text/newsgroup """ cmd = '/usr/bin/hadoop fs -count %(inpath)s 2> /dev/null' % locals() run(cmd) @task def du(inpath): """ fab hdfs.du:/sample """ cmd = '/usr/bin/hadoop fs -du -h %(inpath)s 2> /dev/null' % locals() run(cmd) @task def text(inpath, count=0): """ fab hdfs.text:/sample/hani_news.head.txt.gz,5 """ if count == 0: cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null' % locals() else: cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null | head -n %(count)s' % locals() run(cmd)
# ... existing code ... @task def text(inpath, count=0): """ # ... modified code ... """ if count == 0: cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null' % locals() else: cmd = '/usr/bin/hadoop fs -text %(inpath)s 2> /dev/null | head -n %(count)s' % locals() run(cmd) # ... rest of the code ...
00aa59468c4dbfde282891f1396e29bd3f28fb62
gunny/reveille/service.py
gunny/reveille/service.py
from twisted.application import internet from twisted.application.service import Service from twisted.internet import reactor from autobahn.websocket import connectWS class ControlService(Service): pass class PlayerService(Service): def __init__(self, factory): self.factory = factory self.conn = None def startService(self): self.factory.startFactory() self.conn = connectWS(self.factory) self.running = 1 def stopService(self): self.factory.stopFactory() if self.conn is not None: self.conn.disconnect() self.running = 0
from twisted.application.service import Service from twisted.internet import stdio from autobahn.websocket import connectWS class CoxswainService(Service): def __init__(self, factory): self.factory = factory self.conn = None def startService(self): #self.factory(ReveilleCommandProtocol()) self.conn = connectWS(self.factory) self.running = True def stopService(self): self.factory.stopFactory() if self.conn is not None: self.conn.disconnect() self.running = False
Rename classes to reflect intended use.
Rename classes to reflect intended use.
Python
bsd-2-clause
davidblewett/gunny,davidblewett/gunny
- from twisted.application import internet from twisted.application.service import Service - from twisted.internet import reactor + from twisted.internet import stdio from autobahn.websocket import connectWS - class ControlService(Service): + class CoxswainService(Service): - pass - - - class PlayerService(Service): def __init__(self, factory): self.factory = factory self.conn = None def startService(self): - self.factory.startFactory() + #self.factory(ReveilleCommandProtocol()) self.conn = connectWS(self.factory) - self.running = 1 + self.running = True def stopService(self): self.factory.stopFactory() if self.conn is not None: self.conn.disconnect() - self.running = 0 + self.running = False
Rename classes to reflect intended use.
## Code Before: from twisted.application import internet from twisted.application.service import Service from twisted.internet import reactor from autobahn.websocket import connectWS class ControlService(Service): pass class PlayerService(Service): def __init__(self, factory): self.factory = factory self.conn = None def startService(self): self.factory.startFactory() self.conn = connectWS(self.factory) self.running = 1 def stopService(self): self.factory.stopFactory() if self.conn is not None: self.conn.disconnect() self.running = 0 ## Instruction: Rename classes to reflect intended use. ## Code After: from twisted.application.service import Service from twisted.internet import stdio from autobahn.websocket import connectWS class CoxswainService(Service): def __init__(self, factory): self.factory = factory self.conn = None def startService(self): #self.factory(ReveilleCommandProtocol()) self.conn = connectWS(self.factory) self.running = True def stopService(self): self.factory.stopFactory() if self.conn is not None: self.conn.disconnect() self.running = False
// ... existing code ... from twisted.application.service import Service from twisted.internet import stdio // ... modified code ... class CoxswainService(Service): ... def startService(self): #self.factory(ReveilleCommandProtocol()) self.conn = connectWS(self.factory) self.running = True ... self.conn.disconnect() self.running = False // ... rest of the code ...
11f43c583fb3b7e8ed2aa74f0f58445a6c2fbecf
bot/api/api.py
bot/api/api.py
from bot.api.domain import Message from bot.api.telegram import TelegramBotApi from bot.storage import State class Api: def __init__(self, telegram_api: TelegramBotApi, state: State): self.telegram_api = telegram_api self.state = state def send_message(self, message: Message, **params): message_params = message.data.copy() message_params.update(params) return self.telegram_api.sendMessage(**message_params) def get_pending_updates(self): return self.get_updates(timeout=0) def get_updates(self, timeout=45): updates = self.telegram_api.getUpdates(offset=self.__get_updates_offset(), timeout=timeout) for update in updates: self.__set_updates_offset(update.update_id) yield update def __get_updates_offset(self): return self.state.next_update_id def __set_updates_offset(self, last_update_id): self.state.next_update_id = str(last_update_id + 1) def __getattr__(self, item): return self.telegram_api.__getattr__(item)
from bot.api.domain import Message from bot.api.telegram import TelegramBotApi from bot.storage import State class Api: def __init__(self, telegram_api: TelegramBotApi, state: State): self.telegram_api = telegram_api self.state = state def send_message(self, message: Message, **params): message_params = message.data.copy() message_params.update(params) return self.telegram_api.sendMessage(**message_params) def get_pending_updates(self): there_are_pending_updates = True while there_are_pending_updates: there_are_pending_updates = False for update in self.get_updates(timeout=0): there_are_pending_updates = True yield update def get_updates(self, timeout=45): updates = self.telegram_api.getUpdates(offset=self.__get_updates_offset(), timeout=timeout) for update in updates: self.__set_updates_offset(update.update_id) yield update def __get_updates_offset(self): return self.state.next_update_id def __set_updates_offset(self, last_update_id): self.state.next_update_id = str(last_update_id + 1) def __getattr__(self, item): return self.telegram_api.__getattr__(item)
Fix get_pending_updates not correctly returning all pending updates
Fix get_pending_updates not correctly returning all pending updates It was only returning the first 100 ones returned in the first telegram API call.
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
from bot.api.domain import Message from bot.api.telegram import TelegramBotApi from bot.storage import State class Api: def __init__(self, telegram_api: TelegramBotApi, state: State): self.telegram_api = telegram_api self.state = state def send_message(self, message: Message, **params): message_params = message.data.copy() message_params.update(params) return self.telegram_api.sendMessage(**message_params) def get_pending_updates(self): + there_are_pending_updates = True + while there_are_pending_updates: + there_are_pending_updates = False - return self.get_updates(timeout=0) + for update in self.get_updates(timeout=0): + there_are_pending_updates = True + yield update def get_updates(self, timeout=45): updates = self.telegram_api.getUpdates(offset=self.__get_updates_offset(), timeout=timeout) for update in updates: self.__set_updates_offset(update.update_id) yield update def __get_updates_offset(self): return self.state.next_update_id def __set_updates_offset(self, last_update_id): self.state.next_update_id = str(last_update_id + 1) def __getattr__(self, item): return self.telegram_api.__getattr__(item)
Fix get_pending_updates not correctly returning all pending updates
## Code Before: from bot.api.domain import Message from bot.api.telegram import TelegramBotApi from bot.storage import State class Api: def __init__(self, telegram_api: TelegramBotApi, state: State): self.telegram_api = telegram_api self.state = state def send_message(self, message: Message, **params): message_params = message.data.copy() message_params.update(params) return self.telegram_api.sendMessage(**message_params) def get_pending_updates(self): return self.get_updates(timeout=0) def get_updates(self, timeout=45): updates = self.telegram_api.getUpdates(offset=self.__get_updates_offset(), timeout=timeout) for update in updates: self.__set_updates_offset(update.update_id) yield update def __get_updates_offset(self): return self.state.next_update_id def __set_updates_offset(self, last_update_id): self.state.next_update_id = str(last_update_id + 1) def __getattr__(self, item): return self.telegram_api.__getattr__(item) ## Instruction: Fix get_pending_updates not correctly returning all pending updates ## Code After: from bot.api.domain import Message from bot.api.telegram import TelegramBotApi from bot.storage import State class Api: def __init__(self, telegram_api: TelegramBotApi, state: State): self.telegram_api = telegram_api self.state = state def send_message(self, message: Message, **params): message_params = message.data.copy() message_params.update(params) return self.telegram_api.sendMessage(**message_params) def get_pending_updates(self): there_are_pending_updates = True while there_are_pending_updates: there_are_pending_updates = False for update in self.get_updates(timeout=0): there_are_pending_updates = True yield update def get_updates(self, timeout=45): updates = self.telegram_api.getUpdates(offset=self.__get_updates_offset(), timeout=timeout) for update in updates: self.__set_updates_offset(update.update_id) yield update def __get_updates_offset(self): return self.state.next_update_id def __set_updates_offset(self, last_update_id): self.state.next_update_id = str(last_update_id + 1) def __getattr__(self, item): return self.telegram_api.__getattr__(item)
# ... existing code ... def get_pending_updates(self): there_are_pending_updates = True while there_are_pending_updates: there_are_pending_updates = False for update in self.get_updates(timeout=0): there_are_pending_updates = True yield update # ... rest of the code ...
7b9b144ce8e7fca38500f5f0c4e2f5ec3b5d9e0f
tests/px_rambar_test.py
tests/px_rambar_test.py
import os import sys from px import px_rambar from px import px_terminal def test_render_bar_happy_path(): names_and_numbers = [(u"apa", 1000), (u"bepa", 300), (u"cepa", 50)] + [ (u"long tail", 1) ] * 300 assert px_rambar.render_bar(10, names_and_numbers) == ( px_terminal.red(u" apa ") + px_terminal.yellow(u" b") + px_terminal.blue(u" ") + px_terminal.inverse_video(u" ") )
import os import sys from px import px_rambar from px import px_terminal def test_render_bar_happy_path(): names_and_numbers = [(u"apa", 1000), (u"bepa", 300), (u"cepa", 50)] + [ (u"long tail", 1) ] * 300 assert px_rambar.render_bar(10, names_and_numbers) == ( px_terminal.red(u" apa ") + px_terminal.yellow(u" b") + px_terminal.blue(u" ") + px_terminal.inverse_video(u" ") ) def test_render_bar_happy_path_unicode(): names_and_numbers = [(u"åpa", 1000), (u"bäpa", 300), (u"cäpa", 50)] + [ (u"lång svans", 1) ] * 300 assert px_rambar.render_bar(10, names_and_numbers) == ( px_terminal.red(u" åpa ") + px_terminal.yellow(u" b") + px_terminal.blue(u" ") + px_terminal.inverse_video(u" ") )
Verify rambar can do unicode
Verify rambar can do unicode
Python
mit
walles/px,walles/px
+ import os import sys from px import px_rambar from px import px_terminal def test_render_bar_happy_path(): names_and_numbers = [(u"apa", 1000), (u"bepa", 300), (u"cepa", 50)] + [ (u"long tail", 1) ] * 300 assert px_rambar.render_bar(10, names_and_numbers) == ( px_terminal.red(u" apa ") + px_terminal.yellow(u" b") + px_terminal.blue(u" ") + px_terminal.inverse_video(u" ") ) + + def test_render_bar_happy_path_unicode(): + names_and_numbers = [(u"åpa", 1000), (u"bäpa", 300), (u"cäpa", 50)] + [ + (u"lång svans", 1) + ] * 300 + assert px_rambar.render_bar(10, names_and_numbers) == ( + px_terminal.red(u" åpa ") + + px_terminal.yellow(u" b") + + px_terminal.blue(u" ") + + px_terminal.inverse_video(u" ") + ) +
Verify rambar can do unicode
## Code Before: import os import sys from px import px_rambar from px import px_terminal def test_render_bar_happy_path(): names_and_numbers = [(u"apa", 1000), (u"bepa", 300), (u"cepa", 50)] + [ (u"long tail", 1) ] * 300 assert px_rambar.render_bar(10, names_and_numbers) == ( px_terminal.red(u" apa ") + px_terminal.yellow(u" b") + px_terminal.blue(u" ") + px_terminal.inverse_video(u" ") ) ## Instruction: Verify rambar can do unicode ## Code After: import os import sys from px import px_rambar from px import px_terminal def test_render_bar_happy_path(): names_and_numbers = [(u"apa", 1000), (u"bepa", 300), (u"cepa", 50)] + [ (u"long tail", 1) ] * 300 assert px_rambar.render_bar(10, names_and_numbers) == ( px_terminal.red(u" apa ") + px_terminal.yellow(u" b") + px_terminal.blue(u" ") + px_terminal.inverse_video(u" ") ) def test_render_bar_happy_path_unicode(): names_and_numbers = [(u"åpa", 1000), (u"bäpa", 300), (u"cäpa", 50)] + [ (u"lång svans", 1) ] * 300 assert px_rambar.render_bar(10, names_and_numbers) == ( px_terminal.red(u" åpa ") + px_terminal.yellow(u" b") + px_terminal.blue(u" ") + px_terminal.inverse_video(u" ") )
# ... existing code ... import os # ... modified code ... ) def test_render_bar_happy_path_unicode(): names_and_numbers = [(u"åpa", 1000), (u"bäpa", 300), (u"cäpa", 50)] + [ (u"lång svans", 1) ] * 300 assert px_rambar.render_bar(10, names_and_numbers) == ( px_terminal.red(u" åpa ") + px_terminal.yellow(u" b") + px_terminal.blue(u" ") + px_terminal.inverse_video(u" ") ) # ... rest of the code ...
7654a81760d228227c3e3ef9ff9cac9927b4674a
scheduler/tests.py
scheduler/tests.py
from django.test import TestCase # Create your tests here.
from django.test import TestCase from .models import Event, Volunteer class VolunteerTestCase(TestCase): def test_gets_public_name(self): event = Event.objects.create(name='event', slug='event', description='event', slots_per_day=1, number_of_days=1) volunteer = Volunteer.objects.create(event=event, real_name='Real Name', email_address='[email protected]', phone_number='123456789') volunteer.ensure_has_public_name() self.assertIsNot(volunteer.public_name, None) self.assertIsNot(volunteer.slug, None)
Add a test for public names
Add a test for public names
Python
mit
thomasleese/rooster,thomasleese/rooster,thomasleese/rooster
from django.test import TestCase - # Create your tests here. + from .models import Event, Volunteer + + class VolunteerTestCase(TestCase): + + def test_gets_public_name(self): + event = Event.objects.create(name='event', slug='event', + description='event', slots_per_day=1, + number_of_days=1) + volunteer = Volunteer.objects.create(event=event, + real_name='Real Name', + email_address='[email protected]', + phone_number='123456789') + volunteer.ensure_has_public_name() + self.assertIsNot(volunteer.public_name, None) + self.assertIsNot(volunteer.slug, None) +
Add a test for public names
## Code Before: from django.test import TestCase # Create your tests here. ## Instruction: Add a test for public names ## Code After: from django.test import TestCase from .models import Event, Volunteer class VolunteerTestCase(TestCase): def test_gets_public_name(self): event = Event.objects.create(name='event', slug='event', description='event', slots_per_day=1, number_of_days=1) volunteer = Volunteer.objects.create(event=event, real_name='Real Name', email_address='[email protected]', phone_number='123456789') volunteer.ensure_has_public_name() self.assertIsNot(volunteer.public_name, None) self.assertIsNot(volunteer.slug, None)
... from .models import Event, Volunteer class VolunteerTestCase(TestCase): def test_gets_public_name(self): event = Event.objects.create(name='event', slug='event', description='event', slots_per_day=1, number_of_days=1) volunteer = Volunteer.objects.create(event=event, real_name='Real Name', email_address='[email protected]', phone_number='123456789') volunteer.ensure_has_public_name() self.assertIsNot(volunteer.public_name, None) self.assertIsNot(volunteer.slug, None) ...
1e64e4f5c584ffaf88cc419765e408cc725f0c19
models.py
models.py
from enum import Enum class LineChange: class ChangeType(Enum): added = 1 deleted = 2 modified = 3 def __init__(self, number=None, change_type=None, filename=None, commit=None): self.number = number self.change_type = change_type self.filename = filename self.commit = commit self.author = None def __str__(self): return ', '.join("{}: {}".format(k, str(v)) for k,v in vars(self).items()) def __repr__(self): return "<{klass} {str}>".format(klass=self.__class__.__name__, str=str(self))
from enum import Enum class LineChange: class ChangeType(Enum): added = 1 deleted = 2 modified = 3 def __init__(self, line_number=None, change_type=None, file_path=None, commit_sha=None): self.line_number = line_number self.change_type = change_type self.file_path = file_path self.commit_sha = commit_sha self.author = None def __str__(self): return ', '.join("{}: {}".format(k, str(v)) for k,v in vars(self).items()) def __repr__(self): return "<{klass} {str}>".format(klass=self.__class__.__name__, str=str(self)) def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other)
Add equlaity comparisons to LineChange class.
Add equlaity comparisons to LineChange class.
Python
mit
chrisma/marvin,chrisma/marvin
from enum import Enum class LineChange: class ChangeType(Enum): - added = 1 + added = 1 - deleted = 2 + deleted = 2 - modified = 3 + modified = 3 - def __init__(self, number=None, change_type=None, filename=None, commit=None): + def __init__(self, line_number=None, change_type=None, file_path=None, commit_sha=None): - self.number = number + self.line_number = line_number self.change_type = change_type - self.filename = filename + self.file_path = file_path - self.commit = commit + self.commit_sha = commit_sha self.author = None def __str__(self): return ', '.join("{}: {}".format(k, str(v)) for k,v in vars(self).items()) def __repr__(self): return "<{klass} {str}>".format(klass=self.__class__.__name__, str=str(self)) + def __eq__(self, other): + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + else: + return False + + def __ne__(self, other): + return not self.__eq__(other)
Add equlaity comparisons to LineChange class.
## Code Before: from enum import Enum class LineChange: class ChangeType(Enum): added = 1 deleted = 2 modified = 3 def __init__(self, number=None, change_type=None, filename=None, commit=None): self.number = number self.change_type = change_type self.filename = filename self.commit = commit self.author = None def __str__(self): return ', '.join("{}: {}".format(k, str(v)) for k,v in vars(self).items()) def __repr__(self): return "<{klass} {str}>".format(klass=self.__class__.__name__, str=str(self)) ## Instruction: Add equlaity comparisons to LineChange class. ## Code After: from enum import Enum class LineChange: class ChangeType(Enum): added = 1 deleted = 2 modified = 3 def __init__(self, line_number=None, change_type=None, file_path=None, commit_sha=None): self.line_number = line_number self.change_type = change_type self.file_path = file_path self.commit_sha = commit_sha self.author = None def __str__(self): return ', '.join("{}: {}".format(k, str(v)) for k,v in vars(self).items()) def __repr__(self): return "<{klass} {str}>".format(klass=self.__class__.__name__, str=str(self)) def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other)
// ... existing code ... class ChangeType(Enum): added = 1 deleted = 2 modified = 3 def __init__(self, line_number=None, change_type=None, file_path=None, commit_sha=None): self.line_number = line_number self.change_type = change_type self.file_path = file_path self.commit_sha = commit_sha self.author = None // ... modified code ... return "<{klass} {str}>".format(klass=self.__class__.__name__, str=str(self)) def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) // ... rest of the code ...
7e373bd4b3c111b38d983e809aa443ff242860db
tests/test_pipelines/test_python.py
tests/test_pipelines/test_python.py
from mock import patch, PropertyMock from .. import BaseTestCase class TestPythonVirtualenv(BaseTestCase): def setUp(self): # Mocking State patcher = patch('facio.pipeline.python.virtualenv.state', new_callable=PropertyMock, create=True) self.mock_state = patcher.start() self.mock_state.project_name = 'foo' self.mock_state.context_variables = { 'PROJECT_NAME': 'foo'} self.addCleanup(patcher.stop)
from facio.pipeline.python.virtualenv import Virtualenv from mock import patch, PropertyMock from .. import BaseTestCase class TestPythonVirtualenv(BaseTestCase): def setUp(self): # Mocking State patcher = patch('facio.state.state.state', new_callable=PropertyMock, create=True) self.mock_state = patcher.start() self.mock_state.project_name = 'foo' self.mock_state.context_variables = { 'PROJECT_NAME': 'foo'} self.addCleanup(patcher.stop) @patch('facio.base.input') def test_get_name(self, mock_input): mock_input.return_value = 'bar' i = Virtualenv() name = i.get_name() self.assertEqual(name, 'bar') @patch('facio.base.input') def test_get_name_default(self, mock_input): mock_input.return_value = '' i = Virtualenv() name = i.get_name() self.assertEqual(name, 'foo')
Test for getting virtualenv name, prompting the user
Test for getting virtualenv name, prompting the user
Python
bsd-3-clause
krak3n/Facio,krak3n/Facio,krak3n/Facio,krak3n/Facio,krak3n/Facio
+ from facio.pipeline.python.virtualenv import Virtualenv from mock import patch, PropertyMock from .. import BaseTestCase class TestPythonVirtualenv(BaseTestCase): def setUp(self): # Mocking State - patcher = patch('facio.pipeline.python.virtualenv.state', + patcher = patch('facio.state.state.state', new_callable=PropertyMock, create=True) self.mock_state = patcher.start() self.mock_state.project_name = 'foo' self.mock_state.context_variables = { 'PROJECT_NAME': 'foo'} self.addCleanup(patcher.stop) + @patch('facio.base.input') + def test_get_name(self, mock_input): + mock_input.return_value = 'bar' + + i = Virtualenv() + name = i.get_name() + + self.assertEqual(name, 'bar') + + @patch('facio.base.input') + def test_get_name_default(self, mock_input): + mock_input.return_value = '' + + i = Virtualenv() + name = i.get_name() + + self.assertEqual(name, 'foo') +
Test for getting virtualenv name, prompting the user
## Code Before: from mock import patch, PropertyMock from .. import BaseTestCase class TestPythonVirtualenv(BaseTestCase): def setUp(self): # Mocking State patcher = patch('facio.pipeline.python.virtualenv.state', new_callable=PropertyMock, create=True) self.mock_state = patcher.start() self.mock_state.project_name = 'foo' self.mock_state.context_variables = { 'PROJECT_NAME': 'foo'} self.addCleanup(patcher.stop) ## Instruction: Test for getting virtualenv name, prompting the user ## Code After: from facio.pipeline.python.virtualenv import Virtualenv from mock import patch, PropertyMock from .. import BaseTestCase class TestPythonVirtualenv(BaseTestCase): def setUp(self): # Mocking State patcher = patch('facio.state.state.state', new_callable=PropertyMock, create=True) self.mock_state = patcher.start() self.mock_state.project_name = 'foo' self.mock_state.context_variables = { 'PROJECT_NAME': 'foo'} self.addCleanup(patcher.stop) @patch('facio.base.input') def test_get_name(self, mock_input): mock_input.return_value = 'bar' i = Virtualenv() name = i.get_name() self.assertEqual(name, 'bar') @patch('facio.base.input') def test_get_name_default(self, mock_input): mock_input.return_value = '' i = Virtualenv() name = i.get_name() self.assertEqual(name, 'foo')
... from facio.pipeline.python.virtualenv import Virtualenv from mock import patch, PropertyMock ... # Mocking State patcher = patch('facio.state.state.state', new_callable=PropertyMock, ... self.addCleanup(patcher.stop) @patch('facio.base.input') def test_get_name(self, mock_input): mock_input.return_value = 'bar' i = Virtualenv() name = i.get_name() self.assertEqual(name, 'bar') @patch('facio.base.input') def test_get_name_default(self, mock_input): mock_input.return_value = '' i = Virtualenv() name = i.get_name() self.assertEqual(name, 'foo') ...
a2abc6342162c9158551b810f4d666d6d13dcd15
client/python/plot_request_times.py
client/python/plot_request_times.py
import requests r = requests.get('http://localhost:8081/monitor_results/1') print(r.json()) for monitoring_data in r.json(): print 'URL: ' + monitoring_data['urlToMonitor']['url']
import requests from plotly.offline import plot import plotly.graph_objs as go r = requests.get('http://localhost:8081/monitor_results/1') print(r.json()) # build traces for plotting from monitoring data request_times = list() timestamps = list() timestamp = 0 url = r.json()[0]['urlToMonitor']['url'] for monitoring_data in r.json(): request_time = monitoring_data['timeNeededForRequest'] request_times.append(request_time) timestamps.append(timestamp) timestamp = timestamp + 1 plot([go.Scatter(x = timestamps, y = request_times, name = 'THE NAME'), go.Scatter(x = timestamps, y = request_times, name = 'THE OTHER NAME')], filename='request_times.html')
Add prototype for plotting client
Add prototype for plotting client
Python
mit
gernd/simple-site-mon
import requests + from plotly.offline import plot + import plotly.graph_objs as go r = requests.get('http://localhost:8081/monitor_results/1') print(r.json()) + # build traces for plotting from monitoring data + request_times = list() + timestamps = list() + timestamp = 0 + url = r.json()[0]['urlToMonitor']['url'] for monitoring_data in r.json(): - print 'URL: ' + monitoring_data['urlToMonitor']['url'] + request_time = monitoring_data['timeNeededForRequest'] + request_times.append(request_time) + timestamps.append(timestamp) + timestamp = timestamp + 1 + plot([go.Scatter(x = timestamps, y = request_times, name = 'THE NAME'), go.Scatter(x = timestamps, y = request_times, name = + 'THE OTHER NAME')], filename='request_times.html') +
Add prototype for plotting client
## Code Before: import requests r = requests.get('http://localhost:8081/monitor_results/1') print(r.json()) for monitoring_data in r.json(): print 'URL: ' + monitoring_data['urlToMonitor']['url'] ## Instruction: Add prototype for plotting client ## Code After: import requests from plotly.offline import plot import plotly.graph_objs as go r = requests.get('http://localhost:8081/monitor_results/1') print(r.json()) # build traces for plotting from monitoring data request_times = list() timestamps = list() timestamp = 0 url = r.json()[0]['urlToMonitor']['url'] for monitoring_data in r.json(): request_time = monitoring_data['timeNeededForRequest'] request_times.append(request_time) timestamps.append(timestamp) timestamp = timestamp + 1 plot([go.Scatter(x = timestamps, y = request_times, name = 'THE NAME'), go.Scatter(x = timestamps, y = request_times, name = 'THE OTHER NAME')], filename='request_times.html')
# ... existing code ... import requests from plotly.offline import plot import plotly.graph_objs as go # ... modified code ... print(r.json()) # build traces for plotting from monitoring data request_times = list() timestamps = list() timestamp = 0 url = r.json()[0]['urlToMonitor']['url'] for monitoring_data in r.json(): request_time = monitoring_data['timeNeededForRequest'] request_times.append(request_time) timestamps.append(timestamp) timestamp = timestamp + 1 plot([go.Scatter(x = timestamps, y = request_times, name = 'THE NAME'), go.Scatter(x = timestamps, y = request_times, name = 'THE OTHER NAME')], filename='request_times.html') # ... rest of the code ...
85220f2830d355245803965ee57886e5c1268833
tests/unit/test_twitter.py
tests/unit/test_twitter.py
from unfurl import Unfurl import unittest class TestTwitter(unittest.TestCase): def test_twitter(self): """ Test a tyipcal and a unique Discord url """ # unit test for a unique Discord url. test = Unfurl() test.add_to_queue(data_type='url', key=None, value='https://twitter.com/_RyanBenson/status/1098230906194546688') test.parse_queue() # test number of nodes self.assertEqual(len(test.nodes.keys()), 13) self.assertEqual(test.total_nodes, 13) # is processing finished empty self.assertTrue(test.queue.empty()) self.assertEqual(len(test.edges), 0) if __name__ == '__main__': unittest.main()
from unfurl import Unfurl import unittest class TestTwitter(unittest.TestCase): def test_twitter(self): """ Test a typical and a unique Twitter url """ test = Unfurl() test.add_to_queue( data_type='url', key=None, value='https://twitter.com/_RyanBenson/status/1098230906194546688') test.parse_queue() # check the number of nodes self.assertEqual(len(test.nodes.keys()), 13) self.assertEqual(test.total_nodes, 13) # confirm that snowflake was detected self.assertIn('Twitter Snowflakes', test.nodes[9].hover) # embedded timestamp parses correctly self.assertEqual('2019-02-20 14:40:26.837', test.nodes[13].value) # make sure the queue finished empty self.assertTrue(test.queue.empty()) self.assertEqual(len(test.edges), 0) if __name__ == '__main__': unittest.main()
Update Twitter test to be more robust
Update Twitter test to be more robust
Python
apache-2.0
obsidianforensics/unfurl,obsidianforensics/unfurl
from unfurl import Unfurl import unittest + class TestTwitter(unittest.TestCase): def test_twitter(self): - """ Test a tyipcal and a unique Discord url """ + """ Test a typical and a unique Twitter url """ + - - # unit test for a unique Discord url. test = Unfurl() - test.add_to_queue(data_type='url', key=None, + test.add_to_queue( + data_type='url', key=None, value='https://twitter.com/_RyanBenson/status/1098230906194546688') test.parse_queue() - # test number of nodes + # check the number of nodes self.assertEqual(len(test.nodes.keys()), 13) self.assertEqual(test.total_nodes, 13) - # is processing finished empty + # confirm that snowflake was detected + self.assertIn('Twitter Snowflakes', test.nodes[9].hover) + + # embedded timestamp parses correctly + self.assertEqual('2019-02-20 14:40:26.837', test.nodes[13].value) + + # make sure the queue finished empty self.assertTrue(test.queue.empty()) self.assertEqual(len(test.edges), 0) + if __name__ == '__main__': unittest.main() +
Update Twitter test to be more robust
## Code Before: from unfurl import Unfurl import unittest class TestTwitter(unittest.TestCase): def test_twitter(self): """ Test a tyipcal and a unique Discord url """ # unit test for a unique Discord url. test = Unfurl() test.add_to_queue(data_type='url', key=None, value='https://twitter.com/_RyanBenson/status/1098230906194546688') test.parse_queue() # test number of nodes self.assertEqual(len(test.nodes.keys()), 13) self.assertEqual(test.total_nodes, 13) # is processing finished empty self.assertTrue(test.queue.empty()) self.assertEqual(len(test.edges), 0) if __name__ == '__main__': unittest.main() ## Instruction: Update Twitter test to be more robust ## Code After: from unfurl import Unfurl import unittest class TestTwitter(unittest.TestCase): def test_twitter(self): """ Test a typical and a unique Twitter url """ test = Unfurl() test.add_to_queue( data_type='url', key=None, value='https://twitter.com/_RyanBenson/status/1098230906194546688') test.parse_queue() # check the number of nodes self.assertEqual(len(test.nodes.keys()), 13) self.assertEqual(test.total_nodes, 13) # confirm that snowflake was detected self.assertIn('Twitter Snowflakes', test.nodes[9].hover) # embedded timestamp parses correctly self.assertEqual('2019-02-20 14:40:26.837', test.nodes[13].value) # make sure the queue finished empty self.assertTrue(test.queue.empty()) self.assertEqual(len(test.edges), 0) if __name__ == '__main__': unittest.main()
// ... existing code ... class TestTwitter(unittest.TestCase): // ... modified code ... def test_twitter(self): """ Test a typical and a unique Twitter url """ test = Unfurl() test.add_to_queue( data_type='url', key=None, value='https://twitter.com/_RyanBenson/status/1098230906194546688') ... # check the number of nodes self.assertEqual(len(test.nodes.keys()), 13) ... # confirm that snowflake was detected self.assertIn('Twitter Snowflakes', test.nodes[9].hover) # embedded timestamp parses correctly self.assertEqual('2019-02-20 14:40:26.837', test.nodes[13].value) # make sure the queue finished empty self.assertTrue(test.queue.empty()) ... if __name__ == '__main__': // ... rest of the code ...
0f54780e142cb6bd15df2ed702bd4fa4b2d3fe79
keys.py
keys.py
keys = dict( consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', )
keys = dict( consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', )
Use spaces instead of tabs
Use spaces instead of tabs
Python
mit
bman4789/weatherBot,bman4789/weatherBot,BrianMitchL/weatherBot
keys = dict( - consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - access_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + access_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', - access_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + access_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', )
Use spaces instead of tabs
## Code Before: keys = dict( consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', ) ## Instruction: Use spaces instead of tabs ## Code After: keys = dict( consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', )
... keys = dict( consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', access_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', ) ...
2ecdd2feb18ef23610e55242b70b64ce0d6f6fe9
src/sentry/app.py
src/sentry/app.py
from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) if cls is None: raise ImportError('Unable to find module %s' % path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
Raise an import error when import_string fails on get_buffer
Raise an import error when import_string fails on get_buffer
Python
bsd-3-clause
mvaled/sentry,llonchj/sentry,argonemyth/sentry,songyi199111/sentry,1tush/sentry,fotinakis/sentry,BayanGroup/sentry,alexm92/sentry,NickPresta/sentry,fotinakis/sentry,jokey2k/sentry,looker/sentry,fuziontech/sentry,imankulov/sentry,felixbuenemann/sentry,boneyao/sentry,Kryz/sentry,drcapulet/sentry,rdio/sentry,SilentCircle/sentry,Natim/sentry,jean/sentry,kevinastone/sentry,gencer/sentry,gg7/sentry,zenefits/sentry,gencer/sentry,jokey2k/sentry,ifduyue/sentry,ngonzalvez/sentry,kevinastone/sentry,nicholasserra/sentry,wujuguang/sentry,alexm92/sentry,rdio/sentry,felixbuenemann/sentry,pauloschilling/sentry,JTCunning/sentry,hongliang5623/sentry,JamesMura/sentry,mvaled/sentry,ngonzalvez/sentry,JamesMura/sentry,daevaorn/sentry,mvaled/sentry,imankulov/sentry,wujuguang/sentry,korealerts1/sentry,argonemyth/sentry,JTCunning/sentry,drcapulet/sentry,BuildingLink/sentry,zenefits/sentry,kevinlondon/sentry,NickPresta/sentry,jokey2k/sentry,beeftornado/sentry,1tush/sentry,songyi199111/sentry,mvaled/sentry,Kryz/sentry,ewdurbin/sentry,llonchj/sentry,rdio/sentry,boneyao/sentry,Natim/sentry,BuildingLink/sentry,JackDanger/sentry,ewdurbin/sentry,mitsuhiko/sentry,Natim/sentry,korealerts1/sentry,camilonova/sentry,SilentCircle/sentry,beni55/sentry,jean/sentry,TedaLIEz/sentry,SilentCircle/sentry,daevaorn/sentry,nicholasserra/sentry,looker/sentry,mvaled/sentry,1tush/sentry,ewdurbin/sentry,wujuguang/sentry,SilentCircle/sentry,alexm92/sentry,felixbuenemann/sentry,hongliang5623/sentry,Kryz/sentry,JTCunning/sentry,NickPresta/sentry,fotinakis/sentry,TedaLIEz/sentry,mitsuhiko/sentry,vperron/sentry,beni55/sentry,vperron/sentry,zenefits/sentry,JamesMura/sentry,kevinlondon/sentry,TedaLIEz/sentry,camilonova/sentry,fotinakis/sentry,wong2/sentry,BayanGroup/sentry,nicholasserra/sentry,BuildingLink/sentry,wong2/sentry,beeftornado/sentry,zenefits/sentry,boneyao/sentry,songyi199111/sentry,drcapulet/sentry,ifduyue/sentry,gencer/sentry,llonchj/sentry,JackDanger/sentry,BuildingLink/sentry,pauloschilling/sentry,daevaorn/sentry,beeftornado/sentry,ifduyue/sentry,gg7/sentry,ifduyue/sentry,beni55/sentry,argonemyth/sentry,kevinlondon/sentry,JamesMura/sentry,BuildingLink/sentry,kevinastone/sentry,ifduyue/sentry,jean/sentry,NickPresta/sentry,ngonzalvez/sentry,jean/sentry,pauloschilling/sentry,fuziontech/sentry,korealerts1/sentry,imankulov/sentry,looker/sentry,hongliang5623/sentry,mvaled/sentry,vperron/sentry,daevaorn/sentry,fuziontech/sentry,JamesMura/sentry,JackDanger/sentry,gencer/sentry,looker/sentry,jean/sentry,wong2/sentry,BayanGroup/sentry,rdio/sentry,zenefits/sentry,looker/sentry,camilonova/sentry,gg7/sentry,gencer/sentry
from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) + if cls is None: + raise ImportError('Unable to find module %s' % path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
Raise an import error when import_string fails on get_buffer
## Code Before: from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State() ## Instruction: Raise an import error when import_string fails on get_buffer ## Code After: from sentry.conf import settings from sentry.utils.imports import import_string from threading import local class State(local): request = None def get_buffer(path, options): cls = import_string(path) if cls is None: raise ImportError('Unable to find module %s' % path) return cls(**options) buffer = get_buffer(settings.BUFFER, settings.BUFFER_OPTIONS) env = State()
// ... existing code ... cls = import_string(path) if cls is None: raise ImportError('Unable to find module %s' % path) return cls(**options) // ... rest of the code ...
dd3cc71bb09ab2fb265b3f4bdda69cb1880842c6
tests/utils_test.py
tests/utils_test.py
import unittest from zttf.utils import fixed_version, binary_search_parameters class TestUtils(unittest.TestCase): def test_fixed_version(self): cases = [ (0x00005000, 0.5), (0x00010000, 1.0), (0x00035000, 3.5), (0x00105000, 10.5) ] for case in cases: self.assertEqual(fixed_version(case[0]), case[1]) def test_binary_parameters(self): cases = { 39: (32, 5), 10: (8, 3), 19: (16, 4) } for n, result in cases.items(): self.assertEqual(binary_search_parameters(n), result)
import unittest import struct from zttf.utils import fixed_version, binary_search_parameters, ttf_checksum class TestUtils(unittest.TestCase): def test_fixed_version(self): cases = [ (0x00005000, 0.5), (0x00010000, 1.0), (0x00035000, 3.5), (0x00105000, 10.5) ] for case in cases: self.assertEqual(fixed_version(case[0]), case[1]) def test_binary_parameters(self): cases = { 39: (32, 5), 10: (8, 3), 19: (16, 4) } for n, result in cases.items(): self.assertEqual(binary_search_parameters(n), result) def test_checksum(self): data = struct.pack(">12I", *range(0, 12)) self.assertEqual(len(data), 48) self.assertEqual(ttf_checksum(data), 66) self.assertEqual(ttf_checksum(struct.pack(">12I", *range(1000, 13000, 1000))), 78000) self.assertEqual(ttf_checksum(struct.pack(">512I", *range(1024, 1024 * 2048, 4096))), 0x1FF80000)
Add a simple test for the checksum routine.
Add a simple test for the checksum routine.
Python
apache-2.0
zathras777/zttf
import unittest + import struct - from zttf.utils import fixed_version, binary_search_parameters + from zttf.utils import fixed_version, binary_search_parameters, ttf_checksum class TestUtils(unittest.TestCase): def test_fixed_version(self): cases = [ (0x00005000, 0.5), (0x00010000, 1.0), (0x00035000, 3.5), (0x00105000, 10.5) ] for case in cases: self.assertEqual(fixed_version(case[0]), case[1]) def test_binary_parameters(self): cases = { 39: (32, 5), 10: (8, 3), 19: (16, 4) } for n, result in cases.items(): self.assertEqual(binary_search_parameters(n), result) + def test_checksum(self): + data = struct.pack(">12I", *range(0, 12)) + self.assertEqual(len(data), 48) + self.assertEqual(ttf_checksum(data), 66) + self.assertEqual(ttf_checksum(struct.pack(">12I", *range(1000, 13000, 1000))), 78000) + self.assertEqual(ttf_checksum(struct.pack(">512I", *range(1024, 1024 * 2048, 4096))), 0x1FF80000)
Add a simple test for the checksum routine.
## Code Before: import unittest from zttf.utils import fixed_version, binary_search_parameters class TestUtils(unittest.TestCase): def test_fixed_version(self): cases = [ (0x00005000, 0.5), (0x00010000, 1.0), (0x00035000, 3.5), (0x00105000, 10.5) ] for case in cases: self.assertEqual(fixed_version(case[0]), case[1]) def test_binary_parameters(self): cases = { 39: (32, 5), 10: (8, 3), 19: (16, 4) } for n, result in cases.items(): self.assertEqual(binary_search_parameters(n), result) ## Instruction: Add a simple test for the checksum routine. ## Code After: import unittest import struct from zttf.utils import fixed_version, binary_search_parameters, ttf_checksum class TestUtils(unittest.TestCase): def test_fixed_version(self): cases = [ (0x00005000, 0.5), (0x00010000, 1.0), (0x00035000, 3.5), (0x00105000, 10.5) ] for case in cases: self.assertEqual(fixed_version(case[0]), case[1]) def test_binary_parameters(self): cases = { 39: (32, 5), 10: (8, 3), 19: (16, 4) } for n, result in cases.items(): self.assertEqual(binary_search_parameters(n), result) def test_checksum(self): data = struct.pack(">12I", *range(0, 12)) self.assertEqual(len(data), 48) self.assertEqual(ttf_checksum(data), 66) self.assertEqual(ttf_checksum(struct.pack(">12I", *range(1000, 13000, 1000))), 78000) self.assertEqual(ttf_checksum(struct.pack(">512I", *range(1024, 1024 * 2048, 4096))), 0x1FF80000)
... import unittest import struct from zttf.utils import fixed_version, binary_search_parameters, ttf_checksum ... self.assertEqual(binary_search_parameters(n), result) def test_checksum(self): data = struct.pack(">12I", *range(0, 12)) self.assertEqual(len(data), 48) self.assertEqual(ttf_checksum(data), 66) self.assertEqual(ttf_checksum(struct.pack(">12I", *range(1000, 13000, 1000))), 78000) self.assertEqual(ttf_checksum(struct.pack(">512I", *range(1024, 1024 * 2048, 4096))), 0x1FF80000) ...
e767d25a5e6c088cac6465ce95706e77149f39ef
tests/integration/states/cmd.py
tests/integration/states/cmd.py
''' Tests for the file state ''' # Import python libs import os # # Import salt libs from saltunittest import TestLoader, TextTestRunner import integration from integration import TestDaemon class CMDTest(integration.ModuleCase): ''' Validate the cmd state ''' def test_run(self): ''' cmd.run ''' ret = self.run_state('cmd.run', name='ls', cwd='/') result = ret[next(iter(ret))]['result'] self.assertTrue(result) def test_test_run(self): ''' cmd.run test interface ''' ret = self.run_state('cmd.run', name='ls', test=True) result = ret[next(iter(ret))]['result'] self.assertIsNone(result)
''' Tests for the file state ''' # Import python libs # Import salt libs import integration import tempfile class CMDTest(integration.ModuleCase): ''' Validate the cmd state ''' def test_run(self): ''' cmd.run ''' ret = self.run_state('cmd.run', name='ls', cwd=tempfile.gettempdir()) result = ret[next(iter(ret))]['result'] self.assertTrue(result) def test_test_run(self): ''' cmd.run test interface ''' ret = self.run_state('cmd.run', name='ls', cwd=tempfile.gettempdir(), test=True) result = ret[next(iter(ret))]['result'] self.assertIsNone(result)
Use tempdir to ensure there will always be a directory which can be accessed.
Use tempdir to ensure there will always be a directory which can be accessed.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' Tests for the file state ''' # Import python libs + - import os - # # Import salt libs - from saltunittest import TestLoader, TextTestRunner import integration - from integration import TestDaemon + import tempfile class CMDTest(integration.ModuleCase): ''' Validate the cmd state ''' def test_run(self): ''' cmd.run ''' + - ret = self.run_state('cmd.run', name='ls', cwd='/') + ret = self.run_state('cmd.run', name='ls', cwd=tempfile.gettempdir()) result = ret[next(iter(ret))]['result'] self.assertTrue(result) def test_test_run(self): ''' cmd.run test interface ''' - ret = self.run_state('cmd.run', name='ls', test=True) + ret = self.run_state('cmd.run', name='ls', + cwd=tempfile.gettempdir(), test=True) result = ret[next(iter(ret))]['result'] self.assertIsNone(result)
Use tempdir to ensure there will always be a directory which can be accessed.
## Code Before: ''' Tests for the file state ''' # Import python libs import os # # Import salt libs from saltunittest import TestLoader, TextTestRunner import integration from integration import TestDaemon class CMDTest(integration.ModuleCase): ''' Validate the cmd state ''' def test_run(self): ''' cmd.run ''' ret = self.run_state('cmd.run', name='ls', cwd='/') result = ret[next(iter(ret))]['result'] self.assertTrue(result) def test_test_run(self): ''' cmd.run test interface ''' ret = self.run_state('cmd.run', name='ls', test=True) result = ret[next(iter(ret))]['result'] self.assertIsNone(result) ## Instruction: Use tempdir to ensure there will always be a directory which can be accessed. ## Code After: ''' Tests for the file state ''' # Import python libs # Import salt libs import integration import tempfile class CMDTest(integration.ModuleCase): ''' Validate the cmd state ''' def test_run(self): ''' cmd.run ''' ret = self.run_state('cmd.run', name='ls', cwd=tempfile.gettempdir()) result = ret[next(iter(ret))]['result'] self.assertTrue(result) def test_test_run(self): ''' cmd.run test interface ''' ret = self.run_state('cmd.run', name='ls', cwd=tempfile.gettempdir(), test=True) result = ret[next(iter(ret))]['result'] self.assertIsNone(result)
# ... existing code ... # Import python libs # Import salt libs import integration import tempfile # ... modified code ... ''' ret = self.run_state('cmd.run', name='ls', cwd=tempfile.gettempdir()) result = ret[next(iter(ret))]['result'] ... ''' ret = self.run_state('cmd.run', name='ls', cwd=tempfile.gettempdir(), test=True) result = ret[next(iter(ret))]['result'] # ... rest of the code ...
fff0087f82c3f79d5e60e32071a4e89478d8b85e
tests/test_element.py
tests/test_element.py
import pkg_resources pkg_resources.require('cothread') import cothread import rml.element def test_create_element(): e = rml.element.Element('BPM', 6.0) assert e.get_type() == 'BPM' assert e.get_length() == 6.0 def test_add_element_to_family(): e = rml.element.Element('dummy', 0.0) e.add_to_family('fam') assert 'fam' in e.get_families() def test_get_pv_value(): PV = 'SR22C-DI-EBPM-04:SA:X' e = rml.element.Element('dummy', 0.0, pv=PV) result = e.get_pv('x') assert isinstance(result, float)
import pkg_resources pkg_resources.require('cothread') import cothread import rml import rml.element def test_create_element(): e = rml.element.Element('BPM', 6.0) assert e.get_type() == 'BPM' assert e.get_length() == 6.0 def test_add_element_to_family(): e = rml.element.Element('dummy', 0.0) e.add_to_family('fam') assert 'fam' in e.get_families() def test_get_pv_value(): PV = 'SR22C-DI-EBPM-04:SA:X' e = rml.element.Element('dummy', 0.0) e.set_pv('x', PV) result = e.get_pv('x') assert isinstance(result, float) with pytest.raises(rml.ConfigException): e.get_pv('y')
Make pvs in Element behave more realistically.
Make pvs in Element behave more realistically.
Python
apache-2.0
razvanvasile/RML,willrogers/pml,willrogers/pml
import pkg_resources pkg_resources.require('cothread') import cothread + import rml import rml.element def test_create_element(): e = rml.element.Element('BPM', 6.0) assert e.get_type() == 'BPM' assert e.get_length() == 6.0 def test_add_element_to_family(): e = rml.element.Element('dummy', 0.0) e.add_to_family('fam') assert 'fam' in e.get_families() def test_get_pv_value(): PV = 'SR22C-DI-EBPM-04:SA:X' - e = rml.element.Element('dummy', 0.0, pv=PV) + e = rml.element.Element('dummy', 0.0) + e.set_pv('x', PV) result = e.get_pv('x') assert isinstance(result, float) + with pytest.raises(rml.ConfigException): + e.get_pv('y')
Make pvs in Element behave more realistically.
## Code Before: import pkg_resources pkg_resources.require('cothread') import cothread import rml.element def test_create_element(): e = rml.element.Element('BPM', 6.0) assert e.get_type() == 'BPM' assert e.get_length() == 6.0 def test_add_element_to_family(): e = rml.element.Element('dummy', 0.0) e.add_to_family('fam') assert 'fam' in e.get_families() def test_get_pv_value(): PV = 'SR22C-DI-EBPM-04:SA:X' e = rml.element.Element('dummy', 0.0, pv=PV) result = e.get_pv('x') assert isinstance(result, float) ## Instruction: Make pvs in Element behave more realistically. ## Code After: import pkg_resources pkg_resources.require('cothread') import cothread import rml import rml.element def test_create_element(): e = rml.element.Element('BPM', 6.0) assert e.get_type() == 'BPM' assert e.get_length() == 6.0 def test_add_element_to_family(): e = rml.element.Element('dummy', 0.0) e.add_to_family('fam') assert 'fam' in e.get_families() def test_get_pv_value(): PV = 'SR22C-DI-EBPM-04:SA:X' e = rml.element.Element('dummy', 0.0) e.set_pv('x', PV) result = e.get_pv('x') assert isinstance(result, float) with pytest.raises(rml.ConfigException): e.get_pv('y')
... import cothread import rml import rml.element ... PV = 'SR22C-DI-EBPM-04:SA:X' e = rml.element.Element('dummy', 0.0) e.set_pv('x', PV) result = e.get_pv('x') ... assert isinstance(result, float) with pytest.raises(rml.ConfigException): e.get_pv('y') ...
1b0fdfdc2ff49d6dfc7d239b5a9cda1ff334f20b
candidates/cache.py
candidates/cache.py
from django.core.cache import cache def post_cache_key(mapit_area_id): """Form the cache key used for post data""" return "post:{0}".format(mapit_area_id) def invalidate_posts(post_ids): for post_id in post_ids: post_key = post_cache_key(post_id) cache.delete(post_key) def get_post_cached(api, mapit_area_id): post_key = post_cache_key(mapit_area_id) result_from_cache = cache.get(post_key) if result_from_cache is not None: return result_from_cache mp_post = api.posts(mapit_area_id).get( embed='membership.person.membership.organization') cache.set(post_key, mp_post, None) return mp_post
from django.core.cache import cache def post_cache_key(mapit_area_id): """Form the cache key used for post data""" return "post:{0}".format(mapit_area_id) def person_cache_key(person_id): """Form the cache key used for person data""" return "person:{0}".format(person_id) def invalidate_posts(post_ids): """Delete cache entries for all of these PopIt posts""" cache.delete_many(post_cache_key(post_id) for post_id in post_ids) def invalidate_person(person_id): """Delete the cache entry for a particular person's PopIt data""" person_key = person_cache_key(person_id) cache.delete(person_key) def get_post_cached(api, mapit_area_id): post_key = post_cache_key(mapit_area_id) result_from_cache = cache.get(post_key) if result_from_cache is not None: return result_from_cache mp_post = api.posts(mapit_area_id).get( embed='membership.person.membership.organization') # Add posts data with an indefinite time-out (we should be # invalidating the cached on any change). cache.set(post_key, mp_post, None) return mp_post def get_person_cached(api, person_id): person_key = person_cache_key(person_id) result_from_cache = cache.get(person_key) if result_from_cache is not None: return result_from_cache person_data = api.persons(person_id).get( embed='membership.organization' ) # Add it the person data to the cache with a timeout of # a day. cache.set(person_key, person_data, 86400) return person_data
Add functions for caching person data from PopIt
Add functions for caching person data from PopIt
Python
agpl-3.0
mysociety/yournextrepresentative,openstate/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,openstate/yournextrepresentative,mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,datamade/yournextmp-popit,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,openstate/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,neavouli/yournextrepresentative,datamade/yournextmp-popit,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,openstate/yournextrepresentative
from django.core.cache import cache def post_cache_key(mapit_area_id): """Form the cache key used for post data""" return "post:{0}".format(mapit_area_id) + def person_cache_key(person_id): + """Form the cache key used for person data""" + return "person:{0}".format(person_id) + def invalidate_posts(post_ids): - for post_id in post_ids: - post_key = post_cache_key(post_id) + """Delete cache entries for all of these PopIt posts""" + cache.delete_many(post_cache_key(post_id) for post_id in post_ids) + + def invalidate_person(person_id): + """Delete the cache entry for a particular person's PopIt data""" + person_key = person_cache_key(person_id) - cache.delete(post_key) + cache.delete(person_key) def get_post_cached(api, mapit_area_id): post_key = post_cache_key(mapit_area_id) result_from_cache = cache.get(post_key) if result_from_cache is not None: return result_from_cache mp_post = api.posts(mapit_area_id).get( embed='membership.person.membership.organization') + # Add posts data with an indefinite time-out (we should be + # invalidating the cached on any change). cache.set(post_key, mp_post, None) return mp_post + def get_person_cached(api, person_id): + person_key = person_cache_key(person_id) + result_from_cache = cache.get(person_key) + if result_from_cache is not None: + return result_from_cache + person_data = api.persons(person_id).get( + embed='membership.organization' + ) + # Add it the person data to the cache with a timeout of + # a day. + cache.set(person_key, person_data, 86400) + return person_data +
Add functions for caching person data from PopIt
## Code Before: from django.core.cache import cache def post_cache_key(mapit_area_id): """Form the cache key used for post data""" return "post:{0}".format(mapit_area_id) def invalidate_posts(post_ids): for post_id in post_ids: post_key = post_cache_key(post_id) cache.delete(post_key) def get_post_cached(api, mapit_area_id): post_key = post_cache_key(mapit_area_id) result_from_cache = cache.get(post_key) if result_from_cache is not None: return result_from_cache mp_post = api.posts(mapit_area_id).get( embed='membership.person.membership.organization') cache.set(post_key, mp_post, None) return mp_post ## Instruction: Add functions for caching person data from PopIt ## Code After: from django.core.cache import cache def post_cache_key(mapit_area_id): """Form the cache key used for post data""" return "post:{0}".format(mapit_area_id) def person_cache_key(person_id): """Form the cache key used for person data""" return "person:{0}".format(person_id) def invalidate_posts(post_ids): """Delete cache entries for all of these PopIt posts""" cache.delete_many(post_cache_key(post_id) for post_id in post_ids) def invalidate_person(person_id): """Delete the cache entry for a particular person's PopIt data""" person_key = person_cache_key(person_id) cache.delete(person_key) def get_post_cached(api, mapit_area_id): post_key = post_cache_key(mapit_area_id) result_from_cache = cache.get(post_key) if result_from_cache is not None: return result_from_cache mp_post = api.posts(mapit_area_id).get( embed='membership.person.membership.organization') # Add posts data with an indefinite time-out (we should be # invalidating the cached on any change). cache.set(post_key, mp_post, None) return mp_post def get_person_cached(api, person_id): person_key = person_cache_key(person_id) result_from_cache = cache.get(person_key) if result_from_cache is not None: return result_from_cache person_data = api.persons(person_id).get( embed='membership.organization' ) # Add it the person data to the cache with a timeout of # a day. cache.set(person_key, person_data, 86400) return person_data
... def person_cache_key(person_id): """Form the cache key used for person data""" return "person:{0}".format(person_id) def invalidate_posts(post_ids): """Delete cache entries for all of these PopIt posts""" cache.delete_many(post_cache_key(post_id) for post_id in post_ids) def invalidate_person(person_id): """Delete the cache entry for a particular person's PopIt data""" person_key = person_cache_key(person_id) cache.delete(person_key) ... embed='membership.person.membership.organization') # Add posts data with an indefinite time-out (we should be # invalidating the cached on any change). cache.set(post_key, mp_post, None) ... return mp_post def get_person_cached(api, person_id): person_key = person_cache_key(person_id) result_from_cache = cache.get(person_key) if result_from_cache is not None: return result_from_cache person_data = api.persons(person_id).get( embed='membership.organization' ) # Add it the person data to the cache with a timeout of # a day. cache.set(person_key, person_data, 86400) return person_data ...
2a23e72f7ad01976bcd80aa91f89882e2a37cbf6
test/test_model.py
test/test_model.py
import os, sys sys.path.append(os.path.join(sys.path[0], '..')) from carlo import model, entity, generate def test_minimal_model(): m = model(entity('const', {'int': lambda: 42})).build() assert [('const', {'int': 42})] == m.create() m = model(entity('const2', {'str': lambda: 'hello'})).build() assert [('const2', {'str': 'hello'})] == m.create() def test_model_with_multiple_entities(): m = model( entity('first', {'name': lambda: 'elves'}), entity('second', {'name': lambda: 'humans'})).build() assert [('first', {'name': 'elves'}), ('second', {'name': 'humans'})] == m.create() def test_model_with_multiple_params(): m = model(entity('human', { 'head': lambda: 1, 'hands': lambda: 2, 'name': lambda: 'Hurin', })).build() assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create()
import os, sys sys.path.append(os.path.join(sys.path[0], '..')) from carlo import model, entity, generate def test_minimal_model(): m = model(entity('const', {'int': lambda: 42})).build() assert [('const', {'int': 42})] == m.create() m = model(entity('const2', {'str': lambda: 'hello'})).build() assert [('const2', {'str': 'hello'})] == m.create() def test_model_with_multiple_entities(): m = model( entity('first', {'name': lambda: 'elves'}), entity('second', {'name': lambda: 'humans'})).build() assert [('first', {'name': 'elves'}), ('second', {'name': 'humans'})] == m.create() def test_model_with_multiple_params(): m = model(entity('human', { 'head': lambda: 1, 'hands': lambda: 2, 'name': lambda: 'Hurin', })).build() assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create() # error handling def test_same_enitities_should_throw_error(): pass def test_same_params_should_throw_error(): pass
Test blueprints for corner cases
Test blueprints for corner cases
Python
mit
ahitrin/carlo
import os, sys sys.path.append(os.path.join(sys.path[0], '..')) from carlo import model, entity, generate def test_minimal_model(): m = model(entity('const', {'int': lambda: 42})).build() assert [('const', {'int': 42})] == m.create() m = model(entity('const2', {'str': lambda: 'hello'})).build() assert [('const2', {'str': 'hello'})] == m.create() def test_model_with_multiple_entities(): m = model( entity('first', {'name': lambda: 'elves'}), entity('second', {'name': lambda: 'humans'})).build() assert [('first', {'name': 'elves'}), ('second', {'name': 'humans'})] == m.create() def test_model_with_multiple_params(): m = model(entity('human', { 'head': lambda: 1, 'hands': lambda: 2, 'name': lambda: 'Hurin', })).build() assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create() + # error handling + + def test_same_enitities_should_throw_error(): + pass + + def test_same_params_should_throw_error(): + pass +
Test blueprints for corner cases
## Code Before: import os, sys sys.path.append(os.path.join(sys.path[0], '..')) from carlo import model, entity, generate def test_minimal_model(): m = model(entity('const', {'int': lambda: 42})).build() assert [('const', {'int': 42})] == m.create() m = model(entity('const2', {'str': lambda: 'hello'})).build() assert [('const2', {'str': 'hello'})] == m.create() def test_model_with_multiple_entities(): m = model( entity('first', {'name': lambda: 'elves'}), entity('second', {'name': lambda: 'humans'})).build() assert [('first', {'name': 'elves'}), ('second', {'name': 'humans'})] == m.create() def test_model_with_multiple_params(): m = model(entity('human', { 'head': lambda: 1, 'hands': lambda: 2, 'name': lambda: 'Hurin', })).build() assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create() ## Instruction: Test blueprints for corner cases ## Code After: import os, sys sys.path.append(os.path.join(sys.path[0], '..')) from carlo import model, entity, generate def test_minimal_model(): m = model(entity('const', {'int': lambda: 42})).build() assert [('const', {'int': 42})] == m.create() m = model(entity('const2', {'str': lambda: 'hello'})).build() assert [('const2', {'str': 'hello'})] == m.create() def test_model_with_multiple_entities(): m = model( entity('first', {'name': lambda: 'elves'}), entity('second', {'name': lambda: 'humans'})).build() assert [('first', {'name': 'elves'}), ('second', {'name': 'humans'})] == m.create() def test_model_with_multiple_params(): m = model(entity('human', { 'head': lambda: 1, 'hands': lambda: 2, 'name': lambda: 'Hurin', })).build() assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create() # error handling def test_same_enitities_should_throw_error(): pass def test_same_params_should_throw_error(): pass
... assert [('human', {'head': 1, 'hands': 2, 'name': 'Hurin'})] == m.create() # error handling def test_same_enitities_should_throw_error(): pass def test_same_params_should_throw_error(): pass ...
b56c1cb1185c8d20276688f29509947cb46a26d4
test/test_compiled.py
test/test_compiled.py
import os import platform import sys import jedi from .helpers import cwd_at @cwd_at('test/extensions') def test_completions(): if platform.architecture()[0] == '64bit': package_name = "compiled%s%s" % sys.version_info[:2] sys.path.insert(0, os.getcwd()) if os.path.exists(package_name): s = jedi.Script("from %s import compiled; compiled." % package_name) assert len(s.completions()) >= 2 @cwd_at('test/extensions') def test_call_signatures(): if platform.architecture()[0] == '64bit': package_name = "compiled%s%s" % sys.version_info[:2] sys.path.insert(0, os.getcwd()) if os.path.exists(package_name): s = jedi.Script("from %s import compiled; compiled.Foo(" % package_name) defs = s.call_signatures() for call_def in defs: for param in call_def.params: pass
import os import platform import sys import jedi from .helpers import cwd_at @cwd_at('test/extensions') def test_completions(): if platform.architecture()[0] == '64bit': package_name = "compiled%s%s" % sys.version_info[:2] sys.path.insert(0, os.getcwd()) if os.path.exists(package_name): s = jedi.Script("from %s import compiled; compiled." % package_name) assert len(s.completions()) >= 2 @cwd_at('test/extensions') def test_call_signatures_extension(): # with a cython extension if platform.architecture()[0] == '64bit': package_name = "compiled%s%s" % sys.version_info[:2] sys.path.insert(0, os.getcwd()) if os.path.exists(package_name): s = jedi.Script("from %s import compiled; compiled.Foo(" % package_name) defs = s.call_signatures() for call_def in defs: for param in call_def.params: pass def test_call_signatures_stdlib(): code = "import math; math.cos(" s = jedi.Script(code) defs = s.call_signatures() for call_def in defs: for p in call_def.params: assert str(p) == 'x'
Add test with standard lib
Add test with standard lib math.cos( should return <Param: x @0,0>
Python
mit
WoLpH/jedi,WoLpH/jedi,dwillmer/jedi,jonashaag/jedi,mfussenegger/jedi,flurischt/jedi,mfussenegger/jedi,dwillmer/jedi,jonashaag/jedi,tjwei/jedi,tjwei/jedi,flurischt/jedi
import os import platform import sys import jedi from .helpers import cwd_at @cwd_at('test/extensions') def test_completions(): if platform.architecture()[0] == '64bit': package_name = "compiled%s%s" % sys.version_info[:2] sys.path.insert(0, os.getcwd()) if os.path.exists(package_name): s = jedi.Script("from %s import compiled; compiled." % package_name) assert len(s.completions()) >= 2 @cwd_at('test/extensions') - def test_call_signatures(): + def test_call_signatures_extension(): + # with a cython extension if platform.architecture()[0] == '64bit': package_name = "compiled%s%s" % sys.version_info[:2] sys.path.insert(0, os.getcwd()) if os.path.exists(package_name): s = jedi.Script("from %s import compiled; compiled.Foo(" % package_name) defs = s.call_signatures() for call_def in defs: for param in call_def.params: pass + + + def test_call_signatures_stdlib(): + code = "import math; math.cos(" + s = jedi.Script(code) + defs = s.call_signatures() + for call_def in defs: + for p in call_def.params: + assert str(p) == 'x' +
Add test with standard lib
## Code Before: import os import platform import sys import jedi from .helpers import cwd_at @cwd_at('test/extensions') def test_completions(): if platform.architecture()[0] == '64bit': package_name = "compiled%s%s" % sys.version_info[:2] sys.path.insert(0, os.getcwd()) if os.path.exists(package_name): s = jedi.Script("from %s import compiled; compiled." % package_name) assert len(s.completions()) >= 2 @cwd_at('test/extensions') def test_call_signatures(): if platform.architecture()[0] == '64bit': package_name = "compiled%s%s" % sys.version_info[:2] sys.path.insert(0, os.getcwd()) if os.path.exists(package_name): s = jedi.Script("from %s import compiled; compiled.Foo(" % package_name) defs = s.call_signatures() for call_def in defs: for param in call_def.params: pass ## Instruction: Add test with standard lib ## Code After: import os import platform import sys import jedi from .helpers import cwd_at @cwd_at('test/extensions') def test_completions(): if platform.architecture()[0] == '64bit': package_name = "compiled%s%s" % sys.version_info[:2] sys.path.insert(0, os.getcwd()) if os.path.exists(package_name): s = jedi.Script("from %s import compiled; compiled." % package_name) assert len(s.completions()) >= 2 @cwd_at('test/extensions') def test_call_signatures_extension(): # with a cython extension if platform.architecture()[0] == '64bit': package_name = "compiled%s%s" % sys.version_info[:2] sys.path.insert(0, os.getcwd()) if os.path.exists(package_name): s = jedi.Script("from %s import compiled; compiled.Foo(" % package_name) defs = s.call_signatures() for call_def in defs: for param in call_def.params: pass def test_call_signatures_stdlib(): code = "import math; math.cos(" s = jedi.Script(code) defs = s.call_signatures() for call_def in defs: for p in call_def.params: assert str(p) == 'x'
... @cwd_at('test/extensions') def test_call_signatures_extension(): # with a cython extension if platform.architecture()[0] == '64bit': ... pass def test_call_signatures_stdlib(): code = "import math; math.cos(" s = jedi.Script(code) defs = s.call_signatures() for call_def in defs: for p in call_def.params: assert str(p) == 'x' ...
661d42468359836c0ce9ee4e267241a4aaf7a021
lot/views.py
lot/views.py
import json from django.conf import settings from django.http import HttpResponseRedirect, HttpResponseNotFound from django.shortcuts import get_object_or_404, resolve_url from django.utils.http import is_safe_url from django.views.generic import View from django.contrib.auth import authenticate, login from .models import LOT class LOTLogin(View): def get(self, request, uuid): lot = get_object_or_404(LOT, uuid=uuid) if not lot.verify(): lot.delete() return HttpResponseNotFound() user = authenticate(lot_uuid=uuid) login(request, user) try: session_data = json.loads(lot.session_data) request.session.update(session_data) except Exception: # If not correctly serialized not set the session_data pass if lot.is_one_time(): lot.delete() redirect_to = request.GET.get('next') if lot.next_url: redirect_to = resolve_url(lot.next_url) if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) return HttpResponseRedirect(redirect_to)
import json from django.conf import settings from django.http import HttpResponseRedirect, HttpResponseNotFound from django.shortcuts import get_object_or_404, resolve_url from django.utils.http import is_safe_url from django.views.generic import View from django.contrib.auth import authenticate, login from .models import LOT class LOTLogin(View): def get(self, request, uuid): lot = get_object_or_404(LOT, uuid=uuid) if not lot.verify(): lot.delete() return HttpResponseNotFound() user = authenticate(request, lot_uuid=uuid) if user is not None: login(request, user) else: raise RuntimeError('The authentication backend did not return a user') try: session_data = json.loads(lot.session_data) request.session.update(session_data) except Exception: # If not correctly serialized not set the session_data pass if lot.is_one_time(): lot.delete() redirect_to = request.GET.get('next') if lot.next_url: redirect_to = resolve_url(lot.next_url) if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) return HttpResponseRedirect(redirect_to)
Check for an empty user
Check for an empty user
Python
bsd-3-clause
ABASystems/django-lot
import json from django.conf import settings from django.http import HttpResponseRedirect, HttpResponseNotFound from django.shortcuts import get_object_or_404, resolve_url from django.utils.http import is_safe_url from django.views.generic import View from django.contrib.auth import authenticate, login from .models import LOT class LOTLogin(View): def get(self, request, uuid): lot = get_object_or_404(LOT, uuid=uuid) if not lot.verify(): lot.delete() return HttpResponseNotFound() - user = authenticate(lot_uuid=uuid) + user = authenticate(request, lot_uuid=uuid) + if user is not None: - login(request, user) + login(request, user) + else: + raise RuntimeError('The authentication backend did not return a user') try: session_data = json.loads(lot.session_data) request.session.update(session_data) except Exception: # If not correctly serialized not set the session_data pass if lot.is_one_time(): lot.delete() redirect_to = request.GET.get('next') if lot.next_url: redirect_to = resolve_url(lot.next_url) if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) return HttpResponseRedirect(redirect_to)
Check for an empty user
## Code Before: import json from django.conf import settings from django.http import HttpResponseRedirect, HttpResponseNotFound from django.shortcuts import get_object_or_404, resolve_url from django.utils.http import is_safe_url from django.views.generic import View from django.contrib.auth import authenticate, login from .models import LOT class LOTLogin(View): def get(self, request, uuid): lot = get_object_or_404(LOT, uuid=uuid) if not lot.verify(): lot.delete() return HttpResponseNotFound() user = authenticate(lot_uuid=uuid) login(request, user) try: session_data = json.loads(lot.session_data) request.session.update(session_data) except Exception: # If not correctly serialized not set the session_data pass if lot.is_one_time(): lot.delete() redirect_to = request.GET.get('next') if lot.next_url: redirect_to = resolve_url(lot.next_url) if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) return HttpResponseRedirect(redirect_to) ## Instruction: Check for an empty user ## Code After: import json from django.conf import settings from django.http import HttpResponseRedirect, HttpResponseNotFound from django.shortcuts import get_object_or_404, resolve_url from django.utils.http import is_safe_url from django.views.generic import View from django.contrib.auth import authenticate, login from .models import LOT class LOTLogin(View): def get(self, request, uuid): lot = get_object_or_404(LOT, uuid=uuid) if not lot.verify(): lot.delete() return HttpResponseNotFound() user = authenticate(request, lot_uuid=uuid) if user is not None: login(request, user) else: raise RuntimeError('The authentication backend did not return a user') try: session_data = json.loads(lot.session_data) request.session.update(session_data) except Exception: # If not correctly serialized not set the session_data pass if lot.is_one_time(): lot.delete() redirect_to = request.GET.get('next') if lot.next_url: redirect_to = resolve_url(lot.next_url) if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) return HttpResponseRedirect(redirect_to)
// ... existing code ... user = authenticate(request, lot_uuid=uuid) if user is not None: login(request, user) else: raise RuntimeError('The authentication backend did not return a user') // ... rest of the code ...
4d1a50b1765cd5da46ac9633b3c91eb5e0a72f3d
tests/toolchains/test_atmel_studio.py
tests/toolchains/test_atmel_studio.py
import sys import unittest from asninja.parser import AtmelStudioProject from asninja.toolchains.atmel_studio import * class TestAtmelStudioGccToolchain(unittest.TestCase): def test_constructor(self): tc = AtmelStudioGccToolchain('arm-') self.assertEqual('arm-', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_from_project(self): asp = AtmelStudioProject('Korsar3.cproj', 'Korsar3') tc = AtmelStudioGccToolchain.from_project(asp) self.assertEqual('C:\\Program Files (x86)\\Atmel\\Atmel Studio 6.2\\..\\Atmel Toolchain\\ARM GCC\\Native\\' '4.8.1437\\arm-gnu-toolchain\\bin', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_read_reg(self): pass if __name__ == '__main__': unittest.main()
import sys import unittest from unittest.mock import patch from asninja.parser import AtmelStudioProject from asninja.toolchains.atmel_studio import * class TestAtmelStudioGccToolchain(unittest.TestCase): def test_constructor(self): tc = AtmelStudioGccToolchain('arm-') self.assertEqual('arm-', tc.path) self.assertEqual('arm', tc.tool_type) @patch.object(AtmelStudioGccToolchain, 'read_reg', return_value = 'DUMMY_PATH') def test_from_project(self, mock_method): asp = AtmelStudioProject('Korsar3.cproj', 'Korsar3') tc = AtmelStudioGccToolchain.from_project(asp) self.assertEqual('DUMMY_PATH\\..\\Atmel Toolchain\\ARM GCC\\Native\\4.8.1437\\arm-gnu-toolchain\\bin', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_read_reg(self): pass if __name__ == '__main__': unittest.main()
Use unittest.mock to mock Windows Registry read.
tests: Use unittest.mock to mock Windows Registry read.
Python
mit
alunegov/AtmelStudioToNinja
import sys import unittest + from unittest.mock import patch from asninja.parser import AtmelStudioProject from asninja.toolchains.atmel_studio import * class TestAtmelStudioGccToolchain(unittest.TestCase): def test_constructor(self): tc = AtmelStudioGccToolchain('arm-') self.assertEqual('arm-', tc.path) self.assertEqual('arm', tc.tool_type) - @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") + @patch.object(AtmelStudioGccToolchain, 'read_reg', return_value = 'DUMMY_PATH') - def test_from_project(self): + def test_from_project(self, mock_method): asp = AtmelStudioProject('Korsar3.cproj', 'Korsar3') tc = AtmelStudioGccToolchain.from_project(asp) + self.assertEqual('DUMMY_PATH\\..\\Atmel Toolchain\\ARM GCC\\Native\\4.8.1437\\arm-gnu-toolchain\\bin', tc.path) - self.assertEqual('C:\\Program Files (x86)\\Atmel\\Atmel Studio 6.2\\..\\Atmel Toolchain\\ARM GCC\\Native\\' - '4.8.1437\\arm-gnu-toolchain\\bin', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_read_reg(self): pass if __name__ == '__main__': unittest.main()
Use unittest.mock to mock Windows Registry read.
## Code Before: import sys import unittest from asninja.parser import AtmelStudioProject from asninja.toolchains.atmel_studio import * class TestAtmelStudioGccToolchain(unittest.TestCase): def test_constructor(self): tc = AtmelStudioGccToolchain('arm-') self.assertEqual('arm-', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_from_project(self): asp = AtmelStudioProject('Korsar3.cproj', 'Korsar3') tc = AtmelStudioGccToolchain.from_project(asp) self.assertEqual('C:\\Program Files (x86)\\Atmel\\Atmel Studio 6.2\\..\\Atmel Toolchain\\ARM GCC\\Native\\' '4.8.1437\\arm-gnu-toolchain\\bin', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_read_reg(self): pass if __name__ == '__main__': unittest.main() ## Instruction: Use unittest.mock to mock Windows Registry read. ## Code After: import sys import unittest from unittest.mock import patch from asninja.parser import AtmelStudioProject from asninja.toolchains.atmel_studio import * class TestAtmelStudioGccToolchain(unittest.TestCase): def test_constructor(self): tc = AtmelStudioGccToolchain('arm-') self.assertEqual('arm-', tc.path) self.assertEqual('arm', tc.tool_type) @patch.object(AtmelStudioGccToolchain, 'read_reg', return_value = 'DUMMY_PATH') def test_from_project(self, mock_method): asp = AtmelStudioProject('Korsar3.cproj', 'Korsar3') tc = AtmelStudioGccToolchain.from_project(asp) self.assertEqual('DUMMY_PATH\\..\\Atmel Toolchain\\ARM GCC\\Native\\4.8.1437\\arm-gnu-toolchain\\bin', tc.path) self.assertEqual('arm', tc.tool_type) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_read_reg(self): pass if __name__ == '__main__': unittest.main()
... import unittest from unittest.mock import patch ... @patch.object(AtmelStudioGccToolchain, 'read_reg', return_value = 'DUMMY_PATH') def test_from_project(self, mock_method): asp = AtmelStudioProject('Korsar3.cproj', 'Korsar3') ... tc = AtmelStudioGccToolchain.from_project(asp) self.assertEqual('DUMMY_PATH\\..\\Atmel Toolchain\\ARM GCC\\Native\\4.8.1437\\arm-gnu-toolchain\\bin', tc.path) self.assertEqual('arm', tc.tool_type) ...
9a81879bd4eb01be5ed74acfdaf22acb635a9817
pikalang/__init__.py
pikalang/__init__.py
import sys import os from pikalang.interpreter import PikalangProgram def load_source(file): if os.path.isfile(file): if os.path.splitext(file)[1] == ".pokeball": with open(file, "r") as pikalang_file: pikalang_data = pikalang_file.read() return pikalang_data else: print("pikalang: file is not a pokeball", file=sys.stderr) return False else: print("pikalang: file does not exist", file=sys.stderr) return False def evaluate(source): """Run Pikalang system.""" program = PikalangProgram(source) program.run()
from __future__ import print_function import sys import os from pikalang.interpreter import PikalangProgram def load_source(file): if os.path.isfile(file): if os.path.splitext(file)[1] == ".pokeball": with open(file, "r") as pikalang_file: pikalang_data = pikalang_file.read() return pikalang_data else: print("pikalang: file is not a pokeball", file=sys.stderr) return False else: print("pikalang: file does not exist", file=sys.stderr) return False def evaluate(source): """Run Pikalang system.""" program = PikalangProgram(source) program.run()
Add proper printing for py2
Add proper printing for py2
Python
mit
groteworld/pikalang,grotewold/pikalang
+ + from __future__ import print_function import sys import os from pikalang.interpreter import PikalangProgram def load_source(file): if os.path.isfile(file): if os.path.splitext(file)[1] == ".pokeball": with open(file, "r") as pikalang_file: pikalang_data = pikalang_file.read() return pikalang_data else: print("pikalang: file is not a pokeball", file=sys.stderr) return False else: print("pikalang: file does not exist", file=sys.stderr) return False def evaluate(source): """Run Pikalang system.""" program = PikalangProgram(source) program.run()
Add proper printing for py2
## Code Before: import sys import os from pikalang.interpreter import PikalangProgram def load_source(file): if os.path.isfile(file): if os.path.splitext(file)[1] == ".pokeball": with open(file, "r") as pikalang_file: pikalang_data = pikalang_file.read() return pikalang_data else: print("pikalang: file is not a pokeball", file=sys.stderr) return False else: print("pikalang: file does not exist", file=sys.stderr) return False def evaluate(source): """Run Pikalang system.""" program = PikalangProgram(source) program.run() ## Instruction: Add proper printing for py2 ## Code After: from __future__ import print_function import sys import os from pikalang.interpreter import PikalangProgram def load_source(file): if os.path.isfile(file): if os.path.splitext(file)[1] == ".pokeball": with open(file, "r") as pikalang_file: pikalang_data = pikalang_file.read() return pikalang_data else: print("pikalang: file is not a pokeball", file=sys.stderr) return False else: print("pikalang: file does not exist", file=sys.stderr) return False def evaluate(source): """Run Pikalang system.""" program = PikalangProgram(source) program.run()
# ... existing code ... from __future__ import print_function # ... rest of the code ...
3b30a036f9f9fb861c0ed1711b5bd967756a072d
flask_cors/__init__.py
flask_cors/__init__.py
from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. 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())
from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass # Set initial level to WARN. Users must manually enable logging for # flask_cors to see our logging. rootlogger = logging.getLogger(__name__) rootlogger.addHandler(NullHandler()) if rootlogger.level == logging.NOTSET: rootlogger.setLevel(logging.WARN)
Disable logging for flask_cors by default
Disable logging for flask_cors by default
Python
mit
corydolphin/flask-cors,ashleysommer/sanic-cors
from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. 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()) + # Set initial level to WARN. Users must manually enable logging for + # flask_cors to see our logging. + rootlogger = logging.getLogger(__name__) + rootlogger.addHandler(NullHandler()) + + if rootlogger.level == logging.NOTSET: + rootlogger.setLevel(logging.WARN)
Disable logging for flask_cors by default
## Code Before: from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. 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: Disable logging for flask_cors by default ## Code After: from .decorator import cross_origin from .extension import CORS from .version import __version__ __all__ = ['CORS', 'cross_origin'] # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass # Set initial level to WARN. Users must manually enable logging for # flask_cors to see our logging. rootlogger = logging.getLogger(__name__) rootlogger.addHandler(NullHandler()) if rootlogger.level == logging.NOTSET: rootlogger.setLevel(logging.WARN)
# ... existing code ... # Set initial level to WARN. Users must manually enable logging for # flask_cors to see our logging. rootlogger = logging.getLogger(__name__) rootlogger.addHandler(NullHandler()) if rootlogger.level == logging.NOTSET: rootlogger.setLevel(logging.WARN) # ... rest of the code ...
d7bf66d84aee271cbcd99cd91eaedea8942d5a93
exponent/auth/service.py
exponent/auth/service.py
from exponent.auth import common from twisted.cred import checkers, portal from twisted.internet import defer from twisted.protocols import amp from zope import interface def _getUserByIdentifier(rootStore, userIdentifier): """ Gets a user by uid. """ user = common.User.findUnique(rootStore, userIdentifier) return defer.succeed(user) class AuthenticationLocator(amp.CommandLocator): """ A base class for responder locators that allow users to authenticate. """ credentialInterfaces = [] def __init__(self, store): """ Initializes an authentication responder locator. :param store: The root store. """ self.store = store storeCheckers = store.powerupsFor(checkers.ICredentialsChecker) self.portal = portal.Portal(Realm(store), storeCheckers) def acquireStore(self, userIdentifier): """ Acquires a user store. """ @interface.implementer(portal.IRealm) class Realm(object): """ A realm that produces box receivers for users. """ def __init__(self, getUserByUid): self._getUser = getUserByUid def requestAvatar(self, uid, mind, *interfaces): """ Attempts to get a lock on the user, then adapts it to ``IBoxReceiver``. """ if amp.IBoxReceiver not in interfaces: raise NotImplementedError() return self._getUser(uid).addCallback(_gotUser) def _gotUser(user): """ Adapts the user to ``IBoxReceiver`` and returns a 3-tuple suitable as the return value for ``requestAvatar``. """ return amp.IBoxReceiver, amp.IBoxReceiver(user), lambda: None
from twisted.cred import checkers, portal from twisted.protocols import amp from zope import interface class AuthenticationLocator(amp.CommandLocator): """ A base class for responder locators that allow users to authenticate. """ credentialInterfaces = [] def __init__(self, store): """ Initializes an authentication responder locator. :param store: The root store. """ self.store = store storeCheckers = store.powerupsFor(checkers.ICredentialsChecker) self.portal = portal.Portal(Realm(store), storeCheckers) def acquireStore(self, userIdentifier): """ Acquires a user store. """ @interface.implementer(portal.IRealm) class Realm(object): """ A realm that produces box receivers for users. """ def __init__(self, getUserByUid): self._getUser = getUserByUid def requestAvatar(self, uid, mind, *interfaces): """ Attempts to get a lock on the user, then adapts it to ``IBoxReceiver``. """ if amp.IBoxReceiver not in interfaces: raise NotImplementedError() return self._getUser(uid).addCallback(_gotUser) def _gotUser(user): """ Adapts the user to ``IBoxReceiver`` and returns a 3-tuple suitable as the return value for ``requestAvatar``. """ return amp.IBoxReceiver, amp.IBoxReceiver(user), lambda: None
Remove get user by id nonsense, now exponent.auth.name
Remove get user by id nonsense, now exponent.auth.name
Python
isc
lvh/exponent
- from exponent.auth import common from twisted.cred import checkers, portal - from twisted.internet import defer from twisted.protocols import amp from zope import interface - - - def _getUserByIdentifier(rootStore, userIdentifier): - """ - Gets a user by uid. - """ - user = common.User.findUnique(rootStore, userIdentifier) - return defer.succeed(user) - class AuthenticationLocator(amp.CommandLocator): """ A base class for responder locators that allow users to authenticate. """ credentialInterfaces = [] def __init__(self, store): """ Initializes an authentication responder locator. :param store: The root store. """ self.store = store storeCheckers = store.powerupsFor(checkers.ICredentialsChecker) self.portal = portal.Portal(Realm(store), storeCheckers) def acquireStore(self, userIdentifier): """ Acquires a user store. """ @interface.implementer(portal.IRealm) class Realm(object): """ A realm that produces box receivers for users. """ def __init__(self, getUserByUid): self._getUser = getUserByUid def requestAvatar(self, uid, mind, *interfaces): """ Attempts to get a lock on the user, then adapts it to ``IBoxReceiver``. """ if amp.IBoxReceiver not in interfaces: raise NotImplementedError() return self._getUser(uid).addCallback(_gotUser) def _gotUser(user): """ Adapts the user to ``IBoxReceiver`` and returns a 3-tuple suitable as the return value for ``requestAvatar``. """ return amp.IBoxReceiver, amp.IBoxReceiver(user), lambda: None
Remove get user by id nonsense, now exponent.auth.name
## Code Before: from exponent.auth import common from twisted.cred import checkers, portal from twisted.internet import defer from twisted.protocols import amp from zope import interface def _getUserByIdentifier(rootStore, userIdentifier): """ Gets a user by uid. """ user = common.User.findUnique(rootStore, userIdentifier) return defer.succeed(user) class AuthenticationLocator(amp.CommandLocator): """ A base class for responder locators that allow users to authenticate. """ credentialInterfaces = [] def __init__(self, store): """ Initializes an authentication responder locator. :param store: The root store. """ self.store = store storeCheckers = store.powerupsFor(checkers.ICredentialsChecker) self.portal = portal.Portal(Realm(store), storeCheckers) def acquireStore(self, userIdentifier): """ Acquires a user store. """ @interface.implementer(portal.IRealm) class Realm(object): """ A realm that produces box receivers for users. """ def __init__(self, getUserByUid): self._getUser = getUserByUid def requestAvatar(self, uid, mind, *interfaces): """ Attempts to get a lock on the user, then adapts it to ``IBoxReceiver``. """ if amp.IBoxReceiver not in interfaces: raise NotImplementedError() return self._getUser(uid).addCallback(_gotUser) def _gotUser(user): """ Adapts the user to ``IBoxReceiver`` and returns a 3-tuple suitable as the return value for ``requestAvatar``. """ return amp.IBoxReceiver, amp.IBoxReceiver(user), lambda: None ## Instruction: Remove get user by id nonsense, now exponent.auth.name ## Code After: from twisted.cred import checkers, portal from twisted.protocols import amp from zope import interface class AuthenticationLocator(amp.CommandLocator): """ A base class for responder locators that allow users to authenticate. """ credentialInterfaces = [] def __init__(self, store): """ Initializes an authentication responder locator. :param store: The root store. """ self.store = store storeCheckers = store.powerupsFor(checkers.ICredentialsChecker) self.portal = portal.Portal(Realm(store), storeCheckers) def acquireStore(self, userIdentifier): """ Acquires a user store. """ @interface.implementer(portal.IRealm) class Realm(object): """ A realm that produces box receivers for users. """ def __init__(self, getUserByUid): self._getUser = getUserByUid def requestAvatar(self, uid, mind, *interfaces): """ Attempts to get a lock on the user, then adapts it to ``IBoxReceiver``. """ if amp.IBoxReceiver not in interfaces: raise NotImplementedError() return self._getUser(uid).addCallback(_gotUser) def _gotUser(user): """ Adapts the user to ``IBoxReceiver`` and returns a 3-tuple suitable as the return value for ``requestAvatar``. """ return amp.IBoxReceiver, amp.IBoxReceiver(user), lambda: None
... from twisted.cred import checkers, portal from twisted.protocols import amp ... from zope import interface ...
e2735cba808ac4eb33e555fbb3d5d5f774ace032
swf/actors/helpers.py
swf/actors/helpers.py
import time import threading class Heart(threading.Thread): """Implementation of an heart beating routine To be used by actors to send swf heartbeats notifications once in a while. :param heartbeating_closure: Function to be called on heart beat tick. It takes not argument as input :type heartbeating_closure: function :param heartbeat_interval: interval between each heartbeats (in seconds) :type heartbeat_interval: integer """ def __init__(self, heartbeating_closure, heartbeat_interval, *args, **kwargs): threading.Thread.__init__(self) self.heartbeating_closure = heartbeating_closure self.heartbeat_interval = heartbeat_interval self.keep_beating = True def stop(self): """Explicitly call for a heart stop. .join() method should be called after stop though. """ self.keep_beating = False def run(self): while self.keep_beating is True: self.heartbeating_closure() time.sleep(self.heartbeat_interval)
import time import threading class Heart(threading.Thread): """Implementation of an heart beating routine To be used by actors to send swf heartbeats notifications once in a while. :param heartbeating_closure: Function to be called on heart beat tick. It takes not argument as input :type heartbeating_closure: function :param heartbeat_interval: interval between each heartbeats (in seconds) :type heartbeat_interval: integer :param closure_args: feel free to provide arguments to your heartbeating closure """ def __init__(self, heartbeating_closure, closure_args, heartbeat_interval, *args, **kwargs): threading.Thread.__init__(self) self.heartbeating_closure = heartbeating_closure self.closure_args = closure_args self.heartbeat_interval = heartbeat_interval self.keep_beating = True def stop(self): """Explicitly call for a heart stop. .join() method should be called after stop though. """ self.keep_beating = False def run(self): while self.keep_beating is True: self.heartbeating_closure(self.closure_args) time.sleep(self.heartbeat_interval)
Update Heart actors helper class to handle args
Update Heart actors helper class to handle args
Python
mit
botify-labs/python-simple-workflow,botify-labs/python-simple-workflow
import time import threading class Heart(threading.Thread): """Implementation of an heart beating routine To be used by actors to send swf heartbeats notifications once in a while. :param heartbeating_closure: Function to be called on heart beat tick. It takes not argument as input :type heartbeating_closure: function :param heartbeat_interval: interval between each heartbeats (in seconds) :type heartbeat_interval: integer + + :param closure_args: feel free to provide arguments to your heartbeating closure """ - def __init__(self, heartbeating_closure, + def __init__(self, heartbeating_closure, closure_args, heartbeat_interval, *args, **kwargs): threading.Thread.__init__(self) self.heartbeating_closure = heartbeating_closure + self.closure_args = closure_args self.heartbeat_interval = heartbeat_interval self.keep_beating = True def stop(self): """Explicitly call for a heart stop. .join() method should be called after stop though. """ self.keep_beating = False def run(self): while self.keep_beating is True: - self.heartbeating_closure() + self.heartbeating_closure(self.closure_args) time.sleep(self.heartbeat_interval)
Update Heart actors helper class to handle args
## Code Before: import time import threading class Heart(threading.Thread): """Implementation of an heart beating routine To be used by actors to send swf heartbeats notifications once in a while. :param heartbeating_closure: Function to be called on heart beat tick. It takes not argument as input :type heartbeating_closure: function :param heartbeat_interval: interval between each heartbeats (in seconds) :type heartbeat_interval: integer """ def __init__(self, heartbeating_closure, heartbeat_interval, *args, **kwargs): threading.Thread.__init__(self) self.heartbeating_closure = heartbeating_closure self.heartbeat_interval = heartbeat_interval self.keep_beating = True def stop(self): """Explicitly call for a heart stop. .join() method should be called after stop though. """ self.keep_beating = False def run(self): while self.keep_beating is True: self.heartbeating_closure() time.sleep(self.heartbeat_interval) ## Instruction: Update Heart actors helper class to handle args ## Code After: import time import threading class Heart(threading.Thread): """Implementation of an heart beating routine To be used by actors to send swf heartbeats notifications once in a while. :param heartbeating_closure: Function to be called on heart beat tick. It takes not argument as input :type heartbeating_closure: function :param heartbeat_interval: interval between each heartbeats (in seconds) :type heartbeat_interval: integer :param closure_args: feel free to provide arguments to your heartbeating closure """ def __init__(self, heartbeating_closure, closure_args, heartbeat_interval, *args, **kwargs): threading.Thread.__init__(self) self.heartbeating_closure = heartbeating_closure self.closure_args = closure_args self.heartbeat_interval = heartbeat_interval self.keep_beating = True def stop(self): """Explicitly call for a heart stop. .join() method should be called after stop though. """ self.keep_beating = False def run(self): while self.keep_beating is True: self.heartbeating_closure(self.closure_args) time.sleep(self.heartbeat_interval)
# ... existing code ... :type heartbeat_interval: integer :param closure_args: feel free to provide arguments to your heartbeating closure """ # ... modified code ... def __init__(self, heartbeating_closure, closure_args, heartbeat_interval, *args, **kwargs): ... self.heartbeating_closure = heartbeating_closure self.closure_args = closure_args self.heartbeat_interval = heartbeat_interval ... while self.keep_beating is True: self.heartbeating_closure(self.closure_args) time.sleep(self.heartbeat_interval) # ... rest of the code ...
53fbfc19090ce9e2447d3811ef5807422b71f426
indico/modules/events/registration/views.py
indico/modules/events/registration/views.py
from __future__ import unicode_literals from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceModifBase class WPManageRegistration(WPJinjaMixin, WPConferenceModifBase): template_prefix = 'events/registration' sidemenu_option = 'registration' def getJSFiles(self): return WPConferenceModifBase.getJSFiles(self) + self._asset_env['modules_registration_js'].urls()
from __future__ import unicode_literals from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceModifBase class WPManageRegistration(WPJinjaMixin, WPConferenceModifBase): template_prefix = 'events/registration/' sidemenu_option = 'registration' def getJSFiles(self): return (WPConferenceModifBase.getJSFiles(self) + self._asset_env['modules_registration_js'].urls() + self._asset_env['indico_regform'].urls()) def getCSSFiles(self): return WPConferenceModifBase.getCSSFiles(self) + self._asset_env['registrationform_sass'].urls()
Include static files specific to regform
Include static files specific to regform
Python
mit
DirkHoffmann/indico,OmeGak/indico,OmeGak/indico,mvidalgarcia/indico,DirkHoffmann/indico,indico/indico,mvidalgarcia/indico,ThiefMaster/indico,pferreir/indico,mic4ael/indico,DirkHoffmann/indico,pferreir/indico,mic4ael/indico,indico/indico,pferreir/indico,mvidalgarcia/indico,OmeGak/indico,pferreir/indico,mic4ael/indico,DirkHoffmann/indico,mic4ael/indico,ThiefMaster/indico,indico/indico,ThiefMaster/indico,ThiefMaster/indico,mvidalgarcia/indico,indico/indico,OmeGak/indico
from __future__ import unicode_literals from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceModifBase class WPManageRegistration(WPJinjaMixin, WPConferenceModifBase): - template_prefix = 'events/registration' + template_prefix = 'events/registration/' sidemenu_option = 'registration' def getJSFiles(self): - return WPConferenceModifBase.getJSFiles(self) + self._asset_env['modules_registration_js'].urls() + return (WPConferenceModifBase.getJSFiles(self) + self._asset_env['modules_registration_js'].urls() + + self._asset_env['indico_regform'].urls()) + def getCSSFiles(self): + return WPConferenceModifBase.getCSSFiles(self) + self._asset_env['registrationform_sass'].urls() +
Include static files specific to regform
## Code Before: from __future__ import unicode_literals from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceModifBase class WPManageRegistration(WPJinjaMixin, WPConferenceModifBase): template_prefix = 'events/registration' sidemenu_option = 'registration' def getJSFiles(self): return WPConferenceModifBase.getJSFiles(self) + self._asset_env['modules_registration_js'].urls() ## Instruction: Include static files specific to regform ## Code After: from __future__ import unicode_literals from MaKaC.webinterface.pages.base import WPJinjaMixin from MaKaC.webinterface.pages.conferences import WPConferenceModifBase class WPManageRegistration(WPJinjaMixin, WPConferenceModifBase): template_prefix = 'events/registration/' sidemenu_option = 'registration' def getJSFiles(self): return (WPConferenceModifBase.getJSFiles(self) + self._asset_env['modules_registration_js'].urls() + self._asset_env['indico_regform'].urls()) def getCSSFiles(self): return WPConferenceModifBase.getCSSFiles(self) + self._asset_env['registrationform_sass'].urls()
... class WPManageRegistration(WPJinjaMixin, WPConferenceModifBase): template_prefix = 'events/registration/' sidemenu_option = 'registration' ... def getJSFiles(self): return (WPConferenceModifBase.getJSFiles(self) + self._asset_env['modules_registration_js'].urls() + self._asset_env['indico_regform'].urls()) def getCSSFiles(self): return WPConferenceModifBase.getCSSFiles(self) + self._asset_env['registrationform_sass'].urls() ...
5bd9de24e63c557aed1779f6cee611cfeb52ddc0
envs.py
envs.py
import os import gym from gym.spaces.box import Box from baselines import bench from baselines.common.atari_wrappers import wrap_deepmind try: import pybullet_envs except ImportError: pass def make_env(env_id, seed, rank, log_dir): def _thunk(): env = gym.make(env_id) env.seed(seed + rank) env = bench.Monitor(env, os.path.join(log_dir, "{}.monitor.json".format(rank))) # Ugly hack to detect atari. if env.action_space.__class__.__name__ == 'Discrete': env = wrap_deepmind(env) env = WrapPyTorch(env) return env return _thunk class WrapPyTorch(gym.ObservationWrapper): def __init__(self, env=None): super(WrapPyTorch, self).__init__(env) self.observation_space = Box(0.0, 1.0, [1, 84, 84]) def _observation(self, observation): return observation.transpose(2, 0, 1)
import os import gym from gym.spaces.box import Box from baselines import bench from baselines.common.atari_wrappers import wrap_deepmind try: import pybullet_envs except ImportError: pass def make_env(env_id, seed, rank, log_dir): def _thunk(): env = gym.make(env_id) env.seed(seed + rank) env = bench.Monitor(env, os.path.join(log_dir, "{}.monitor.json".format(rank))) # Ugly hack to detect atari. if hasattr(env.env, 'env') and hasattr(env.env.env, 'ale'): env = wrap_deepmind(env) env = WrapPyTorch(env) return env return _thunk class WrapPyTorch(gym.ObservationWrapper): def __init__(self, env=None): super(WrapPyTorch, self).__init__(env) self.observation_space = Box(0.0, 1.0, [1, 84, 84]) def _observation(self, observation): return observation.transpose(2, 0, 1)
Change the ugly hack to detect atari
Change the ugly hack to detect atari
Python
mit
YuhangSong/GTN,YuhangSong/GTN,ikostrikov/pytorch-a2c-ppo-acktr
import os import gym from gym.spaces.box import Box from baselines import bench from baselines.common.atari_wrappers import wrap_deepmind try: import pybullet_envs except ImportError: pass def make_env(env_id, seed, rank, log_dir): def _thunk(): env = gym.make(env_id) env.seed(seed + rank) env = bench.Monitor(env, os.path.join(log_dir, "{}.monitor.json".format(rank))) # Ugly hack to detect atari. - if env.action_space.__class__.__name__ == 'Discrete': + if hasattr(env.env, 'env') and hasattr(env.env.env, 'ale'): env = wrap_deepmind(env) env = WrapPyTorch(env) return env return _thunk class WrapPyTorch(gym.ObservationWrapper): def __init__(self, env=None): super(WrapPyTorch, self).__init__(env) self.observation_space = Box(0.0, 1.0, [1, 84, 84]) def _observation(self, observation): return observation.transpose(2, 0, 1)
Change the ugly hack to detect atari
## Code Before: import os import gym from gym.spaces.box import Box from baselines import bench from baselines.common.atari_wrappers import wrap_deepmind try: import pybullet_envs except ImportError: pass def make_env(env_id, seed, rank, log_dir): def _thunk(): env = gym.make(env_id) env.seed(seed + rank) env = bench.Monitor(env, os.path.join(log_dir, "{}.monitor.json".format(rank))) # Ugly hack to detect atari. if env.action_space.__class__.__name__ == 'Discrete': env = wrap_deepmind(env) env = WrapPyTorch(env) return env return _thunk class WrapPyTorch(gym.ObservationWrapper): def __init__(self, env=None): super(WrapPyTorch, self).__init__(env) self.observation_space = Box(0.0, 1.0, [1, 84, 84]) def _observation(self, observation): return observation.transpose(2, 0, 1) ## Instruction: Change the ugly hack to detect atari ## Code After: import os import gym from gym.spaces.box import Box from baselines import bench from baselines.common.atari_wrappers import wrap_deepmind try: import pybullet_envs except ImportError: pass def make_env(env_id, seed, rank, log_dir): def _thunk(): env = gym.make(env_id) env.seed(seed + rank) env = bench.Monitor(env, os.path.join(log_dir, "{}.monitor.json".format(rank))) # Ugly hack to detect atari. if hasattr(env.env, 'env') and hasattr(env.env.env, 'ale'): env = wrap_deepmind(env) env = WrapPyTorch(env) return env return _thunk class WrapPyTorch(gym.ObservationWrapper): def __init__(self, env=None): super(WrapPyTorch, self).__init__(env) self.observation_space = Box(0.0, 1.0, [1, 84, 84]) def _observation(self, observation): return observation.transpose(2, 0, 1)
# ... existing code ... # Ugly hack to detect atari. if hasattr(env.env, 'env') and hasattr(env.env.env, 'ale'): env = wrap_deepmind(env) # ... rest of the code ...
bc8e548e51fddc251eb2e915883e3ee57bb9515b
zc_common/jwt_auth/utils.py
zc_common/jwt_auth/utils.py
import jwt from rest_framework_jwt.settings import api_settings def jwt_payload_handler(user): # The handler from rest_framework_jwt removed user_id, so this is a fork payload = { 'id': user.pk, 'roles': user.get_roles(), } return payload def jwt_encode_handler(payload): return jwt.encode( payload, api_settings.JWT_SECRET_KEY, api_settings.JWT_ALGORITHM ).decode('utf-8')
import jwt from rest_framework_jwt.settings import api_settings def jwt_payload_handler(user): '''Constructs a payload for a user JWT. This is a slimmed down version of https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest_framework_jwt/utils.py#L11 :param User: an object with `pk` and `get_roles()` :return: A dictionary that can be passed into `jwt_encode_handler` ''' payload = { 'id': user.pk, 'roles': user.get_roles(), } return payload def jwt_encode_handler(payload): ''' Encodes a payload into a valid JWT. :param payload: a dictionary :return: an encoded JWT string ''' return jwt.encode( payload, api_settings.JWT_SECRET_KEY, api_settings.JWT_ALGORITHM ).decode('utf-8')
Add docstrings to jwt handlers
Add docstrings to jwt handlers
Python
mit
ZeroCater/zc_common,ZeroCater/zc_common
import jwt from rest_framework_jwt.settings import api_settings def jwt_payload_handler(user): - # The handler from rest_framework_jwt removed user_id, so this is a fork + '''Constructs a payload for a user JWT. This is a slimmed down version of + https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest_framework_jwt/utils.py#L11 + + :param User: an object with `pk` and `get_roles()` + :return: A dictionary that can be passed into `jwt_encode_handler` + ''' + payload = { 'id': user.pk, 'roles': user.get_roles(), } return payload def jwt_encode_handler(payload): + ''' + Encodes a payload into a valid JWT. + + :param payload: a dictionary + :return: an encoded JWT string + ''' + return jwt.encode( payload, api_settings.JWT_SECRET_KEY, api_settings.JWT_ALGORITHM ).decode('utf-8')
Add docstrings to jwt handlers
## Code Before: import jwt from rest_framework_jwt.settings import api_settings def jwt_payload_handler(user): # The handler from rest_framework_jwt removed user_id, so this is a fork payload = { 'id': user.pk, 'roles': user.get_roles(), } return payload def jwt_encode_handler(payload): return jwt.encode( payload, api_settings.JWT_SECRET_KEY, api_settings.JWT_ALGORITHM ).decode('utf-8') ## Instruction: Add docstrings to jwt handlers ## Code After: import jwt from rest_framework_jwt.settings import api_settings def jwt_payload_handler(user): '''Constructs a payload for a user JWT. This is a slimmed down version of https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest_framework_jwt/utils.py#L11 :param User: an object with `pk` and `get_roles()` :return: A dictionary that can be passed into `jwt_encode_handler` ''' payload = { 'id': user.pk, 'roles': user.get_roles(), } return payload def jwt_encode_handler(payload): ''' Encodes a payload into a valid JWT. :param payload: a dictionary :return: an encoded JWT string ''' return jwt.encode( payload, api_settings.JWT_SECRET_KEY, api_settings.JWT_ALGORITHM ).decode('utf-8')
// ... existing code ... def jwt_payload_handler(user): '''Constructs a payload for a user JWT. This is a slimmed down version of https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest_framework_jwt/utils.py#L11 :param User: an object with `pk` and `get_roles()` :return: A dictionary that can be passed into `jwt_encode_handler` ''' payload = { // ... modified code ... def jwt_encode_handler(payload): ''' Encodes a payload into a valid JWT. :param payload: a dictionary :return: an encoded JWT string ''' return jwt.encode( // ... rest of the code ...
30f03692eff862f1456b9c376c21fe8e57de7eaa
dbt/clients/agate_helper.py
dbt/clients/agate_helper.py
import agate DEFAULT_TYPE_TESTER = agate.TypeTester(types=[ agate.data_types.Number(), agate.data_types.Date(), agate.data_types.DateTime(), agate.data_types.Boolean(), agate.data_types.Text() ]) def table_from_data(data, column_names): "Convert list of dictionaries into an Agate table" # The agate table is generated from a list of dicts, so the column order # from `data` is not preserved. We can use `select` to reorder the columns # # If there is no data, create an empty table with the specified columns if len(data) == 0: return agate.Table([], column_names=column_names) else: table = agate.Table.from_object(data, column_types=DEFAULT_TYPE_TESTER) return table.select(column_names) def empty_table(): "Returns an empty Agate table. To be used in place of None" return agate.Table(rows=[]) def as_matrix(table): "Return an agate table as a matrix of data sans columns" return [r.values() for r in table.rows.values()] def from_csv(abspath): return agate.Table.from_csv(abspath, column_types=DEFAULT_TYPE_TESTER)
import agate DEFAULT_TYPE_TESTER = agate.TypeTester(types=[ agate.data_types.Boolean(true_values=('true',), false_values=('false',), null_values=('null',)), agate.data_types.Number(null_values=('null',)), agate.data_types.TimeDelta(null_values=('null',)), agate.data_types.Date(null_values=('null',)), agate.data_types.DateTime(null_values=('null',)), agate.data_types.Text(null_values=('null',)) ]) def table_from_data(data, column_names): "Convert list of dictionaries into an Agate table" # The agate table is generated from a list of dicts, so the column order # from `data` is not preserved. We can use `select` to reorder the columns # # If there is no data, create an empty table with the specified columns if len(data) == 0: return agate.Table([], column_names=column_names) else: table = agate.Table.from_object(data, column_types=DEFAULT_TYPE_TESTER) return table.select(column_names) def empty_table(): "Returns an empty Agate table. To be used in place of None" return agate.Table(rows=[]) def as_matrix(table): "Return an agate table as a matrix of data sans columns" return [r.values() for r in table.rows.values()] def from_csv(abspath): return agate.Table.from_csv(abspath, column_types=DEFAULT_TYPE_TESTER)
Make the agate table type tester more restrictive on what counts as null/true/false
Make the agate table type tester more restrictive on what counts as null/true/false
Python
apache-2.0
analyst-collective/dbt,nave91/dbt,nave91/dbt,fishtown-analytics/dbt,fishtown-analytics/dbt,fishtown-analytics/dbt,analyst-collective/dbt
import agate DEFAULT_TYPE_TESTER = agate.TypeTester(types=[ - agate.data_types.Number(), - agate.data_types.Date(), - agate.data_types.DateTime(), - agate.data_types.Boolean(), + agate.data_types.Boolean(true_values=('true',), - agate.data_types.Text() + false_values=('false',), + null_values=('null',)), + agate.data_types.Number(null_values=('null',)), + agate.data_types.TimeDelta(null_values=('null',)), + agate.data_types.Date(null_values=('null',)), + agate.data_types.DateTime(null_values=('null',)), + agate.data_types.Text(null_values=('null',)) ]) def table_from_data(data, column_names): "Convert list of dictionaries into an Agate table" # The agate table is generated from a list of dicts, so the column order # from `data` is not preserved. We can use `select` to reorder the columns # # If there is no data, create an empty table with the specified columns if len(data) == 0: return agate.Table([], column_names=column_names) else: table = agate.Table.from_object(data, column_types=DEFAULT_TYPE_TESTER) return table.select(column_names) def empty_table(): "Returns an empty Agate table. To be used in place of None" return agate.Table(rows=[]) def as_matrix(table): "Return an agate table as a matrix of data sans columns" return [r.values() for r in table.rows.values()] def from_csv(abspath): return agate.Table.from_csv(abspath, column_types=DEFAULT_TYPE_TESTER)
Make the agate table type tester more restrictive on what counts as null/true/false
## Code Before: import agate DEFAULT_TYPE_TESTER = agate.TypeTester(types=[ agate.data_types.Number(), agate.data_types.Date(), agate.data_types.DateTime(), agate.data_types.Boolean(), agate.data_types.Text() ]) def table_from_data(data, column_names): "Convert list of dictionaries into an Agate table" # The agate table is generated from a list of dicts, so the column order # from `data` is not preserved. We can use `select` to reorder the columns # # If there is no data, create an empty table with the specified columns if len(data) == 0: return agate.Table([], column_names=column_names) else: table = agate.Table.from_object(data, column_types=DEFAULT_TYPE_TESTER) return table.select(column_names) def empty_table(): "Returns an empty Agate table. To be used in place of None" return agate.Table(rows=[]) def as_matrix(table): "Return an agate table as a matrix of data sans columns" return [r.values() for r in table.rows.values()] def from_csv(abspath): return agate.Table.from_csv(abspath, column_types=DEFAULT_TYPE_TESTER) ## Instruction: Make the agate table type tester more restrictive on what counts as null/true/false ## Code After: import agate DEFAULT_TYPE_TESTER = agate.TypeTester(types=[ agate.data_types.Boolean(true_values=('true',), false_values=('false',), null_values=('null',)), agate.data_types.Number(null_values=('null',)), agate.data_types.TimeDelta(null_values=('null',)), agate.data_types.Date(null_values=('null',)), agate.data_types.DateTime(null_values=('null',)), agate.data_types.Text(null_values=('null',)) ]) def table_from_data(data, column_names): "Convert list of dictionaries into an Agate table" # The agate table is generated from a list of dicts, so the column order # from `data` is not preserved. We can use `select` to reorder the columns # # If there is no data, create an empty table with the specified columns if len(data) == 0: return agate.Table([], column_names=column_names) else: table = agate.Table.from_object(data, column_types=DEFAULT_TYPE_TESTER) return table.select(column_names) def empty_table(): "Returns an empty Agate table. To be used in place of None" return agate.Table(rows=[]) def as_matrix(table): "Return an agate table as a matrix of data sans columns" return [r.values() for r in table.rows.values()] def from_csv(abspath): return agate.Table.from_csv(abspath, column_types=DEFAULT_TYPE_TESTER)
// ... existing code ... DEFAULT_TYPE_TESTER = agate.TypeTester(types=[ agate.data_types.Boolean(true_values=('true',), false_values=('false',), null_values=('null',)), agate.data_types.Number(null_values=('null',)), agate.data_types.TimeDelta(null_values=('null',)), agate.data_types.Date(null_values=('null',)), agate.data_types.DateTime(null_values=('null',)), agate.data_types.Text(null_values=('null',)) ]) // ... rest of the code ...
34fe4bb5cd5c4c35a659698e8d258c78da01887a
pynexus/api_client.py
pynexus/api_client.py
import requests class ApiClient: def __init__(self, host, username, password): self.uri = host + '/nexus/service/local/' self.username = username self.password = password def get_all_repositories(self): r = requests.get(self.uri + 'all_repositories', headers={'Accept': 'application/json'}) return r def get_status(self): r = requests.get(self.uri + 'status', headers={'Accept': 'application/json'}) return r
import requests class ApiClient: def __init__(self, host, username, password): self.uri = host + '/nexus/service/local/' self.username = username self.password = password def get_all_repositories(self): r = requests.get(self.uri + 'all_repositories', headers={'Accept': 'application/json'}) return r def get_status(self): r = requests.get(self.uri + 'status', headers={'Accept': 'application/json'}) return r def get_users(self): r = requests.get(self.uri + 'users', auth=(self.username, self.password), headers={'Accept': 'application/json'}) return r
Add get_users method to get a list of users
Add get_users method to get a list of users
Python
apache-2.0
rcarrillocruz/pynexus
import requests class ApiClient: def __init__(self, host, username, password): self.uri = host + '/nexus/service/local/' self.username = username self.password = password def get_all_repositories(self): r = requests.get(self.uri + 'all_repositories', headers={'Accept': 'application/json'}) return r def get_status(self): r = requests.get(self.uri + 'status', headers={'Accept': 'application/json'}) return r + def get_users(self): + r = requests.get(self.uri + 'users', auth=(self.username, self.password), headers={'Accept': 'application/json'}) + + return r +
Add get_users method to get a list of users
## Code Before: import requests class ApiClient: def __init__(self, host, username, password): self.uri = host + '/nexus/service/local/' self.username = username self.password = password def get_all_repositories(self): r = requests.get(self.uri + 'all_repositories', headers={'Accept': 'application/json'}) return r def get_status(self): r = requests.get(self.uri + 'status', headers={'Accept': 'application/json'}) return r ## Instruction: Add get_users method to get a list of users ## Code After: import requests class ApiClient: def __init__(self, host, username, password): self.uri = host + '/nexus/service/local/' self.username = username self.password = password def get_all_repositories(self): r = requests.get(self.uri + 'all_repositories', headers={'Accept': 'application/json'}) return r def get_status(self): r = requests.get(self.uri + 'status', headers={'Accept': 'application/json'}) return r def get_users(self): r = requests.get(self.uri + 'users', auth=(self.username, self.password), headers={'Accept': 'application/json'}) return r
... return r def get_users(self): r = requests.get(self.uri + 'users', auth=(self.username, self.password), headers={'Accept': 'application/json'}) return r ...
d851aae653ce87aed9b9f6ac3cf7f5312672a08c
radmin/templatetags/radmin_extras.py
radmin/templatetags/radmin_extras.py
from django import template import json from django.conf import settings register = template.Library() @register.simple_tag(takes_context=True) def get_admin_context(context): ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL} try: context['app_list'] if len(context['app_list']) > 1: # we are at /admin/ ctx['location'] = 'admin_index' return json.dumps(ctx) elif len(context['app_list']) == 1: #We are at the app index eg: /admin/app/ ctx['location'] = 'app_index' ctx['param1'] = context['app_list'][0]['name'].lower() return json.dumps(ctx) except KeyError: pass try: # we are in the list view of the model eg: admin/app/model/ ctx['location']= 'model_list' module_name = context['module_name'].lower() # django adds an 's' to every model name in this view, so we are gonna ctx['param1'] = module_name return json.dumps(ctx) except KeyError: pass try: # editing a model ctx['location']= 'model_edit' ctx['param1'] = context['original'].__class__.__name__.lower() ctx['param2'] = context['original'].pk return json.dumps(ctx) except KeyError: pass return json.dumps(ctx)
from django import template import json from django.conf import settings register = template.Library() @register.simple_tag(takes_context=True) def get_admin_context(context): ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL} try: context['app_list'] if len(context['app_list']) > 1: # we are at /admin/ ctx['location'] = 'admin_index' return json.dumps(ctx) elif len(context['app_list']) == 1: #We are at the app index eg: /admin/app/ ctx['location'] = 'app_index' ctx['param1'] = context['app_list'][0]['name'].lower() return json.dumps(ctx) except KeyError: pass try: # we are in the list view of the model eg: admin/app/model/ ctx['location']= 'model_list' module_name = context['module_name'].lower() # django adds an 's' to every model name in this view, so we are gonna ctx['param1'] = module_name return json.dumps(ctx) except KeyError: pass try: # editing a model ctx['location']= 'model_edit' if context['original'] is not None: ctx['param1'] = context['original'].__class__.__name__.lower() ctx['param2'] = context['original'].pk return json.dumps(ctx) except KeyError: pass return json.dumps(ctx)
Check if original object is None
Check if original object is None
Python
bsd-2-clause
mick-t/django-radmin-console,mick-t/django-radmin-console,mick-t/django-radmin-console
from django import template import json from django.conf import settings register = template.Library() @register.simple_tag(takes_context=True) def get_admin_context(context): ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL} try: context['app_list'] if len(context['app_list']) > 1: # we are at /admin/ ctx['location'] = 'admin_index' return json.dumps(ctx) elif len(context['app_list']) == 1: #We are at the app index eg: /admin/app/ ctx['location'] = 'app_index' ctx['param1'] = context['app_list'][0]['name'].lower() return json.dumps(ctx) except KeyError: pass try: # we are in the list view of the model eg: admin/app/model/ ctx['location']= 'model_list' module_name = context['module_name'].lower() # django adds an 's' to every model name in this view, so we are gonna ctx['param1'] = module_name return json.dumps(ctx) except KeyError: pass try: # editing a model ctx['location']= 'model_edit' + if context['original'] is not None: - ctx['param1'] = context['original'].__class__.__name__.lower() + ctx['param1'] = context['original'].__class__.__name__.lower() - ctx['param2'] = context['original'].pk + ctx['param2'] = context['original'].pk return json.dumps(ctx) except KeyError: pass return json.dumps(ctx)
Check if original object is None
## Code Before: from django import template import json from django.conf import settings register = template.Library() @register.simple_tag(takes_context=True) def get_admin_context(context): ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL} try: context['app_list'] if len(context['app_list']) > 1: # we are at /admin/ ctx['location'] = 'admin_index' return json.dumps(ctx) elif len(context['app_list']) == 1: #We are at the app index eg: /admin/app/ ctx['location'] = 'app_index' ctx['param1'] = context['app_list'][0]['name'].lower() return json.dumps(ctx) except KeyError: pass try: # we are in the list view of the model eg: admin/app/model/ ctx['location']= 'model_list' module_name = context['module_name'].lower() # django adds an 's' to every model name in this view, so we are gonna ctx['param1'] = module_name return json.dumps(ctx) except KeyError: pass try: # editing a model ctx['location']= 'model_edit' ctx['param1'] = context['original'].__class__.__name__.lower() ctx['param2'] = context['original'].pk return json.dumps(ctx) except KeyError: pass return json.dumps(ctx) ## Instruction: Check if original object is None ## Code After: from django import template import json from django.conf import settings register = template.Library() @register.simple_tag(takes_context=True) def get_admin_context(context): ctx = {'location':None, 'param1':None, 'param2':None, 'static':settings.STATIC_URL} try: context['app_list'] if len(context['app_list']) > 1: # we are at /admin/ ctx['location'] = 'admin_index' return json.dumps(ctx) elif len(context['app_list']) == 1: #We are at the app index eg: /admin/app/ ctx['location'] = 'app_index' ctx['param1'] = context['app_list'][0]['name'].lower() return json.dumps(ctx) except KeyError: pass try: # we are in the list view of the model eg: admin/app/model/ ctx['location']= 'model_list' module_name = context['module_name'].lower() # django adds an 's' to every model name in this view, so we are gonna ctx['param1'] = module_name return json.dumps(ctx) except KeyError: pass try: # editing a model ctx['location']= 'model_edit' if context['original'] is not None: ctx['param1'] = context['original'].__class__.__name__.lower() ctx['param2'] = context['original'].pk return json.dumps(ctx) except KeyError: pass return json.dumps(ctx)
// ... existing code ... ctx['location']= 'model_edit' if context['original'] is not None: ctx['param1'] = context['original'].__class__.__name__.lower() ctx['param2'] = context['original'].pk return json.dumps(ctx) // ... rest of the code ...
78ebec64e51c43005488bc1b9ce84fca65d069e4
planet_alignment/app/app_factory.py
planet_alignment/app/app_factory.py
from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface import IAppFactory from planet_alignment.config.bunch_parser import BunchParser from planet_alignment.data.system_data import SystemData from planet_alignment.mgr.plugins_mgr import PluginsManager class AppFactory(object): implements(IAppFactory) def __init__(self, cmd_args): data = BunchParser().parse(cmd_args.config) self._system_data = SystemData(data) self._plugins = PluginsManager(cmd_args.plugins) self._time = cmd_args.time def create(self): return App(self._system_data, self._plugins, self._time)
from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface import IAppFactory from planet_alignment.config.bunch_parser import BunchParser from planet_alignment.data.system_data import SystemData from planet_alignment.mgr.plugins_mgr import PluginsManager class AppFactory(object): """This is the class factory for the App. - **parameters** and **types**:: :param cmd_args: The command-line args. :type cmd_args: argparse Namespace """ implements(IAppFactory) def __init__(self, cmd_args): data = BunchParser().parse(cmd_args.config) self._system_data = SystemData(data) self._plugins = PluginsManager(cmd_args.plugins) self._time = cmd_args.time def create(self): """Returns the created App object. :return: Returns the App object. :rtype: App class. """ return App(self._system_data, self._plugins, self._time)
Document the AppFactory, add the doc headers.
Document the AppFactory, add the doc headers.
Python
mit
paulfanelli/planet_alignment
from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface import IAppFactory from planet_alignment.config.bunch_parser import BunchParser from planet_alignment.data.system_data import SystemData from planet_alignment.mgr.plugins_mgr import PluginsManager class AppFactory(object): + """This is the class factory for the App. + + - **parameters** and **types**:: + + :param cmd_args: The command-line args. + :type cmd_args: argparse Namespace + """ implements(IAppFactory) def __init__(self, cmd_args): data = BunchParser().parse(cmd_args.config) self._system_data = SystemData(data) self._plugins = PluginsManager(cmd_args.plugins) self._time = cmd_args.time def create(self): + """Returns the created App object. + + :return: Returns the App object. + :rtype: App class. + """ return App(self._system_data, self._plugins, self._time)
Document the AppFactory, add the doc headers.
## Code Before: from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface import IAppFactory from planet_alignment.config.bunch_parser import BunchParser from planet_alignment.data.system_data import SystemData from planet_alignment.mgr.plugins_mgr import PluginsManager class AppFactory(object): implements(IAppFactory) def __init__(self, cmd_args): data = BunchParser().parse(cmd_args.config) self._system_data = SystemData(data) self._plugins = PluginsManager(cmd_args.plugins) self._time = cmd_args.time def create(self): return App(self._system_data, self._plugins, self._time) ## Instruction: Document the AppFactory, add the doc headers. ## Code After: from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface import IAppFactory from planet_alignment.config.bunch_parser import BunchParser from planet_alignment.data.system_data import SystemData from planet_alignment.mgr.plugins_mgr import PluginsManager class AppFactory(object): """This is the class factory for the App. - **parameters** and **types**:: :param cmd_args: The command-line args. :type cmd_args: argparse Namespace """ implements(IAppFactory) def __init__(self, cmd_args): data = BunchParser().parse(cmd_args.config) self._system_data = SystemData(data) self._plugins = PluginsManager(cmd_args.plugins) self._time = cmd_args.time def create(self): """Returns the created App object. :return: Returns the App object. :rtype: App class. """ return App(self._system_data, self._plugins, self._time)
# ... existing code ... class AppFactory(object): """This is the class factory for the App. - **parameters** and **types**:: :param cmd_args: The command-line args. :type cmd_args: argparse Namespace """ implements(IAppFactory) # ... modified code ... def create(self): """Returns the created App object. :return: Returns the App object. :rtype: App class. """ return App(self._system_data, self._plugins, self._time) # ... rest of the code ...
ca4a312e09138d295932d200cebf787b911cd2b2
blog/tests.py
blog/tests.py
from django.test import TestCase from django.urls import reverse from .models import Post # Create your tests here. class PostModelTest(TestCase): def test_render_markdown(self): p = Post(content='aa') self.assertEqual(p.html_content, '<p>aa</p>\n') class PostViewTest(TestCase): def test_post_view(self): p = Post( slug='first-blog', title='First blog', content='I am hhb', ) p.save() url = reverse('blog:post', args=(p.slug,)) resp = self.client.get(url) self.assertContains(resp, 'I am hhb')
from django.test import TestCase from django.urls import reverse from .models import Post # Create your tests here. class PostModelTest(TestCase): def test_render_markdown(self): p = Post(content='aa') self.assertEqual(p.html_content, '<p>aa</p>\n') class PostViewTest(TestCase): def test_post_view(self): p = Post( slug='first-blog', title='First blog', content='I am hhb', ) p.save() url = reverse('blog:post', args=(p.slug,)) resp = self.client.get(url) self.assertContains(resp, 'I am hhb, i will fail')
Test fail not to deploy
Test fail not to deploy
Python
mit
graycarl/iamhhb,graycarl/iamhhb,graycarl/iamhhb,graycarl/iamhhb
from django.test import TestCase from django.urls import reverse from .models import Post # Create your tests here. class PostModelTest(TestCase): def test_render_markdown(self): p = Post(content='aa') self.assertEqual(p.html_content, '<p>aa</p>\n') class PostViewTest(TestCase): def test_post_view(self): p = Post( slug='first-blog', title='First blog', content='I am hhb', ) p.save() url = reverse('blog:post', args=(p.slug,)) resp = self.client.get(url) - self.assertContains(resp, 'I am hhb') + self.assertContains(resp, 'I am hhb, i will fail')
Test fail not to deploy
## Code Before: from django.test import TestCase from django.urls import reverse from .models import Post # Create your tests here. class PostModelTest(TestCase): def test_render_markdown(self): p = Post(content='aa') self.assertEqual(p.html_content, '<p>aa</p>\n') class PostViewTest(TestCase): def test_post_view(self): p = Post( slug='first-blog', title='First blog', content='I am hhb', ) p.save() url = reverse('blog:post', args=(p.slug,)) resp = self.client.get(url) self.assertContains(resp, 'I am hhb') ## Instruction: Test fail not to deploy ## Code After: from django.test import TestCase from django.urls import reverse from .models import Post # Create your tests here. class PostModelTest(TestCase): def test_render_markdown(self): p = Post(content='aa') self.assertEqual(p.html_content, '<p>aa</p>\n') class PostViewTest(TestCase): def test_post_view(self): p = Post( slug='first-blog', title='First blog', content='I am hhb', ) p.save() url = reverse('blog:post', args=(p.slug,)) resp = self.client.get(url) self.assertContains(resp, 'I am hhb, i will fail')
// ... existing code ... resp = self.client.get(url) self.assertContains(resp, 'I am hhb, i will fail') // ... rest of the code ...