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
4a62214f0c9e8789b8453a48c0a880c4ac6236cb
saleor/product/migrations/0123_auto_20200904_1251.py
saleor/product/migrations/0123_auto_20200904_1251.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("product", "0122_auto_20200828_1135"), ] operations = [ migrations.AlterUniqueTogether( name="variantimage", unique_together={("variant", "image")}, ), ]
from django.db import migrations from django.db.models import Count def remove_variant_image_duplicates(apps, schema_editor): ProductImage = apps.get_model("product", "ProductImage") VariantImage = apps.get_model("product", "VariantImage") duplicated_images = ( ProductImage.objects.values("pk", "variant_images__variant") .annotate(variant_count=Count("variant_images__variant")) .filter(variant_count__gte=2) ) variant_image_ids_to_remove = [] for image_data in duplicated_images: ids = VariantImage.objects.filter( variant=image_data["variant_images__variant"], image__pk=image_data["pk"], )[1:].values_list("pk", flat=True) variant_image_ids_to_remove += ids VariantImage.objects.filter(pk__in=variant_image_ids_to_remove).delete() class Migration(migrations.Migration): dependencies = [ ("product", "0122_auto_20200828_1135"), ] operations = [ migrations.RunPython( remove_variant_image_duplicates, migrations.RunPython.noop ), migrations.AlterUniqueTogether( name="variantimage", unique_together={("variant", "image")}, ), ]
Drop duplicated VariantImages before migration to unique together
Drop duplicated VariantImages before migration to unique together
Python
bsd-3-clause
mociepka/saleor,mociepka/saleor,mociepka/saleor
from django.db import migrations + from django.db.models import Count + + + def remove_variant_image_duplicates(apps, schema_editor): + ProductImage = apps.get_model("product", "ProductImage") + VariantImage = apps.get_model("product", "VariantImage") + + duplicated_images = ( + ProductImage.objects.values("pk", "variant_images__variant") + .annotate(variant_count=Count("variant_images__variant")) + .filter(variant_count__gte=2) + ) + + variant_image_ids_to_remove = [] + for image_data in duplicated_images: + ids = VariantImage.objects.filter( + variant=image_data["variant_images__variant"], image__pk=image_data["pk"], + )[1:].values_list("pk", flat=True) + variant_image_ids_to_remove += ids + + VariantImage.objects.filter(pk__in=variant_image_ids_to_remove).delete() class Migration(migrations.Migration): dependencies = [ ("product", "0122_auto_20200828_1135"), ] operations = [ + migrations.RunPython( + remove_variant_image_duplicates, migrations.RunPython.noop + ), migrations.AlterUniqueTogether( name="variantimage", unique_together={("variant", "image")}, ), ]
Drop duplicated VariantImages before migration to unique together
## Code Before: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("product", "0122_auto_20200828_1135"), ] operations = [ migrations.AlterUniqueTogether( name="variantimage", unique_together={("variant", "image")}, ), ] ## Instruction: Drop duplicated VariantImages before migration to unique together ## Code After: from django.db import migrations from django.db.models import Count def remove_variant_image_duplicates(apps, schema_editor): ProductImage = apps.get_model("product", "ProductImage") VariantImage = apps.get_model("product", "VariantImage") duplicated_images = ( ProductImage.objects.values("pk", "variant_images__variant") .annotate(variant_count=Count("variant_images__variant")) .filter(variant_count__gte=2) ) variant_image_ids_to_remove = [] for image_data in duplicated_images: ids = VariantImage.objects.filter( variant=image_data["variant_images__variant"], image__pk=image_data["pk"], )[1:].values_list("pk", flat=True) variant_image_ids_to_remove += ids VariantImage.objects.filter(pk__in=variant_image_ids_to_remove).delete() class Migration(migrations.Migration): dependencies = [ ("product", "0122_auto_20200828_1135"), ] operations = [ migrations.RunPython( remove_variant_image_duplicates, migrations.RunPython.noop ), migrations.AlterUniqueTogether( name="variantimage", unique_together={("variant", "image")}, ), ]
... from django.db import migrations from django.db.models import Count def remove_variant_image_duplicates(apps, schema_editor): ProductImage = apps.get_model("product", "ProductImage") VariantImage = apps.get_model("product", "VariantImage") duplicated_images = ( ProductImage.objects.values("pk", "variant_images__variant") .annotate(variant_count=Count("variant_images__variant")) .filter(variant_count__gte=2) ) variant_image_ids_to_remove = [] for image_data in duplicated_images: ids = VariantImage.objects.filter( variant=image_data["variant_images__variant"], image__pk=image_data["pk"], )[1:].values_list("pk", flat=True) variant_image_ids_to_remove += ids VariantImage.objects.filter(pk__in=variant_image_ids_to_remove).delete() ... operations = [ migrations.RunPython( remove_variant_image_duplicates, migrations.RunPython.noop ), migrations.AlterUniqueTogether( ...
219c474860ca7674070ef19fa95f0282b7c92399
mpages/admin.py
mpages/admin.py
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "parent": kwargs["queryset"] = Page.objects.order_by("title") return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
Order parents in Admin select field
Order parents in Admin select field
Python
bsd-3-clause
ahernp/DMCM,ahernp/DMCM,ahernp/DMCM
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) + def formfield_for_foreignkey(self, db_field, request, **kwargs): + if db_field.name == "parent": + kwargs["queryset"] = Page.objects.order_by("title") + return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) + admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
Order parents in Admin select field
## Code Before: from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag) ## Instruction: Order parents in Admin select field ## Code After: from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "parent": kwargs["queryset"] = Page.objects.order_by("title") return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
... def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "parent": kwargs["queryset"] = Page.objects.order_by("title") return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) ...
d7598e96ba5bd0bb53635a62b61df077280967cc
jenkins/scripts/xstatic_check_version.py
jenkins/scripts/xstatic_check_version.py
import importlib import os import sys from setuptools_scm import get_version xs = None for name in os.listdir('xstatic/pkg'): if os.path.isdir('xstatic/pkg/' + name): if xs is not None: sys.exit('More than one xstatic.pkg package found.') xs = importlib.import_module('xstatic.pkg.' + name) if xs is None: sys.exit('No xstatic.pkg package found.') git_version = get_version() if git_version != xs.PACKAGE_VERSION: sys.exit('git tag version ({}) does not match package version ({})'. format(git_version, xs.PACKAGE_VERSION))
import importlib import os import sys from setuptools_scm import get_version # add the xstatic repos checkout to the PYTHONPATH so we can # import its contents sys.path.append(os.getcwd()) xs = None for name in os.listdir('xstatic/pkg'): if os.path.isdir('xstatic/pkg/' + name): if xs is not None: sys.exit('More than one xstatic.pkg package found.') xs = importlib.import_module('xstatic.pkg.' + name) if xs is None: sys.exit('No xstatic.pkg package found.') git_version = get_version() if git_version != xs.PACKAGE_VERSION: sys.exit('git tag version ({}) does not match package version ({})'. format(git_version, xs.PACKAGE_VERSION))
Fix script to include repos in PYTHONPATH
Fix script to include repos in PYTHONPATH The repos checkout needs to be in the PYTHONPATH for the import of the xstatic module to work. Since we invoke the xstatic_check_version.py by absolute path, Python does not include the cwd() in the PYTHONPATH. Change-Id: Idd4f8db6334c9f29168e3bc39de3ed95a4e1c60f
Python
apache-2.0
dongwenjuan/project-config,Tesora/tesora-project-config,dongwenjuan/project-config,openstack-infra/project-config,openstack-infra/project-config,Tesora/tesora-project-config
import importlib import os import sys from setuptools_scm import get_version + + # add the xstatic repos checkout to the PYTHONPATH so we can + # import its contents + sys.path.append(os.getcwd()) xs = None for name in os.listdir('xstatic/pkg'): if os.path.isdir('xstatic/pkg/' + name): if xs is not None: sys.exit('More than one xstatic.pkg package found.') xs = importlib.import_module('xstatic.pkg.' + name) if xs is None: sys.exit('No xstatic.pkg package found.') git_version = get_version() if git_version != xs.PACKAGE_VERSION: sys.exit('git tag version ({}) does not match package version ({})'. format(git_version, xs.PACKAGE_VERSION))
Fix script to include repos in PYTHONPATH
## Code Before: import importlib import os import sys from setuptools_scm import get_version xs = None for name in os.listdir('xstatic/pkg'): if os.path.isdir('xstatic/pkg/' + name): if xs is not None: sys.exit('More than one xstatic.pkg package found.') xs = importlib.import_module('xstatic.pkg.' + name) if xs is None: sys.exit('No xstatic.pkg package found.') git_version = get_version() if git_version != xs.PACKAGE_VERSION: sys.exit('git tag version ({}) does not match package version ({})'. format(git_version, xs.PACKAGE_VERSION)) ## Instruction: Fix script to include repos in PYTHONPATH ## Code After: import importlib import os import sys from setuptools_scm import get_version # add the xstatic repos checkout to the PYTHONPATH so we can # import its contents sys.path.append(os.getcwd()) xs = None for name in os.listdir('xstatic/pkg'): if os.path.isdir('xstatic/pkg/' + name): if xs is not None: sys.exit('More than one xstatic.pkg package found.') xs = importlib.import_module('xstatic.pkg.' + name) if xs is None: sys.exit('No xstatic.pkg package found.') git_version = get_version() if git_version != xs.PACKAGE_VERSION: sys.exit('git tag version ({}) does not match package version ({})'. format(git_version, xs.PACKAGE_VERSION))
... from setuptools_scm import get_version # add the xstatic repos checkout to the PYTHONPATH so we can # import its contents sys.path.append(os.getcwd()) ...
3856b48af3e83f49a66c0c29b81e0a80ad3248d9
nubes/connectors/aws/connector.py
nubes/connectors/aws/connector.py
import boto3.session from nubes.connectors import base class AWSConnector(base.BaseConnector): def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): self.connection = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) @classmethod def name(cls): return "aws" def create_server(self, image_id, min_count, max_count, **kwargs): ec2_resource = self.connection.resource("ec2") server = ec2_resource.create_instances(ImageId=image_id, MinCount=min_count, MaxCount=max_count, **kwargs) return server def list_servers(self): ec2_client = self.connection.client("ec2") desc = ec2_client.describe_instances() return desc def delete_server(self, instance_id): ec2_resource = self.connection.resource("ec2") ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate()
import boto3.session from nubes.connectors import base class AWSConnector(base.BaseConnector): def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): self.connection = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) self.ec2_resource = self.connection.resource("ec2") self.ec2_client = self.connection.client("ec2") @classmethod def name(cls): return "aws" def create_server(self, image_id, min_count, max_count, **kwargs): server = self.ec2_resource.create_instances(ImageId=image_id, MinCount=min_count, MaxCount=max_count, **kwargs) return server def list_servers(self): desc = self.ec2_client.describe_instances() return desc def delete_server(self, instance_id): self.ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() self.ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate()
Move client and resource to __init__
Move client and resource to __init__ * moved the calls to create the ec2 session resource session client to the init
Python
apache-2.0
omninubes/nubes
import boto3.session from nubes.connectors import base class AWSConnector(base.BaseConnector): def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): self.connection = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) + self.ec2_resource = self.connection.resource("ec2") + self.ec2_client = self.connection.client("ec2") + @classmethod def name(cls): return "aws" def create_server(self, image_id, min_count, max_count, **kwargs): - ec2_resource = self.connection.resource("ec2") - server = ec2_resource.create_instances(ImageId=image_id, + server = self.ec2_resource.create_instances(ImageId=image_id, - MinCount=min_count, + MinCount=min_count, - MaxCount=max_count, + MaxCount=max_count, - **kwargs) + **kwargs) return server def list_servers(self): - ec2_client = self.connection.client("ec2") - desc = ec2_client.describe_instances() + desc = self.ec2_client.describe_instances() return desc def delete_server(self, instance_id): - ec2_resource = self.connection.resource("ec2") - ec2_resource.instances.filter( + self.ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() - ec2_resource.instances.filter( + self.ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate()
Move client and resource to __init__
## Code Before: import boto3.session from nubes.connectors import base class AWSConnector(base.BaseConnector): def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): self.connection = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) @classmethod def name(cls): return "aws" def create_server(self, image_id, min_count, max_count, **kwargs): ec2_resource = self.connection.resource("ec2") server = ec2_resource.create_instances(ImageId=image_id, MinCount=min_count, MaxCount=max_count, **kwargs) return server def list_servers(self): ec2_client = self.connection.client("ec2") desc = ec2_client.describe_instances() return desc def delete_server(self, instance_id): ec2_resource = self.connection.resource("ec2") ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate() ## Instruction: Move client and resource to __init__ ## Code After: import boto3.session from nubes.connectors import base class AWSConnector(base.BaseConnector): def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): self.connection = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) self.ec2_resource = self.connection.resource("ec2") self.ec2_client = self.connection.client("ec2") @classmethod def name(cls): return "aws" def create_server(self, image_id, min_count, max_count, **kwargs): server = self.ec2_resource.create_instances(ImageId=image_id, MinCount=min_count, MaxCount=max_count, **kwargs) return server def list_servers(self): desc = self.ec2_client.describe_instances() return desc def delete_server(self, instance_id): self.ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() self.ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate()
... self.ec2_resource = self.connection.resource("ec2") self.ec2_client = self.connection.client("ec2") @classmethod ... def create_server(self, image_id, min_count, max_count, **kwargs): server = self.ec2_resource.create_instances(ImageId=image_id, MinCount=min_count, MaxCount=max_count, **kwargs) return server ... def list_servers(self): desc = self.ec2_client.describe_instances() return desc ... def delete_server(self, instance_id): self.ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() self.ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate() ...
9931bd1d5459a983717fb502826f3cca87225b96
src/qrl/services/grpcHelper.py
src/qrl/services/grpcHelper.py
from grpc import StatusCode from qrl.core.misc import logger class GrpcExceptionWrapper(object): def __init__(self, response_type, state_code=StatusCode.UNKNOWN): self.response_type = response_type self.state_code = state_code def _set_context(self, context, exception): if context is not None: context.set_code(self.state_code) context.set_details(str(exception)) def __call__(self, f): def wrap_f(caller_self, request, context): try: return f(caller_self, request, context) except ValueError as e: self._set_context(context, e) logger.info(str(e)) return self.response_type() except Exception as e: self._set_context(context, e) logger.exception(e) return self.response_type() return wrap_f
from grpc import StatusCode from qrl.core.misc import logger class GrpcExceptionWrapper(object): def __init__(self, response_type, state_code=StatusCode.UNKNOWN): self.response_type = response_type self.state_code = state_code def _set_context(self, context, exception): if context is not None: context.set_code(self.state_code) context.set_details(str(exception)) def __call__(self, f): def wrap_f(caller_self, request, context): try: return f(caller_self, request, context) except ValueError as e: context.set_code(StatusCode.INVALID_ARGUMENT) self._set_context(context, e) logger.info(str(e)) return self.response_type() except Exception as e: self._set_context(context, e) logger.exception(e) return self.response_type() return wrap_f
Set code to Invalid argument for ValueErrors
Set code to Invalid argument for ValueErrors
Python
mit
jleni/QRL,cyyber/QRL,jleni/QRL,cyyber/QRL,theQRL/QRL,randomshinichi/QRL,theQRL/QRL,randomshinichi/QRL
from grpc import StatusCode from qrl.core.misc import logger class GrpcExceptionWrapper(object): def __init__(self, response_type, state_code=StatusCode.UNKNOWN): self.response_type = response_type self.state_code = state_code def _set_context(self, context, exception): if context is not None: context.set_code(self.state_code) context.set_details(str(exception)) def __call__(self, f): def wrap_f(caller_self, request, context): try: return f(caller_self, request, context) except ValueError as e: + context.set_code(StatusCode.INVALID_ARGUMENT) self._set_context(context, e) logger.info(str(e)) return self.response_type() except Exception as e: self._set_context(context, e) logger.exception(e) return self.response_type() return wrap_f
Set code to Invalid argument for ValueErrors
## Code Before: from grpc import StatusCode from qrl.core.misc import logger class GrpcExceptionWrapper(object): def __init__(self, response_type, state_code=StatusCode.UNKNOWN): self.response_type = response_type self.state_code = state_code def _set_context(self, context, exception): if context is not None: context.set_code(self.state_code) context.set_details(str(exception)) def __call__(self, f): def wrap_f(caller_self, request, context): try: return f(caller_self, request, context) except ValueError as e: self._set_context(context, e) logger.info(str(e)) return self.response_type() except Exception as e: self._set_context(context, e) logger.exception(e) return self.response_type() return wrap_f ## Instruction: Set code to Invalid argument for ValueErrors ## Code After: from grpc import StatusCode from qrl.core.misc import logger class GrpcExceptionWrapper(object): def __init__(self, response_type, state_code=StatusCode.UNKNOWN): self.response_type = response_type self.state_code = state_code def _set_context(self, context, exception): if context is not None: context.set_code(self.state_code) context.set_details(str(exception)) def __call__(self, f): def wrap_f(caller_self, request, context): try: return f(caller_self, request, context) except ValueError as e: context.set_code(StatusCode.INVALID_ARGUMENT) self._set_context(context, e) logger.info(str(e)) return self.response_type() except Exception as e: self._set_context(context, e) logger.exception(e) return self.response_type() return wrap_f
# ... existing code ... except ValueError as e: context.set_code(StatusCode.INVALID_ARGUMENT) self._set_context(context, e) # ... rest of the code ...
d45c14c1ee3275212535a98db161a0dbd23ed292
src/hue/BridgeScanner.py
src/hue/BridgeScanner.py
__author__ = 'hira'
import requests import json def get_bridge_ips(): res = requests.get('http://www.meethue.com/api/nupnp').text data = json.loads(res) return [map['internalipaddress'] for map in data] print(get_bridge_ips())
Enable finding Hue bridge on network.
Enable finding Hue bridge on network.
Python
mit
almichest/hue_app,almichest/hue_app
- __author__ = 'hira' + import requests + import json + def get_bridge_ips(): + res = requests.get('http://www.meethue.com/api/nupnp').text + data = json.loads(res) + return [map['internalipaddress'] for map in data] + + print(get_bridge_ips()) +
Enable finding Hue bridge on network.
## Code Before: __author__ = 'hira' ## Instruction: Enable finding Hue bridge on network. ## Code After: import requests import json def get_bridge_ips(): res = requests.get('http://www.meethue.com/api/nupnp').text data = json.loads(res) return [map['internalipaddress'] for map in data] print(get_bridge_ips())
// ... existing code ... import requests import json def get_bridge_ips(): res = requests.get('http://www.meethue.com/api/nupnp').text data = json.loads(res) return [map['internalipaddress'] for map in data] print(get_bridge_ips()) // ... rest of the code ...
7d6c5ead9f754606d732db8566311c4d3e6fe54f
tests.py
tests.py
"""Tests runner for modoboa_admin.""" import unittest from modoboa.lib.test_utils import TestRunnerMixin class TestRunner(TestRunnerMixin, unittest.TestCase): """The tests runner.""" extension = "modoboa_admin_limits"
"""Tests runner for modoboa_admin.""" import unittest from modoboa.lib.test_utils import TestRunnerMixin class TestRunner(TestRunnerMixin, unittest.TestCase): """The tests runner.""" extension = "modoboa_admin_limits" dependencies = [ "modoboa_admin" ]
Make sure to activate modoboa_admin.
Make sure to activate modoboa_admin.
Python
mit
disko/modoboa-admin-limits,disko/modoboa-admin-limits
"""Tests runner for modoboa_admin.""" import unittest from modoboa.lib.test_utils import TestRunnerMixin class TestRunner(TestRunnerMixin, unittest.TestCase): """The tests runner.""" extension = "modoboa_admin_limits" + dependencies = [ + "modoboa_admin" + ]
Make sure to activate modoboa_admin.
## Code Before: """Tests runner for modoboa_admin.""" import unittest from modoboa.lib.test_utils import TestRunnerMixin class TestRunner(TestRunnerMixin, unittest.TestCase): """The tests runner.""" extension = "modoboa_admin_limits" ## Instruction: Make sure to activate modoboa_admin. ## Code After: """Tests runner for modoboa_admin.""" import unittest from modoboa.lib.test_utils import TestRunnerMixin class TestRunner(TestRunnerMixin, unittest.TestCase): """The tests runner.""" extension = "modoboa_admin_limits" dependencies = [ "modoboa_admin" ]
# ... existing code ... extension = "modoboa_admin_limits" dependencies = [ "modoboa_admin" ] # ... rest of the code ...
1e562decdc03295dec4cb37d26162e5d9aa31079
neutron/tests/common/agents/l3_agent.py
neutron/tests/common/agents/l3_agent.py
from neutron.agent.l3 import agent class TestL3NATAgent(agent.L3NATAgentWithStateReport): NESTED_NAMESPACE_SEPARATOR = '@' def get_ns_name(self, router_id): ns_name = super(TestL3NATAgent, self).get_ns_name(router_id) return "%s%s%s" % (ns_name, self.NESTED_NAMESPACE_SEPARATOR, self.host) def get_router_id(self, ns_name): # 'ns_name' should be in the format of: 'qrouter-<id>@<host>'. return super(TestL3NATAgent, self).get_router_id( ns_name.split(self.NESTED_NAMESPACE_SEPARATOR)[0])
from neutron.agent.l3 import agent class TestL3NATAgent(agent.L3NATAgentWithStateReport): NESTED_NAMESPACE_SEPARATOR = '@' def __init__(self, host, conf=None): super(TestL3NATAgent, self).__init__(host, conf) self.event_observers.observers = set( observer.__class__(self) for observer in self.event_observers.observers) def get_ns_name(self, router_id): ns_name = super(TestL3NATAgent, self).get_ns_name(router_id) return "%s%s%s" % (ns_name, self.NESTED_NAMESPACE_SEPARATOR, self.host) def get_router_id(self, ns_name): # 'ns_name' should be in the format of: 'qrouter-<id>@<host>'. return super(TestL3NATAgent, self).get_router_id( ns_name.split(self.NESTED_NAMESPACE_SEPARATOR)[0])
Update L3 agent drivers singletons to look at new agent
Update L3 agent drivers singletons to look at new agent L3 agent drivers are singletons. They're created once, and hold self.l3_agent. During testing, the agent is tossed away and re-built, but the drivers singletons are pointing at the old agent, and its old configuration. Change-Id: Ie8a15318e71ea47cccad3b788751d914d51cbf18 Closes-Bug: #1404662
Python
apache-2.0
JianyuWang/neutron,SmartInfrastructures/neutron,eayunstack/neutron,skyddv/neutron,MaximNevrov/neutron,watonyweng/neutron,gkotton/neutron,openstack/neutron,mandeepdhami/neutron,glove747/liberty-neutron,projectcalico/calico-neutron,SamYaple/neutron,takeshineshiro/neutron,dims/neutron,watonyweng/neutron,miyakz1192/neutron,mandeepdhami/neutron,asgard-lab/neutron,mmnelemane/neutron,magic0704/neutron,bgxavier/neutron,mahak/neutron,gkotton/neutron,wenhuizhang/neutron,sasukeh/neutron,blueboxgroup/neutron,adelina-t/neutron,dhanunjaya/neutron,swdream/neutron,shahbazn/neutron,sebrandon1/neutron,Metaswitch/calico-neutron,vivekanand1101/neutron,swdream/neutron,antonioUnina/neutron,noironetworks/neutron,cisco-openstack/neutron,blueboxgroup/neutron,cloudbase/neutron-virtualbox,mmnelemane/neutron,huntxu/neutron,openstack/neutron,skyddv/neutron,eayunstack/neutron,NeCTAR-RC/neutron,projectcalico/calico-neutron,antonioUnina/neutron,apporc/neutron,SmartInfrastructures/neutron,alexandrucoman/vbox-neutron-agent,miyakz1192/neutron,suneeth51/neutron,JioCloud/neutron,barnsnake351/neutron,takeshineshiro/neutron,gkotton/neutron,mahak/neutron,noironetworks/neutron,cloudbase/neutron,mattt416/neutron,cisco-openstack/neutron,mahak/neutron,asgard-lab/neutron,sasukeh/neutron,glove747/liberty-neutron,klmitch/neutron,igor-toga/local-snat,paninetworks/neutron,Stavitsky/neutron,silenci/neutron,bigswitch/neutron,infobloxopen/neutron,dhanunjaya/neutron,vveerava/Openstack,vveerava/Openstack,adelina-t/neutron,shahbazn/neutron,MaximNevrov/neutron,cloudbase/neutron,pnavarro/neutron,bgxavier/neutron,alexandrucoman/vbox-neutron-agent,eonpatapon/neutron,magic0704/neutron,yuewko/neutron,blueboxgroup/neutron,wolverineav/neutron,chitr/neutron,wenhuizhang/neutron,jerryz1982/neutron,eonpatapon/neutron,barnsnake351/neutron,SamYaple/neutron,vivekanand1101/neutron,jumpojoy/neutron,huntxu/neutron,JianyuWang/neutron,paninetworks/neutron,waltBB/neutron_read,sebrandon1/neutron,JioCloud/neutron,bigswitch/neutron,javaos74/neutron,igor-toga/local-snat,jacknjzhou/neutron,infobloxopen/neutron,neoareslinux/neutron,yuewko/neutron,Stavitsky/neutron,wolverineav/neutron,aristanetworks/neutron,openstack/neutron,javaos74/neutron,neoareslinux/neutron,dims/neutron,jerryz1982/neutron,mattt416/neutron,chitr/neutron,yanheven/neutron,aristanetworks/neutron,klmitch/neutron,rdo-management/neutron,suneeth51/neutron,pnavarro/neutron,silenci/neutron,NeCTAR-RC/neutron,yanheven/neutron,jacknjzhou/neutron,cloudbase/neutron-virtualbox,waltBB/neutron_read,Metaswitch/calico-neutron,vveerava/Openstack,apporc/neutron,rdo-management/neutron,jumpojoy/neutron
from neutron.agent.l3 import agent class TestL3NATAgent(agent.L3NATAgentWithStateReport): NESTED_NAMESPACE_SEPARATOR = '@' + + def __init__(self, host, conf=None): + super(TestL3NATAgent, self).__init__(host, conf) + self.event_observers.observers = set( + observer.__class__(self) for observer in + self.event_observers.observers) def get_ns_name(self, router_id): ns_name = super(TestL3NATAgent, self).get_ns_name(router_id) return "%s%s%s" % (ns_name, self.NESTED_NAMESPACE_SEPARATOR, self.host) def get_router_id(self, ns_name): # 'ns_name' should be in the format of: 'qrouter-<id>@<host>'. return super(TestL3NATAgent, self).get_router_id( ns_name.split(self.NESTED_NAMESPACE_SEPARATOR)[0])
Update L3 agent drivers singletons to look at new agent
## Code Before: from neutron.agent.l3 import agent class TestL3NATAgent(agent.L3NATAgentWithStateReport): NESTED_NAMESPACE_SEPARATOR = '@' def get_ns_name(self, router_id): ns_name = super(TestL3NATAgent, self).get_ns_name(router_id) return "%s%s%s" % (ns_name, self.NESTED_NAMESPACE_SEPARATOR, self.host) def get_router_id(self, ns_name): # 'ns_name' should be in the format of: 'qrouter-<id>@<host>'. return super(TestL3NATAgent, self).get_router_id( ns_name.split(self.NESTED_NAMESPACE_SEPARATOR)[0]) ## Instruction: Update L3 agent drivers singletons to look at new agent ## Code After: from neutron.agent.l3 import agent class TestL3NATAgent(agent.L3NATAgentWithStateReport): NESTED_NAMESPACE_SEPARATOR = '@' def __init__(self, host, conf=None): super(TestL3NATAgent, self).__init__(host, conf) self.event_observers.observers = set( observer.__class__(self) for observer in self.event_observers.observers) def get_ns_name(self, router_id): ns_name = super(TestL3NATAgent, self).get_ns_name(router_id) return "%s%s%s" % (ns_name, self.NESTED_NAMESPACE_SEPARATOR, self.host) def get_router_id(self, ns_name): # 'ns_name' should be in the format of: 'qrouter-<id>@<host>'. return super(TestL3NATAgent, self).get_router_id( ns_name.split(self.NESTED_NAMESPACE_SEPARATOR)[0])
// ... existing code ... NESTED_NAMESPACE_SEPARATOR = '@' def __init__(self, host, conf=None): super(TestL3NATAgent, self).__init__(host, conf) self.event_observers.observers = set( observer.__class__(self) for observer in self.event_observers.observers) // ... rest of the code ...
9e85483d7baef82e7081639e2df746ed80c38418
tests/test_wheeler.py
tests/test_wheeler.py
import os.path as path import unittest from devpi_builder import wheeler class WheelTest(unittest.TestCase): def test_build(self): with wheeler.Builder() as builder: wheel_file = builder('progressbar', '2.2') self.assertRegexpMatches(wheel_file, '\.whl$') self.assert_(path.exists(wheel_file)) def test_cleans_up_created_files(self): with wheeler.Builder() as builder: wheel_file = builder('progressbar', '2.2') self.assertFalse(path.exists(wheel_file)) def test_provides_file_that_is_already_a_wheel(self): with wheeler.Builder() as builder: wheel_file = builder('wheel', '0.24') self.assert_(path.exists(wheel_file)) def test_throws_custom_on_build_failure(self): with wheeler.Builder() as builder: with self.assertRaises(wheeler.BuildError): builder('package_that_hopefully_does_not_exist', '99.999') if __name__ == '__main__': unittest.main()
import os.path as path import unittest from devpi_builder import wheeler class WheelTest(unittest.TestCase): def test_build(self): with wheeler.Builder() as builder: wheel_file = builder('progressbar', '2.2') self.assertRegexpMatches(wheel_file, '\.whl$') self.assert_(path.exists(wheel_file)) def test_cleans_up_created_files(self): with wheeler.Builder() as builder: wheel_file = builder('progressbar', '2.2') self.assertFalse(path.exists(wheel_file)) def test_provides_file_that_is_already_a_wheel(self): with wheeler.Builder() as builder: wheel_file = builder('wheel', '0.24') self.assert_(path.exists(wheel_file)) def test_throws_custom_on_build_failure(self): with wheeler.Builder() as builder: with self.assertRaises(wheeler.BuildError): builder('package_that_hopefully_does_not_exist', '99.999') def test_look_for_non_existing_wheel(self): with wheeler.Builder() as builder: with self.assertRaises(wheeler.BuildError): builder('nothing_can_be_found', '1.1') if __name__ == '__main__': unittest.main()
Cover the line that handles the pip<=1.5.2 error case.
Cover the line that handles the pip<=1.5.2 error case.
Python
bsd-3-clause
tylerdave/devpi-builder
import os.path as path import unittest from devpi_builder import wheeler class WheelTest(unittest.TestCase): def test_build(self): with wheeler.Builder() as builder: wheel_file = builder('progressbar', '2.2') self.assertRegexpMatches(wheel_file, '\.whl$') self.assert_(path.exists(wheel_file)) def test_cleans_up_created_files(self): with wheeler.Builder() as builder: wheel_file = builder('progressbar', '2.2') self.assertFalse(path.exists(wheel_file)) def test_provides_file_that_is_already_a_wheel(self): with wheeler.Builder() as builder: wheel_file = builder('wheel', '0.24') self.assert_(path.exists(wheel_file)) def test_throws_custom_on_build_failure(self): with wheeler.Builder() as builder: with self.assertRaises(wheeler.BuildError): builder('package_that_hopefully_does_not_exist', '99.999') + def test_look_for_non_existing_wheel(self): + with wheeler.Builder() as builder: + with self.assertRaises(wheeler.BuildError): + builder('nothing_can_be_found', '1.1') + if __name__ == '__main__': unittest.main()
Cover the line that handles the pip<=1.5.2 error case.
## Code Before: import os.path as path import unittest from devpi_builder import wheeler class WheelTest(unittest.TestCase): def test_build(self): with wheeler.Builder() as builder: wheel_file = builder('progressbar', '2.2') self.assertRegexpMatches(wheel_file, '\.whl$') self.assert_(path.exists(wheel_file)) def test_cleans_up_created_files(self): with wheeler.Builder() as builder: wheel_file = builder('progressbar', '2.2') self.assertFalse(path.exists(wheel_file)) def test_provides_file_that_is_already_a_wheel(self): with wheeler.Builder() as builder: wheel_file = builder('wheel', '0.24') self.assert_(path.exists(wheel_file)) def test_throws_custom_on_build_failure(self): with wheeler.Builder() as builder: with self.assertRaises(wheeler.BuildError): builder('package_that_hopefully_does_not_exist', '99.999') if __name__ == '__main__': unittest.main() ## Instruction: Cover the line that handles the pip<=1.5.2 error case. ## Code After: import os.path as path import unittest from devpi_builder import wheeler class WheelTest(unittest.TestCase): def test_build(self): with wheeler.Builder() as builder: wheel_file = builder('progressbar', '2.2') self.assertRegexpMatches(wheel_file, '\.whl$') self.assert_(path.exists(wheel_file)) def test_cleans_up_created_files(self): with wheeler.Builder() as builder: wheel_file = builder('progressbar', '2.2') self.assertFalse(path.exists(wheel_file)) def test_provides_file_that_is_already_a_wheel(self): with wheeler.Builder() as builder: wheel_file = builder('wheel', '0.24') self.assert_(path.exists(wheel_file)) def test_throws_custom_on_build_failure(self): with wheeler.Builder() as builder: with self.assertRaises(wheeler.BuildError): builder('package_that_hopefully_does_not_exist', '99.999') def test_look_for_non_existing_wheel(self): with wheeler.Builder() as builder: with self.assertRaises(wheeler.BuildError): builder('nothing_can_be_found', '1.1') if __name__ == '__main__': unittest.main()
# ... existing code ... def test_look_for_non_existing_wheel(self): with wheeler.Builder() as builder: with self.assertRaises(wheeler.BuildError): builder('nothing_can_be_found', '1.1') if __name__ == '__main__': # ... rest of the code ...
b6742ef3f8d1888e46938b2c678bfb093b7a31f2
pymortgage/d3_schedule.py
pymortgage/d3_schedule.py
import json class D3_Schedule: def __init__(self, schedule): self.schedule = schedule def get_d3_schedule(self, by_year=None): d3_data = [] if by_year: d3_data.insert(0, self.add_year_key("balance")) d3_data.insert(1, self.add_year_key("principal")) d3_data.insert(2, self.add_year_key("interest")) d3_data.insert(3, self.add_year_key("amount")) else: d3_data.insert(0, self.add_month_key("balance")) d3_data.insert(1, self.add_month_key("principal")) d3_data.insert(2, self.add_month_key("interest")) d3_data.insert(3, self.add_month_key("amount")) return json.dumps(d3_data) def add_month_key(self, key): return self.add_key(key, 'month') def add_year_key(self, key): return self.add_key(key, 'year') # color would be added to the new set for each key def add_key(self, key, term): new_set = dict() new_set['key'] = key.capitalize() new_set['values'] = [] for item in self.schedule: new_set['values'].append([item[term], item[key]]) return new_set
import json class D3_Schedule: def __init__(self, schedule): self.schedule = schedule def get_d3_schedule(self, by_year=None): d3_data = [] keys = ['balance', 'principal', 'interest', 'amount'] if by_year: for i in range(len(keys)): d3_data.insert(i, self.add_key(keys[i], 'year')) else: for i in range(len(keys)): d3_data.insert(i, self.add_key(keys[i], 'month')) return json.dumps(d3_data) # color would be added to the new set for each key def add_key(self, key, term): new_set = dict() new_set['key'] = key.capitalize() new_set['values'] = [] for item in self.schedule: new_set['values'].append([item[term], item[key]]) return new_set
Put some recurring things into a loop to simply code.
Put some recurring things into a loop to simply code.
Python
apache-2.0
csutherl/pymortgage,csutherl/pymortgage,csutherl/pymortgage
import json class D3_Schedule: def __init__(self, schedule): self.schedule = schedule def get_d3_schedule(self, by_year=None): d3_data = [] + keys = ['balance', 'principal', 'interest', 'amount'] + if by_year: + for i in range(len(keys)): + d3_data.insert(i, self.add_key(keys[i], 'year')) - d3_data.insert(0, self.add_year_key("balance")) - d3_data.insert(1, self.add_year_key("principal")) - d3_data.insert(2, self.add_year_key("interest")) - d3_data.insert(3, self.add_year_key("amount")) else: + for i in range(len(keys)): + d3_data.insert(i, self.add_key(keys[i], 'month')) - d3_data.insert(0, self.add_month_key("balance")) - d3_data.insert(1, self.add_month_key("principal")) - d3_data.insert(2, self.add_month_key("interest")) - d3_data.insert(3, self.add_month_key("amount")) return json.dumps(d3_data) - - def add_month_key(self, key): - return self.add_key(key, 'month') - - def add_year_key(self, key): - return self.add_key(key, 'year') # color would be added to the new set for each key def add_key(self, key, term): new_set = dict() new_set['key'] = key.capitalize() new_set['values'] = [] for item in self.schedule: new_set['values'].append([item[term], item[key]]) return new_set
Put some recurring things into a loop to simply code.
## Code Before: import json class D3_Schedule: def __init__(self, schedule): self.schedule = schedule def get_d3_schedule(self, by_year=None): d3_data = [] if by_year: d3_data.insert(0, self.add_year_key("balance")) d3_data.insert(1, self.add_year_key("principal")) d3_data.insert(2, self.add_year_key("interest")) d3_data.insert(3, self.add_year_key("amount")) else: d3_data.insert(0, self.add_month_key("balance")) d3_data.insert(1, self.add_month_key("principal")) d3_data.insert(2, self.add_month_key("interest")) d3_data.insert(3, self.add_month_key("amount")) return json.dumps(d3_data) def add_month_key(self, key): return self.add_key(key, 'month') def add_year_key(self, key): return self.add_key(key, 'year') # color would be added to the new set for each key def add_key(self, key, term): new_set = dict() new_set['key'] = key.capitalize() new_set['values'] = [] for item in self.schedule: new_set['values'].append([item[term], item[key]]) return new_set ## Instruction: Put some recurring things into a loop to simply code. ## Code After: import json class D3_Schedule: def __init__(self, schedule): self.schedule = schedule def get_d3_schedule(self, by_year=None): d3_data = [] keys = ['balance', 'principal', 'interest', 'amount'] if by_year: for i in range(len(keys)): d3_data.insert(i, self.add_key(keys[i], 'year')) else: for i in range(len(keys)): d3_data.insert(i, self.add_key(keys[i], 'month')) return json.dumps(d3_data) # color would be added to the new set for each key def add_key(self, key, term): new_set = dict() new_set['key'] = key.capitalize() new_set['values'] = [] for item in self.schedule: new_set['values'].append([item[term], item[key]]) return new_set
# ... existing code ... keys = ['balance', 'principal', 'interest', 'amount'] if by_year: for i in range(len(keys)): d3_data.insert(i, self.add_key(keys[i], 'year')) else: for i in range(len(keys)): d3_data.insert(i, self.add_key(keys[i], 'month')) # ... modified code ... return json.dumps(d3_data) # ... rest of the code ...
668a5240c29047d86fe9451f3078bb163bea0db9
skan/__init__.py
skan/__init__.py
from .csr import skeleton_to_csgraph, branch_statistics, summarise __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise']
from .csr import skeleton_to_csgraph, branch_statistics, summarise __version__ = '0.1-dev' __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise']
Add version info to package init
Add version info to package init
Python
bsd-3-clause
jni/skan
from .csr import skeleton_to_csgraph, branch_statistics, summarise + + __version__ = '0.1-dev' __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise'] +
Add version info to package init
## Code Before: from .csr import skeleton_to_csgraph, branch_statistics, summarise __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise'] ## Instruction: Add version info to package init ## Code After: from .csr import skeleton_to_csgraph, branch_statistics, summarise __version__ = '0.1-dev' __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise']
... from .csr import skeleton_to_csgraph, branch_statistics, summarise __version__ = '0.1-dev' ...
4fec805a0a6c04ac16fd4439298a4fa05709c7ea
armstrong/hatband/tests/hatband_support/admin.py
armstrong/hatband/tests/hatband_support/admin.py
from armstrong import hatband from hatband_support import models from django.forms.widgets import TextInput class ArticleAdmin(hatband.ModelAdmin): class Meta: model = models.TestArticle class ArticleOverrideAdmin(hatband.ModelAdmin): formfield_overrides = { models.TextField: {'widget': TextInput}, } class Meta: model = models.TestArticle class ArticleTabbedInline(hatband.TabbedInline): class Meta: model = models.TestArticle class ArticleStackedInline(hatband.StackedInline): class Meta: model = models.TestArticle class CategoryAdminTabbed(hatband.ModelAdmin): inlines = ArticleTabbedInline class Meta: model = models.TestCategory class CategoryAdminStacked(hatband.ModelAdmin): inlines = ArticleStackedInline class Meta: model = models.TestCategory
from armstrong import hatband from . import models from django.db.models import TextField from django.forms.widgets import TextInput class ArticleAdmin(hatband.ModelAdmin): class Meta: model = models.TestArticle class ArticleOverrideAdmin(hatband.ModelAdmin): formfield_overrides = { TextField: {'widget': TextInput}, } class Meta: model = models.TestArticle class ArticleTabularInline(hatband.TabularInline): class Meta: model = models.TestArticle class ArticleStackedInline(hatband.StackedInline): class Meta: model = models.TestArticle class CategoryAdminTabbed(hatband.ModelAdmin): inlines = ArticleTabularInline class Meta: model = models.TestCategory class CategoryAdminStacked(hatband.ModelAdmin): inlines = ArticleStackedInline class Meta: model = models.TestCategory
Fix these class names and imports so it works
Fix these class names and imports so it works
Python
apache-2.0
armstrong/armstrong.hatband,texastribune/armstrong.hatband,texastribune/armstrong.hatband,armstrong/armstrong.hatband,armstrong/armstrong.hatband,texastribune/armstrong.hatband
from armstrong import hatband - from hatband_support import models + from . import models + from django.db.models import TextField from django.forms.widgets import TextInput class ArticleAdmin(hatband.ModelAdmin): class Meta: model = models.TestArticle class ArticleOverrideAdmin(hatband.ModelAdmin): formfield_overrides = { - models.TextField: {'widget': TextInput}, + TextField: {'widget': TextInput}, } class Meta: model = models.TestArticle - class ArticleTabbedInline(hatband.TabbedInline): + class ArticleTabularInline(hatband.TabularInline): class Meta: model = models.TestArticle class ArticleStackedInline(hatband.StackedInline): class Meta: model = models.TestArticle class CategoryAdminTabbed(hatband.ModelAdmin): - inlines = ArticleTabbedInline + inlines = ArticleTabularInline class Meta: model = models.TestCategory class CategoryAdminStacked(hatband.ModelAdmin): inlines = ArticleStackedInline class Meta: model = models.TestCategory
Fix these class names and imports so it works
## Code Before: from armstrong import hatband from hatband_support import models from django.forms.widgets import TextInput class ArticleAdmin(hatband.ModelAdmin): class Meta: model = models.TestArticle class ArticleOverrideAdmin(hatband.ModelAdmin): formfield_overrides = { models.TextField: {'widget': TextInput}, } class Meta: model = models.TestArticle class ArticleTabbedInline(hatband.TabbedInline): class Meta: model = models.TestArticle class ArticleStackedInline(hatband.StackedInline): class Meta: model = models.TestArticle class CategoryAdminTabbed(hatband.ModelAdmin): inlines = ArticleTabbedInline class Meta: model = models.TestCategory class CategoryAdminStacked(hatband.ModelAdmin): inlines = ArticleStackedInline class Meta: model = models.TestCategory ## Instruction: Fix these class names and imports so it works ## Code After: from armstrong import hatband from . import models from django.db.models import TextField from django.forms.widgets import TextInput class ArticleAdmin(hatband.ModelAdmin): class Meta: model = models.TestArticle class ArticleOverrideAdmin(hatband.ModelAdmin): formfield_overrides = { TextField: {'widget': TextInput}, } class Meta: model = models.TestArticle class ArticleTabularInline(hatband.TabularInline): class Meta: model = models.TestArticle class ArticleStackedInline(hatband.StackedInline): class Meta: model = models.TestArticle class CategoryAdminTabbed(hatband.ModelAdmin): inlines = ArticleTabularInline class Meta: model = models.TestCategory class CategoryAdminStacked(hatband.ModelAdmin): inlines = ArticleStackedInline class Meta: model = models.TestCategory
# ... existing code ... from armstrong import hatband from . import models from django.db.models import TextField from django.forms.widgets import TextInput # ... modified code ... formfield_overrides = { TextField: {'widget': TextInput}, } ... class ArticleTabularInline(hatband.TabularInline): ... inlines = ArticleTabularInline # ... rest of the code ...
222628c6747bdc3574bcb7cf6257c785ffa6451d
inventory_control/database/sql.py
inventory_control/database/sql.py
CREATE_SQL = """ CREATE TABLE component_type ( id INT PRIMARY KEY AUTO_INCREMENT, type VARCHAR(255) UNIQUE ); CREATE TABLE components ( id INT PRIMARY KEY AUTO_INCREMENT, sku TEXT, type INT, status INT, FOREIGN KEY (type) REFERENCES component_type(id) ); CREATE TABLE projects ( id INT PRIMARY KEY AUTO_INCREMENT, motherboard INT, power_supply INT, cpu INT, hard_drive INT, proj_case INT, memory INT, FOREIGN KEY (motherboard) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (cpu) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (power_supply) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (hard_drive) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (proj_case) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (memory) REFERENCES components(id) ON DELETE CASCADE ); """ ADD_COMPONENT_TYPE = """INSERT IGNORE INTO component_type (type) VALUES ('{text}') """ GET_COMPONENT_TYPE="""SELECT * FROM component_type WHERE type='{text}'""" DELETE_COMPONENT_TYPE = """DELETE FROM component_type WHERE type='{text}' """ SELECT_ALL_COMPONENTS = """ SELECT * FROM components INNER JOIN component_type ON components.type = component_type.id; """ DROP_SQL = """ DROP TABLE projects; DROP TABLE components; DROP TABLE component_type; """
CREATE_SQL = """ CREATE TABLE component_type ( id INT PRIMARY KEY AUTO_INCREMENT, type VARCHAR(255) UNIQUE ); CREATE TABLE components ( id INT PRIMARY KEY AUTO_INCREMENT, serial_number VARCHAR(255), sku TEXT, type INT, status INT, FOREIGN KEY (type) REFERENCES component_type(id) ); CREATE TABLE projects ( id INT PRIMARY KEY AUTO_INCREMENT, product_number INT, motherboard INT, power_supply INT, cpu INT, hard_drive INT, proj_case INT, memory INT, FOREIGN KEY (motherboard) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (cpu) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (power_supply) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (hard_drive) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (proj_case) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (memory) REFERENCES components(id) ON DELETE CASCADE ); """ ADD_COMPONENT_TYPE = """INSERT IGNORE INTO component_type (type) VALUES ('{text}') """ GET_COMPONENT_TYPE="""SELECT * FROM component_type WHERE type='{text}'""" DELETE_COMPONENT_TYPE = """DELETE FROM component_type WHERE type='{text}' """ SELECT_ALL_COMPONENTS = """ SELECT * FROM components INNER JOIN component_type ON components.type = component_type.id; """ DROP_SQL = """ DROP TABLE projects; DROP TABLE components; DROP TABLE component_type; """
Add product_number and serial_number identifiers
Add product_number and serial_number identifiers
Python
mit
worldcomputerxchange/inventory-control,codeforsanjose/inventory-control
CREATE_SQL = """ CREATE TABLE component_type ( id INT PRIMARY KEY AUTO_INCREMENT, type VARCHAR(255) UNIQUE ); CREATE TABLE components ( id INT PRIMARY KEY AUTO_INCREMENT, + serial_number VARCHAR(255), sku TEXT, type INT, status INT, FOREIGN KEY (type) REFERENCES component_type(id) ); CREATE TABLE projects ( id INT PRIMARY KEY AUTO_INCREMENT, + product_number INT, motherboard INT, power_supply INT, cpu INT, hard_drive INT, proj_case INT, memory INT, FOREIGN KEY (motherboard) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (cpu) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (power_supply) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (hard_drive) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (proj_case) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (memory) REFERENCES components(id) ON DELETE CASCADE ); """ ADD_COMPONENT_TYPE = """INSERT IGNORE INTO component_type (type) VALUES ('{text}') """ GET_COMPONENT_TYPE="""SELECT * FROM component_type WHERE type='{text}'""" DELETE_COMPONENT_TYPE = """DELETE FROM component_type WHERE type='{text}' """ SELECT_ALL_COMPONENTS = """ SELECT * FROM components INNER JOIN component_type ON components.type = component_type.id; """ DROP_SQL = """ DROP TABLE projects; DROP TABLE components; DROP TABLE component_type; """
Add product_number and serial_number identifiers
## Code Before: CREATE_SQL = """ CREATE TABLE component_type ( id INT PRIMARY KEY AUTO_INCREMENT, type VARCHAR(255) UNIQUE ); CREATE TABLE components ( id INT PRIMARY KEY AUTO_INCREMENT, sku TEXT, type INT, status INT, FOREIGN KEY (type) REFERENCES component_type(id) ); CREATE TABLE projects ( id INT PRIMARY KEY AUTO_INCREMENT, motherboard INT, power_supply INT, cpu INT, hard_drive INT, proj_case INT, memory INT, FOREIGN KEY (motherboard) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (cpu) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (power_supply) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (hard_drive) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (proj_case) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (memory) REFERENCES components(id) ON DELETE CASCADE ); """ ADD_COMPONENT_TYPE = """INSERT IGNORE INTO component_type (type) VALUES ('{text}') """ GET_COMPONENT_TYPE="""SELECT * FROM component_type WHERE type='{text}'""" DELETE_COMPONENT_TYPE = """DELETE FROM component_type WHERE type='{text}' """ SELECT_ALL_COMPONENTS = """ SELECT * FROM components INNER JOIN component_type ON components.type = component_type.id; """ DROP_SQL = """ DROP TABLE projects; DROP TABLE components; DROP TABLE component_type; """ ## Instruction: Add product_number and serial_number identifiers ## Code After: CREATE_SQL = """ CREATE TABLE component_type ( id INT PRIMARY KEY AUTO_INCREMENT, type VARCHAR(255) UNIQUE ); CREATE TABLE components ( id INT PRIMARY KEY AUTO_INCREMENT, serial_number VARCHAR(255), sku TEXT, type INT, status INT, FOREIGN KEY (type) REFERENCES component_type(id) ); CREATE TABLE projects ( id INT PRIMARY KEY AUTO_INCREMENT, product_number INT, motherboard INT, power_supply INT, cpu INT, hard_drive INT, proj_case INT, memory INT, FOREIGN KEY (motherboard) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (cpu) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (power_supply) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (hard_drive) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (proj_case) REFERENCES components(id) ON DELETE CASCADE, FOREIGN KEY (memory) REFERENCES components(id) ON DELETE CASCADE ); """ ADD_COMPONENT_TYPE = """INSERT IGNORE INTO component_type (type) VALUES ('{text}') """ GET_COMPONENT_TYPE="""SELECT * FROM component_type WHERE type='{text}'""" DELETE_COMPONENT_TYPE = """DELETE FROM component_type WHERE type='{text}' """ SELECT_ALL_COMPONENTS = """ SELECT * FROM components INNER JOIN component_type ON components.type = component_type.id; """ DROP_SQL = """ DROP TABLE projects; DROP TABLE components; DROP TABLE component_type; """
... id INT PRIMARY KEY AUTO_INCREMENT, serial_number VARCHAR(255), sku TEXT, ... id INT PRIMARY KEY AUTO_INCREMENT, product_number INT, motherboard INT, ...
540273ac75880925934e69275c9da1de61fbd699
PyBingWallpaper.py
PyBingWallpaper.py
import win32gui from urllib.request import urlopen, urlretrieve from xml.dom import minidom from PIL import Image import os #Variables: saveDir = 'C:\BingWallPaper\\' i = 0 while i<1: try: usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN') except: i = 0 else: i = 1 xmldoc = minidom.parse(usock) num = 1 #Parsing the XML File for element in xmldoc.getElementsByTagName('url'): url = 'http://www.bing.com' + element.firstChild.nodeValue #Get Current Date as fileName for the downloaded Picture picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg' urlretrieve(url, picPath) #Convert Image picData = Image.open(picPath) picData.save(picPath.replace('jpg','bmp')) picPath = picPath.replace('jpg','bmp') num = num+1 #Set Wallpaper: win32gui.SystemParametersInfo(0x0014, picPath, 1+2)
import win32gui from urllib.request import urlopen, urlretrieve from xml.dom import minidom from PIL import Image import os if __name__=="__main__": #Variables: saveDir = "C:\\BingWallPaper\\" if (not os.path.exists(saveDir)): os.mkdir(saveDir) i = 0 while i<1: try: usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN') except: i = 0 else: i = 1 xmldoc = minidom.parse(usock) num = 1 #Parsing the XML File for element in xmldoc.getElementsByTagName('url'): url = 'http://www.bing.com' + element.firstChild.nodeValue #Get Current Date as fileName for the downloaded Picture picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg' urlretrieve(url, picPath) #Convert Image picData = Image.open(picPath) picData.save(picPath.replace('jpg','bmp')) picPath = picPath.replace('jpg','bmp') num = num+1 #Set Wallpaper: win32gui.SystemParametersInfo(0x0014, picPath, 1+2)
Create directory in case not exist
Create directory in case not exist
Python
mit
adamadanandy/PyBingWallpaper
import win32gui from urllib.request import urlopen, urlretrieve from xml.dom import minidom from PIL import Image import os + if __name__=="__main__": + #Variables: + saveDir = "C:\\BingWallPaper\\" + + if (not os.path.exists(saveDir)): + os.mkdir(saveDir) + + i = 0 + while i<1: + try: + usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN') + except: + i = 0 + else: + i = 1 + xmldoc = minidom.parse(usock) + num = 1 + + #Parsing the XML File + for element in xmldoc.getElementsByTagName('url'): + url = 'http://www.bing.com' + element.firstChild.nodeValue + + #Get Current Date as fileName for the downloaded Picture + picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg' + urlretrieve(url, picPath) + #Convert Image + picData = Image.open(picPath) + picData.save(picPath.replace('jpg','bmp')) + picPath = picPath.replace('jpg','bmp') + num = num+1 + #Set Wallpaper: + win32gui.SystemParametersInfo(0x0014, picPath, 1+2) - #Variables: - saveDir = 'C:\BingWallPaper\\' - i = 0 - while i<1: - try: - usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN') - except: - i = 0 - else: - i = 1 - xmldoc = minidom.parse(usock) - num = 1 - #Parsing the XML File - for element in xmldoc.getElementsByTagName('url'): - url = 'http://www.bing.com' + element.firstChild.nodeValue - - #Get Current Date as fileName for the downloaded Picture - picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg' - urlretrieve(url, picPath) - #Convert Image - picData = Image.open(picPath) - picData.save(picPath.replace('jpg','bmp')) - picPath = picPath.replace('jpg','bmp') - num = num+1 - #Set Wallpaper: - win32gui.SystemParametersInfo(0x0014, picPath, 1+2) -
Create directory in case not exist
## Code Before: import win32gui from urllib.request import urlopen, urlretrieve from xml.dom import minidom from PIL import Image import os #Variables: saveDir = 'C:\BingWallPaper\\' i = 0 while i<1: try: usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN') except: i = 0 else: i = 1 xmldoc = minidom.parse(usock) num = 1 #Parsing the XML File for element in xmldoc.getElementsByTagName('url'): url = 'http://www.bing.com' + element.firstChild.nodeValue #Get Current Date as fileName for the downloaded Picture picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg' urlretrieve(url, picPath) #Convert Image picData = Image.open(picPath) picData.save(picPath.replace('jpg','bmp')) picPath = picPath.replace('jpg','bmp') num = num+1 #Set Wallpaper: win32gui.SystemParametersInfo(0x0014, picPath, 1+2) ## Instruction: Create directory in case not exist ## Code After: import win32gui from urllib.request import urlopen, urlretrieve from xml.dom import minidom from PIL import Image import os if __name__=="__main__": #Variables: saveDir = "C:\\BingWallPaper\\" if (not os.path.exists(saveDir)): os.mkdir(saveDir) i = 0 while i<1: try: usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN') except: i = 0 else: i = 1 xmldoc = minidom.parse(usock) num = 1 #Parsing the XML File for element in xmldoc.getElementsByTagName('url'): url = 'http://www.bing.com' + element.firstChild.nodeValue #Get Current Date as fileName for the downloaded Picture picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg' urlretrieve(url, picPath) #Convert Image picData = Image.open(picPath) picData.save(picPath.replace('jpg','bmp')) picPath = picPath.replace('jpg','bmp') num = num+1 #Set Wallpaper: win32gui.SystemParametersInfo(0x0014, picPath, 1+2)
# ... existing code ... if __name__=="__main__": #Variables: saveDir = "C:\\BingWallPaper\\" if (not os.path.exists(saveDir)): os.mkdir(saveDir) i = 0 while i<1: try: usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN') except: i = 0 else: i = 1 xmldoc = minidom.parse(usock) num = 1 #Parsing the XML File for element in xmldoc.getElementsByTagName('url'): url = 'http://www.bing.com' + element.firstChild.nodeValue #Get Current Date as fileName for the downloaded Picture picPath = saveDir + 'bingwallpaper' + '%d'%num + '.jpg' urlretrieve(url, picPath) #Convert Image picData = Image.open(picPath) picData.save(picPath.replace('jpg','bmp')) picPath = picPath.replace('jpg','bmp') num = num+1 #Set Wallpaper: win32gui.SystemParametersInfo(0x0014, picPath, 1+2) # ... rest of the code ...
ccb9aebb5f2338e12d8aa79d65fa1a6e972e76c2
todobackend/__init__.py
todobackend/__init__.py
from logging import getLogger, basicConfig, INFO from os import getenv from aiohttp import web from .middleware import cors_middleware_factory from .views import ( IndexView, TodoView, ) IP = '0.0.0.0' PORT = getenv('PORT', '8000') basicConfig(level=INFO) logger = getLogger(__name__) async def init(loop): app = web.Application(loop=loop, middlewares=[cors_middleware_factory]) # Routes app.router.add_route('*', '/', IndexView.dispatch) app.router.add_route('*', '/{uuid}', TodoView.dispatch) # Config logger.info("Starting server at %s:%s", IP, PORT) srv = await loop.create_server(app.make_handler(), IP, PORT) return srv
from logging import getLogger, basicConfig, INFO from os import getenv from aiohttp import web from .middleware import cors_middleware_factory from .views import ( IndexView, TodoView, ) IP = getenv('IP', '0.0.0.0') PORT = getenv('PORT', '8000') basicConfig(level=INFO) logger = getLogger(__name__) async def init(loop): app = web.Application(loop=loop, middlewares=[cors_middleware_factory]) # Routes app.router.add_route('*', '/', IndexView.dispatch) app.router.add_route('*', '/{uuid}', TodoView.dispatch) # Config logger.info("Starting server at %s:%s", IP, PORT) srv = await loop.create_server(app.make_handler(), IP, PORT) return srv
Allow users to specify IP
MOD: Allow users to specify IP
Python
mit
justuswilhelm/todobackend-aiohttp
from logging import getLogger, basicConfig, INFO from os import getenv from aiohttp import web from .middleware import cors_middleware_factory from .views import ( IndexView, TodoView, ) - IP = '0.0.0.0' + IP = getenv('IP', '0.0.0.0') PORT = getenv('PORT', '8000') basicConfig(level=INFO) logger = getLogger(__name__) async def init(loop): app = web.Application(loop=loop, middlewares=[cors_middleware_factory]) # Routes app.router.add_route('*', '/', IndexView.dispatch) app.router.add_route('*', '/{uuid}', TodoView.dispatch) # Config logger.info("Starting server at %s:%s", IP, PORT) srv = await loop.create_server(app.make_handler(), IP, PORT) return srv
Allow users to specify IP
## Code Before: from logging import getLogger, basicConfig, INFO from os import getenv from aiohttp import web from .middleware import cors_middleware_factory from .views import ( IndexView, TodoView, ) IP = '0.0.0.0' PORT = getenv('PORT', '8000') basicConfig(level=INFO) logger = getLogger(__name__) async def init(loop): app = web.Application(loop=loop, middlewares=[cors_middleware_factory]) # Routes app.router.add_route('*', '/', IndexView.dispatch) app.router.add_route('*', '/{uuid}', TodoView.dispatch) # Config logger.info("Starting server at %s:%s", IP, PORT) srv = await loop.create_server(app.make_handler(), IP, PORT) return srv ## Instruction: Allow users to specify IP ## Code After: from logging import getLogger, basicConfig, INFO from os import getenv from aiohttp import web from .middleware import cors_middleware_factory from .views import ( IndexView, TodoView, ) IP = getenv('IP', '0.0.0.0') PORT = getenv('PORT', '8000') basicConfig(level=INFO) logger = getLogger(__name__) async def init(loop): app = web.Application(loop=loop, middlewares=[cors_middleware_factory]) # Routes app.router.add_route('*', '/', IndexView.dispatch) app.router.add_route('*', '/{uuid}', TodoView.dispatch) # Config logger.info("Starting server at %s:%s", IP, PORT) srv = await loop.create_server(app.make_handler(), IP, PORT) return srv
... IP = getenv('IP', '0.0.0.0') PORT = getenv('PORT', '8000') ...
5babccca12e1cbef655957b038594eadb1fe63bc
nose2/tests/unit/test_prof_plugin.py
nose2/tests/unit/test_prof_plugin.py
import unittest2 from ..plugins import prof from ._common import Stub, FakeStartTestRunEvent class TestProfPlugin(unittest2.TestCase): tags = ['unit'] def setUp(self): self.plugin = prof.Profiler() self.hotshot = prof.hotshot self.stats = prof.stats prof.hotshot = Stub() prof.stats = Stub() def tearDown(self): prof.hotshot = self.hotshot prof.stats = self.stats def test_startTestRun_sets_executeTests(self): _prof = Stub() _prof.runcall = object() prof.hotshot.Profile = lambda filename: _prof event = FakeStartTestRunEvent() self.plugin.startTestRun(event) assert event.executeTests is _prof.runcall, \ "executeTests was not replaced"
from nose2.plugins import prof from nose2.events import StartTestRunEvent from nose2.tests._common import Stub, TestCase class TestProfPlugin(TestCase): tags = ['unit'] def setUp(self): self.plugin = prof.Profiler() self.hotshot = prof.hotshot self.stats = prof.stats prof.hotshot = Stub() prof.stats = Stub() def tearDown(self): prof.hotshot = self.hotshot prof.stats = self.stats def test_startTestRun_sets_executeTests(self): _prof = Stub() _prof.runcall = object() prof.hotshot.Profile = lambda filename: _prof event = StartTestRunEvent(runner=None, suite=None, result=None, startTime=None, executeTests=None) self.plugin.startTestRun(event) assert event.executeTests is _prof.runcall, \ "executeTests was not replaced"
Use real events and proper TestCase
Use real events and proper TestCase
Python
bsd-2-clause
ojengwa/nose2,ezigman/nose2,leth/nose2,ptthiem/nose2,leth/nose2,little-dude/nose2,ptthiem/nose2,ezigman/nose2,little-dude/nose2,ojengwa/nose2
- import unittest2 - - from ..plugins import prof + from nose2.plugins import prof - from ._common import Stub, FakeStartTestRunEvent + from nose2.events import StartTestRunEvent + from nose2.tests._common import Stub, TestCase - class TestProfPlugin(unittest2.TestCase): + class TestProfPlugin(TestCase): tags = ['unit'] def setUp(self): self.plugin = prof.Profiler() self.hotshot = prof.hotshot self.stats = prof.stats prof.hotshot = Stub() prof.stats = Stub() def tearDown(self): prof.hotshot = self.hotshot prof.stats = self.stats def test_startTestRun_sets_executeTests(self): _prof = Stub() _prof.runcall = object() prof.hotshot.Profile = lambda filename: _prof - event = FakeStartTestRunEvent() + event = StartTestRunEvent(runner=None, suite=None, result=None, + startTime=None, executeTests=None) self.plugin.startTestRun(event) assert event.executeTests is _prof.runcall, \ "executeTests was not replaced"
Use real events and proper TestCase
## Code Before: import unittest2 from ..plugins import prof from ._common import Stub, FakeStartTestRunEvent class TestProfPlugin(unittest2.TestCase): tags = ['unit'] def setUp(self): self.plugin = prof.Profiler() self.hotshot = prof.hotshot self.stats = prof.stats prof.hotshot = Stub() prof.stats = Stub() def tearDown(self): prof.hotshot = self.hotshot prof.stats = self.stats def test_startTestRun_sets_executeTests(self): _prof = Stub() _prof.runcall = object() prof.hotshot.Profile = lambda filename: _prof event = FakeStartTestRunEvent() self.plugin.startTestRun(event) assert event.executeTests is _prof.runcall, \ "executeTests was not replaced" ## Instruction: Use real events and proper TestCase ## Code After: from nose2.plugins import prof from nose2.events import StartTestRunEvent from nose2.tests._common import Stub, TestCase class TestProfPlugin(TestCase): tags = ['unit'] def setUp(self): self.plugin = prof.Profiler() self.hotshot = prof.hotshot self.stats = prof.stats prof.hotshot = Stub() prof.stats = Stub() def tearDown(self): prof.hotshot = self.hotshot prof.stats = self.stats def test_startTestRun_sets_executeTests(self): _prof = Stub() _prof.runcall = object() prof.hotshot.Profile = lambda filename: _prof event = StartTestRunEvent(runner=None, suite=None, result=None, startTime=None, executeTests=None) self.plugin.startTestRun(event) assert event.executeTests is _prof.runcall, \ "executeTests was not replaced"
... from nose2.plugins import prof from nose2.events import StartTestRunEvent from nose2.tests._common import Stub, TestCase ... class TestProfPlugin(TestCase): tags = ['unit'] ... prof.hotshot.Profile = lambda filename: _prof event = StartTestRunEvent(runner=None, suite=None, result=None, startTime=None, executeTests=None) self.plugin.startTestRun(event) ...
d1628356c7981748e2446c7b43d33d21cdef7e02
geoengine_partner/geo_partner.py
geoengine_partner/geo_partner.py
from openerp.osv import fields from base_geoengine import geo_model class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _name = "res.partner" _inherit = "res.partner" _columns = { 'geo_point': fields.geo_point('Addresses coordinate') }
from openerp.osv import fields from openerp.addons.base_geoengine import geo_model class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _name = "res.partner" _inherit = "res.partner" _columns = { 'geo_point': fields.geo_point('Addresses coordinate') }
Use absolute imports on opnerp.addons
[FIX] Use absolute imports on opnerp.addons
Python
agpl-3.0
OCA/geospatial,OCA/geospatial,OCA/geospatial
from openerp.osv import fields - from base_geoengine import geo_model + from openerp.addons.base_geoengine import geo_model class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _name = "res.partner" _inherit = "res.partner" _columns = { 'geo_point': fields.geo_point('Addresses coordinate') }
Use absolute imports on opnerp.addons
## Code Before: from openerp.osv import fields from base_geoengine import geo_model class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _name = "res.partner" _inherit = "res.partner" _columns = { 'geo_point': fields.geo_point('Addresses coordinate') } ## Instruction: Use absolute imports on opnerp.addons ## Code After: from openerp.osv import fields from openerp.addons.base_geoengine import geo_model class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _name = "res.partner" _inherit = "res.partner" _columns = { 'geo_point': fields.geo_point('Addresses coordinate') }
# ... existing code ... from openerp.osv import fields from openerp.addons.base_geoengine import geo_model # ... rest of the code ...
9ec0c5dc170db0f6ffa05c09ea1d0f3e950b76a5
djstripe/management/commands/djstripe_sync_customers.py
djstripe/management/commands/djstripe_sync_customers.py
from __future__ import unicode_literals from django.core.management.base import BaseCommand from ...settings import get_user_model from ...sync import sync_customer User = get_user_model() class Command(BaseCommand): help = "Sync customer data with stripe" def handle(self, *args, **options): qs = User.objects.exclude(customer__isnull=True) count = 0 total = qs.count() for user in qs: count += 1 perc = int(round(100 * (float(count) / float(total)))) print("[{0}/{1} {2}%] Syncing {3} [{4}]").format( count, total, perc, user.username, user.pk ) sync_customer(user)
from __future__ import unicode_literals from django.core.management.base import BaseCommand from ...settings import User from ...sync import sync_customer class Command(BaseCommand): help = "Sync customer data with stripe" def handle(self, *args, **options): qs = User.objects.exclude(customer__isnull=True) count = 0 total = qs.count() for user in qs: count += 1 perc = int(round(100 * (float(count) / float(total)))) print("[{0}/{1} {2}%] Syncing {3} [{4}]").format( count, total, perc, user.username, user.pk ) sync_customer(user)
Make this work with Django 1.4
Make this work with Django 1.4
Python
mit
cjrh/dj-stripe,koobs/dj-stripe,tkwon/dj-stripe,aliev/dj-stripe,kavdev/dj-stripe,ctrengove/dj-stripe,StErMi/dj-stripe,kavdev/dj-stripe,mthornhill/dj-stripe,areski/dj-stripe,aliev/dj-stripe,maxmalynowsky/django-stripe-rest,areski/dj-stripe,jleclanche/dj-stripe,rawjam/dj-stripe,koobs/dj-stripe,doctorwidget/dj-stripe,rawjam/dj-stripe,jameshiew/dj-stripe,davidgillies/dj-stripe,jleclanche/dj-stripe,benmurden/dj-stripe,iddqd1/dj-stripe,photocrowd/dj-stripe,jameshiew/dj-stripe,andrewyoung1991/dj-stripe,LaunchlabAU/dj-stripe,davidgillies/dj-stripe,benmurden/dj-stripe,mwarkentin/dj-stripe,tkwon/dj-stripe,dj-stripe/dj-stripe,andrewyoung1991/dj-stripe,LaunchlabAU/dj-stripe,dj-stripe/dj-stripe,mwarkentin/dj-stripe,StErMi/dj-stripe,cjrh/dj-stripe,pydanny/dj-stripe,doctorwidget/dj-stripe,mthornhill/dj-stripe,ctrengove/dj-stripe,iddqd1/dj-stripe,photocrowd/dj-stripe,jpadilla/dj-stripe,jpadilla/dj-stripe,pydanny/dj-stripe
from __future__ import unicode_literals from django.core.management.base import BaseCommand - - from ...settings import get_user_model + from ...settings import User from ...sync import sync_customer - User = get_user_model() class Command(BaseCommand): help = "Sync customer data with stripe" def handle(self, *args, **options): qs = User.objects.exclude(customer__isnull=True) count = 0 total = qs.count() for user in qs: count += 1 perc = int(round(100 * (float(count) / float(total)))) print("[{0}/{1} {2}%] Syncing {3} [{4}]").format( count, total, perc, user.username, user.pk ) sync_customer(user)
Make this work with Django 1.4
## Code Before: from __future__ import unicode_literals from django.core.management.base import BaseCommand from ...settings import get_user_model from ...sync import sync_customer User = get_user_model() class Command(BaseCommand): help = "Sync customer data with stripe" def handle(self, *args, **options): qs = User.objects.exclude(customer__isnull=True) count = 0 total = qs.count() for user in qs: count += 1 perc = int(round(100 * (float(count) / float(total)))) print("[{0}/{1} {2}%] Syncing {3} [{4}]").format( count, total, perc, user.username, user.pk ) sync_customer(user) ## Instruction: Make this work with Django 1.4 ## Code After: from __future__ import unicode_literals from django.core.management.base import BaseCommand from ...settings import User from ...sync import sync_customer class Command(BaseCommand): help = "Sync customer data with stripe" def handle(self, *args, **options): qs = User.objects.exclude(customer__isnull=True) count = 0 total = qs.count() for user in qs: count += 1 perc = int(round(100 * (float(count) / float(total)))) print("[{0}/{1} {2}%] Syncing {3} [{4}]").format( count, total, perc, user.username, user.pk ) sync_customer(user)
// ... existing code ... from ...settings import User from ...sync import sync_customer // ... modified code ... // ... rest of the code ...
72068701db46dc3d66cde295187b7d167cbfd880
gather/account/api.py
gather/account/api.py
from flask import g, jsonify from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token )
from flask import g, jsonify, request from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) @bp.route("/account/change_password/", methods=["POST"]) def _change_password(): new_password = request.form["password"] user = Account.query.filter_by(username="Madimo").first_or_404() user.change_password(new_password) user.save return jsonify( code=200, user=user )
Add API to change password
Add API to change password
Python
mit
whtsky/Gather,whtsky/Gather
- from flask import g, jsonify + from flask import g, jsonify, request from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) + + @bp.route("/account/change_password/", methods=["POST"]) + def _change_password(): + new_password = request.form["password"] + user = Account.query.filter_by(username="Madimo").first_or_404() + user.change_password(new_password) + user.save + return jsonify( + code=200, + user=user + ) +
Add API to change password
## Code Before: from flask import g, jsonify from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) ## Instruction: Add API to change password ## Code After: from flask import g, jsonify, request from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) @bp.route("/account/change_password/", methods=["POST"]) def _change_password(): new_password = request.form["password"] user = Account.query.filter_by(username="Madimo").first_or_404() user.change_password(new_password) user.save return jsonify( code=200, user=user )
# ... existing code ... from flask import g, jsonify, request from gather.account.models import Account # ... modified code ... ) @bp.route("/account/change_password/", methods=["POST"]) def _change_password(): new_password = request.form["password"] user = Account.query.filter_by(username="Madimo").first_or_404() user.change_password(new_password) user.save return jsonify( code=200, user=user ) # ... rest of the code ...
e2d51e23f530202b82ba13ae11c686deb1388435
prototype/BioID.py
prototype/BioID.py
import re import json import mmap class BioID: defs = None def __init__(self, defpath): with open(defpath, "r") as deffile: conts = deffile.read() self.defs = json.loads(conts)["formats"] @classmethod def identify(cls, files): recog = {} for file in files: with open(file, "r") as infile: buff = infile.read() mem_map = mmap.mmap(infile.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ) if len(buff) == 0: recog[file] = "empty" # Empty files have no format :) continue for fdef in cls.defs: matched = True if "regexen" in fdef: for regex in fdef["regexen"]: if not re.findall(regex.replace("\\n", "\n"), buff, re.IGNORECASE): matched = False break if "bytes" in fdef: for bytes in fdef["bytes"]: if mem_map.find(bytes.decode("string_escape")) == -1: matched = False break if matched: recog[file] = fdef["name"] break mem_map.close() if file not in recog: recog[file] = "unrecognized" return recog
import re import json import mmap class BioID: defs = None def __init__(self, defpath): with open(defpath, "r") as deffile: conts = deffile.read() self.defs = json.loads(conts)["formats"] @classmethod def identify(cls, files): recog = {} for file in files: with open(file, "r") as infile: buff = infile.read() mem_map = mmap.mmap(infile.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ) if len(buff) == 0: recog[file] = "empty" # Empty files have no format :) continue for fdef in cls.defs: matched = True if "regexen" in fdef: for regex in fdef["regexen"]: if not re.findall(regex.replace("\\n", "\n"), buff, re.IGNORECASE): matched = False break if "bytes" in fdef: for bytes in fdef["bytes"]: if mem_map.find(bytes.decode("string_escape")) == -1: matched = False break if matched: recog[file] = fdef["name"] break mem_map.close() if file not in recog: recog[file] = "unrecognized" return recog
Indent return in identify class.
Indent return in identify class.
Python
mit
LeeBergstrand/BioMagick,LeeBergstrand/BioMagick
import re import json import mmap class BioID: - defs = None + defs = None - def __init__(self, defpath): + def __init__(self, defpath): - with open(defpath, "r") as deffile: + with open(defpath, "r") as deffile: - conts = deffile.read() + conts = deffile.read() - self.defs = json.loads(conts)["formats"] + self.defs = json.loads(conts)["formats"] - @classmethod + @classmethod - def identify(cls, files): + def identify(cls, files): - recog = {} + recog = {} - for file in files: + for file in files: - with open(file, "r") as infile: + with open(file, "r") as infile: - buff = infile.read() + buff = infile.read() - mem_map = mmap.mmap(infile.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ) + mem_map = mmap.mmap(infile.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ) - if len(buff) == 0: + if len(buff) == 0: - recog[file] = "empty" # Empty files have no format :) + recog[file] = "empty" # Empty files have no format :) - continue + continue - for fdef in cls.defs: - matched = True - if "regexen" in fdef: - for regex in fdef["regexen"]: + for fdef in cls.defs: + matched = True + if "regexen" in fdef: + for regex in fdef["regexen"]: if not re.findall(regex.replace("\\n", "\n"), buff, re.IGNORECASE): - matched = False - break - if "bytes" in fdef: - for bytes in fdef["bytes"]: + matched = False + break + if "bytes" in fdef: + for bytes in fdef["bytes"]: - if mem_map.find(bytes.decode("string_escape")) == -1: + if mem_map.find(bytes.decode("string_escape")) == -1: - matched = False - break - if matched: - recog[file] = fdef["name"] - break + matched = False + break + if matched: + recog[file] = fdef["name"] + break - mem_map.close() + mem_map.close() - if file not in recog: + if file not in recog: - recog[file] = "unrecognized" + recog[file] = "unrecognized" - return recog + return recog
Indent return in identify class.
## Code Before: import re import json import mmap class BioID: defs = None def __init__(self, defpath): with open(defpath, "r") as deffile: conts = deffile.read() self.defs = json.loads(conts)["formats"] @classmethod def identify(cls, files): recog = {} for file in files: with open(file, "r") as infile: buff = infile.read() mem_map = mmap.mmap(infile.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ) if len(buff) == 0: recog[file] = "empty" # Empty files have no format :) continue for fdef in cls.defs: matched = True if "regexen" in fdef: for regex in fdef["regexen"]: if not re.findall(regex.replace("\\n", "\n"), buff, re.IGNORECASE): matched = False break if "bytes" in fdef: for bytes in fdef["bytes"]: if mem_map.find(bytes.decode("string_escape")) == -1: matched = False break if matched: recog[file] = fdef["name"] break mem_map.close() if file not in recog: recog[file] = "unrecognized" return recog ## Instruction: Indent return in identify class. ## Code After: import re import json import mmap class BioID: defs = None def __init__(self, defpath): with open(defpath, "r") as deffile: conts = deffile.read() self.defs = json.loads(conts)["formats"] @classmethod def identify(cls, files): recog = {} for file in files: with open(file, "r") as infile: buff = infile.read() mem_map = mmap.mmap(infile.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ) if len(buff) == 0: recog[file] = "empty" # Empty files have no format :) continue for fdef in cls.defs: matched = True if "regexen" in fdef: for regex in fdef["regexen"]: if not re.findall(regex.replace("\\n", "\n"), buff, re.IGNORECASE): matched = False break if "bytes" in fdef: for bytes in fdef["bytes"]: if mem_map.find(bytes.decode("string_escape")) == -1: matched = False break if matched: recog[file] = fdef["name"] break mem_map.close() if file not in recog: recog[file] = "unrecognized" return recog
// ... existing code ... class BioID: defs = None def __init__(self, defpath): with open(defpath, "r") as deffile: conts = deffile.read() self.defs = json.loads(conts)["formats"] @classmethod def identify(cls, files): recog = {} for file in files: with open(file, "r") as infile: buff = infile.read() mem_map = mmap.mmap(infile.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ) if len(buff) == 0: recog[file] = "empty" # Empty files have no format :) continue for fdef in cls.defs: matched = True if "regexen" in fdef: for regex in fdef["regexen"]: if not re.findall(regex.replace("\\n", "\n"), buff, re.IGNORECASE): matched = False break if "bytes" in fdef: for bytes in fdef["bytes"]: if mem_map.find(bytes.decode("string_escape")) == -1: matched = False break if matched: recog[file] = fdef["name"] break mem_map.close() if file not in recog: recog[file] = "unrecognized" return recog // ... rest of the code ...
6a4046aafe43930c202e2f18a55b1cd8517d95f9
testanalyzer/javaanalyzer.py
testanalyzer/javaanalyzer.py
import re from fileanalyzer import FileAnalyzer class JavaAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_]+ *\n*\{", content)) # TODO: Accept angle brackets and decline "else if" def get_function_count(self, content): return len( re.findall( "[a-zA-Z ]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\] \n]*\)[a-zA-Z \n]*\{", content))
import re from fileanalyzer import FileAnalyzer class JavaAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_<>, ]+\n*\{", content)) def get_function_count(self, content): matches = re.findall( "[a-zA-Z <>]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\]<>\?\. \n]*\)[a-zA-Z \n]*\{", content) matches = [ m for m in matches if "if " not in m.strip() and "if(" not in m.strip() ] return len(matches)
Fix regex to match generics
Fix regex to match generics
Python
mpl-2.0
CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer
import re from fileanalyzer import FileAnalyzer class JavaAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( - re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_]+ *\n*\{", content)) + re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_<>, ]+\n*\{", content)) - # TODO: Accept angle brackets and decline "else if" def get_function_count(self, content): - return len( - re.findall( + matches = re.findall( - "[a-zA-Z ]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\] \n]*\)[a-zA-Z \n]*\{", + "[a-zA-Z <>]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\]<>\?\. \n]*\)[a-zA-Z \n]*\{", - content)) + content) + matches = [ + m for m in matches + if "if " not in m.strip() and "if(" not in m.strip() + ] + return len(matches)
Fix regex to match generics
## Code Before: import re from fileanalyzer import FileAnalyzer class JavaAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_]+ *\n*\{", content)) # TODO: Accept angle brackets and decline "else if" def get_function_count(self, content): return len( re.findall( "[a-zA-Z ]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\] \n]*\)[a-zA-Z \n]*\{", content)) ## Instruction: Fix regex to match generics ## Code After: import re from fileanalyzer import FileAnalyzer class JavaAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_<>, ]+\n*\{", content)) def get_function_count(self, content): matches = re.findall( "[a-zA-Z <>]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\]<>\?\. \n]*\)[a-zA-Z \n]*\{", content) matches = [ m for m in matches if "if " not in m.strip() and "if(" not in m.strip() ] return len(matches)
# ... existing code ... return len( re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_<>, ]+\n*\{", content)) def get_function_count(self, content): matches = re.findall( "[a-zA-Z <>]+ +[a-zA-Z0-9_]+ *\n*\([a-zA-Z0-9_,\[\]<>\?\. \n]*\)[a-zA-Z \n]*\{", content) matches = [ m for m in matches if "if " not in m.strip() and "if(" not in m.strip() ] return len(matches) # ... rest of the code ...
4b1b5d0b71100fea17f127683a58533ef0e06fe9
bintools/splitter.py
bintools/splitter.py
import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os.path.basename(fromfile) filesize = os.path.getsize(fromfile) cont = True partnum = 0 while cont: if chunksize > filesize: cont = False chunksize = filesize chunk = __read_write_block(fromfile, chunksize) if not chunk: break partnum = partnum + 1 filename = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() chunksize *= 2 #### Private methods def __read_write_block(f, n): stream = open(f, 'rb') chunk = stream.read(n) stream.close() return chunk
import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir = os.getcwd(), offset = 0, limit = None, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os.path.basename(fromfile) filesize = os.path.getsize(fromfile) cont = True partnum = 0 while cont: if chunksize > filesize: # Do 1 more read if chunksize > filesize cont = False chunksize = filesize partnum = partnum + 1 tofile = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) chunk = __read_write_block(fromfile, chunksize, tofile) chunksize *= 2 #### Private methods def __read_write_block(fromfile, n, tofile, offset = 0): stream = open(fromfile, 'rb') chunk = stream.read(n) stream.close() if not chunk: return fileobj = open(tofile, 'wb') fileobj.write(chunk) fileobj.close() return fileobj
Refactor functions & add params
Refactor functions & add params
Python
apache-2.0
FernandoDoming/offset_finder
import os # Splits a file using the dsplit mechanism - def dsplit(fromfile, todir, chunksize = 1024): + def dsplit(fromfile, todir = os.getcwd(), offset = 0, limit = None, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os.path.basename(fromfile) filesize = os.path.getsize(fromfile) cont = True partnum = 0 while cont: if chunksize > filesize: + # Do 1 more read if chunksize > filesize cont = False chunksize = filesize - chunk = __read_write_block(fromfile, chunksize) - if not chunk: break partnum = partnum + 1 - filename = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) + tofile = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) + chunk = __read_write_block(fromfile, chunksize, tofile) - fileobj = open(filename, 'wb') - fileobj.write(chunk) - fileobj.close() chunksize *= 2 #### Private methods - def __read_write_block(f, n): + def __read_write_block(fromfile, n, tofile, offset = 0): - stream = open(f, 'rb') + stream = open(fromfile, 'rb') chunk = stream.read(n) stream.close() - return chunk + if not chunk: return + fileobj = open(tofile, 'wb') + fileobj.write(chunk) + fileobj.close() + return fileobj +
Refactor functions & add params
## Code Before: import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os.path.basename(fromfile) filesize = os.path.getsize(fromfile) cont = True partnum = 0 while cont: if chunksize > filesize: cont = False chunksize = filesize chunk = __read_write_block(fromfile, chunksize) if not chunk: break partnum = partnum + 1 filename = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() chunksize *= 2 #### Private methods def __read_write_block(f, n): stream = open(f, 'rb') chunk = stream.read(n) stream.close() return chunk ## Instruction: Refactor functions & add params ## Code After: import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir = os.getcwd(), offset = 0, limit = None, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os.path.basename(fromfile) filesize = os.path.getsize(fromfile) cont = True partnum = 0 while cont: if chunksize > filesize: # Do 1 more read if chunksize > filesize cont = False chunksize = filesize partnum = partnum + 1 tofile = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) chunk = __read_write_block(fromfile, chunksize, tofile) chunksize *= 2 #### Private methods def __read_write_block(fromfile, n, tofile, offset = 0): stream = open(fromfile, 'rb') chunk = stream.read(n) stream.close() if not chunk: return fileobj = open(tofile, 'wb') fileobj.write(chunk) fileobj.close() return fileobj
... # Splits a file using the dsplit mechanism def dsplit(fromfile, todir = os.getcwd(), offset = 0, limit = None, chunksize = 1024): if not os.path.exists(todir): # caller handles errors ... if chunksize > filesize: # Do 1 more read if chunksize > filesize cont = False ... chunksize = filesize partnum = partnum + 1 tofile = os.path.join(todir, ('%s.part%d' % (original_file, partnum))) chunk = __read_write_block(fromfile, chunksize, tofile) chunksize *= 2 ... def __read_write_block(fromfile, n, tofile, offset = 0): stream = open(fromfile, 'rb') chunk = stream.read(n) ... stream.close() if not chunk: return fileobj = open(tofile, 'wb') fileobj.write(chunk) fileobj.close() return fileobj ...
4b6afd36114fbe1871f17998f9e3f4ec0e116f0f
spacy/lang/en/__init__.py
spacy/lang/en/__init__.py
from typing import Optional from thinc.api import Model from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .punctuation import TOKENIZER_INFIXES from .lemmatizer import EnglishLemmatizer from ...language import Language from ...lookups import Lookups from ...util import load_config_from_str DEFAULT_CONFIG = """ [initialize] [initialize.lookups] @misc = "spacy.LookupsDataLoader.v1" lang = ${nlp.lang} tables = ["lexeme_norm"] """ class EnglishDefaults(Language.Defaults): config = load_config_from_str(DEFAULT_CONFIG) tokenizer_exceptions = TOKENIZER_EXCEPTIONS infixes = TOKENIZER_INFIXES lex_attr_getters = LEX_ATTRS syntax_iterators = SYNTAX_ITERATORS stop_words = STOP_WORDS class English(Language): lang = "en" Defaults = EnglishDefaults @English.factory( "lemmatizer", assigns=["token.lemma"], default_config={"model": None, "mode": "rule", "lookups": None}, default_score_weights={"lemma_acc": 1.0}, ) def make_lemmatizer( nlp: Language, model: Optional[Model], name: str, mode: str, lookups: Optional[Lookups], ): lookups = EnglishLemmatizer.load_lookups(nlp.lang, mode, lookups) return EnglishLemmatizer(nlp.vocab, model, name, mode=mode, lookups=lookups) __all__ = ["English"]
from typing import Optional from thinc.api import Model from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .punctuation import TOKENIZER_INFIXES from .lemmatizer import EnglishLemmatizer from ...language import Language from ...lookups import Lookups class EnglishDefaults(Language.Defaults): tokenizer_exceptions = TOKENIZER_EXCEPTIONS infixes = TOKENIZER_INFIXES lex_attr_getters = LEX_ATTRS syntax_iterators = SYNTAX_ITERATORS stop_words = STOP_WORDS class English(Language): lang = "en" Defaults = EnglishDefaults @English.factory( "lemmatizer", assigns=["token.lemma"], default_config={"model": None, "mode": "rule", "lookups": None}, default_score_weights={"lemma_acc": 1.0}, ) def make_lemmatizer( nlp: Language, model: Optional[Model], name: str, mode: str, lookups: Optional[Lookups], ): lookups = EnglishLemmatizer.load_lookups(nlp.lang, mode, lookups) return EnglishLemmatizer(nlp.vocab, model, name, mode=mode, lookups=lookups) __all__ = ["English"]
Remove English [initialize] default block for now to get tests to pass
Remove English [initialize] default block for now to get tests to pass
Python
mit
spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy
from typing import Optional from thinc.api import Model from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .punctuation import TOKENIZER_INFIXES from .lemmatizer import EnglishLemmatizer from ...language import Language from ...lookups import Lookups - from ...util import load_config_from_str - - - DEFAULT_CONFIG = """ - [initialize] - - [initialize.lookups] - @misc = "spacy.LookupsDataLoader.v1" - lang = ${nlp.lang} - tables = ["lexeme_norm"] - """ class EnglishDefaults(Language.Defaults): - config = load_config_from_str(DEFAULT_CONFIG) tokenizer_exceptions = TOKENIZER_EXCEPTIONS infixes = TOKENIZER_INFIXES lex_attr_getters = LEX_ATTRS syntax_iterators = SYNTAX_ITERATORS stop_words = STOP_WORDS class English(Language): lang = "en" Defaults = EnglishDefaults @English.factory( "lemmatizer", assigns=["token.lemma"], default_config={"model": None, "mode": "rule", "lookups": None}, default_score_weights={"lemma_acc": 1.0}, ) def make_lemmatizer( nlp: Language, model: Optional[Model], name: str, mode: str, lookups: Optional[Lookups], ): lookups = EnglishLemmatizer.load_lookups(nlp.lang, mode, lookups) return EnglishLemmatizer(nlp.vocab, model, name, mode=mode, lookups=lookups) __all__ = ["English"]
Remove English [initialize] default block for now to get tests to pass
## Code Before: from typing import Optional from thinc.api import Model from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .punctuation import TOKENIZER_INFIXES from .lemmatizer import EnglishLemmatizer from ...language import Language from ...lookups import Lookups from ...util import load_config_from_str DEFAULT_CONFIG = """ [initialize] [initialize.lookups] @misc = "spacy.LookupsDataLoader.v1" lang = ${nlp.lang} tables = ["lexeme_norm"] """ class EnglishDefaults(Language.Defaults): config = load_config_from_str(DEFAULT_CONFIG) tokenizer_exceptions = TOKENIZER_EXCEPTIONS infixes = TOKENIZER_INFIXES lex_attr_getters = LEX_ATTRS syntax_iterators = SYNTAX_ITERATORS stop_words = STOP_WORDS class English(Language): lang = "en" Defaults = EnglishDefaults @English.factory( "lemmatizer", assigns=["token.lemma"], default_config={"model": None, "mode": "rule", "lookups": None}, default_score_weights={"lemma_acc": 1.0}, ) def make_lemmatizer( nlp: Language, model: Optional[Model], name: str, mode: str, lookups: Optional[Lookups], ): lookups = EnglishLemmatizer.load_lookups(nlp.lang, mode, lookups) return EnglishLemmatizer(nlp.vocab, model, name, mode=mode, lookups=lookups) __all__ = ["English"] ## Instruction: Remove English [initialize] default block for now to get tests to pass ## Code After: from typing import Optional from thinc.api import Model from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .punctuation import TOKENIZER_INFIXES from .lemmatizer import EnglishLemmatizer from ...language import Language from ...lookups import Lookups class EnglishDefaults(Language.Defaults): tokenizer_exceptions = TOKENIZER_EXCEPTIONS infixes = TOKENIZER_INFIXES lex_attr_getters = LEX_ATTRS syntax_iterators = SYNTAX_ITERATORS stop_words = STOP_WORDS class English(Language): lang = "en" Defaults = EnglishDefaults @English.factory( "lemmatizer", assigns=["token.lemma"], default_config={"model": None, "mode": "rule", "lookups": None}, default_score_weights={"lemma_acc": 1.0}, ) def make_lemmatizer( nlp: Language, model: Optional[Model], name: str, mode: str, lookups: Optional[Lookups], ): lookups = EnglishLemmatizer.load_lookups(nlp.lang, mode, lookups) return EnglishLemmatizer(nlp.vocab, model, name, mode=mode, lookups=lookups) __all__ = ["English"]
// ... existing code ... from ...lookups import Lookups // ... modified code ... class EnglishDefaults(Language.Defaults): tokenizer_exceptions = TOKENIZER_EXCEPTIONS // ... rest of the code ...
e9fd097aac951e6d38246fc4fb01db0e0b6513eb
scikits/talkbox/__init__.py
scikits/talkbox/__init__.py
from linpred import * import linpred __all__ = linpred.__all__ from tools import * import tools __all__ += tools.__all__
from linpred import * import linpred __all__ = linpred.__all__ from tools import * import tools __all__ += tools.__all__ from numpy.testing import Tester test = Tester().test bench = Tester().bench
Add module-wide bench and test functions.
Add module-wide bench and test functions.
Python
mit
cournape/talkbox,cournape/talkbox
from linpred import * import linpred __all__ = linpred.__all__ from tools import * import tools __all__ += tools.__all__ + from numpy.testing import Tester + + test = Tester().test + bench = Tester().bench +
Add module-wide bench and test functions.
## Code Before: from linpred import * import linpred __all__ = linpred.__all__ from tools import * import tools __all__ += tools.__all__ ## Instruction: Add module-wide bench and test functions. ## Code After: from linpred import * import linpred __all__ = linpred.__all__ from tools import * import tools __all__ += tools.__all__ from numpy.testing import Tester test = Tester().test bench = Tester().bench
# ... existing code ... __all__ += tools.__all__ from numpy.testing import Tester test = Tester().test bench = Tester().bench # ... rest of the code ...
6c59040e8c4aab37ff0c053e295b5b9705365d94
diylang/interpreter.py
diylang/interpreter.py
from os.path import dirname, join from .evaluator import evaluate from .parser import parse, unparse, parse_multiple from .types import Environment def interpret(source, env=None): """ Interpret a DIY Lang program statement Accepts a program statement as a string, interprets it, and then returns the resulting DIY Lang expression as string. """ if env is None: env = Environment() return unparse(evaluate(parse(source), env)) def interpret_file(filename, env=None): """ Interpret a DIY Lang file Accepts the name of a DIY Lang file containing a series of statements. Returns the value of the last expression of the file. """ if env is None: env = Environment() with open(filename, 'r') as sourcefile: source = "".join(sourcefile.readlines()) asts = parse_multiple(source) results = [evaluate(ast, env) for ast in asts] return unparse(results[-1])
from .evaluator import evaluate from .parser import parse, unparse, parse_multiple from .types import Environment def interpret(source, env=None): """ Interpret a DIY Lang program statement Accepts a program statement as a string, interprets it, and then returns the resulting DIY Lang expression as string. """ if env is None: env = Environment() return unparse(evaluate(parse(source), env)) def interpret_file(filename, env=None): """ Interpret a DIY Lang file Accepts the name of a DIY Lang file containing a series of statements. Returns the value of the last expression of the file. """ if env is None: env = Environment() with open(filename, 'r') as sourcefile: source = "".join(sourcefile.readlines()) asts = parse_multiple(source) results = [evaluate(ast, env) for ast in asts] return unparse(results[-1])
Remove unused imports in interpeter.
Remove unused imports in interpeter.
Python
bsd-3-clause
kvalle/diy-lang,kvalle/diy-lang,kvalle/diy-lisp,kvalle/diy-lisp
- - from os.path import dirname, join from .evaluator import evaluate from .parser import parse, unparse, parse_multiple from .types import Environment def interpret(source, env=None): """ Interpret a DIY Lang program statement Accepts a program statement as a string, interprets it, and then returns the resulting DIY Lang expression as string. """ if env is None: env = Environment() return unparse(evaluate(parse(source), env)) def interpret_file(filename, env=None): """ Interpret a DIY Lang file Accepts the name of a DIY Lang file containing a series of statements. Returns the value of the last expression of the file. """ if env is None: env = Environment() with open(filename, 'r') as sourcefile: source = "".join(sourcefile.readlines()) asts = parse_multiple(source) results = [evaluate(ast, env) for ast in asts] return unparse(results[-1])
Remove unused imports in interpeter.
## Code Before: from os.path import dirname, join from .evaluator import evaluate from .parser import parse, unparse, parse_multiple from .types import Environment def interpret(source, env=None): """ Interpret a DIY Lang program statement Accepts a program statement as a string, interprets it, and then returns the resulting DIY Lang expression as string. """ if env is None: env = Environment() return unparse(evaluate(parse(source), env)) def interpret_file(filename, env=None): """ Interpret a DIY Lang file Accepts the name of a DIY Lang file containing a series of statements. Returns the value of the last expression of the file. """ if env is None: env = Environment() with open(filename, 'r') as sourcefile: source = "".join(sourcefile.readlines()) asts = parse_multiple(source) results = [evaluate(ast, env) for ast in asts] return unparse(results[-1]) ## Instruction: Remove unused imports in interpeter. ## Code After: from .evaluator import evaluate from .parser import parse, unparse, parse_multiple from .types import Environment def interpret(source, env=None): """ Interpret a DIY Lang program statement Accepts a program statement as a string, interprets it, and then returns the resulting DIY Lang expression as string. """ if env is None: env = Environment() return unparse(evaluate(parse(source), env)) def interpret_file(filename, env=None): """ Interpret a DIY Lang file Accepts the name of a DIY Lang file containing a series of statements. Returns the value of the last expression of the file. """ if env is None: env = Environment() with open(filename, 'r') as sourcefile: source = "".join(sourcefile.readlines()) asts = parse_multiple(source) results = [evaluate(ast, env) for ast in asts] return unparse(results[-1])
... ...
f22beb7995fb20c477d837c0400b77480e5f1a13
yunity/users/tests/test_model.py
yunity/users/tests/test_model.py
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.exampleuser = { 'display_name': 'bla', 'email': '[email protected]', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long)
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase from yunity.users.factories import UserFactory class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = UserFactory() cls.exampleuser = { 'display_name': 'bla', 'email': '[email protected]', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) def test_user_representation(self): r = repr(self.user) self.assertTrue(self.user.display_name in r)
Add test for model representation
Add test for model representation
Python
agpl-3.0
yunity/foodsaving-backend,yunity/yunity-core,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase + + from yunity.users.factories import UserFactory class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() + cls.user = UserFactory() cls.exampleuser = { 'display_name': 'bla', 'email': '[email protected]', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) + def test_user_representation(self): + r = repr(self.user) + self.assertTrue(self.user.display_name in r) +
Add test for model representation
## Code Before: from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.exampleuser = { 'display_name': 'bla', 'email': '[email protected]', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) ## Instruction: Add test for model representation ## Code After: from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase from yunity.users.factories import UserFactory class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = UserFactory() cls.exampleuser = { 'display_name': 'bla', 'email': '[email protected]', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) def test_user_representation(self): r = repr(self.user) self.assertTrue(self.user.display_name in r)
... from django.test import TestCase from yunity.users.factories import UserFactory ... super().setUpClass() cls.user = UserFactory() cls.exampleuser = { ... get_user_model().objects.create_user(**too_long) def test_user_representation(self): r = repr(self.user) self.assertTrue(self.user.display_name in r) ...
73eacdde5067e60f40af000237d198748c5b3cc7
PYNWapp/PYNWsite/models.py
PYNWapp/PYNWsite/models.py
from __future__ import unicode_literals from django.db import models from django.utils import timezone # Create your models here. class Event(models.Model): name = models.CharField(max_length=200) location = models.CharField(max_length=300) event_date = models.DateTimeField('event date') description = models.TextField() def __str__(self): return self.name def is_future(self): return self.event_date > timezone.now() class Post(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) body = models.TextField() posted = models.DateField(db_index=True, auto_now_add=True) category = models.ForeignKey('Category') class Category(models.Model): title = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True)
from __future__ import unicode_literals from django.db import models from django.utils import timezone # Create your models here. class Event(models.Model): name = models.CharField(max_length=200) location = models.CharField(max_length=300) event_date = models.DateTimeField('event date') description = models.TextField() def __str__(self): return self.name def is_future(self): return self.event_date > timezone.now() class Post(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) body = models.TextField() posted = models.DateField(db_index=True, auto_now_add=True) category = models.ForeignKey('Category') class Category(models.Model): title = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) class Meta: verbose_name_plural = 'Categories'
Fix plural name for Categories model.
Fix plural name for Categories model.
Python
mit
PythonNorthwestEngland/pynw-website,PythonNorthwestEngland/pynw-website
from __future__ import unicode_literals from django.db import models from django.utils import timezone # Create your models here. class Event(models.Model): name = models.CharField(max_length=200) location = models.CharField(max_length=300) event_date = models.DateTimeField('event date') description = models.TextField() def __str__(self): return self.name def is_future(self): return self.event_date > timezone.now() class Post(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) body = models.TextField() posted = models.DateField(db_index=True, auto_now_add=True) category = models.ForeignKey('Category') class Category(models.Model): title = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) + class Meta: + verbose_name_plural = 'Categories' +
Fix plural name for Categories model.
## Code Before: from __future__ import unicode_literals from django.db import models from django.utils import timezone # Create your models here. class Event(models.Model): name = models.CharField(max_length=200) location = models.CharField(max_length=300) event_date = models.DateTimeField('event date') description = models.TextField() def __str__(self): return self.name def is_future(self): return self.event_date > timezone.now() class Post(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) body = models.TextField() posted = models.DateField(db_index=True, auto_now_add=True) category = models.ForeignKey('Category') class Category(models.Model): title = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) ## Instruction: Fix plural name for Categories model. ## Code After: from __future__ import unicode_literals from django.db import models from django.utils import timezone # Create your models here. class Event(models.Model): name = models.CharField(max_length=200) location = models.CharField(max_length=300) event_date = models.DateTimeField('event date') description = models.TextField() def __str__(self): return self.name def is_future(self): return self.event_date > timezone.now() class Post(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) body = models.TextField() posted = models.DateField(db_index=True, auto_now_add=True) category = models.ForeignKey('Category') class Category(models.Model): title = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) class Meta: verbose_name_plural = 'Categories'
# ... existing code ... slug = models.SlugField(max_length=100, db_index=True) class Meta: verbose_name_plural = 'Categories' # ... rest of the code ...
e29b1f6243fb7f9d2322b80573617ff9a0582d01
pinax/blog/parsers/markdown_parser.py
pinax/blog/parsers/markdown_parser.py
from markdown import Markdown from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE from ..models import Image class ImageLookupImagePattern(ImagePattern): def sanitize_url(self, url): if url.startswith("http"): return url else: try: image = Image.objects.get(pk=int(url)) return image.image_path.url except Image.DoesNotExist: pass except ValueError: return url return "" def parse(text): md = Markdown(extensions=["codehilite"]) md.inlinePatterns["image_link"] = ImageLookupImagePattern(IMAGE_LINK_RE, md) html = md.convert(text) return html
from markdown import Markdown from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE from ..models import Image class ImageLookupImagePattern(ImagePattern): def sanitize_url(self, url): if url.startswith("http"): return url else: try: image = Image.objects.get(pk=int(url)) return image.image_path.url except Image.DoesNotExist: pass except ValueError: return url return "" def parse(text): md = Markdown(extensions=["codehilite", "tables", "smarty", "admonition", "toc"]) md.inlinePatterns["image_link"] = ImageLookupImagePattern(IMAGE_LINK_RE, md) html = md.convert(text) return html
Add some extensions to the markdown parser
Add some extensions to the markdown parser Ultimately we should make this a setting or hookset so it could be overridden at the site level.
Python
mit
swilcox/pinax-blog,pinax/pinax-blog,miurahr/pinax-blog,miurahr/pinax-blog,swilcox/pinax-blog,easton402/pinax-blog,pinax/pinax-blog,pinax/pinax-blog,easton402/pinax-blog
from markdown import Markdown from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE from ..models import Image class ImageLookupImagePattern(ImagePattern): def sanitize_url(self, url): if url.startswith("http"): return url else: try: image = Image.objects.get(pk=int(url)) return image.image_path.url except Image.DoesNotExist: pass except ValueError: return url return "" def parse(text): - md = Markdown(extensions=["codehilite"]) + md = Markdown(extensions=["codehilite", "tables", "smarty", "admonition", "toc"]) md.inlinePatterns["image_link"] = ImageLookupImagePattern(IMAGE_LINK_RE, md) html = md.convert(text) return html
Add some extensions to the markdown parser
## Code Before: from markdown import Markdown from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE from ..models import Image class ImageLookupImagePattern(ImagePattern): def sanitize_url(self, url): if url.startswith("http"): return url else: try: image = Image.objects.get(pk=int(url)) return image.image_path.url except Image.DoesNotExist: pass except ValueError: return url return "" def parse(text): md = Markdown(extensions=["codehilite"]) md.inlinePatterns["image_link"] = ImageLookupImagePattern(IMAGE_LINK_RE, md) html = md.convert(text) return html ## Instruction: Add some extensions to the markdown parser ## Code After: from markdown import Markdown from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE from ..models import Image class ImageLookupImagePattern(ImagePattern): def sanitize_url(self, url): if url.startswith("http"): return url else: try: image = Image.objects.get(pk=int(url)) return image.image_path.url except Image.DoesNotExist: pass except ValueError: return url return "" def parse(text): md = Markdown(extensions=["codehilite", "tables", "smarty", "admonition", "toc"]) md.inlinePatterns["image_link"] = ImageLookupImagePattern(IMAGE_LINK_RE, md) html = md.convert(text) return html
... def parse(text): md = Markdown(extensions=["codehilite", "tables", "smarty", "admonition", "toc"]) md.inlinePatterns["image_link"] = ImageLookupImagePattern(IMAGE_LINK_RE, md) ...
a077a5b7731e7d609b5c3adc8f8176ad79053f17
rmake/lib/twisted_extras/tools.py
rmake/lib/twisted_extras/tools.py
from twisted.internet import defer class Serializer(object): def __init__(self): self._lock = defer.DeferredLock() self._waiting = {} def call(self, func, args=(), kwargs=None, collapsible=False): d = self._lock.acquire() self._waiting[d] = collapsible if not kwargs: kwargs = {} @d.addCallback def _locked(_): if collapsible and len(self._waiting) > 1: # Superseded return return func(*args, **kwargs) @d.addBoth def _unlock(result): self._lock.release() del self._waiting[d] return result return d
from twisted.internet import defer class Serializer(object): def __init__(self): self._lock = defer.DeferredLock() self._waiting = {} def call(self, func, args=(), kwargs=None, collapsible=False): d = self._lock.acquire() self._waiting[d] = collapsible if not kwargs: kwargs = {} @d.addCallback def _locked(_): if collapsible and len(self._waiting) > 1: # Superseded return return func(*args, **kwargs) @d.addBoth def _unlock(result): del self._waiting[d] self._lock.release() return result return d
Fix Serializer locking bug that caused it to skip calls it should have made
Fix Serializer locking bug that caused it to skip calls it should have made
Python
apache-2.0
sassoftware/rmake3,sassoftware/rmake3,sassoftware/rmake3
from twisted.internet import defer class Serializer(object): def __init__(self): self._lock = defer.DeferredLock() self._waiting = {} def call(self, func, args=(), kwargs=None, collapsible=False): d = self._lock.acquire() self._waiting[d] = collapsible if not kwargs: kwargs = {} @d.addCallback def _locked(_): if collapsible and len(self._waiting) > 1: # Superseded return return func(*args, **kwargs) @d.addBoth def _unlock(result): + del self._waiting[d] self._lock.release() - del self._waiting[d] return result return d
Fix Serializer locking bug that caused it to skip calls it should have made
## Code Before: from twisted.internet import defer class Serializer(object): def __init__(self): self._lock = defer.DeferredLock() self._waiting = {} def call(self, func, args=(), kwargs=None, collapsible=False): d = self._lock.acquire() self._waiting[d] = collapsible if not kwargs: kwargs = {} @d.addCallback def _locked(_): if collapsible and len(self._waiting) > 1: # Superseded return return func(*args, **kwargs) @d.addBoth def _unlock(result): self._lock.release() del self._waiting[d] return result return d ## Instruction: Fix Serializer locking bug that caused it to skip calls it should have made ## Code After: from twisted.internet import defer class Serializer(object): def __init__(self): self._lock = defer.DeferredLock() self._waiting = {} def call(self, func, args=(), kwargs=None, collapsible=False): d = self._lock.acquire() self._waiting[d] = collapsible if not kwargs: kwargs = {} @d.addCallback def _locked(_): if collapsible and len(self._waiting) > 1: # Superseded return return func(*args, **kwargs) @d.addBoth def _unlock(result): del self._waiting[d] self._lock.release() return result return d
# ... existing code ... def _unlock(result): del self._waiting[d] self._lock.release() return result # ... rest of the code ...
bd78472c14ce9ed487a563a958082b356e0b7c79
src/epiweb/apps/reminder/admin.py
src/epiweb/apps/reminder/admin.py
from django.contrib import admin from epiweb.apps.reminder.models import Reminder class ReminderAdmin(admin.ModelAdmin): list_display = ('user', 'wday', 'active', 'last_reminder', 'next_reminder') admin.site.register(Reminder, ReminderAdmin)
from django.contrib import admin from epiweb.apps.reminder.models import Reminder def make_active(modeladmin, request, queryset): queryset.update(active=True) make_active.short_description = 'Make selected reminders active' def make_inactive(modeladmin, request, queryset): queryset.update(active=False) make_inactive.short_description = 'Make selected reminders inactive' class ReminderAdmin(admin.ModelAdmin): list_display = ('user', 'wday', 'active', 'last_reminder', 'next_reminder') ordering = ('user__username',) actions = (make_active, make_inactive,) admin.site.register(Reminder, ReminderAdmin)
Add actions to make reminders active or inactive
Add actions to make reminders active or inactive
Python
agpl-3.0
ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website
from django.contrib import admin from epiweb.apps.reminder.models import Reminder + def make_active(modeladmin, request, queryset): + queryset.update(active=True) + make_active.short_description = 'Make selected reminders active' + + def make_inactive(modeladmin, request, queryset): + queryset.update(active=False) + make_inactive.short_description = 'Make selected reminders inactive' + class ReminderAdmin(admin.ModelAdmin): list_display = ('user', 'wday', 'active', 'last_reminder', 'next_reminder') + ordering = ('user__username',) + actions = (make_active, make_inactive,) admin.site.register(Reminder, ReminderAdmin)
Add actions to make reminders active or inactive
## Code Before: from django.contrib import admin from epiweb.apps.reminder.models import Reminder class ReminderAdmin(admin.ModelAdmin): list_display = ('user', 'wday', 'active', 'last_reminder', 'next_reminder') admin.site.register(Reminder, ReminderAdmin) ## Instruction: Add actions to make reminders active or inactive ## Code After: from django.contrib import admin from epiweb.apps.reminder.models import Reminder def make_active(modeladmin, request, queryset): queryset.update(active=True) make_active.short_description = 'Make selected reminders active' def make_inactive(modeladmin, request, queryset): queryset.update(active=False) make_inactive.short_description = 'Make selected reminders inactive' class ReminderAdmin(admin.ModelAdmin): list_display = ('user', 'wday', 'active', 'last_reminder', 'next_reminder') ordering = ('user__username',) actions = (make_active, make_inactive,) admin.site.register(Reminder, ReminderAdmin)
// ... existing code ... def make_active(modeladmin, request, queryset): queryset.update(active=True) make_active.short_description = 'Make selected reminders active' def make_inactive(modeladmin, request, queryset): queryset.update(active=False) make_inactive.short_description = 'Make selected reminders inactive' class ReminderAdmin(admin.ModelAdmin): // ... modified code ... 'last_reminder', 'next_reminder') ordering = ('user__username',) actions = (make_active, make_inactive,) // ... rest of the code ...
32ac109aec82210ccfa617b438a844b0f300157c
comics/core/context_processors.py
comics/core/context_processors.py
from django.conf import settings from django.db.models import Count, Max from comics.core.models import Comic def site_settings(request): return { 'site_title': settings.COMICS_SITE_TITLE, 'site_tagline': settings.COMICS_SITE_TAGLINE, 'google_analytics_code': settings.COMICS_GOOGLE_ANALYTICS_CODE, } def all_comics(request): all_comics = Comic.objects.sort_by_name() all_comics = all_comics.annotate(Max('release__fetched')) all_comics = all_comics.annotate(Count('release')) return {'all_comics': all_comics}
from django.conf import settings from django.db.models import Count, Max from comics.core.models import Comic def site_settings(request): return { 'site_title': settings.COMICS_SITE_TITLE, 'site_tagline': settings.COMICS_SITE_TAGLINE, 'google_analytics_code': settings.COMICS_GOOGLE_ANALYTICS_CODE, 'search_enabled': 'comics.search' in settings.INSTALLED_APPS, } def all_comics(request): all_comics = Comic.objects.sort_by_name() all_comics = all_comics.annotate(Max('release__fetched')) all_comics = all_comics.annotate(Count('release')) return {'all_comics': all_comics}
Add search_enabled to site settings context processor
Add search_enabled to site settings context processor
Python
agpl-3.0
jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,klette/comics,klette/comics,datagutten/comics,klette/comics,jodal/comics,datagutten/comics,jodal/comics
from django.conf import settings from django.db.models import Count, Max from comics.core.models import Comic def site_settings(request): return { 'site_title': settings.COMICS_SITE_TITLE, 'site_tagline': settings.COMICS_SITE_TAGLINE, 'google_analytics_code': settings.COMICS_GOOGLE_ANALYTICS_CODE, + 'search_enabled': 'comics.search' in settings.INSTALLED_APPS, } def all_comics(request): all_comics = Comic.objects.sort_by_name() all_comics = all_comics.annotate(Max('release__fetched')) all_comics = all_comics.annotate(Count('release')) return {'all_comics': all_comics}
Add search_enabled to site settings context processor
## Code Before: from django.conf import settings from django.db.models import Count, Max from comics.core.models import Comic def site_settings(request): return { 'site_title': settings.COMICS_SITE_TITLE, 'site_tagline': settings.COMICS_SITE_TAGLINE, 'google_analytics_code': settings.COMICS_GOOGLE_ANALYTICS_CODE, } def all_comics(request): all_comics = Comic.objects.sort_by_name() all_comics = all_comics.annotate(Max('release__fetched')) all_comics = all_comics.annotate(Count('release')) return {'all_comics': all_comics} ## Instruction: Add search_enabled to site settings context processor ## Code After: from django.conf import settings from django.db.models import Count, Max from comics.core.models import Comic def site_settings(request): return { 'site_title': settings.COMICS_SITE_TITLE, 'site_tagline': settings.COMICS_SITE_TAGLINE, 'google_analytics_code': settings.COMICS_GOOGLE_ANALYTICS_CODE, 'search_enabled': 'comics.search' in settings.INSTALLED_APPS, } def all_comics(request): all_comics = Comic.objects.sort_by_name() all_comics = all_comics.annotate(Max('release__fetched')) all_comics = all_comics.annotate(Count('release')) return {'all_comics': all_comics}
# ... existing code ... 'google_analytics_code': settings.COMICS_GOOGLE_ANALYTICS_CODE, 'search_enabled': 'comics.search' in settings.INSTALLED_APPS, } # ... rest of the code ...
cd219d5ee0ecbd54705c5add4239cef1513b8c2a
dodocs/__init__.py
dodocs/__init__.py
import sys import colorama from dodocs.cmdline import parse __version__ = "0.0.1" colorama.init(autoreset=True) def main(argv=None): """ Main code Parameters ---------- argv : list of strings, optional command line arguments """ args = parse(argv=argv) if args.subparser_name == "profile": from dodocs.profiles import main main(args) # elif args.subparser_name == "mkvenv": # from dodocs.venvs import create # create(args) # elif args.subparser_name == "build": # print("building") else: msg = colorama.Fore.RED + "Please provide a command." msg += " Valid commands are:\n * profile" # \n * create" sys.exit(msg)
import sys import colorama from dodocs.cmdline import parse __version__ = "0.0.1" colorama.init(autoreset=True) def main(argv=None): """ Main code Parameters ---------- argv : list of strings, optional command line arguments """ args = parse(argv=argv) try: args.func(args) except AttributeError: # defaults profile to list if args.subparser_name == 'profile' and args.profile_cmd is None: main([args.subparser_name, 'list']) # in the other cases suggest to run -h msg = colorama.Fore.RED + "Please provide a valid command." print(msg) msg = "Type\n " + sys.argv[0] if args.subparser_name is not None: msg += " " + args.subparser_name msg += ' -h' print(msg)
Use args.func. Deal with failures, default "profile'
Use args.func. Deal with failures, default "profile'
Python
mit
montefra/dodocs
import sys import colorama from dodocs.cmdline import parse __version__ = "0.0.1" colorama.init(autoreset=True) def main(argv=None): """ Main code Parameters ---------- argv : list of strings, optional command line arguments """ args = parse(argv=argv) + try: - if args.subparser_name == "profile": - from dodocs.profiles import main - main(args) + args.func(args) + except AttributeError: + # defaults profile to list + if args.subparser_name == 'profile' and args.profile_cmd is None: + main([args.subparser_name, 'list']) - # elif args.subparser_name == "mkvenv": - # from dodocs.venvs import create - # create(args) - # elif args.subparser_name == "build": - # print("building") - else: - msg = colorama.Fore.RED + "Please provide a command." - msg += " Valid commands are:\n * profile" # \n * create" - sys.exit(msg) + # in the other cases suggest to run -h + msg = colorama.Fore.RED + "Please provide a valid command." + print(msg) + msg = "Type\n " + sys.argv[0] + if args.subparser_name is not None: + msg += " " + args.subparser_name + msg += ' -h' + print(msg) +
Use args.func. Deal with failures, default "profile'
## Code Before: import sys import colorama from dodocs.cmdline import parse __version__ = "0.0.1" colorama.init(autoreset=True) def main(argv=None): """ Main code Parameters ---------- argv : list of strings, optional command line arguments """ args = parse(argv=argv) if args.subparser_name == "profile": from dodocs.profiles import main main(args) # elif args.subparser_name == "mkvenv": # from dodocs.venvs import create # create(args) # elif args.subparser_name == "build": # print("building") else: msg = colorama.Fore.RED + "Please provide a command." msg += " Valid commands are:\n * profile" # \n * create" sys.exit(msg) ## Instruction: Use args.func. Deal with failures, default "profile' ## Code After: import sys import colorama from dodocs.cmdline import parse __version__ = "0.0.1" colorama.init(autoreset=True) def main(argv=None): """ Main code Parameters ---------- argv : list of strings, optional command line arguments """ args = parse(argv=argv) try: args.func(args) except AttributeError: # defaults profile to list if args.subparser_name == 'profile' and args.profile_cmd is None: main([args.subparser_name, 'list']) # in the other cases suggest to run -h msg = colorama.Fore.RED + "Please provide a valid command." print(msg) msg = "Type\n " + sys.argv[0] if args.subparser_name is not None: msg += " " + args.subparser_name msg += ' -h' print(msg)
# ... existing code ... try: args.func(args) except AttributeError: # defaults profile to list if args.subparser_name == 'profile' and args.profile_cmd is None: main([args.subparser_name, 'list']) # in the other cases suggest to run -h msg = colorama.Fore.RED + "Please provide a valid command." print(msg) msg = "Type\n " + sys.argv[0] if args.subparser_name is not None: msg += " " + args.subparser_name msg += ' -h' print(msg) # ... rest of the code ...
282d6ae5911e4fcf4625a7e82e7024c5dc0722d8
tests/test_simple_persistence.py
tests/test_simple_persistence.py
from __future__ import unicode_literals, division, absolute_import from tests import FlexGetBase class TestSimplePersistence(FlexGetBase): __yaml__ = """ tasks: test: mock: - {title: 'irrelevant'} """ def test_setdefault(self): self.execute_task('test') task = self.task value1 = task.simple_persistence.setdefault('test', 'abc') value2 = task.simple_persistence.setdefault('test', 'def') assert value1 == value2, 'set default broken'
from __future__ import unicode_literals, division, absolute_import from flexget.manager import Session from flexget.utils.simple_persistence import SimplePersistence from tests import FlexGetBase class TestSimplePersistence(FlexGetBase): __yaml__ = """ tasks: test: mock: - {title: 'irrelevant'} """ def test_setdefault(self): self.execute_task('test') task = self.task value1 = task.simple_persistence.setdefault('test', 'abc') value2 = task.simple_persistence.setdefault('test', 'def') assert value1 == value2, 'set default broken' def test_nosession(self): persist = SimplePersistence('testplugin') persist['aoeu'] = 'test' assert persist['aoeu'] == 'test' # Make sure it commits and actually persists persist = SimplePersistence('testplugin') assert persist['aoeu'] == 'test' def test_withsession(self): session = Session() persist = SimplePersistence('testplugin', session=session) persist['aoeu'] = 'test' assert persist['aoeu'] == 'test' # Make sure it didn't commit or close our session session.rollback() assert 'aoeu' not in persist
Add some more tests for simple_persistence
Add some more tests for simple_persistence
Python
mit
cvium/Flexget,OmgOhnoes/Flexget,jawilson/Flexget,patsissons/Flexget,ZefQ/Flexget,tarzasai/Flexget,X-dark/Flexget,qk4l/Flexget,tsnoam/Flexget,Danfocus/Flexget,spencerjanssen/Flexget,crawln45/Flexget,oxc/Flexget,tvcsantos/Flexget,Flexget/Flexget,tarzasai/Flexget,tobinjt/Flexget,qvazzler/Flexget,Pretagonist/Flexget,LynxyssCZ/Flexget,ianstalk/Flexget,thalamus/Flexget,vfrc2/Flexget,LynxyssCZ/Flexget,camon/Flexget,thalamus/Flexget,spencerjanssen/Flexget,sean797/Flexget,offbyone/Flexget,offbyone/Flexget,xfouloux/Flexget,malkavi/Flexget,poulpito/Flexget,sean797/Flexget,dsemi/Flexget,patsissons/Flexget,ZefQ/Flexget,malkavi/Flexget,ZefQ/Flexget,drwyrm/Flexget,malkavi/Flexget,tvcsantos/Flexget,tsnoam/Flexget,grrr2/Flexget,Flexget/Flexget,jacobmetrick/Flexget,OmgOhnoes/Flexget,ibrahimkarahan/Flexget,Pretagonist/Flexget,qk4l/Flexget,ratoaq2/Flexget,gazpachoking/Flexget,drwyrm/Flexget,jawilson/Flexget,tarzasai/Flexget,spencerjanssen/Flexget,lildadou/Flexget,LynxyssCZ/Flexget,qvazzler/Flexget,asm0dey/Flexget,crawln45/Flexget,cvium/Flexget,tobinjt/Flexget,poulpito/Flexget,vfrc2/Flexget,JorisDeRieck/Flexget,jawilson/Flexget,offbyone/Flexget,qvazzler/Flexget,antivirtel/Flexget,xfouloux/Flexget,tobinjt/Flexget,thalamus/Flexget,Danfocus/Flexget,lildadou/Flexget,JorisDeRieck/Flexget,v17al/Flexget,malkavi/Flexget,X-dark/Flexget,lildadou/Flexget,dsemi/Flexget,oxc/Flexget,dsemi/Flexget,cvium/Flexget,v17al/Flexget,jawilson/Flexget,qk4l/Flexget,voriux/Flexget,voriux/Flexget,jacobmetrick/Flexget,antivirtel/Flexget,grrr2/Flexget,ianstalk/Flexget,tobinjt/Flexget,X-dark/Flexget,oxc/Flexget,jacobmetrick/Flexget,poulpito/Flexget,Danfocus/Flexget,ibrahimkarahan/Flexget,crawln45/Flexget,ibrahimkarahan/Flexget,gazpachoking/Flexget,v17al/Flexget,ianstalk/Flexget,tsnoam/Flexget,drwyrm/Flexget,patsissons/Flexget,Flexget/Flexget,ratoaq2/Flexget,JorisDeRieck/Flexget,JorisDeRieck/Flexget,LynxyssCZ/Flexget,sean797/Flexget,asm0dey/Flexget,OmgOhnoes/Flexget,Flexget/Flexget,vfrc2/Flexget,ratoaq2/Flexget,Danfocus/Flexget,grrr2/Flexget,antivirtel/Flexget,asm0dey/Flexget,Pretagonist/Flexget,xfouloux/Flexget,camon/Flexget,crawln45/Flexget
from __future__ import unicode_literals, division, absolute_import + + from flexget.manager import Session + from flexget.utils.simple_persistence import SimplePersistence from tests import FlexGetBase class TestSimplePersistence(FlexGetBase): __yaml__ = """ tasks: test: mock: - {title: 'irrelevant'} """ def test_setdefault(self): self.execute_task('test') task = self.task value1 = task.simple_persistence.setdefault('test', 'abc') value2 = task.simple_persistence.setdefault('test', 'def') assert value1 == value2, 'set default broken' + def test_nosession(self): + persist = SimplePersistence('testplugin') + persist['aoeu'] = 'test' + assert persist['aoeu'] == 'test' + # Make sure it commits and actually persists + persist = SimplePersistence('testplugin') + assert persist['aoeu'] == 'test' + + def test_withsession(self): + session = Session() + persist = SimplePersistence('testplugin', session=session) + persist['aoeu'] = 'test' + assert persist['aoeu'] == 'test' + # Make sure it didn't commit or close our session + session.rollback() + assert 'aoeu' not in persist +
Add some more tests for simple_persistence
## Code Before: from __future__ import unicode_literals, division, absolute_import from tests import FlexGetBase class TestSimplePersistence(FlexGetBase): __yaml__ = """ tasks: test: mock: - {title: 'irrelevant'} """ def test_setdefault(self): self.execute_task('test') task = self.task value1 = task.simple_persistence.setdefault('test', 'abc') value2 = task.simple_persistence.setdefault('test', 'def') assert value1 == value2, 'set default broken' ## Instruction: Add some more tests for simple_persistence ## Code After: from __future__ import unicode_literals, division, absolute_import from flexget.manager import Session from flexget.utils.simple_persistence import SimplePersistence from tests import FlexGetBase class TestSimplePersistence(FlexGetBase): __yaml__ = """ tasks: test: mock: - {title: 'irrelevant'} """ def test_setdefault(self): self.execute_task('test') task = self.task value1 = task.simple_persistence.setdefault('test', 'abc') value2 = task.simple_persistence.setdefault('test', 'def') assert value1 == value2, 'set default broken' def test_nosession(self): persist = SimplePersistence('testplugin') persist['aoeu'] = 'test' assert persist['aoeu'] == 'test' # Make sure it commits and actually persists persist = SimplePersistence('testplugin') assert persist['aoeu'] == 'test' def test_withsession(self): session = Session() persist = SimplePersistence('testplugin', session=session) persist['aoeu'] = 'test' assert persist['aoeu'] == 'test' # Make sure it didn't commit or close our session session.rollback() assert 'aoeu' not in persist
# ... existing code ... from __future__ import unicode_literals, division, absolute_import from flexget.manager import Session from flexget.utils.simple_persistence import SimplePersistence from tests import FlexGetBase # ... modified code ... assert value1 == value2, 'set default broken' def test_nosession(self): persist = SimplePersistence('testplugin') persist['aoeu'] = 'test' assert persist['aoeu'] == 'test' # Make sure it commits and actually persists persist = SimplePersistence('testplugin') assert persist['aoeu'] == 'test' def test_withsession(self): session = Session() persist = SimplePersistence('testplugin', session=session) persist['aoeu'] = 'test' assert persist['aoeu'] == 'test' # Make sure it didn't commit or close our session session.rollback() assert 'aoeu' not in persist # ... rest of the code ...
22b92437c1ae672297bed8567b335ef7da100103
dotfiles/utils.py
dotfiles/utils.py
import os.path from dotfiles.compat import islink, realpath def compare_path(path1, path2): return (realpath_expanduser(path1) == realpath_expanduser(path2)) def realpath_expanduser(path): return realpath(os.path.expanduser(path)) def is_link_to(path, target): def normalize(path): return os.path.normcase(os.path.normpath(path)) return islink(path) and \ normalize(realpath(path)) == normalize(target)
import os.path from dotfiles.compat import islink, realpath def compare_path(path1, path2): return (realpath_expanduser(path1) == realpath_expanduser(path2)) def realpath_expanduser(path): return realpath(os.path.expanduser(path)) def is_link_to(path, target): def normalize(path): return os.path.normcase(os.path.normpath(path)) return islink(path) and \ normalize(realpath(path)) == normalize(realpath(target))
Fix link detection when target is itself a symlink
Fix link detection when target is itself a symlink This shows up on OSX where /tmp is actually a symlink to /private/tmp.
Python
isc
aparente/Dotfiles,nilehmann/dotfiles-1,aparente/Dotfiles,aparente/Dotfiles,aparente/Dotfiles,Bklyn/dotfiles
import os.path from dotfiles.compat import islink, realpath def compare_path(path1, path2): return (realpath_expanduser(path1) == realpath_expanduser(path2)) def realpath_expanduser(path): return realpath(os.path.expanduser(path)) def is_link_to(path, target): def normalize(path): return os.path.normcase(os.path.normpath(path)) return islink(path) and \ - normalize(realpath(path)) == normalize(target) + normalize(realpath(path)) == normalize(realpath(target)) -
Fix link detection when target is itself a symlink
## Code Before: import os.path from dotfiles.compat import islink, realpath def compare_path(path1, path2): return (realpath_expanduser(path1) == realpath_expanduser(path2)) def realpath_expanduser(path): return realpath(os.path.expanduser(path)) def is_link_to(path, target): def normalize(path): return os.path.normcase(os.path.normpath(path)) return islink(path) and \ normalize(realpath(path)) == normalize(target) ## Instruction: Fix link detection when target is itself a symlink ## Code After: import os.path from dotfiles.compat import islink, realpath def compare_path(path1, path2): return (realpath_expanduser(path1) == realpath_expanduser(path2)) def realpath_expanduser(path): return realpath(os.path.expanduser(path)) def is_link_to(path, target): def normalize(path): return os.path.normcase(os.path.normpath(path)) return islink(path) and \ normalize(realpath(path)) == normalize(realpath(target))
# ... existing code ... return islink(path) and \ normalize(realpath(path)) == normalize(realpath(target)) # ... rest of the code ...
481028f075bf46696b8adc5904663e97bc883c52
notfound.py
notfound.py
from google.appengine.ext.webapp import template import webapp2 import os class NotFound(webapp2.RequestHandler): def get(self): path = os.path.join(os.path.dirname(__file__), 'templates/notfound.html') self.response.out.write(template.render(path, {})) app = webapp2.WSGIApplication([('/.*', NotFound)])
from google.appengine.ext.webapp import template import webapp2 import os class NotFound(webapp2.RequestHandler): def get(self): self.error(404) path = os.path.join(os.path.dirname(__file__), 'templates/notfound.html') self.response.out.write(template.render(path, {})) app = webapp2.WSGIApplication([('/.*', NotFound)])
Return HTTP Status Code 404 for not found errors
Return HTTP Status Code 404 for not found errors
Python
mit
mback2k/appengine-oauth-profile,mback2k/appengine-oauth-profile
from google.appengine.ext.webapp import template import webapp2 import os class NotFound(webapp2.RequestHandler): def get(self): + self.error(404) + path = os.path.join(os.path.dirname(__file__), 'templates/notfound.html') self.response.out.write(template.render(path, {})) app = webapp2.WSGIApplication([('/.*', NotFound)])
Return HTTP Status Code 404 for not found errors
## Code Before: from google.appengine.ext.webapp import template import webapp2 import os class NotFound(webapp2.RequestHandler): def get(self): path = os.path.join(os.path.dirname(__file__), 'templates/notfound.html') self.response.out.write(template.render(path, {})) app = webapp2.WSGIApplication([('/.*', NotFound)]) ## Instruction: Return HTTP Status Code 404 for not found errors ## Code After: from google.appengine.ext.webapp import template import webapp2 import os class NotFound(webapp2.RequestHandler): def get(self): self.error(404) path = os.path.join(os.path.dirname(__file__), 'templates/notfound.html') self.response.out.write(template.render(path, {})) app = webapp2.WSGIApplication([('/.*', NotFound)])
// ... existing code ... def get(self): self.error(404) path = os.path.join(os.path.dirname(__file__), 'templates/notfound.html') // ... rest of the code ...
f94bc30004aa9977bac652d337f69069efc132bd
marmoset/pxe/__init__.py
marmoset/pxe/__init__.py
from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) pxe_client.create(Label.find(args.label)) msg = 'Created %s with password %s' print(msg % (pxe_client.file_path(), pxe_client.password)) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address)
from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) used_options = pxe_client.create(Label.find(args.label)) msg = 'Created %s with following Options:' print(msg % pxe_client.file_path()) for option in used_options: print("\t%s" % option) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address)
Implement better result output for pxe config file crete
Implement better result output for pxe config file crete
Python
agpl-3.0
aibor/marmoset
from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) - pxe_client.create(Label.find(args.label)) + used_options = pxe_client.create(Label.find(args.label)) - msg = 'Created %s with password %s' + + msg = 'Created %s with following Options:' + - print(msg % (pxe_client.file_path(), pxe_client.password)) + print(msg % pxe_client.file_path()) + for option in used_options: + print("\t%s" % option) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address)
Implement better result output for pxe config file crete
## Code Before: from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) pxe_client.create(Label.find(args.label)) msg = 'Created %s with password %s' print(msg % (pxe_client.file_path(), pxe_client.password)) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address) ## Instruction: Implement better result output for pxe config file crete ## Code After: from .label import Label from .client_config import ClientConfig def create(args): pxe_client = ClientConfig(args.ip_address, args.password, args.script) used_options = pxe_client.create(Label.find(args.label)) msg = 'Created %s with following Options:' print(msg % pxe_client.file_path()) for option in used_options: print("\t%s" % option) def list(args): for pxe_client in ClientConfig.all(): print('%s: %s' % (pxe_client.ip_address, pxe_client.label)) def remove(args): pxe_client = ClientConfig(args.ip_address) if pxe_client.remove(): print('Removed', pxe_client.file_path()) else: print('No entry found for', pxe_client.ip_address)
// ... existing code ... pxe_client = ClientConfig(args.ip_address, args.password, args.script) used_options = pxe_client.create(Label.find(args.label)) msg = 'Created %s with following Options:' print(msg % pxe_client.file_path()) for option in used_options: print("\t%s" % option) // ... rest of the code ...
9b10f600b5611380f72fe2aeacfe2ee6f02e4e3a
kicad_footprint_load.py
kicad_footprint_load.py
import pcbnew import sys import os pretties = [] for dirname, dirnames, filenames in os.walk(sys.argv[1]): # don't go into any .git directories. if '.git' in dirnames: dirnames.remove('.git') for filename in filenames: if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'): pretties.append(os.path.realpath(dirname)) break src_plugin = pcbnew.IO_MGR.PluginFind(1) for libpath in pretties: #Ignore paths with unicode as KiCad can't deal with them in enumerate list_of_footprints = src_plugin.FootprintEnumerate(libpath, False)
import pcbnew import sys import os pretties = [] for dirname, dirnames, filenames in os.walk(sys.argv[1]): # don't go into any .git directories. if '.git' in dirnames: dirnames.remove('.git') for filename in filenames: if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'): pretties.append(os.path.realpath(dirname)) break src_plugin = pcbnew.IO_MGR.PluginFind(1) for libpath in pretties: list_of_footprints = src_plugin.FootprintEnumerate(libpath)
Switch to old invocation of FootprintEnumerate
Switch to old invocation of FootprintEnumerate
Python
mit
monostable/haskell-kicad-data,monostable/haskell-kicad-data,kasbah/haskell-kicad-data
import pcbnew import sys import os pretties = [] for dirname, dirnames, filenames in os.walk(sys.argv[1]): # don't go into any .git directories. if '.git' in dirnames: dirnames.remove('.git') for filename in filenames: if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'): pretties.append(os.path.realpath(dirname)) break src_plugin = pcbnew.IO_MGR.PluginFind(1) for libpath in pretties: - #Ignore paths with unicode as KiCad can't deal with them in enumerate - list_of_footprints = src_plugin.FootprintEnumerate(libpath, False) + list_of_footprints = src_plugin.FootprintEnumerate(libpath)
Switch to old invocation of FootprintEnumerate
## Code Before: import pcbnew import sys import os pretties = [] for dirname, dirnames, filenames in os.walk(sys.argv[1]): # don't go into any .git directories. if '.git' in dirnames: dirnames.remove('.git') for filename in filenames: if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'): pretties.append(os.path.realpath(dirname)) break src_plugin = pcbnew.IO_MGR.PluginFind(1) for libpath in pretties: #Ignore paths with unicode as KiCad can't deal with them in enumerate list_of_footprints = src_plugin.FootprintEnumerate(libpath, False) ## Instruction: Switch to old invocation of FootprintEnumerate ## Code After: import pcbnew import sys import os pretties = [] for dirname, dirnames, filenames in os.walk(sys.argv[1]): # don't go into any .git directories. if '.git' in dirnames: dirnames.remove('.git') for filename in filenames: if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'): pretties.append(os.path.realpath(dirname)) break src_plugin = pcbnew.IO_MGR.PluginFind(1) for libpath in pretties: list_of_footprints = src_plugin.FootprintEnumerate(libpath)
# ... existing code ... for libpath in pretties: list_of_footprints = src_plugin.FootprintEnumerate(libpath) # ... rest of the code ...
0c04f8cac3e1cbe24a5e4ed699e7c743b962e945
pygotham/filters.py
pygotham/filters.py
"""Template filters for use across apps.""" import bleach from docutils import core __all__ = 'rst_to_html' _ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p'] def rst_to_html(value): """Return HTML generated from reStructuredText.""" parts = core.publish_parts(source=value, writer_name='html') return bleach.clean( parts['body_pre_docinfo'] + parts['fragment'], tags=_ALLOWED_TAGS)
"""Template filters for use across apps.""" import bleach from docutils import core __all__ = 'rst_to_html' _ALLOWED_TAGS = bleach.ALLOWED_TAGS + [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'dl', 'dt', 'dd', 'cite', ] def rst_to_html(value): """Return HTML generated from reStructuredText.""" parts = core.publish_parts(source=value, writer_name='html') return bleach.clean( parts['body_pre_docinfo'] + parts['fragment'], tags=_ALLOWED_TAGS)
Add additional HTML tags to reST filter
Add additional HTML tags to reST filter
Python
bsd-3-clause
djds23/pygotham-1,djds23/pygotham-1,PyGotham/pygotham,djds23/pygotham-1,djds23/pygotham-1,pathunstrom/pygotham,pathunstrom/pygotham,PyGotham/pygotham,PyGotham/pygotham,pathunstrom/pygotham,pathunstrom/pygotham,djds23/pygotham-1,PyGotham/pygotham,pathunstrom/pygotham,PyGotham/pygotham
"""Template filters for use across apps.""" import bleach from docutils import core __all__ = 'rst_to_html' - _ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p'] + _ALLOWED_TAGS = bleach.ALLOWED_TAGS + [ + 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'dl', 'dt', 'dd', 'cite', + ] def rst_to_html(value): """Return HTML generated from reStructuredText.""" parts = core.publish_parts(source=value, writer_name='html') return bleach.clean( parts['body_pre_docinfo'] + parts['fragment'], tags=_ALLOWED_TAGS)
Add additional HTML tags to reST filter
## Code Before: """Template filters for use across apps.""" import bleach from docutils import core __all__ = 'rst_to_html' _ALLOWED_TAGS = bleach.ALLOWED_TAGS + ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p'] def rst_to_html(value): """Return HTML generated from reStructuredText.""" parts = core.publish_parts(source=value, writer_name='html') return bleach.clean( parts['body_pre_docinfo'] + parts['fragment'], tags=_ALLOWED_TAGS) ## Instruction: Add additional HTML tags to reST filter ## Code After: """Template filters for use across apps.""" import bleach from docutils import core __all__ = 'rst_to_html' _ALLOWED_TAGS = bleach.ALLOWED_TAGS + [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'dl', 'dt', 'dd', 'cite', ] def rst_to_html(value): """Return HTML generated from reStructuredText.""" parts = core.publish_parts(source=value, writer_name='html') return bleach.clean( parts['body_pre_docinfo'] + parts['fragment'], tags=_ALLOWED_TAGS)
# ... existing code ... _ALLOWED_TAGS = bleach.ALLOWED_TAGS + [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'dl', 'dt', 'dd', 'cite', ] # ... rest of the code ...
e118ee78b534a83b33f91b27cfc1f75d64e8e924
test_utils/testmaker/base_serializer.py
test_utils/testmaker/base_serializer.py
import cPickle as pickle import logging import time ser = logging.getLogger('testserializer') class Serializer(object): """A pluggable Serializer class""" name = "default" def __init__(self, name='default'): """Constructor""" self.data = {} self.name = name def save_request(self, request): """Saves the Request to the serialization stream""" request_dict = { 'name': self.name, 'time': time.time(), 'path': request.path, 'get': request.GET, 'post': request.POST, 'arg_dict': request.REQUEST, } ser.info(pickle.dumps(request_dict)) ser.info('---REQUEST_BREAK---') def save_response(self, path, response): """Saves the Response-like objects information that might be tested""" response_dict = { 'name': self.name, 'time': time.time(), 'path': path, 'context': response.context, 'content': response.content, 'status_code': response.status_code, 'cookies': response.cookies, 'headers': response._headers, } try: ser.info(pickle.dumps(response_dict)) ser.info('---RESPONSE_BREAK---') except (TypeError, pickle.PicklingError): #Can't pickle wsgi.error objects pass
import cPickle as pickle import logging import time class Serializer(object): """A pluggable Serializer class""" name = "default" def __init__(self, name='default'): """Constructor""" self.ser = logging.getLogger('testserializer') self.data = {} self.name = name def process_request(self, request): request_dict = { 'name': self.name, 'time': time.time(), 'path': request.path, 'get': request.GET, 'post': request.POST, 'arg_dict': request.REQUEST, 'method': request.method, } return request_dict def save_request(self, request): """Saves the Request to the serialization stream""" request_dict = self.process_request(request) self.ser.info(pickle.dumps(request_dict)) self.ser.info('---REQUEST_BREAK---') def process_response(self, path, response): response_dict = { 'name': self.name, 'time': time.time(), 'path': path, 'context': response.context, 'content': response.content, 'status_code': response.status_code, 'cookies': response.cookies, 'headers': response._headers, } return response_dict def save_response(self, path, response): """Saves the Response-like objects information that might be tested""" response_dict = self.process_response(path, response) try: self.ser.info(pickle.dumps(response_dict)) self.ser.info('---RESPONSE_BREAK---') except (TypeError, pickle.PicklingError): #Can't pickle wsgi.error objects pass
Move serializer into the class so it can be subclassed.
Move serializer into the class so it can be subclassed.
Python
mit
frac/django-test-utils,acdha/django-test-utils,ericholscher/django-test-utils,frac/django-test-utils,ericholscher/django-test-utils,acdha/django-test-utils
import cPickle as pickle import logging import time - ser = logging.getLogger('testserializer') class Serializer(object): """A pluggable Serializer class""" name = "default" def __init__(self, name='default'): """Constructor""" + self.ser = logging.getLogger('testserializer') self.data = {} self.name = name - def save_request(self, request): + def process_request(self, request): - """Saves the Request to the serialization stream""" request_dict = { 'name': self.name, 'time': time.time(), 'path': request.path, - 'get': request.GET, 'post': request.POST, 'arg_dict': request.REQUEST, + 'method': request.method, } + return request_dict - ser.info(pickle.dumps(request_dict)) - ser.info('---REQUEST_BREAK---') + def save_request(self, request): + """Saves the Request to the serialization stream""" + request_dict = self.process_request(request) + self.ser.info(pickle.dumps(request_dict)) + self.ser.info('---REQUEST_BREAK---') + - def save_response(self, path, response): + def process_response(self, path, response): - """Saves the Response-like objects information that might be tested""" response_dict = { 'name': self.name, 'time': time.time(), 'path': path, 'context': response.context, 'content': response.content, 'status_code': response.status_code, 'cookies': response.cookies, 'headers': response._headers, } + return response_dict + + + def save_response(self, path, response): + """Saves the Response-like objects information that might be tested""" + response_dict = self.process_response(path, response) try: - ser.info(pickle.dumps(response_dict)) + self.ser.info(pickle.dumps(response_dict)) - ser.info('---RESPONSE_BREAK---') + self.ser.info('---RESPONSE_BREAK---') except (TypeError, pickle.PicklingError): #Can't pickle wsgi.error objects pass
Move serializer into the class so it can be subclassed.
## Code Before: import cPickle as pickle import logging import time ser = logging.getLogger('testserializer') class Serializer(object): """A pluggable Serializer class""" name = "default" def __init__(self, name='default'): """Constructor""" self.data = {} self.name = name def save_request(self, request): """Saves the Request to the serialization stream""" request_dict = { 'name': self.name, 'time': time.time(), 'path': request.path, 'get': request.GET, 'post': request.POST, 'arg_dict': request.REQUEST, } ser.info(pickle.dumps(request_dict)) ser.info('---REQUEST_BREAK---') def save_response(self, path, response): """Saves the Response-like objects information that might be tested""" response_dict = { 'name': self.name, 'time': time.time(), 'path': path, 'context': response.context, 'content': response.content, 'status_code': response.status_code, 'cookies': response.cookies, 'headers': response._headers, } try: ser.info(pickle.dumps(response_dict)) ser.info('---RESPONSE_BREAK---') except (TypeError, pickle.PicklingError): #Can't pickle wsgi.error objects pass ## Instruction: Move serializer into the class so it can be subclassed. ## Code After: import cPickle as pickle import logging import time class Serializer(object): """A pluggable Serializer class""" name = "default" def __init__(self, name='default'): """Constructor""" self.ser = logging.getLogger('testserializer') self.data = {} self.name = name def process_request(self, request): request_dict = { 'name': self.name, 'time': time.time(), 'path': request.path, 'get': request.GET, 'post': request.POST, 'arg_dict': request.REQUEST, 'method': request.method, } return request_dict def save_request(self, request): """Saves the Request to the serialization stream""" request_dict = self.process_request(request) self.ser.info(pickle.dumps(request_dict)) self.ser.info('---REQUEST_BREAK---') def process_response(self, path, response): response_dict = { 'name': self.name, 'time': time.time(), 'path': path, 'context': response.context, 'content': response.content, 'status_code': response.status_code, 'cookies': response.cookies, 'headers': response._headers, } return response_dict def save_response(self, path, response): """Saves the Response-like objects information that might be tested""" response_dict = self.process_response(path, response) try: self.ser.info(pickle.dumps(response_dict)) self.ser.info('---RESPONSE_BREAK---') except (TypeError, pickle.PicklingError): #Can't pickle wsgi.error objects pass
// ... existing code ... // ... modified code ... """Constructor""" self.ser = logging.getLogger('testserializer') self.data = {} ... def process_request(self, request): request_dict = { ... 'path': request.path, 'get': request.GET, ... 'arg_dict': request.REQUEST, 'method': request.method, } return request_dict def save_request(self, request): """Saves the Request to the serialization stream""" request_dict = self.process_request(request) self.ser.info(pickle.dumps(request_dict)) self.ser.info('---REQUEST_BREAK---') def process_response(self, path, response): response_dict = { ... } return response_dict def save_response(self, path, response): """Saves the Response-like objects information that might be tested""" response_dict = self.process_response(path, response) try: self.ser.info(pickle.dumps(response_dict)) self.ser.info('---RESPONSE_BREAK---') except (TypeError, pickle.PicklingError): // ... rest of the code ...
d106719a0b7bcbd87989bd36f618f90c4df02c46
sequana/gui/browser.py
sequana/gui/browser.py
from PyQt5 import QtCore from PyQt5.QtWebKitWidgets import QWebView class MyBrowser(QWebView): closing = QtCore.Signal() def __init(self): super().__init__() self.loadFinished.connec(self._results_available) def _results_available(self, ok): print("results") frame = self.page().mainFrame() print(unicode(frame.toHtml()).encode('utf-8')) def closeEvent(self, event): print("done") self.closing.emit()
from PyQt5 import QtCore from PyQt5.QtWebKitWidgets import QWebView class MyBrowser(QWebView): #closing = QtCore.Signal() def __init(self): super().__init__() self.loadFinished.connec(self._results_available) def _results_available(self, ok): frame = self.page().mainFrame() print(unicode(frame.toHtml()).encode('utf-8')) def closeEvent(self, event): #print("done") pass #self.closing.emit()
Fix issue with signal on tars
Fix issue with signal on tars
Python
bsd-3-clause
sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana
from PyQt5 import QtCore - from PyQt5.QtWebKitWidgets import QWebView class MyBrowser(QWebView): - closing = QtCore.Signal() + #closing = QtCore.Signal() + def __init(self): super().__init__() self.loadFinished.connec(self._results_available) + def _results_available(self, ok): - print("results") frame = self.page().mainFrame() print(unicode(frame.toHtml()).encode('utf-8')) def closeEvent(self, event): - print("done") + #print("done") + pass - self.closing.emit() + #self.closing.emit()
Fix issue with signal on tars
## Code Before: from PyQt5 import QtCore from PyQt5.QtWebKitWidgets import QWebView class MyBrowser(QWebView): closing = QtCore.Signal() def __init(self): super().__init__() self.loadFinished.connec(self._results_available) def _results_available(self, ok): print("results") frame = self.page().mainFrame() print(unicode(frame.toHtml()).encode('utf-8')) def closeEvent(self, event): print("done") self.closing.emit() ## Instruction: Fix issue with signal on tars ## Code After: from PyQt5 import QtCore from PyQt5.QtWebKitWidgets import QWebView class MyBrowser(QWebView): #closing = QtCore.Signal() def __init(self): super().__init__() self.loadFinished.connec(self._results_available) def _results_available(self, ok): frame = self.page().mainFrame() print(unicode(frame.toHtml()).encode('utf-8')) def closeEvent(self, event): #print("done") pass #self.closing.emit()
// ... existing code ... from PyQt5 import QtCore from PyQt5.QtWebKitWidgets import QWebView // ... modified code ... class MyBrowser(QWebView): #closing = QtCore.Signal() def __init(self): ... self.loadFinished.connec(self._results_available) def _results_available(self, ok): frame = self.page().mainFrame() ... def closeEvent(self, event): #print("done") pass #self.closing.emit() // ... rest of the code ...
c7e4fc5038cb2069193aa888c4978e9aeff995f7
source/segue/backend/processor/background.py
source/segue/backend/processor/background.py
import subprocess import pickle import base64 try: from shlex import quote except ImportError: from pipes import quote from .base import Processor from .. import pickle_support class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' if args is None: args = () if kw is None: kw = {} serialised = base64.b64encode( pickle.dumps( {'command': command, 'args': args, 'kw': kw}, pickle.HIGHEST_PROTOCOL ) ) python_statement = ( 'import pickle;' 'import base64;' 'data = base64.b64decode(\'{0}\');' 'data = pickle.loads(data);' 'data[\'command\'](*data[\'args\'], **data[\'kw\'])' ).format(serialised.replace("'", r"\'")) command = ' '.join(['python', '-c', '"{0}"'.format(python_statement)]) process = subprocess.Popen(command) return 'Background process started: {0}'.format(process.pid)
import subprocess import pickle import base64 try: from shlex import quote except ImportError: from pipes import quote from .base import Processor from .. import pickle_support class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' if args is None: args = () if kw is None: kw = {} serialised = base64.b64encode( pickle.dumps( {'command': command, 'args': args, 'kw': kw}, pickle.HIGHEST_PROTOCOL ) ) python_statement = ( 'import pickle;' 'import base64;' 'data = base64.b64decode(\'{0}\');' 'data = pickle.loads(data);' 'data[\'command\'](*data[\'args\'], **data[\'kw\'])' ).format(serialised.replace("'", r"\'")) command = ['python', '-c', python_statement] process = subprocess.Popen(command) return 'Background process started: {0}'.format(process.pid)
Fix failing command on Linux.
Fix failing command on Linux.
Python
apache-2.0
4degrees/segue
import subprocess import pickle import base64 try: from shlex import quote except ImportError: from pipes import quote from .base import Processor from .. import pickle_support class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' if args is None: args = () if kw is None: kw = {} serialised = base64.b64encode( pickle.dumps( {'command': command, 'args': args, 'kw': kw}, pickle.HIGHEST_PROTOCOL ) ) python_statement = ( 'import pickle;' 'import base64;' 'data = base64.b64decode(\'{0}\');' 'data = pickle.loads(data);' 'data[\'command\'](*data[\'args\'], **data[\'kw\'])' ).format(serialised.replace("'", r"\'")) - command = ' '.join(['python', '-c', '"{0}"'.format(python_statement)]) + command = ['python', '-c', python_statement] process = subprocess.Popen(command) return 'Background process started: {0}'.format(process.pid)
Fix failing command on Linux.
## Code Before: import subprocess import pickle import base64 try: from shlex import quote except ImportError: from pipes import quote from .base import Processor from .. import pickle_support class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' if args is None: args = () if kw is None: kw = {} serialised = base64.b64encode( pickle.dumps( {'command': command, 'args': args, 'kw': kw}, pickle.HIGHEST_PROTOCOL ) ) python_statement = ( 'import pickle;' 'import base64;' 'data = base64.b64decode(\'{0}\');' 'data = pickle.loads(data);' 'data[\'command\'](*data[\'args\'], **data[\'kw\'])' ).format(serialised.replace("'", r"\'")) command = ' '.join(['python', '-c', '"{0}"'.format(python_statement)]) process = subprocess.Popen(command) return 'Background process started: {0}'.format(process.pid) ## Instruction: Fix failing command on Linux. ## Code After: import subprocess import pickle import base64 try: from shlex import quote except ImportError: from pipes import quote from .base import Processor from .. import pickle_support class BackgroundProcessor(Processor): '''Local background processor.''' def process(self, command, args=None, kw=None): '''Process *command* with *args* and *kw*.''' if args is None: args = () if kw is None: kw = {} serialised = base64.b64encode( pickle.dumps( {'command': command, 'args': args, 'kw': kw}, pickle.HIGHEST_PROTOCOL ) ) python_statement = ( 'import pickle;' 'import base64;' 'data = base64.b64decode(\'{0}\');' 'data = pickle.loads(data);' 'data[\'command\'](*data[\'args\'], **data[\'kw\'])' ).format(serialised.replace("'", r"\'")) command = ['python', '-c', python_statement] process = subprocess.Popen(command) return 'Background process started: {0}'.format(process.pid)
... command = ['python', '-c', python_statement] ...
2e9b87a7409f1995f96867270361f23a9fc3d1ab
flaskext/clevercss.py
flaskext/clevercss.py
import os import sys import orig_clevercss def clevercss(app): @app.before_request def _render_clever_css(): static_dir = app.root_path + app.static_path clever_paths = [] for path, subdirs, filenames in os.walk(static_dir): clever_paths.extend([ os.path.join(path, f) for f in filenames if os.path.splitext(f)[1] == '.ccss' ]) for clever_path in clever_paths: css_path = os.path.splitext(clever_path)[0] + '.css' if not os.path.isfile(css_path): css_mtime = -1 else: css_mtime = os.path.getmtime(css_path) clever_mtime = os.path.getmtime(clever_path) if clever_mtime >= css_mtime: sys.argv[1:] = [clever_path] orig_clevercss.main()
import os import sys import orig_clevercss def clevercss(app): @app.before_request def _render_clever_css(): static_dir = os.path.join(app.root_path, app._static_folder) clever_paths = [] for path, subdirs, filenames in os.walk(static_dir): clever_paths.extend([ os.path.join(path, f) for f in filenames if os.path.splitext(f)[1] == '.ccss' ]) for clever_path in clever_paths: css_path = os.path.splitext(clever_path)[0] + '.css' if not os.path.isfile(css_path): css_mtime = -1 else: css_mtime = os.path.getmtime(css_path) clever_mtime = os.path.getmtime(clever_path) if clever_mtime >= css_mtime: sys.argv[1:] = [clever_path] orig_clevercss.main()
Fix for specifying the static directory in later versions of flask
Fix for specifying the static directory in later versions of flask
Python
mit
suzanshakya/flask-clevercss,suzanshakya/flask-clevercss
import os import sys import orig_clevercss def clevercss(app): @app.before_request def _render_clever_css(): - static_dir = app.root_path + app.static_path + static_dir = os.path.join(app.root_path, app._static_folder) clever_paths = [] for path, subdirs, filenames in os.walk(static_dir): clever_paths.extend([ os.path.join(path, f) for f in filenames if os.path.splitext(f)[1] == '.ccss' ]) for clever_path in clever_paths: css_path = os.path.splitext(clever_path)[0] + '.css' if not os.path.isfile(css_path): css_mtime = -1 else: css_mtime = os.path.getmtime(css_path) clever_mtime = os.path.getmtime(clever_path) if clever_mtime >= css_mtime: sys.argv[1:] = [clever_path] orig_clevercss.main()
Fix for specifying the static directory in later versions of flask
## Code Before: import os import sys import orig_clevercss def clevercss(app): @app.before_request def _render_clever_css(): static_dir = app.root_path + app.static_path clever_paths = [] for path, subdirs, filenames in os.walk(static_dir): clever_paths.extend([ os.path.join(path, f) for f in filenames if os.path.splitext(f)[1] == '.ccss' ]) for clever_path in clever_paths: css_path = os.path.splitext(clever_path)[0] + '.css' if not os.path.isfile(css_path): css_mtime = -1 else: css_mtime = os.path.getmtime(css_path) clever_mtime = os.path.getmtime(clever_path) if clever_mtime >= css_mtime: sys.argv[1:] = [clever_path] orig_clevercss.main() ## Instruction: Fix for specifying the static directory in later versions of flask ## Code After: import os import sys import orig_clevercss def clevercss(app): @app.before_request def _render_clever_css(): static_dir = os.path.join(app.root_path, app._static_folder) clever_paths = [] for path, subdirs, filenames in os.walk(static_dir): clever_paths.extend([ os.path.join(path, f) for f in filenames if os.path.splitext(f)[1] == '.ccss' ]) for clever_path in clever_paths: css_path = os.path.splitext(clever_path)[0] + '.css' if not os.path.isfile(css_path): css_mtime = -1 else: css_mtime = os.path.getmtime(css_path) clever_mtime = os.path.getmtime(clever_path) if clever_mtime >= css_mtime: sys.argv[1:] = [clever_path] orig_clevercss.main()
... def _render_clever_css(): static_dir = os.path.join(app.root_path, app._static_folder) ...
9bb1aebbfc0ca0ff893bafe99de3c32c2ba99952
tests/test_model.py
tests/test_model.py
from context import models from models import model import unittest class test_logic_core(unittest.TestCase): def setUp(self): self.room = model.Room(20, 'new_room') self.room1 = model.Room(6, 'new_room1') self.livingspace = model.LivingSpace('orange') self.office = model.Office('manjaro') def test_Room_instance(self): self.assertIsInstance(self.room, model.Room) self.assertIsInstance(self.room1, model.Room) def test_Room_max_occupation(self): self.assertEqual(20, self.room.max_occupants) def test_Room_name(self): self.assertEqual('new_room1', self.room1.name) def test_office_ocupants(self): self.assertEqual(6, self.office.max_occupants) def test_livingspace_ocupants(self): self.assertEqual(4, self.livingspace.max_occupants) def test_sublclass_Room(self): self.assertTrue(issubclass(model.Office, model.Room)) self.assertTrue(issubclass(model.LivingSpace, model.Room))
from context import models from models import model import unittest class test_model(unittest.TestCase): def setUp(self): self.room = model.Room(20, 'new_room') self.room1 = model.Room(6, 'new_room1') self.livingspace = model.LivingSpace('orange') self.office = model.Office('manjaro') def test_Room_instance(self): self.assertIsInstance(self.room, model.Room) self.assertIsInstance(self.room1, model.Room) def test_Room_max_occupation(self): self.assertEqual(20, self.room.max_occupants) def test_Room_name(self): self.assertEqual('new_room1', self.room1.name) self.room1.name = "changedname" self.assertEqual('changedname', self.room1.name) def test_office_ocupants(self): self.assertEqual(6, self.office.max_occupants) def test_livingspace_ocupants(self): self.assertEqual(4, self.livingspace.max_occupants) def test_sublclass_Room(self): self.assertTrue(issubclass(model.Office, model.Room)) self.assertTrue(issubclass(model.LivingSpace, model.Room)) def test_room_current_population(self): self.assertEqual(self.room.current_population, 0)
Refactor model test to test added properties
Refactor model test to test added properties
Python
mit
georgreen/Geoogreen-Mamboleo-Dojo-Project
from context import models from models import model import unittest - class test_logic_core(unittest.TestCase): + class test_model(unittest.TestCase): def setUp(self): self.room = model.Room(20, 'new_room') self.room1 = model.Room(6, 'new_room1') self.livingspace = model.LivingSpace('orange') self.office = model.Office('manjaro') def test_Room_instance(self): self.assertIsInstance(self.room, model.Room) self.assertIsInstance(self.room1, model.Room) def test_Room_max_occupation(self): self.assertEqual(20, self.room.max_occupants) def test_Room_name(self): self.assertEqual('new_room1', self.room1.name) + self.room1.name = "changedname" + self.assertEqual('changedname', self.room1.name) def test_office_ocupants(self): self.assertEqual(6, self.office.max_occupants) def test_livingspace_ocupants(self): self.assertEqual(4, self.livingspace.max_occupants) def test_sublclass_Room(self): self.assertTrue(issubclass(model.Office, model.Room)) self.assertTrue(issubclass(model.LivingSpace, model.Room)) + def test_room_current_population(self): + self.assertEqual(self.room.current_population, 0) +
Refactor model test to test added properties
## Code Before: from context import models from models import model import unittest class test_logic_core(unittest.TestCase): def setUp(self): self.room = model.Room(20, 'new_room') self.room1 = model.Room(6, 'new_room1') self.livingspace = model.LivingSpace('orange') self.office = model.Office('manjaro') def test_Room_instance(self): self.assertIsInstance(self.room, model.Room) self.assertIsInstance(self.room1, model.Room) def test_Room_max_occupation(self): self.assertEqual(20, self.room.max_occupants) def test_Room_name(self): self.assertEqual('new_room1', self.room1.name) def test_office_ocupants(self): self.assertEqual(6, self.office.max_occupants) def test_livingspace_ocupants(self): self.assertEqual(4, self.livingspace.max_occupants) def test_sublclass_Room(self): self.assertTrue(issubclass(model.Office, model.Room)) self.assertTrue(issubclass(model.LivingSpace, model.Room)) ## Instruction: Refactor model test to test added properties ## Code After: from context import models from models import model import unittest class test_model(unittest.TestCase): def setUp(self): self.room = model.Room(20, 'new_room') self.room1 = model.Room(6, 'new_room1') self.livingspace = model.LivingSpace('orange') self.office = model.Office('manjaro') def test_Room_instance(self): self.assertIsInstance(self.room, model.Room) self.assertIsInstance(self.room1, model.Room) def test_Room_max_occupation(self): self.assertEqual(20, self.room.max_occupants) def test_Room_name(self): self.assertEqual('new_room1', self.room1.name) self.room1.name = "changedname" self.assertEqual('changedname', self.room1.name) def test_office_ocupants(self): self.assertEqual(6, self.office.max_occupants) def test_livingspace_ocupants(self): self.assertEqual(4, self.livingspace.max_occupants) def test_sublclass_Room(self): self.assertTrue(issubclass(model.Office, model.Room)) self.assertTrue(issubclass(model.LivingSpace, model.Room)) def test_room_current_population(self): self.assertEqual(self.room.current_population, 0)
... class test_model(unittest.TestCase): def setUp(self): ... self.assertEqual('new_room1', self.room1.name) self.room1.name = "changedname" self.assertEqual('changedname', self.room1.name) ... self.assertTrue(issubclass(model.LivingSpace, model.Room)) def test_room_current_population(self): self.assertEqual(self.room.current_population, 0) ...
f694b582e72412d4022d6ff21a97d32f77484b9b
heap/heap.py
heap/heap.py
import numpy as np class ArrayHeap(object): def __init__(self, sz, data = None): self.sz = sz self.cnt = 0 self.heap = [0 for i in range(sz + 1)] if data is not None: for i, val in enumerate(data): self.heap[i + 1] = val self.cnt = len(data) self._build_heap() def _build_heap(self): last_non_leaf = self.cnt // 2 for x in range(last_non_leaf, 0, -1): max_pos = x i = x while True: if i <= self.cnt and self.heap[i] < self.heap[2 *i ]: max_pos = 2 * i if i <= self.cnt and self.heap[max_pos] < self.heap[2 * i + 1]: max_pos = 2 * i + 1 if max_pos == i: break self.heap[i], self.heap[max_pos] = self.heap[max_pos], self.heap[i] i = max_pos if __name__ == '__main__': data = np.random.randint(0, 100, 10) print(data) heap = ArrayHeap(100, data) print(heap.heap)
import numpy as np class MaxHeap(object): def __init__(self, sz, data): self.sz = sz self.heap = [0] * (sz + 1) self.cnt = len(data) self.heap[1: self.cnt + 1] = data self.build_heap() def build_heap(self): last_non_leaf = self.cnt // 2 for x in range(last_non_leaf, 0, -1): max_pos = x i = x while True: if i <= self.cnt and self.heap[i] < self.heap[2 *i ]: max_pos = 2 * i if i <= self.cnt and self.heap[max_pos] < self.heap[2 * i + 1]: max_pos = 2 * i + 1 if max_pos == i: break self.heap[i], self.heap[max_pos] = self.heap[max_pos], self.heap[i] i = max_pos if __name__ == '__main__': data = np.random.randint(0, 100, 10) print(data) heap = MaxHeap(100, data) print(heap.heap)
Rename the class named ArrayHeap to the class named MaxHeap. Simplify __init__ method code to make it readable
Rename the class named ArrayHeap to the class named MaxHeap. Simplify __init__ method code to make it readable
Python
apache-2.0
free-free/algorithm,free-free/algorithm
import numpy as np - class ArrayHeap(object): + class MaxHeap(object): - def __init__(self, sz, data = None): + def __init__(self, sz, data): self.sz = sz - self.cnt = 0 - self.heap = [0 for i in range(sz + 1)] + self.heap = [0] * (sz + 1) - if data is not None: - for i, val in enumerate(data): - self.heap[i + 1] = val - self.cnt = len(data) + self.cnt = len(data) + self.heap[1: self.cnt + 1] = data - self._build_heap() + self.build_heap() - def _build_heap(self): + def build_heap(self): last_non_leaf = self.cnt // 2 for x in range(last_non_leaf, 0, -1): max_pos = x i = x while True: if i <= self.cnt and self.heap[i] < self.heap[2 *i ]: max_pos = 2 * i if i <= self.cnt and self.heap[max_pos] < self.heap[2 * i + 1]: max_pos = 2 * i + 1 if max_pos == i: break self.heap[i], self.heap[max_pos] = self.heap[max_pos], self.heap[i] i = max_pos if __name__ == '__main__': data = np.random.randint(0, 100, 10) print(data) - heap = ArrayHeap(100, data) + heap = MaxHeap(100, data) print(heap.heap)
Rename the class named ArrayHeap to the class named MaxHeap. Simplify __init__ method code to make it readable
## Code Before: import numpy as np class ArrayHeap(object): def __init__(self, sz, data = None): self.sz = sz self.cnt = 0 self.heap = [0 for i in range(sz + 1)] if data is not None: for i, val in enumerate(data): self.heap[i + 1] = val self.cnt = len(data) self._build_heap() def _build_heap(self): last_non_leaf = self.cnt // 2 for x in range(last_non_leaf, 0, -1): max_pos = x i = x while True: if i <= self.cnt and self.heap[i] < self.heap[2 *i ]: max_pos = 2 * i if i <= self.cnt and self.heap[max_pos] < self.heap[2 * i + 1]: max_pos = 2 * i + 1 if max_pos == i: break self.heap[i], self.heap[max_pos] = self.heap[max_pos], self.heap[i] i = max_pos if __name__ == '__main__': data = np.random.randint(0, 100, 10) print(data) heap = ArrayHeap(100, data) print(heap.heap) ## Instruction: Rename the class named ArrayHeap to the class named MaxHeap. Simplify __init__ method code to make it readable ## Code After: import numpy as np class MaxHeap(object): def __init__(self, sz, data): self.sz = sz self.heap = [0] * (sz + 1) self.cnt = len(data) self.heap[1: self.cnt + 1] = data self.build_heap() def build_heap(self): last_non_leaf = self.cnt // 2 for x in range(last_non_leaf, 0, -1): max_pos = x i = x while True: if i <= self.cnt and self.heap[i] < self.heap[2 *i ]: max_pos = 2 * i if i <= self.cnt and self.heap[max_pos] < self.heap[2 * i + 1]: max_pos = 2 * i + 1 if max_pos == i: break self.heap[i], self.heap[max_pos] = self.heap[max_pos], self.heap[i] i = max_pos if __name__ == '__main__': data = np.random.randint(0, 100, 10) print(data) heap = MaxHeap(100, data) print(heap.heap)
... class MaxHeap(object): ... def __init__(self, sz, data): self.sz = sz self.heap = [0] * (sz + 1) self.cnt = len(data) self.heap[1: self.cnt + 1] = data self.build_heap() def build_heap(self): last_non_leaf = self.cnt // 2 ... print(data) heap = MaxHeap(100, data) print(heap.heap) ...
59ec54bbe49013826d2c15ce2162c2e0e335bd57
modules/module_urlsize.py
modules/module_urlsize.py
"""Warns about large files""" def handle_url(bot, user, channel, url, msg): if channel == "#wow": return # inform about large files (over 5MB) size = getUrl(url).getSize() contentType = getUrl(url).getHeaders()['content-type'] if not size: return size = size / 1024 if size > 5: bot.say(channel, "File size: %s MB - Content-Type: %s" % (size, contentType))
"""Warns about large files""" def handle_url(bot, user, channel, url, msg): if channel == "#wow": return # inform about large files (over 5MB) size = getUrl(url).getSize() headers = getUrl(url).getHeaders()['content-type'] if 'content-type' in headers: contentType = headers['content-type'] else: contentType = "Unknown" if not size: return size = size / 1024 if size > 5: bot.say(channel, "File size: %s MB - Content-Type: %s" % (size, contentType))
Handle cases where the server doesn't return content-type
Handle cases where the server doesn't return content-type git-svn-id: 056f9092885898c4775d98c479d2d33d00273e45@120 dda364a1-ef19-0410-af65-756c83048fb2
Python
bsd-3-clause
rnyberg/pyfibot,lepinkainen/pyfibot,lepinkainen/pyfibot,rnyberg/pyfibot,EArmour/pyfibot,nigeljonez/newpyfibot,aapa/pyfibot,huqa/pyfibot,huqa/pyfibot,aapa/pyfibot,EArmour/pyfibot
"""Warns about large files""" def handle_url(bot, user, channel, url, msg): if channel == "#wow": return # inform about large files (over 5MB) size = getUrl(url).getSize() - contentType = getUrl(url).getHeaders()['content-type'] + headers = getUrl(url).getHeaders()['content-type'] + if 'content-type' in headers: + contentType = headers['content-type'] + else: + contentType = "Unknown" if not size: return size = size / 1024 if size > 5: bot.say(channel, "File size: %s MB - Content-Type: %s" % (size, contentType))
Handle cases where the server doesn't return content-type
## Code Before: """Warns about large files""" def handle_url(bot, user, channel, url, msg): if channel == "#wow": return # inform about large files (over 5MB) size = getUrl(url).getSize() contentType = getUrl(url).getHeaders()['content-type'] if not size: return size = size / 1024 if size > 5: bot.say(channel, "File size: %s MB - Content-Type: %s" % (size, contentType)) ## Instruction: Handle cases where the server doesn't return content-type ## Code After: """Warns about large files""" def handle_url(bot, user, channel, url, msg): if channel == "#wow": return # inform about large files (over 5MB) size = getUrl(url).getSize() headers = getUrl(url).getHeaders()['content-type'] if 'content-type' in headers: contentType = headers['content-type'] else: contentType = "Unknown" if not size: return size = size / 1024 if size > 5: bot.say(channel, "File size: %s MB - Content-Type: %s" % (size, contentType))
// ... existing code ... size = getUrl(url).getSize() headers = getUrl(url).getHeaders()['content-type'] if 'content-type' in headers: contentType = headers['content-type'] else: contentType = "Unknown" if not size: return // ... rest of the code ...
215746e2fd7e5f78b6dae031aae6a935ab164dd1
pyjokes/pyjokes.py
pyjokes/pyjokes.py
from __future__ import absolute_import import random import importlib def get_joke(category='neutral', language='en'): """ Parameters ---------- category: str Choices: 'neutral', 'explicit', 'chuck', 'all' lang: str Choices: 'en', 'de', 'es' Returns ------- joke: str """ if language == 'en': from .jokes_en import jokes elif language == 'de': from .jokes_de import jokes elif language == 'es': from .jokes_es import jokes try: jokes = jokes[category] except: return 'Could not get the joke. Choose another category.' else: return random.choice(jokes)
from __future__ import absolute_import import random from .jokes_en import jokes as jokes_en from .jokes_de import jokes as jokes_de from .jokes_es import jokes as jokes_es all_jokes = { 'en': jokes_en, 'de': jokes_de, 'es': jokes_es, } class LanguageNotFoundError(Exception): pass class CategoryNotFoundError(Exception): pass def get_joke(category='neutral', language='en'): """ Parameters ---------- category: str Choices: 'neutral', 'explicit', 'chuck', 'all' lang: str Choices: 'en', 'de', 'es' Returns ------- joke: str """ if language in all_jokes: jokes = all_jokes[language] else: raise LanguageNotFoundError('No such language %s' % language) if category in jokes: jokes = jokes[category] return random.choice(jokes) else: raise CategoryNotFound('No such category %s' % category)
Use dict not if/else, add exceptions
Use dict not if/else, add exceptions
Python
bsd-3-clause
borjaayerdi/pyjokes,birdsarah/pyjokes,pyjokes/pyjokes,bennuttall/pyjokes,trojjer/pyjokes,gmarkall/pyjokes,martinohanlon/pyjokes,ElectronicsGeek/pyjokes
from __future__ import absolute_import import random - import importlib + + from .jokes_en import jokes as jokes_en + from .jokes_de import jokes as jokes_de + from .jokes_es import jokes as jokes_es + + + all_jokes = { + 'en': jokes_en, + 'de': jokes_de, + 'es': jokes_es, + } + + + class LanguageNotFoundError(Exception): + pass + + + class CategoryNotFoundError(Exception): + pass + def get_joke(category='neutral', language='en'): """ Parameters ---------- category: str Choices: 'neutral', 'explicit', 'chuck', 'all' lang: str Choices: 'en', 'de', 'es' Returns ------- joke: str """ + if language in all_jokes: + jokes = all_jokes[language] + else: + raise LanguageNotFoundError('No such language %s' % language) - if language == 'en': - from .jokes_en import jokes - elif language == 'de': - from .jokes_de import jokes - elif language == 'es': - from .jokes_es import jokes - try: + if category in jokes: jokes = jokes[category] + return random.choice(jokes) - except: - return 'Could not get the joke. Choose another category.' else: - return random.choice(jokes) + raise CategoryNotFound('No such category %s' % category)
Use dict not if/else, add exceptions
## Code Before: from __future__ import absolute_import import random import importlib def get_joke(category='neutral', language='en'): """ Parameters ---------- category: str Choices: 'neutral', 'explicit', 'chuck', 'all' lang: str Choices: 'en', 'de', 'es' Returns ------- joke: str """ if language == 'en': from .jokes_en import jokes elif language == 'de': from .jokes_de import jokes elif language == 'es': from .jokes_es import jokes try: jokes = jokes[category] except: return 'Could not get the joke. Choose another category.' else: return random.choice(jokes) ## Instruction: Use dict not if/else, add exceptions ## Code After: from __future__ import absolute_import import random from .jokes_en import jokes as jokes_en from .jokes_de import jokes as jokes_de from .jokes_es import jokes as jokes_es all_jokes = { 'en': jokes_en, 'de': jokes_de, 'es': jokes_es, } class LanguageNotFoundError(Exception): pass class CategoryNotFoundError(Exception): pass def get_joke(category='neutral', language='en'): """ Parameters ---------- category: str Choices: 'neutral', 'explicit', 'chuck', 'all' lang: str Choices: 'en', 'de', 'es' Returns ------- joke: str """ if language in all_jokes: jokes = all_jokes[language] else: raise LanguageNotFoundError('No such language %s' % language) if category in jokes: jokes = jokes[category] return random.choice(jokes) else: raise CategoryNotFound('No such category %s' % category)
// ... existing code ... import random from .jokes_en import jokes as jokes_en from .jokes_de import jokes as jokes_de from .jokes_es import jokes as jokes_es all_jokes = { 'en': jokes_en, 'de': jokes_de, 'es': jokes_es, } class LanguageNotFoundError(Exception): pass class CategoryNotFoundError(Exception): pass // ... modified code ... if language in all_jokes: jokes = all_jokes[language] else: raise LanguageNotFoundError('No such language %s' % language) if category in jokes: jokes = jokes[category] return random.choice(jokes) else: raise CategoryNotFound('No such category %s' % category) // ... rest of the code ...
963f9ed01b400cd95e14aecdee7c265fe48a4d41
mopidy_nad/__init__.py
mopidy_nad/__init__.py
import os import pkg_resources from mopidy import config, ext __version__ = pkg_resources.get_distribution("Mopidy-NAD").version class Extension(ext.Extension): dist_name = "Mopidy-NAD" ext_name = "nad" version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), "ext.conf") return config.read(conf_file) def get_config_schema(self): schema = super().get_config_schema() schema["port"] = config.String() schema["source"] = config.String(optional=True) schema["speakers-a"] = config.Boolean(optional=True) schema["speakers-b"] = config.Boolean(optional=True) return schema def setup(self, registry): from mopidy_nad.mixer import NadMixer registry.add("mixer", NadMixer)
import pathlib import pkg_resources from mopidy import config, ext __version__ = pkg_resources.get_distribution("Mopidy-NAD").version class Extension(ext.Extension): dist_name = "Mopidy-NAD" ext_name = "nad" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_schema(self): schema = super().get_config_schema() schema["port"] = config.String() schema["source"] = config.String(optional=True) schema["speakers-a"] = config.Boolean(optional=True) schema["speakers-b"] = config.Boolean(optional=True) return schema def setup(self, registry): from mopidy_nad.mixer import NadMixer registry.add("mixer", NadMixer)
Use pathlib to read ext.conf
Use pathlib to read ext.conf
Python
apache-2.0
mopidy/mopidy-nad
- import os + import pathlib import pkg_resources from mopidy import config, ext __version__ = pkg_resources.get_distribution("Mopidy-NAD").version class Extension(ext.Extension): dist_name = "Mopidy-NAD" ext_name = "nad" version = __version__ def get_default_config(self): + return config.read(pathlib.Path(__file__).parent / "ext.conf") - conf_file = os.path.join(os.path.dirname(__file__), "ext.conf") - return config.read(conf_file) def get_config_schema(self): schema = super().get_config_schema() schema["port"] = config.String() schema["source"] = config.String(optional=True) schema["speakers-a"] = config.Boolean(optional=True) schema["speakers-b"] = config.Boolean(optional=True) return schema def setup(self, registry): from mopidy_nad.mixer import NadMixer registry.add("mixer", NadMixer)
Use pathlib to read ext.conf
## Code Before: import os import pkg_resources from mopidy import config, ext __version__ = pkg_resources.get_distribution("Mopidy-NAD").version class Extension(ext.Extension): dist_name = "Mopidy-NAD" ext_name = "nad" version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), "ext.conf") return config.read(conf_file) def get_config_schema(self): schema = super().get_config_schema() schema["port"] = config.String() schema["source"] = config.String(optional=True) schema["speakers-a"] = config.Boolean(optional=True) schema["speakers-b"] = config.Boolean(optional=True) return schema def setup(self, registry): from mopidy_nad.mixer import NadMixer registry.add("mixer", NadMixer) ## Instruction: Use pathlib to read ext.conf ## Code After: import pathlib import pkg_resources from mopidy import config, ext __version__ = pkg_resources.get_distribution("Mopidy-NAD").version class Extension(ext.Extension): dist_name = "Mopidy-NAD" ext_name = "nad" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_schema(self): schema = super().get_config_schema() schema["port"] = config.String() schema["source"] = config.String(optional=True) schema["speakers-a"] = config.Boolean(optional=True) schema["speakers-b"] = config.Boolean(optional=True) return schema def setup(self, registry): from mopidy_nad.mixer import NadMixer registry.add("mixer", NadMixer)
// ... existing code ... import pathlib // ... modified code ... def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") // ... rest of the code ...
cdd8b6a7b669dc81e360fa1bcc9b71b5e798cfd5
map_loader.py
map_loader.py
import os def read_map_file(map_name): """ Load map data from disk. """ root = os.path.dirname(os.path.abspath(__file__)) map_path = os.path.join(root, 'maps', map_name + '.txt') print('Loading map file [{}]'.format(map_name)) if not os.path.isfile(map_path): print('Map file [{}] does not exist'.format(map_path)) else: try: with open(map_path, 'r') as f: return f.read() except IOError: print('IOError exception reading map file [{}]'.format(map_path))
import logging import os def read_map_file(map_name): """ Load map data from disk. """ root = os.path.dirname(os.path.abspath(__file__)) map_path = os.path.join(root, 'maps', map_name + '.txt') if not os.path.isfile(map_path): logging.error('Map file [{}] does not exist'.format(map_path)) else: try: with open(map_path, 'r') as f: return f.read() except IOError: print('IOError exception reading map file [{}]'.format(map_path))
Remove debug print and log properly
Remove debug print and log properly
Python
mit
supermitch/mech-ai,supermitch/mech-ai,supermitch/mech-ai
+ import logging import os def read_map_file(map_name): """ Load map data from disk. """ root = os.path.dirname(os.path.abspath(__file__)) map_path = os.path.join(root, 'maps', map_name + '.txt') - print('Loading map file [{}]'.format(map_name)) if not os.path.isfile(map_path): - print('Map file [{}] does not exist'.format(map_path)) + logging.error('Map file [{}] does not exist'.format(map_path)) else: try: with open(map_path, 'r') as f: return f.read() except IOError: print('IOError exception reading map file [{}]'.format(map_path))
Remove debug print and log properly
## Code Before: import os def read_map_file(map_name): """ Load map data from disk. """ root = os.path.dirname(os.path.abspath(__file__)) map_path = os.path.join(root, 'maps', map_name + '.txt') print('Loading map file [{}]'.format(map_name)) if not os.path.isfile(map_path): print('Map file [{}] does not exist'.format(map_path)) else: try: with open(map_path, 'r') as f: return f.read() except IOError: print('IOError exception reading map file [{}]'.format(map_path)) ## Instruction: Remove debug print and log properly ## Code After: import logging import os def read_map_file(map_name): """ Load map data from disk. """ root = os.path.dirname(os.path.abspath(__file__)) map_path = os.path.join(root, 'maps', map_name + '.txt') if not os.path.isfile(map_path): logging.error('Map file [{}] does not exist'.format(map_path)) else: try: with open(map_path, 'r') as f: return f.read() except IOError: print('IOError exception reading map file [{}]'.format(map_path))
... import logging import os ... if not os.path.isfile(map_path): logging.error('Map file [{}] does not exist'.format(map_path)) else: ...
d46d0b5a5392b6ca047b519a9d6280b5b0581e81
system_maintenance/tests/functional/tests.py
system_maintenance/tests/functional/tests.py
from django.test import LiveServerTestCase from selenium import webdriver class FunctionalTest(LiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_app_home_title(self): self.browser.get('http://localhost:8000/system_maintenance') self.assertIn('System Maintenance', self.browser.title)
from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver class FunctionalTest(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_app_home_title(self): self.browser.get('http://localhost:8000/system_maintenance') self.assertIn('System Maintenance', self.browser.title)
Switch to 'StaticLiveServerTestCase' to avoid having to set 'settings.STATIC_ROOT'
Switch to 'StaticLiveServerTestCase' to avoid having to set 'settings.STATIC_ROOT'
Python
bsd-3-clause
mfcovington/django-system-maintenance,mfcovington/django-system-maintenance,mfcovington/django-system-maintenance
- from django.test import LiveServerTestCase + from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver - class FunctionalTest(LiveServerTestCase): + class FunctionalTest(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_app_home_title(self): self.browser.get('http://localhost:8000/system_maintenance') self.assertIn('System Maintenance', self.browser.title)
Switch to 'StaticLiveServerTestCase' to avoid having to set 'settings.STATIC_ROOT'
## Code Before: from django.test import LiveServerTestCase from selenium import webdriver class FunctionalTest(LiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_app_home_title(self): self.browser.get('http://localhost:8000/system_maintenance') self.assertIn('System Maintenance', self.browser.title) ## Instruction: Switch to 'StaticLiveServerTestCase' to avoid having to set 'settings.STATIC_ROOT' ## Code After: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver class FunctionalTest(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_app_home_title(self): self.browser.get('http://localhost:8000/system_maintenance') self.assertIn('System Maintenance', self.browser.title)
... from django.contrib.staticfiles.testing import StaticLiveServerTestCase ... class FunctionalTest(StaticLiveServerTestCase): ...
a6d49059851450c7ea527941600564cb3f48cc72
flask_profiler/storage/base.py
flask_profiler/storage/base.py
class BaseStorage(object): """docstring for BaseStorage""" def __init__(self): super(BaseStorage, self).__init__() def filter(self, criteria): raise Exception("Not implemneted Error") def getSummary(self, criteria): raise Exception("Not implemneted Error") def insert(self, measurement): raise Exception("Not implemented Error") def delete(self, measurementId): raise Exception("Not imlemented Error")
class BaseStorage(object): """docstring for BaseStorage""" def __init__(self): super(BaseStorage, self).__init__() def filter(self, criteria): raise Exception("Not implemneted Error") def getSummary(self, criteria): raise Exception("Not implemneted Error") def insert(self, measurement): raise Exception("Not implemented Error") def delete(self, measurementId): raise Exception("Not imlemented Error") def truncate(self): raise Exception("Not imlemented Error")
Add tuncate method to BaseStorage class
Add tuncate method to BaseStorage class This will provide an interface for supporting any new database, there by, making the code more robust.
Python
mit
muatik/flask-profiler
class BaseStorage(object): """docstring for BaseStorage""" def __init__(self): super(BaseStorage, self).__init__() def filter(self, criteria): raise Exception("Not implemneted Error") def getSummary(self, criteria): raise Exception("Not implemneted Error") def insert(self, measurement): raise Exception("Not implemented Error") def delete(self, measurementId): raise Exception("Not imlemented Error") + def truncate(self): + raise Exception("Not imlemented Error") +
Add tuncate method to BaseStorage class
## Code Before: class BaseStorage(object): """docstring for BaseStorage""" def __init__(self): super(BaseStorage, self).__init__() def filter(self, criteria): raise Exception("Not implemneted Error") def getSummary(self, criteria): raise Exception("Not implemneted Error") def insert(self, measurement): raise Exception("Not implemented Error") def delete(self, measurementId): raise Exception("Not imlemented Error") ## Instruction: Add tuncate method to BaseStorage class ## Code After: class BaseStorage(object): """docstring for BaseStorage""" def __init__(self): super(BaseStorage, self).__init__() def filter(self, criteria): raise Exception("Not implemneted Error") def getSummary(self, criteria): raise Exception("Not implemneted Error") def insert(self, measurement): raise Exception("Not implemented Error") def delete(self, measurementId): raise Exception("Not imlemented Error") def truncate(self): raise Exception("Not imlemented Error")
# ... existing code ... raise Exception("Not imlemented Error") def truncate(self): raise Exception("Not imlemented Error") # ... rest of the code ...
4ec22f8a0fdd549967e3a30096867b87bc458dde
tensorflow_cloud/python/tests/integration/call_run_on_script_with_keras_ctl_test.py
tensorflow_cloud/python/tests/integration/call_run_on_script_with_keras_ctl_test.py
import tensorflow_cloud as tfc # MultiWorkerMirroredStrategy tfc.run( entry_point="tensorflow_cloud/python/tests/testdata/mnist_example_using_ctl.py", distribution_strategy=None, worker_count=1, requirements_txt="tensorflow_cloud/python/tests/testdata/requirements.txt", stream_logs=True, )
"""Integration tests for calling tfc.run on script with keras.""" import os import sys from unittest import mock import tensorflow as tf import tensorflow_cloud as tfc class TensorflowCloudOnScriptTest(tf.test.TestCase): def setUp(self): super(TensorflowCloudOnScriptTest, self).setUp() self.test_data_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "../testdata/" ) @mock.patch.object(sys, "exit", autospec=True) def test_MWMS_on_script(self, mock_exit): mock_exit.side_effect = RuntimeError("exit called") with self.assertRaises(RuntimeError): tfc.run( entry_point=os.path.join( self.test_data_path, "mnist_example_using_ctl.py" ), distribution_strategy=None, worker_count=1, requirements_txt=os.path.join( self.test_data_path, "requirements.txt"), ) mock_exit.assert_called_once_with(0) if __name__ == "__main__": tf.test.main()
Add test harness to call_run_on_script_with_keras
Add test harness to call_run_on_script_with_keras
Python
apache-2.0
tensorflow/cloud,tensorflow/cloud
+ """Integration tests for calling tfc.run on script with keras.""" + import os + import sys + from unittest import mock + import tensorflow as tf import tensorflow_cloud as tfc - # MultiWorkerMirroredStrategy - tfc.run( - entry_point="tensorflow_cloud/python/tests/testdata/mnist_example_using_ctl.py", - distribution_strategy=None, - worker_count=1, - requirements_txt="tensorflow_cloud/python/tests/testdata/requirements.txt", - stream_logs=True, - ) + class TensorflowCloudOnScriptTest(tf.test.TestCase): + def setUp(self): + super(TensorflowCloudOnScriptTest, self).setUp() + self.test_data_path = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "../testdata/" + ) + + @mock.patch.object(sys, "exit", autospec=True) + def test_MWMS_on_script(self, mock_exit): + mock_exit.side_effect = RuntimeError("exit called") + with self.assertRaises(RuntimeError): + tfc.run( + entry_point=os.path.join( + self.test_data_path, "mnist_example_using_ctl.py" + ), + distribution_strategy=None, + worker_count=1, + requirements_txt=os.path.join( + self.test_data_path, "requirements.txt"), + ) + mock_exit.assert_called_once_with(0) + + + if __name__ == "__main__": + tf.test.main() +
Add test harness to call_run_on_script_with_keras
## Code Before: import tensorflow_cloud as tfc # MultiWorkerMirroredStrategy tfc.run( entry_point="tensorflow_cloud/python/tests/testdata/mnist_example_using_ctl.py", distribution_strategy=None, worker_count=1, requirements_txt="tensorflow_cloud/python/tests/testdata/requirements.txt", stream_logs=True, ) ## Instruction: Add test harness to call_run_on_script_with_keras ## Code After: """Integration tests for calling tfc.run on script with keras.""" import os import sys from unittest import mock import tensorflow as tf import tensorflow_cloud as tfc class TensorflowCloudOnScriptTest(tf.test.TestCase): def setUp(self): super(TensorflowCloudOnScriptTest, self).setUp() self.test_data_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "../testdata/" ) @mock.patch.object(sys, "exit", autospec=True) def test_MWMS_on_script(self, mock_exit): mock_exit.side_effect = RuntimeError("exit called") with self.assertRaises(RuntimeError): tfc.run( entry_point=os.path.join( self.test_data_path, "mnist_example_using_ctl.py" ), distribution_strategy=None, worker_count=1, requirements_txt=os.path.join( self.test_data_path, "requirements.txt"), ) mock_exit.assert_called_once_with(0) if __name__ == "__main__": tf.test.main()
... """Integration tests for calling tfc.run on script with keras.""" import os import sys from unittest import mock import tensorflow as tf import tensorflow_cloud as tfc ... class TensorflowCloudOnScriptTest(tf.test.TestCase): def setUp(self): super(TensorflowCloudOnScriptTest, self).setUp() self.test_data_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "../testdata/" ) @mock.patch.object(sys, "exit", autospec=True) def test_MWMS_on_script(self, mock_exit): mock_exit.side_effect = RuntimeError("exit called") with self.assertRaises(RuntimeError): tfc.run( entry_point=os.path.join( self.test_data_path, "mnist_example_using_ctl.py" ), distribution_strategy=None, worker_count=1, requirements_txt=os.path.join( self.test_data_path, "requirements.txt"), ) mock_exit.assert_called_once_with(0) if __name__ == "__main__": tf.test.main() ...
b66d8c2d43a28ce6e0824543bd879dc3528e3509
rest/available-phone-numbers/local-basic-example-1/local-get-basic-example-1.6.x.py
rest/available-phone-numbers/local-basic-example-1/local-get-basic-example-1.6.x.py
from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) numbers = client.available_phone_numbers("US") \ .local \ .list(area_code="510") number = client.incoming_phone_numbers \ .create(phone_number=numbers[0].phone_number) print(number.sid)
from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) numbers = client.available_phone_numbers("US") \ .local \ .list(area_code="510") # Purchase the phone number number = client.incoming_phone_numbers \ .create(phone_number=numbers[0].phone_number) print(number.sid)
Add a comment about purchasing the phone number
Add a comment about purchasing the phone number
Python
mit
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) numbers = client.available_phone_numbers("US") \ .local \ .list(area_code="510") + # Purchase the phone number number = client.incoming_phone_numbers \ .create(phone_number=numbers[0].phone_number) print(number.sid)
Add a comment about purchasing the phone number
## Code Before: from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) numbers = client.available_phone_numbers("US") \ .local \ .list(area_code="510") number = client.incoming_phone_numbers \ .create(phone_number=numbers[0].phone_number) print(number.sid) ## Instruction: Add a comment about purchasing the phone number ## Code After: from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) numbers = client.available_phone_numbers("US") \ .local \ .list(area_code="510") # Purchase the phone number number = client.incoming_phone_numbers \ .create(phone_number=numbers[0].phone_number) print(number.sid)
... # Purchase the phone number number = client.incoming_phone_numbers \ ...
33505f9b4dfeead0b01ee1b8cf3f8f228476e866
openpassword/crypt_utils.py
openpassword/crypt_utils.py
from Crypto.Cipher import AES def decrypt(data, key_iv): key = key_iv[0:16] iv = key_iv[16:] print(data) cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.decrypt(data) def encrypt(data, key_iv): key = key_iv[0:16] iv = key_iv[16:] cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.encrypt(data)
from Crypto.Cipher import AES def decrypt(data, key_iv): key = key_iv[0:16] iv = key_iv[16:] cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.decrypt(data) def encrypt(data, key_iv): key = key_iv[0:16] iv = key_iv[16:] cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.encrypt(data)
Remove print statement from crypto utils...
Remove print statement from crypto utils...
Python
mit
openpassword/blimey,openpassword/blimey
from Crypto.Cipher import AES def decrypt(data, key_iv): key = key_iv[0:16] iv = key_iv[16:] - print(data) cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.decrypt(data) def encrypt(data, key_iv): key = key_iv[0:16] iv = key_iv[16:] cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.encrypt(data)
Remove print statement from crypto utils...
## Code Before: from Crypto.Cipher import AES def decrypt(data, key_iv): key = key_iv[0:16] iv = key_iv[16:] print(data) cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.decrypt(data) def encrypt(data, key_iv): key = key_iv[0:16] iv = key_iv[16:] cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.encrypt(data) ## Instruction: Remove print statement from crypto utils... ## Code After: from Crypto.Cipher import AES def decrypt(data, key_iv): key = key_iv[0:16] iv = key_iv[16:] cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.decrypt(data) def encrypt(data, key_iv): key = key_iv[0:16] iv = key_iv[16:] cipher = AES.new(key, AES.MODE_CBC, iv) return cipher.encrypt(data)
# ... existing code ... iv = key_iv[16:] cipher = AES.new(key, AES.MODE_CBC, iv) # ... rest of the code ...
7805f06446f31ac483ba219147f4053661e86647
penchy/jobs/__init__.py
penchy/jobs/__init__.py
from job import * from jvms import * from tools import * from filters import * from workloads import * # all job elements that are interesting for the user have to be enumerated here __all__ = [ # job 'Job', 'JVMNodeConfiguration', # jvm 'JVM', 'ValgrindJVM', # filters # workloads 'Dacapo', 'ScalaBench', # tools 'Tamiflex', 'HProf' ]
from job import * import jvms import tools import filters import workloads from dependency import Edge JVM = jvms.JVM # all job elements that are interesting for the user have to be enumerated here __all__ = [ # job 'Job', 'JVMNodeConfiguration', # dependencies 'Edge', # jvms 'JVM', # modules 'jvms' 'filters' 'workloads' 'tools' ]
Restructure jobs interface to match job description docs.
Restructure jobs interface to match job description docs. Signed-off-by: Michael Markert <[email protected]>
Python
mit
fhirschmann/penchy,fhirschmann/penchy
from job import * - from jvms import * - from tools import * - from filters import * - from workloads import * + import jvms + import tools + import filters + import workloads + from dependency import Edge + + JVM = jvms.JVM # all job elements that are interesting for the user have to be enumerated here __all__ = [ # job 'Job', 'JVMNodeConfiguration', + # dependencies + 'Edge', - # jvm + # jvms 'JVM', - 'ValgrindJVM', + # modules + 'jvms' - # filters + 'filters' - # workloads + 'workloads' - 'Dacapo', - 'ScalaBench', - # tools + 'tools' - 'Tamiflex', - 'HProf' ]
Restructure jobs interface to match job description docs.
## Code Before: from job import * from jvms import * from tools import * from filters import * from workloads import * # all job elements that are interesting for the user have to be enumerated here __all__ = [ # job 'Job', 'JVMNodeConfiguration', # jvm 'JVM', 'ValgrindJVM', # filters # workloads 'Dacapo', 'ScalaBench', # tools 'Tamiflex', 'HProf' ] ## Instruction: Restructure jobs interface to match job description docs. ## Code After: from job import * import jvms import tools import filters import workloads from dependency import Edge JVM = jvms.JVM # all job elements that are interesting for the user have to be enumerated here __all__ = [ # job 'Job', 'JVMNodeConfiguration', # dependencies 'Edge', # jvms 'JVM', # modules 'jvms' 'filters' 'workloads' 'tools' ]
# ... existing code ... from job import * import jvms import tools import filters import workloads from dependency import Edge JVM = jvms.JVM # ... modified code ... 'JVMNodeConfiguration', # dependencies 'Edge', # jvms 'JVM', # modules 'jvms' 'filters' 'workloads' 'tools' ] # ... rest of the code ...
799e79b03a753e5e8ba09a436e325e304a1148d6
apiserver/worker/grab_config.py
apiserver/worker/grab_config.py
import json import requests MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url" SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder" MANAGER_URL = requests.get(MANAGER_URL_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text SECRET_FOLDER = requests.get(SECRET_FOLDER_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text with open("config.json", "w") as configfile: json.dump({ "MANAGER_URL": MANAGER_URL, "SECRET_FOLDER": SECRET_FOLDER, }, configfile)
import json import requests MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url" SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder" GPU_CAPABILITY_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-gpu" MANAGER_URL = requests.get(MANAGER_URL_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text SECRET_FOLDER = requests.get(SECRET_FOLDER_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text HAS_GPU = requests.get(SECRET_FOLDER_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text == "true" with open("config.json", "w") as configfile: json.dump({ "MANAGER_URL": MANAGER_URL, "SECRET_FOLDER": SECRET_FOLDER, "CAPABILITIES": ["gpu"] if HAS_GPU else [], }, configfile)
Determine GPU presence on workers based on instance metadata
Determine GPU presence on workers based on instance metadata
Python
mit
lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II
import json import requests MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url" SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder" + GPU_CAPABILITY_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-gpu" MANAGER_URL = requests.get(MANAGER_URL_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text SECRET_FOLDER = requests.get(SECRET_FOLDER_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text + HAS_GPU = requests.get(SECRET_FOLDER_METADATA_URL, headers={ + "Metadata-Flavor": "Google" + }).text == "true" with open("config.json", "w") as configfile: json.dump({ "MANAGER_URL": MANAGER_URL, "SECRET_FOLDER": SECRET_FOLDER, + "CAPABILITIES": ["gpu"] if HAS_GPU else [], }, configfile)
Determine GPU presence on workers based on instance metadata
## Code Before: import json import requests MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url" SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder" MANAGER_URL = requests.get(MANAGER_URL_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text SECRET_FOLDER = requests.get(SECRET_FOLDER_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text with open("config.json", "w") as configfile: json.dump({ "MANAGER_URL": MANAGER_URL, "SECRET_FOLDER": SECRET_FOLDER, }, configfile) ## Instruction: Determine GPU presence on workers based on instance metadata ## Code After: import json import requests MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url" SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder" GPU_CAPABILITY_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-gpu" MANAGER_URL = requests.get(MANAGER_URL_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text SECRET_FOLDER = requests.get(SECRET_FOLDER_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text HAS_GPU = requests.get(SECRET_FOLDER_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text == "true" with open("config.json", "w") as configfile: json.dump({ "MANAGER_URL": MANAGER_URL, "SECRET_FOLDER": SECRET_FOLDER, "CAPABILITIES": ["gpu"] if HAS_GPU else [], }, configfile)
# ... existing code ... SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder" GPU_CAPABILITY_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-gpu" # ... modified code ... }).text HAS_GPU = requests.get(SECRET_FOLDER_METADATA_URL, headers={ "Metadata-Flavor": "Google" }).text == "true" ... "SECRET_FOLDER": SECRET_FOLDER, "CAPABILITIES": ["gpu"] if HAS_GPU else [], }, configfile) # ... rest of the code ...
0571864eb2d99b746386ace721b8e218f127c6ac
email_obfuscator/templatetags/email_obfuscator.py
email_obfuscator/templatetags/email_obfuscator.py
from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe register = template.Library() def obfuscate_string(value): return ''.join(['&#%s;'.format(str(ord(char))) for char in value]) @register.filter @stringfilter def obfuscate(value): return mark_safe(obfuscate_string(value)) @register.filter @stringfilter def obfuscate_mailto(value, text=False): mail = obfuscate_string(value) if text: link_text = text else: link_text = mail return mark_safe('<a href="%s%s">%s</a>'.format( obfuscate_string('mailto:'), mail, link_text))
from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe register = template.Library() def obfuscate_string(value): return ''.join(['&#{0:s};'.format(str(ord(char))) for char in value]) @register.filter @stringfilter def obfuscate(value): return mark_safe(obfuscate_string(value)) @register.filter @stringfilter def obfuscate_mailto(value, text=False): mail = obfuscate_string(value) if text: link_text = text else: link_text = mail return mark_safe('<a href="{0:s}{1:s}">{2:s}</a>'.format( obfuscate_string('mailto:'), mail, link_text))
Fix mixup of old and new-style string formatting
Fix mixup of old and new-style string formatting
Python
mit
morninj/django-email-obfuscator
from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe register = template.Library() def obfuscate_string(value): - return ''.join(['&#%s;'.format(str(ord(char))) for char in value]) + return ''.join(['&#{0:s};'.format(str(ord(char))) for char in value]) @register.filter @stringfilter def obfuscate(value): return mark_safe(obfuscate_string(value)) @register.filter @stringfilter def obfuscate_mailto(value, text=False): mail = obfuscate_string(value) if text: link_text = text else: link_text = mail - return mark_safe('<a href="%s%s">%s</a>'.format( + return mark_safe('<a href="{0:s}{1:s}">{2:s}</a>'.format( obfuscate_string('mailto:'), mail, link_text))
Fix mixup of old and new-style string formatting
## Code Before: from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe register = template.Library() def obfuscate_string(value): return ''.join(['&#%s;'.format(str(ord(char))) for char in value]) @register.filter @stringfilter def obfuscate(value): return mark_safe(obfuscate_string(value)) @register.filter @stringfilter def obfuscate_mailto(value, text=False): mail = obfuscate_string(value) if text: link_text = text else: link_text = mail return mark_safe('<a href="%s%s">%s</a>'.format( obfuscate_string('mailto:'), mail, link_text)) ## Instruction: Fix mixup of old and new-style string formatting ## Code After: from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe register = template.Library() def obfuscate_string(value): return ''.join(['&#{0:s};'.format(str(ord(char))) for char in value]) @register.filter @stringfilter def obfuscate(value): return mark_safe(obfuscate_string(value)) @register.filter @stringfilter def obfuscate_mailto(value, text=False): mail = obfuscate_string(value) if text: link_text = text else: link_text = mail return mark_safe('<a href="{0:s}{1:s}">{2:s}</a>'.format( obfuscate_string('mailto:'), mail, link_text))
// ... existing code ... def obfuscate_string(value): return ''.join(['&#{0:s};'.format(str(ord(char))) for char in value]) // ... modified code ... return mark_safe('<a href="{0:s}{1:s}">{2:s}</a>'.format( obfuscate_string('mailto:'), mail, link_text)) // ... rest of the code ...
8a7837a8ce7b35c3141374c6a5c99361261fa70a
Cura/avr_isp/chipDB.py
Cura/avr_isp/chipDB.py
avrChipDB = { 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: return chip return False
avrChipDB = { 'ATMega1280': { 'signature': [0x1E, 0x97, 0x03], 'pageSize': 128, 'pageCount': 512, }, 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: return chip return False
Add ATMega1280 chip to programmer chips.
Add ATMega1280 chip to programmer chips.
Python
agpl-3.0
MolarAmbiguity/OctoPrint,EZ3-India/EZ-Remote,JackGavin13/octoprint-test-not-finished,spapadim/OctoPrint,dragondgold/OctoPrint,hudbrog/OctoPrint,CapnBry/OctoPrint,Javierma/OctoPrint-TFG,chriskoz/OctoPrint,javivi001/OctoPrint,shohei/Octoprint,eddieparker/OctoPrint,MolarAmbiguity/OctoPrint,mayoff/OctoPrint,uuv/OctoPrint,C-o-r-E/OctoPrint,Mikk36/OctoPrint,DanLipsitt/OctoPrint,shohei/Octoprint,beeverycreative/BEEweb,alex1818/OctoPrint,EZ3-India/EZ-Remote,alex1818/OctoPrint,shohei/Octoprint,markwal/OctoPrint,beeverycreative/BEEweb,aerickson/OctoPrint,beeverycreative/BEEweb,aerickson/OctoPrint,nicanor-romero/OctoPrint,punkkeks/OctoPrint,d42/octoprint-fork,Javierma/OctoPrint-TFG,3dprintcanalhouse/octoprint2,ErikDeBruijn/OctoPrint,punkkeks/OctoPrint,masterhou/OctoPrint,shaggythesheep/OctoPrint,chriskoz/OctoPrint,madhuni/AstroBox,Catrodigious/OctoPrint-TAM,alephobjects/Cura,javivi001/OctoPrint,uuv/OctoPrint,leductan-nguyen/RaionPi,MoonshineSG/OctoPrint,eliasbakken/OctoPrint,nicanor-romero/OctoPrint,Skeen/OctoPrint,javivi001/OctoPrint,Salandora/OctoPrint,jneves/OctoPrint,hudbrog/OctoPrint,shaggythesheep/OctoPrint,MoonshineSG/OctoPrint,skieast/OctoPrint,abinashk-inf/AstroBox,nickverschoor/OctoPrint,eddieparker/OctoPrint,EZ3-India/EZ-Remote,EZ3-India/EZ-Remote,abinashk-inf/AstroBox,mrbeam/OctoPrint,abinashk-inf/AstroBox,mrbeam/OctoPrint,Voxel8/OctoPrint,sstocker46/OctoPrint,bicephale/OctoPrint,dragondgold/OctoPrint,Jaesin/OctoPrint,mcanes/OctoPrint,ryanneufeld/OctoPrint,Salandora/OctoPrint,CapnBry/OctoPrint,foosel/OctoPrint,nickverschoor/OctoPrint,alephobjects/Cura,mcanes/OctoPrint,markwal/OctoPrint,sstocker46/OctoPrint,Jaesin/OctoPrint,3dprintcanalhouse/octoprint1,skieast/OctoPrint,madhuni/AstroBox,markwal/OctoPrint,Mikk36/OctoPrint,AstroPrint/AstroBox,ymilord/OctoPrint-MrBeam,dansantee/OctoPrint,Jaesin/OctoPrint,punkkeks/OctoPrint,ymilord/OctoPrint-MrBeam,rurkowce/octoprint-fork,foosel/OctoPrint,Salandora/OctoPrint,spapadim/OctoPrint,MoonshineSG/OctoPrint,spapadim/OctoPrint,madhuni/AstroBox,masterhou/OctoPrint,ymilord/OctoPrint-MrBeam,alephobjects/Cura,ryanneufeld/OctoPrint,chriskoz/OctoPrint,hudbrog/OctoPrint,Mikk36/OctoPrint,eddieparker/OctoPrint,leductan-nguyen/RaionPi,JackGavin13/octoprint-test-not-finished,beeverycreative/BEEweb,bicephale/OctoPrint,nicanor-romero/OctoPrint,jneves/OctoPrint,JackGavin13/octoprint-test-not-finished,ErikDeBruijn/OctoPrint,leductan-nguyen/RaionPi,CapnBry/OctoPrint,chriskoz/OctoPrint,ryanneufeld/OctoPrint,3dprintcanalhouse/octoprint1,mrbeam/OctoPrint,senttech/OctoPrint,Javierma/OctoPrint-TFG,dansantee/OctoPrint,Voxel8/OctoPrint,bicephale/OctoPrint,MolarAmbiguity/OctoPrint,MaxOLydian/OctoPrint,eliasbakken/OctoPrint,DanLipsitt/OctoPrint,mayoff/OctoPrint,Skeen/OctoPrint,Jaesin/OctoPrint,rurkowce/octoprint-fork,CapnBry/OctoPrint,AstroPrint/AstroBox,madhuni/AstroBox,uuv/OctoPrint,abinashk-inf/AstroBox,JackGavin13/octoprint-test-not-finished,SeveQ/OctoPrint,sstocker46/OctoPrint,dansantee/OctoPrint,skieast/OctoPrint,mayoff/OctoPrint,C-o-r-E/OctoPrint,eliasbakken/OctoPrint,ryanneufeld/OctoPrint,foosel/OctoPrint,nickverschoor/OctoPrint,bicephale/OctoPrint,SeveQ/OctoPrint,MoonshineSG/OctoPrint,SeveQ/OctoPrint,senttech/OctoPrint,shohei/Octoprint,ymilord/OctoPrint-MrBeam,3dprintcanalhouse/octoprint2,d42/octoprint-fork,mcanes/OctoPrint,Voxel8/OctoPrint,senttech/OctoPrint,ymilord/OctoPrint-MrBeam,leductan-nguyen/RaionPi,Javierma/OctoPrint-TFG,Salandora/OctoPrint,C-o-r-E/OctoPrint,alex1818/OctoPrint,MaxOLydian/OctoPrint,shaggythesheep/OctoPrint,masterhou/OctoPrint,shohei/Octoprint,ErikDeBruijn/OctoPrint,jneves/OctoPrint,Catrodigious/OctoPrint-TAM,foosel/OctoPrint,dragondgold/OctoPrint,senttech/OctoPrint,aerickson/OctoPrint,MaxOLydian/OctoPrint,nickverschoor/OctoPrint,Skeen/OctoPrint,Catrodigious/OctoPrint-TAM,AstroPrint/AstroBox
avrChipDB = { + 'ATMega1280': { + 'signature': [0x1E, 0x97, 0x03], + 'pageSize': 128, + 'pageCount': 512, + }, 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: return chip return False
Add ATMega1280 chip to programmer chips.
## Code Before: avrChipDB = { 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: return chip return False ## Instruction: Add ATMega1280 chip to programmer chips. ## Code After: avrChipDB = { 'ATMega1280': { 'signature': [0x1E, 0x97, 0x03], 'pageSize': 128, 'pageCount': 512, }, 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: return chip return False
... avrChipDB = { 'ATMega1280': { 'signature': [0x1E, 0x97, 0x03], 'pageSize': 128, 'pageCount': 512, }, 'ATMega2560': { ...
f32621c2c8ad207e152f10279e36f56970f48026
python/ecep/portal/widgets.py
python/ecep/portal/widgets.py
from django.forms import widgets from django.utils.safestring import mark_safe class MapWidget(widgets.HiddenInput): """Custom map widget for displaying interactive google map to geocode addresses of learning centers. This widget displays a readonly input box to store lat+lng data, an empty help div, a map div for the google map, and a button to initiate geocoding. """ def render(self, name, value, attrs=None): """Overrides the render method. This controls the actual html output of a form on the page See widget docs for more information: https://docs.djangoproject.com/en/1.4/ref/forms/widgets/ """ widget = super(MapWidget, self).render(name, value, attrs) return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60"> <br> <input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()> (<a onclick=ecepAdmin.mapHelp() href="#">?</a>) <div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
from django.forms import widgets from django.utils.safestring import mark_safe class MapWidget(widgets.HiddenInput): """Custom map widget for displaying interactive google map to geocode addresses of learning centers. This widget displays a readonly input box to store lat+lng data, an empty help div, a map div for the google map, and a button to initiate geocoding. """ def render(self, name, value, attrs=None): """Overrides the render method. This controls the actual html output of a form on the page See widget docs for more information: https://docs.djangoproject.com/en/1.4/ref/forms/widgets/ """ widget = super(MapWidget, self).render(name, value, attrs) return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60" class="%s"> <br> <input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()> (<a onclick=ecepAdmin.mapHelp() href="#">?</a>) <div id='map-help'></div><div id="map">%s</div>""" % (value, self.attrs.get('class', None), widget))
Set optional class on map widget if class attribute passed
Set optional class on map widget if class attribute passed
Python
mit
smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning
from django.forms import widgets from django.utils.safestring import mark_safe class MapWidget(widgets.HiddenInput): """Custom map widget for displaying interactive google map to geocode addresses of learning centers. This widget displays a readonly input box to store lat+lng data, an empty help div, a map div for the google map, and a button to initiate geocoding. """ def render(self, name, value, attrs=None): """Overrides the render method. This controls the actual html output of a form on the page See widget docs for more information: https://docs.djangoproject.com/en/1.4/ref/forms/widgets/ """ widget = super(MapWidget, self).render(name, value, attrs) - return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60"> + return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60" class="%s"> <br> <input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()> (<a onclick=ecepAdmin.mapHelp() href="#">?</a>) - <div id='map-help'></div><div id="map">%s</div>""" % (value, widget)) + <div id='map-help'></div><div id="map">%s</div>""" % (value, self.attrs.get('class', None), widget))
Set optional class on map widget if class attribute passed
## Code Before: from django.forms import widgets from django.utils.safestring import mark_safe class MapWidget(widgets.HiddenInput): """Custom map widget for displaying interactive google map to geocode addresses of learning centers. This widget displays a readonly input box to store lat+lng data, an empty help div, a map div for the google map, and a button to initiate geocoding. """ def render(self, name, value, attrs=None): """Overrides the render method. This controls the actual html output of a form on the page See widget docs for more information: https://docs.djangoproject.com/en/1.4/ref/forms/widgets/ """ widget = super(MapWidget, self).render(name, value, attrs) return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60"> <br> <input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()> (<a onclick=ecepAdmin.mapHelp() href="#">?</a>) <div id='map-help'></div><div id="map">%s</div>""" % (value, widget)) ## Instruction: Set optional class on map widget if class attribute passed ## Code After: from django.forms import widgets from django.utils.safestring import mark_safe class MapWidget(widgets.HiddenInput): """Custom map widget for displaying interactive google map to geocode addresses of learning centers. This widget displays a readonly input box to store lat+lng data, an empty help div, a map div for the google map, and a button to initiate geocoding. """ def render(self, name, value, attrs=None): """Overrides the render method. This controls the actual html output of a form on the page See widget docs for more information: https://docs.djangoproject.com/en/1.4/ref/forms/widgets/ """ widget = super(MapWidget, self).render(name, value, attrs) return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60" class="%s"> <br> <input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()> (<a onclick=ecepAdmin.mapHelp() href="#">?</a>) <div id='map-help'></div><div id="map">%s</div>""" % (value, self.attrs.get('class', None), widget))
# ... existing code ... widget = super(MapWidget, self).render(name, value, attrs) return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60" class="%s"> <br> # ... modified code ... (<a onclick=ecepAdmin.mapHelp() href="#">?</a>) <div id='map-help'></div><div id="map">%s</div>""" % (value, self.attrs.get('class', None), widget)) # ... rest of the code ...
297660a27dc5b23beb0f616965c60389bce3c2d8
h2o-py/tests/testdir_algos/rf/pyunit_bigcatRF.py
h2o-py/tests/testdir_algos/rf/pyunit_bigcatRF.py
import sys sys.path.insert(1, "../../../") import h2o def bigcatRF(ip,port): # Connect to h2o h2o.init(ip,port) # Training set has 100 categories from cat001 to cat100 # Categories cat001, cat003, ... are perfect predictors of y = 1 # Categories cat002, cat004, ... are perfect predictors of y = 0 #Log.info("Importing bigcat_5000x2.csv data...\n") bigcat = h2o.import_frame(path=h2o.locate("smalldata/gbm_test/bigcat_5000x2.csv")) bigcat["y"] = bigcat["y"].asfactor() #Log.info("Summary of bigcat_5000x2.csv from H2O:\n") #bigcat.summary() # Train H2O DRF Model: #Log.info("H2O DRF (Naive Split) with parameters:\nclassification = TRUE, ntree = 1, depth = 1, nbins = 100\n") model = h2o.random_forest(x=bigcat[["X"]], y=bigcat["y"], ntrees=1, max_depth=1, nbins=100) model.show() if __name__ == "__main__": h2o.run_test(sys.argv, bigcatRF)
import sys sys.path.insert(1, "../../../") import h2o def bigcatRF(ip,port): # Connect to h2o h2o.init(ip,port) # Training set has 100 categories from cat001 to cat100 # Categories cat001, cat003, ... are perfect predictors of y = 1 # Categories cat002, cat004, ... are perfect predictors of y = 0 #Log.info("Importing bigcat_5000x2.csv data...\n") bigcat = h2o.import_frame(path=h2o.locate("smalldata/gbm_test/bigcat_5000x2.csv")) bigcat["y"] = bigcat["y"].asfactor() #Log.info("Summary of bigcat_5000x2.csv from H2O:\n") #bigcat.summary() # Train H2O DRF Model: #Log.info("H2O DRF (Naive Split) with parameters:\nclassification = TRUE, ntree = 1, depth = 1, nbins = 100, nbins_cats=10\n") model = h2o.random_forest(x=bigcat[["X"]], y=bigcat["y"], ntrees=1, max_depth=1, nbins=100, nbins_cats=10) model.show() if __name__ == "__main__": h2o.run_test(sys.argv, bigcatRF)
Add usage of nbins_cats to RF pyunit.
Add usage of nbins_cats to RF pyunit.
Python
apache-2.0
nilbody/h2o-3,YzPaul3/h2o-3,datachand/h2o-3,michalkurka/h2o-3,brightchen/h2o-3,madmax983/h2o-3,weaver-viii/h2o-3,junwucs/h2o-3,michalkurka/h2o-3,tarasane/h2o-3,michalkurka/h2o-3,datachand/h2o-3,madmax983/h2o-3,spennihana/h2o-3,h2oai/h2o-3,junwucs/h2o-3,datachand/h2o-3,junwucs/h2o-3,YzPaul3/h2o-3,bospetersen/h2o-3,jangorecki/h2o-3,nilbody/h2o-3,printedheart/h2o-3,h2oai/h2o-dev,printedheart/h2o-3,bospetersen/h2o-3,datachand/h2o-3,tarasane/h2o-3,michalkurka/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,weaver-viii/h2o-3,mrgloom/h2o-3,mrgloom/h2o-3,mrgloom/h2o-3,printedheart/h2o-3,h2oai/h2o-3,PawarPawan/h2o-v3,h2oai/h2o-dev,ChristosChristofidis/h2o-3,madmax983/h2o-3,jangorecki/h2o-3,weaver-viii/h2o-3,pchmieli/h2o-3,tarasane/h2o-3,pchmieli/h2o-3,datachand/h2o-3,mrgloom/h2o-3,madmax983/h2o-3,weaver-viii/h2o-3,mathemage/h2o-3,h2oai/h2o-dev,datachand/h2o-3,junwucs/h2o-3,mathemage/h2o-3,mrgloom/h2o-3,h2oai/h2o-3,PawarPawan/h2o-v3,spennihana/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,PawarPawan/h2o-v3,h2oai/h2o-3,weaver-viii/h2o-3,pchmieli/h2o-3,junwucs/h2o-3,brightchen/h2o-3,junwucs/h2o-3,printedheart/h2o-3,printedheart/h2o-3,kyoren/https-github.com-h2oai-h2o-3,nilbody/h2o-3,PawarPawan/h2o-v3,spennihana/h2o-3,YzPaul3/h2o-3,brightchen/h2o-3,ChristosChristofidis/h2o-3,tarasane/h2o-3,ChristosChristofidis/h2o-3,mrgloom/h2o-3,tarasane/h2o-3,h2oai/h2o-3,PawarPawan/h2o-v3,kyoren/https-github.com-h2oai-h2o-3,YzPaul3/h2o-3,michalkurka/h2o-3,kyoren/https-github.com-h2oai-h2o-3,weaver-viii/h2o-3,nilbody/h2o-3,ChristosChristofidis/h2o-3,spennihana/h2o-3,PawarPawan/h2o-v3,nilbody/h2o-3,nilbody/h2o-3,pchmieli/h2o-3,ChristosChristofidis/h2o-3,kyoren/https-github.com-h2oai-h2o-3,nilbody/h2o-3,brightchen/h2o-3,bospetersen/h2o-3,YzPaul3/h2o-3,YzPaul3/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,madmax983/h2o-3,kyoren/https-github.com-h2oai-h2o-3,brightchen/h2o-3,YzPaul3/h2o-3,ChristosChristofidis/h2o-3,pchmieli/h2o-3,mathemage/h2o-3,bospetersen/h2o-3,brightchen/h2o-3,h2oai/h2o-3,weaver-viii/h2o-3,kyoren/https-github.com-h2oai-h2o-3,kyoren/https-github.com-h2oai-h2o-3,h2oai/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,pchmieli/h2o-3,tarasane/h2o-3,mathemage/h2o-3,mathemage/h2o-3,spennihana/h2o-3,brightchen/h2o-3,mathemage/h2o-3,mrgloom/h2o-3,datachand/h2o-3,jangorecki/h2o-3,tarasane/h2o-3,madmax983/h2o-3,pchmieli/h2o-3,bospetersen/h2o-3,printedheart/h2o-3,bospetersen/h2o-3,ChristosChristofidis/h2o-3,printedheart/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,PawarPawan/h2o-v3,h2oai/h2o-3,michalkurka/h2o-3,madmax983/h2o-3,bospetersen/h2o-3,junwucs/h2o-3,jangorecki/h2o-3
import sys sys.path.insert(1, "../../../") import h2o def bigcatRF(ip,port): # Connect to h2o h2o.init(ip,port) # Training set has 100 categories from cat001 to cat100 # Categories cat001, cat003, ... are perfect predictors of y = 1 # Categories cat002, cat004, ... are perfect predictors of y = 0 #Log.info("Importing bigcat_5000x2.csv data...\n") bigcat = h2o.import_frame(path=h2o.locate("smalldata/gbm_test/bigcat_5000x2.csv")) bigcat["y"] = bigcat["y"].asfactor() #Log.info("Summary of bigcat_5000x2.csv from H2O:\n") #bigcat.summary() # Train H2O DRF Model: - #Log.info("H2O DRF (Naive Split) with parameters:\nclassification = TRUE, ntree = 1, depth = 1, nbins = 100\n") + #Log.info("H2O DRF (Naive Split) with parameters:\nclassification = TRUE, ntree = 1, depth = 1, nbins = 100, nbins_cats=10\n") - model = h2o.random_forest(x=bigcat[["X"]], y=bigcat["y"], ntrees=1, max_depth=1, nbins=100) + model = h2o.random_forest(x=bigcat[["X"]], y=bigcat["y"], ntrees=1, max_depth=1, nbins=100, nbins_cats=10) model.show() if __name__ == "__main__": h2o.run_test(sys.argv, bigcatRF)
Add usage of nbins_cats to RF pyunit.
## Code Before: import sys sys.path.insert(1, "../../../") import h2o def bigcatRF(ip,port): # Connect to h2o h2o.init(ip,port) # Training set has 100 categories from cat001 to cat100 # Categories cat001, cat003, ... are perfect predictors of y = 1 # Categories cat002, cat004, ... are perfect predictors of y = 0 #Log.info("Importing bigcat_5000x2.csv data...\n") bigcat = h2o.import_frame(path=h2o.locate("smalldata/gbm_test/bigcat_5000x2.csv")) bigcat["y"] = bigcat["y"].asfactor() #Log.info("Summary of bigcat_5000x2.csv from H2O:\n") #bigcat.summary() # Train H2O DRF Model: #Log.info("H2O DRF (Naive Split) with parameters:\nclassification = TRUE, ntree = 1, depth = 1, nbins = 100\n") model = h2o.random_forest(x=bigcat[["X"]], y=bigcat["y"], ntrees=1, max_depth=1, nbins=100) model.show() if __name__ == "__main__": h2o.run_test(sys.argv, bigcatRF) ## Instruction: Add usage of nbins_cats to RF pyunit. ## Code After: import sys sys.path.insert(1, "../../../") import h2o def bigcatRF(ip,port): # Connect to h2o h2o.init(ip,port) # Training set has 100 categories from cat001 to cat100 # Categories cat001, cat003, ... are perfect predictors of y = 1 # Categories cat002, cat004, ... are perfect predictors of y = 0 #Log.info("Importing bigcat_5000x2.csv data...\n") bigcat = h2o.import_frame(path=h2o.locate("smalldata/gbm_test/bigcat_5000x2.csv")) bigcat["y"] = bigcat["y"].asfactor() #Log.info("Summary of bigcat_5000x2.csv from H2O:\n") #bigcat.summary() # Train H2O DRF Model: #Log.info("H2O DRF (Naive Split) with parameters:\nclassification = TRUE, ntree = 1, depth = 1, nbins = 100, nbins_cats=10\n") model = h2o.random_forest(x=bigcat[["X"]], y=bigcat["y"], ntrees=1, max_depth=1, nbins=100, nbins_cats=10) model.show() if __name__ == "__main__": h2o.run_test(sys.argv, bigcatRF)
... # Train H2O DRF Model: #Log.info("H2O DRF (Naive Split) with parameters:\nclassification = TRUE, ntree = 1, depth = 1, nbins = 100, nbins_cats=10\n") model = h2o.random_forest(x=bigcat[["X"]], y=bigcat["y"], ntrees=1, max_depth=1, nbins=100, nbins_cats=10) model.show() ...
0a884d3c38cb1449a6fa5c650ed06cde647de4a8
settings/sqlite.py
settings/sqlite.py
from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr'
from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr' try: from local_settings import * except: pass
Allow local settings override as well.
Allow local settings override as well.
Python
mit
singingwolfboy/readthedocs.org,laplaceliu/readthedocs.org,kenwang76/readthedocs.org,hach-que/readthedocs.org,fujita-shintaro/readthedocs.org,rtfd/readthedocs.org,tddv/readthedocs.org,raven47git/readthedocs.org,mhils/readthedocs.org,royalwang/readthedocs.org,johncosta/private-readthedocs.org,asampat3090/readthedocs.org,safwanrahman/readthedocs.org,istresearch/readthedocs.org,espdev/readthedocs.org,VishvajitP/readthedocs.org,d0ugal/readthedocs.org,atsuyim/readthedocs.org,kdkeyser/readthedocs.org,GovReady/readthedocs.org,techtonik/readthedocs.org,agjohnson/readthedocs.org,davidfischer/readthedocs.org,fujita-shintaro/readthedocs.org,Tazer/readthedocs.org,nikolas/readthedocs.org,cgourlay/readthedocs.org,wanghaven/readthedocs.org,royalwang/readthedocs.org,sils1297/readthedocs.org,nyergler/pythonslides,agjohnson/readthedocs.org,tddv/readthedocs.org,kenshinthebattosai/readthedocs.org,atsuyim/readthedocs.org,sid-kap/readthedocs.org,soulshake/readthedocs.org,SteveViss/readthedocs.org,kenwang76/readthedocs.org,wijerasa/readthedocs.org,istresearch/readthedocs.org,KamranMackey/readthedocs.org,nyergler/pythonslides,laplaceliu/readthedocs.org,SteveViss/readthedocs.org,attakei/readthedocs-oauth,emawind84/readthedocs.org,jerel/readthedocs.org,takluyver/readthedocs.org,Tazer/readthedocs.org,titiushko/readthedocs.org,gjtorikian/readthedocs.org,emawind84/readthedocs.org,asampat3090/readthedocs.org,nikolas/readthedocs.org,kenwang76/readthedocs.org,dirn/readthedocs.org,emawind84/readthedocs.org,royalwang/readthedocs.org,takluyver/readthedocs.org,rtfd/readthedocs.org,sunnyzwh/readthedocs.org,jerel/readthedocs.org,espdev/readthedocs.org,laplaceliu/readthedocs.org,michaelmcandrew/readthedocs.org,d0ugal/readthedocs.org,techtonik/readthedocs.org,rtfd/readthedocs.org,titiushko/readthedocs.org,istresearch/readthedocs.org,Carreau/readthedocs.org,agjohnson/readthedocs.org,mrshoki/readthedocs.org,sils1297/readthedocs.org,atsuyim/readthedocs.org,ojii/readthedocs.org,clarkperkins/readthedocs.org,sils1297/readthedocs.org,laplaceliu/readthedocs.org,ojii/readthedocs.org,cgourlay/readthedocs.org,singingwolfboy/readthedocs.org,hach-que/readthedocs.org,cgourlay/readthedocs.org,singingwolfboy/readthedocs.org,pombredanne/readthedocs.org,atsuyim/readthedocs.org,sid-kap/readthedocs.org,titiushko/readthedocs.org,hach-que/readthedocs.org,johncosta/private-readthedocs.org,sils1297/readthedocs.org,mrshoki/readthedocs.org,titiushko/readthedocs.org,ojii/readthedocs.org,techtonik/readthedocs.org,techtonik/readthedocs.org,pombredanne/readthedocs.org,fujita-shintaro/readthedocs.org,SteveViss/readthedocs.org,wanghaven/readthedocs.org,stevepiercy/readthedocs.org,kdkeyser/readthedocs.org,wanghaven/readthedocs.org,ojii/readthedocs.org,CedarLogic/readthedocs.org,soulshake/readthedocs.org,kdkeyser/readthedocs.org,SteveViss/readthedocs.org,LukasBoersma/readthedocs.org,d0ugal/readthedocs.org,michaelmcandrew/readthedocs.org,gjtorikian/readthedocs.org,hach-que/readthedocs.org,wijerasa/readthedocs.org,nikolas/readthedocs.org,Carreau/readthedocs.org,raven47git/readthedocs.org,jerel/readthedocs.org,michaelmcandrew/readthedocs.org,mrshoki/readthedocs.org,nyergler/pythonslides,nikolas/readthedocs.org,clarkperkins/readthedocs.org,raven47git/readthedocs.org,mhils/readthedocs.org,stevepiercy/readthedocs.org,rtfd/readthedocs.org,LukasBoersma/readthedocs.org,davidfischer/readthedocs.org,mrshoki/readthedocs.org,tddv/readthedocs.org,CedarLogic/readthedocs.org,dirn/readthedocs.org,kdkeyser/readthedocs.org,safwanrahman/readthedocs.org,sid-kap/readthedocs.org,kenshinthebattosai/readthedocs.org,emawind84/readthedocs.org,pombredanne/readthedocs.org,VishvajitP/readthedocs.org,KamranMackey/readthedocs.org,Carreau/readthedocs.org,safwanrahman/readthedocs.org,soulshake/readthedocs.org,raven47git/readthedocs.org,singingwolfboy/readthedocs.org,KamranMackey/readthedocs.org,takluyver/readthedocs.org,gjtorikian/readthedocs.org,wijerasa/readthedocs.org,Tazer/readthedocs.org,stevepiercy/readthedocs.org,LukasBoersma/readthedocs.org,espdev/readthedocs.org,KamranMackey/readthedocs.org,johncosta/private-readthedocs.org,safwanrahman/readthedocs.org,dirn/readthedocs.org,sunnyzwh/readthedocs.org,GovReady/readthedocs.org,VishvajitP/readthedocs.org,davidfischer/readthedocs.org,GovReady/readthedocs.org,alex/readthedocs.org,sunnyzwh/readthedocs.org,istresearch/readthedocs.org,takluyver/readthedocs.org,royalwang/readthedocs.org,asampat3090/readthedocs.org,soulshake/readthedocs.org,VishvajitP/readthedocs.org,espdev/readthedocs.org,GovReady/readthedocs.org,clarkperkins/readthedocs.org,agjohnson/readthedocs.org,michaelmcandrew/readthedocs.org,mhils/readthedocs.org,alex/readthedocs.org,cgourlay/readthedocs.org,alex/readthedocs.org,jerel/readthedocs.org,davidfischer/readthedocs.org,sunnyzwh/readthedocs.org,alex/readthedocs.org,clarkperkins/readthedocs.org,Carreau/readthedocs.org,kenshinthebattosai/readthedocs.org,Tazer/readthedocs.org,d0ugal/readthedocs.org,fujita-shintaro/readthedocs.org,CedarLogic/readthedocs.org,sid-kap/readthedocs.org,kenwang76/readthedocs.org,attakei/readthedocs-oauth,asampat3090/readthedocs.org,mhils/readthedocs.org,CedarLogic/readthedocs.org,dirn/readthedocs.org,LukasBoersma/readthedocs.org,stevepiercy/readthedocs.org,attakei/readthedocs-oauth,gjtorikian/readthedocs.org,nyergler/pythonslides,wanghaven/readthedocs.org,attakei/readthedocs-oauth,wijerasa/readthedocs.org,kenshinthebattosai/readthedocs.org,espdev/readthedocs.org
from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr' + try: + from local_settings import * + except: + pass +
Allow local settings override as well.
## Code Before: from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr' ## Instruction: Allow local settings override as well. ## Code After: from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr' try: from local_settings import * except: pass
// ... existing code ... try: from local_settings import * except: pass // ... rest of the code ...
4a8c608c545b67f9dc1f436c82e0d83a55e168e9
scripts/database/common.py
scripts/database/common.py
import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password)
import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] if 'port' in conf else 5432 db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password)
Add default port to database connection script
Add default port to database connection script The default port is used if the ~/.catmaid-db file doesn't contain it. This fixes #454.
Python
agpl-3.0
fzadow/CATMAID,htem/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID
import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] - db_port = conf['port'] + db_port = conf['port'] if 'port' in conf else 5432 db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password)
Add default port to database connection script
## Code Before: import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password) ## Instruction: Add default port to database connection script ## Code After: import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] if 'port' in conf else 5432 db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password)
# ... existing code ... db_host = conf['host'] db_port = conf['port'] if 'port' in conf else 5432 db_database = conf['database'] # ... rest of the code ...
484eaaf6349a631f483af12acd358bce5ca567d5
zeeko/messages/setup_package.py
zeeko/messages/setup_package.py
from __future__ import absolute_import import glob import os import copy import zmq from distutils.core import Extension def get_extensions(**kwargs): """Get the Cython extensions""" this_directory = os.path.dirname(__file__) this_name = __name__.split(".")[:-1] extension_args = { 'include_dirs' : ['numpy'] + zmq.get_includes(), 'libraries' : [], 'sources' : [] } extension_args.update(kwargs) extensions = [] for component in glob.iglob(os.path.join(this_directory, "*.pyx")): # Component name and full module name. this_extension_args = copy.deepcopy(extension_args) cname = os.path.splitext(os.path.basename(component))[0] if cname.startswith("_"): cname = cname[1:] name = ".".join(this_name + ["_{0:s}".format(cname)]) else: name = ".".join(this_name + [cname]) this_extension_args['sources'].append(component) # Extension object. extension = Extension(name, **this_extension_args) extensions.append(extension) return extensions
from __future__ import absolute_import import glob import os import copy from distutils.core import Extension def get_extensions(**kwargs): """Get the Cython extensions""" import zmq this_directory = os.path.dirname(__file__) this_name = __name__.split(".")[:-1] extension_args = { 'include_dirs' : ['numpy'] + zmq.get_includes(), 'libraries' : [], 'sources' : [] } extension_args.update(kwargs) extensions = [] for component in glob.iglob(os.path.join(this_directory, "*.pyx")): # Component name and full module name. this_extension_args = copy.deepcopy(extension_args) cname = os.path.splitext(os.path.basename(component))[0] if cname.startswith("_"): cname = cname[1:] name = ".".join(this_name + ["_{0:s}".format(cname)]) else: name = ".".join(this_name + [cname]) this_extension_args['sources'].append(component) # Extension object. extension = Extension(name, **this_extension_args) extensions.append(extension) return extensions
Fix stray zmq import in egg_info
Fix stray zmq import in egg_info
Python
bsd-3-clause
alexrudy/Zeeko,alexrudy/Zeeko
from __future__ import absolute_import import glob import os import copy - import zmq from distutils.core import Extension def get_extensions(**kwargs): """Get the Cython extensions""" + import zmq + this_directory = os.path.dirname(__file__) this_name = __name__.split(".")[:-1] extension_args = { 'include_dirs' : ['numpy'] + zmq.get_includes(), 'libraries' : [], 'sources' : [] } extension_args.update(kwargs) extensions = [] for component in glob.iglob(os.path.join(this_directory, "*.pyx")): # Component name and full module name. this_extension_args = copy.deepcopy(extension_args) cname = os.path.splitext(os.path.basename(component))[0] if cname.startswith("_"): cname = cname[1:] name = ".".join(this_name + ["_{0:s}".format(cname)]) else: name = ".".join(this_name + [cname]) this_extension_args['sources'].append(component) # Extension object. extension = Extension(name, **this_extension_args) extensions.append(extension) return extensions
Fix stray zmq import in egg_info
## Code Before: from __future__ import absolute_import import glob import os import copy import zmq from distutils.core import Extension def get_extensions(**kwargs): """Get the Cython extensions""" this_directory = os.path.dirname(__file__) this_name = __name__.split(".")[:-1] extension_args = { 'include_dirs' : ['numpy'] + zmq.get_includes(), 'libraries' : [], 'sources' : [] } extension_args.update(kwargs) extensions = [] for component in glob.iglob(os.path.join(this_directory, "*.pyx")): # Component name and full module name. this_extension_args = copy.deepcopy(extension_args) cname = os.path.splitext(os.path.basename(component))[0] if cname.startswith("_"): cname = cname[1:] name = ".".join(this_name + ["_{0:s}".format(cname)]) else: name = ".".join(this_name + [cname]) this_extension_args['sources'].append(component) # Extension object. extension = Extension(name, **this_extension_args) extensions.append(extension) return extensions ## Instruction: Fix stray zmq import in egg_info ## Code After: from __future__ import absolute_import import glob import os import copy from distutils.core import Extension def get_extensions(**kwargs): """Get the Cython extensions""" import zmq this_directory = os.path.dirname(__file__) this_name = __name__.split(".")[:-1] extension_args = { 'include_dirs' : ['numpy'] + zmq.get_includes(), 'libraries' : [], 'sources' : [] } extension_args.update(kwargs) extensions = [] for component in glob.iglob(os.path.join(this_directory, "*.pyx")): # Component name and full module name. this_extension_args = copy.deepcopy(extension_args) cname = os.path.splitext(os.path.basename(component))[0] if cname.startswith("_"): cname = cname[1:] name = ".".join(this_name + ["_{0:s}".format(cname)]) else: name = ".".join(this_name + [cname]) this_extension_args['sources'].append(component) # Extension object. extension = Extension(name, **this_extension_args) extensions.append(extension) return extensions
... from distutils.core import Extension ... """Get the Cython extensions""" import zmq this_directory = os.path.dirname(__file__) ...
ab7a546e4a7fb686f61b904777aa26c7d596ff03
pombola/south_africa/lib.py
pombola/south_africa/lib.py
import urlparse def make_pa_url(pombola_object, base_url): parsed_url = list(urlparse.urlparse(base_url)) parsed_url[2] = pombola_object.get_absolute_url() return urlparse.urlunparse(parsed_url) def add_extra_popolo_data_for_person(person, popolo_object, base_url): popolo_object['pa_url'] = make_pa_url(person, base_url) def add_extra_popolo_data_for_organization(organisation, popolo_object, base_url): popolo_object['pa_url'] = make_pa_url(organisation, base_url)
import urlparse def make_pa_url(pombola_object, base_url): parsed_url = list(urlparse.urlparse(base_url)) parsed_url[2] = pombola_object.get_absolute_url() return urlparse.urlunparse(parsed_url) def add_extra_popolo_data_for_person(person, popolo_object, base_url): popolo_object['pa_url'] = make_pa_url(person, base_url) personinterests = person.interests_register_entries.all() if personinterests: interests = {} for entry in personinterests: release = entry.release category = entry.category interests.setdefault(release.name, {}) interests[release.name].setdefault(category.name, []) #assuming no entrylineitems with duplicate keys within an entry entrylineitems = dict((e.key, e.value) for e in entry.line_items.all()) interests[release.name][category.name].append(entrylineitems) popolo_object['interests_register'] = interests def add_extra_popolo_data_for_organization(organisation, popolo_object, base_url): popolo_object['pa_url'] = make_pa_url(organisation, base_url)
Add members interests data to PopIt export
ZA: Add members interests data to PopIt export (Minor refactoring by Mark Longair.)
Python
agpl-3.0
hzj123/56th,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,hzj123/56th,geoffkilpin/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,ken-muturi/pombola,patricmutwiri/pombola,geoffkilpin/pombola,mysociety/pombola,patricmutwiri/pombola,ken-muturi/pombola,ken-muturi/pombola,patricmutwiri/pombola,geoffkilpin/pombola,geoffkilpin/pombola,hzj123/56th,hzj123/56th,ken-muturi/pombola,ken-muturi/pombola,hzj123/56th,mysociety/pombola,ken-muturi/pombola,mysociety/pombola,patricmutwiri/pombola,hzj123/56th,mysociety/pombola
import urlparse def make_pa_url(pombola_object, base_url): parsed_url = list(urlparse.urlparse(base_url)) parsed_url[2] = pombola_object.get_absolute_url() return urlparse.urlunparse(parsed_url) def add_extra_popolo_data_for_person(person, popolo_object, base_url): popolo_object['pa_url'] = make_pa_url(person, base_url) + personinterests = person.interests_register_entries.all() + if personinterests: + interests = {} + for entry in personinterests: + release = entry.release + category = entry.category + interests.setdefault(release.name, {}) + interests[release.name].setdefault(category.name, []) + + #assuming no entrylineitems with duplicate keys within an entry + entrylineitems = dict((e.key, e.value) for e in entry.line_items.all()) + + interests[release.name][category.name].append(entrylineitems) + + popolo_object['interests_register'] = interests + def add_extra_popolo_data_for_organization(organisation, popolo_object, base_url): popolo_object['pa_url'] = make_pa_url(organisation, base_url)
Add members interests data to PopIt export
## Code Before: import urlparse def make_pa_url(pombola_object, base_url): parsed_url = list(urlparse.urlparse(base_url)) parsed_url[2] = pombola_object.get_absolute_url() return urlparse.urlunparse(parsed_url) def add_extra_popolo_data_for_person(person, popolo_object, base_url): popolo_object['pa_url'] = make_pa_url(person, base_url) def add_extra_popolo_data_for_organization(organisation, popolo_object, base_url): popolo_object['pa_url'] = make_pa_url(organisation, base_url) ## Instruction: Add members interests data to PopIt export ## Code After: import urlparse def make_pa_url(pombola_object, base_url): parsed_url = list(urlparse.urlparse(base_url)) parsed_url[2] = pombola_object.get_absolute_url() return urlparse.urlunparse(parsed_url) def add_extra_popolo_data_for_person(person, popolo_object, base_url): popolo_object['pa_url'] = make_pa_url(person, base_url) personinterests = person.interests_register_entries.all() if personinterests: interests = {} for entry in personinterests: release = entry.release category = entry.category interests.setdefault(release.name, {}) interests[release.name].setdefault(category.name, []) #assuming no entrylineitems with duplicate keys within an entry entrylineitems = dict((e.key, e.value) for e in entry.line_items.all()) interests[release.name][category.name].append(entrylineitems) popolo_object['interests_register'] = interests def add_extra_popolo_data_for_organization(organisation, popolo_object, base_url): popolo_object['pa_url'] = make_pa_url(organisation, base_url)
# ... existing code ... personinterests = person.interests_register_entries.all() if personinterests: interests = {} for entry in personinterests: release = entry.release category = entry.category interests.setdefault(release.name, {}) interests[release.name].setdefault(category.name, []) #assuming no entrylineitems with duplicate keys within an entry entrylineitems = dict((e.key, e.value) for e in entry.line_items.all()) interests[release.name][category.name].append(entrylineitems) popolo_object['interests_register'] = interests def add_extra_popolo_data_for_organization(organisation, popolo_object, base_url): # ... rest of the code ...
546f4881974af4516cfaaf4e53c0940d90b6d502
configurations/__init__.py
configurations/__init__.py
from .base import Settings, Configuration from .decorators import pristinemethod __version__ = '0.8' __all__ = ['Configuration', 'pristinemethod', 'Settings'] def load_ipython_extension(ipython): # The `ipython` argument is the currently active `InteractiveShell` # instance, which can be used in any way. This allows you to register # new magics or aliases, for example. from . import importer importer.install() def setup(app): """ The callback for Sphinx that acts as a Sphinx extension. Add this to the ``extensions`` config variable in your ``conf.py``. """ from . import importer importer.install()
from .base import Settings, Configuration from .decorators import pristinemethod __version__ = '0.8' __all__ = ['Configuration', 'pristinemethod', 'Settings'] def load_ipython_extension(ipython): # The `ipython` argument is the currently active `InteractiveShell` # instance, which can be used in any way. This allows you to register # new magics or aliases, for example. from . import importer importer.install() # django >=1.7 try: import django django.setup() except AttributeError: pass def setup(app): """ The callback for Sphinx that acts as a Sphinx extension. Add this to the ``extensions`` config variable in your ``conf.py``. """ from . import importer importer.install()
Add `django.setup()` in `load_ipython_extension` function for django>=1.7 compatibility
Add `django.setup()` in `load_ipython_extension` function for django>=1.7 compatibility
Python
bsd-3-clause
cato-/django-configurations,blindroot/django-configurations,pombredanne/django-configurations,jezdez/django-configurations,seenureddy/django-configurations,incuna/django-configurations,jazzband/django-configurations,nangia/django-configurations,jazzband/django-configurations,NextHub/django-configurations,gatherhealth/django-configurations
from .base import Settings, Configuration from .decorators import pristinemethod __version__ = '0.8' __all__ = ['Configuration', 'pristinemethod', 'Settings'] def load_ipython_extension(ipython): # The `ipython` argument is the currently active `InteractiveShell` # instance, which can be used in any way. This allows you to register # new magics or aliases, for example. from . import importer importer.install() + # django >=1.7 + try: + import django + django.setup() + except AttributeError: + pass + def setup(app): """ The callback for Sphinx that acts as a Sphinx extension. Add this to the ``extensions`` config variable in your ``conf.py``. """ from . import importer importer.install()
Add `django.setup()` in `load_ipython_extension` function for django>=1.7 compatibility
## Code Before: from .base import Settings, Configuration from .decorators import pristinemethod __version__ = '0.8' __all__ = ['Configuration', 'pristinemethod', 'Settings'] def load_ipython_extension(ipython): # The `ipython` argument is the currently active `InteractiveShell` # instance, which can be used in any way. This allows you to register # new magics or aliases, for example. from . import importer importer.install() def setup(app): """ The callback for Sphinx that acts as a Sphinx extension. Add this to the ``extensions`` config variable in your ``conf.py``. """ from . import importer importer.install() ## Instruction: Add `django.setup()` in `load_ipython_extension` function for django>=1.7 compatibility ## Code After: from .base import Settings, Configuration from .decorators import pristinemethod __version__ = '0.8' __all__ = ['Configuration', 'pristinemethod', 'Settings'] def load_ipython_extension(ipython): # The `ipython` argument is the currently active `InteractiveShell` # instance, which can be used in any way. This allows you to register # new magics or aliases, for example. from . import importer importer.install() # django >=1.7 try: import django django.setup() except AttributeError: pass def setup(app): """ The callback for Sphinx that acts as a Sphinx extension. Add this to the ``extensions`` config variable in your ``conf.py``. """ from . import importer importer.install()
# ... existing code ... # django >=1.7 try: import django django.setup() except AttributeError: pass # ... rest of the code ...
ce9cbc4144c105e9cb59836274ef25a29a9b20a7
webserver/codemanagement/tasks.py
webserver/codemanagement/tasks.py
from celery import task from celery.result import AsyncResult from .models import TeamSubmission import logging logger = logging.getLogger(__name__) @task() def create_shellai_tag(instance): """Tags the repo's HEAD as "ShellAI" to provide a default tag for the arena to use""" team_name = instance.team.name if instance.repository.task_id is not None: # Wait for the repo to be created AsyncResult(instance.repository.task_id).wait() msg = "Waiting for {}'s repository to be created..." logger.info(msg.format(team_name)) logger.info("{}'s repository is ready".format(team_name)) # Create a submission for the HEAD commit TeamSubmission.objects.create(team=instance.team, commit=instance.repository.repo['HEAD'].id, name="ShellAI", submitter=None) logger.info("Tagged {}'s repo".format(team_name))
from celery import task from celery.result import AsyncResult from .models import TeamSubmission import logging logger = logging.getLogger(__name__) @task() def create_shellai_tag(instance): """Tags the repo's HEAD as "ShellAI" to provide a default tag for the arena to use""" team_name = instance.team.name if instance.repository.task_id is not None: # Wait for the repo to be created AsyncResult(instance.repository.task_id).wait() msg = "Waiting for {}'s repository to be created..." logger.info(msg.format(team_name)) logger.info("{}'s repository is ready".format(team_name)) try: commit = instance.repository.repo['HEAD'] except KeyError: # Log an error if we can't get a commit msg = "Unable to tag {}'s repo. Bad ref 'HEAD'. Is the repo empty?" logger.error(msg.format(team_name)) else: # Create a submission for the HEAD commit TeamSubmission.objects.create(teamclient=instance, commit=commit.id, name="ShellAI", submitter=None) logger.info("Tagged {}'s repo".format(team_name))
Handle attempts to tag empty shell repos
Handle attempts to tag empty shell repos
Python
bsd-3-clause
siggame/webserver,siggame/webserver,siggame/webserver
from celery import task from celery.result import AsyncResult from .models import TeamSubmission import logging logger = logging.getLogger(__name__) @task() def create_shellai_tag(instance): """Tags the repo's HEAD as "ShellAI" to provide a default tag for the arena to use""" team_name = instance.team.name if instance.repository.task_id is not None: # Wait for the repo to be created AsyncResult(instance.repository.task_id).wait() msg = "Waiting for {}'s repository to be created..." logger.info(msg.format(team_name)) logger.info("{}'s repository is ready".format(team_name)) + try: + commit = instance.repository.repo['HEAD'] + except KeyError: + # Log an error if we can't get a commit + msg = "Unable to tag {}'s repo. Bad ref 'HEAD'. Is the repo empty?" + logger.error(msg.format(team_name)) + else: - # Create a submission for the HEAD commit + # Create a submission for the HEAD commit - TeamSubmission.objects.create(team=instance.team, + TeamSubmission.objects.create(teamclient=instance, - commit=instance.repository.repo['HEAD'].id, + commit=commit.id, - name="ShellAI", + name="ShellAI", - submitter=None) + submitter=None) - logger.info("Tagged {}'s repo".format(team_name)) + logger.info("Tagged {}'s repo".format(team_name))
Handle attempts to tag empty shell repos
## Code Before: from celery import task from celery.result import AsyncResult from .models import TeamSubmission import logging logger = logging.getLogger(__name__) @task() def create_shellai_tag(instance): """Tags the repo's HEAD as "ShellAI" to provide a default tag for the arena to use""" team_name = instance.team.name if instance.repository.task_id is not None: # Wait for the repo to be created AsyncResult(instance.repository.task_id).wait() msg = "Waiting for {}'s repository to be created..." logger.info(msg.format(team_name)) logger.info("{}'s repository is ready".format(team_name)) # Create a submission for the HEAD commit TeamSubmission.objects.create(team=instance.team, commit=instance.repository.repo['HEAD'].id, name="ShellAI", submitter=None) logger.info("Tagged {}'s repo".format(team_name)) ## Instruction: Handle attempts to tag empty shell repos ## Code After: from celery import task from celery.result import AsyncResult from .models import TeamSubmission import logging logger = logging.getLogger(__name__) @task() def create_shellai_tag(instance): """Tags the repo's HEAD as "ShellAI" to provide a default tag for the arena to use""" team_name = instance.team.name if instance.repository.task_id is not None: # Wait for the repo to be created AsyncResult(instance.repository.task_id).wait() msg = "Waiting for {}'s repository to be created..." logger.info(msg.format(team_name)) logger.info("{}'s repository is ready".format(team_name)) try: commit = instance.repository.repo['HEAD'] except KeyError: # Log an error if we can't get a commit msg = "Unable to tag {}'s repo. Bad ref 'HEAD'. Is the repo empty?" logger.error(msg.format(team_name)) else: # Create a submission for the HEAD commit TeamSubmission.objects.create(teamclient=instance, commit=commit.id, name="ShellAI", submitter=None) logger.info("Tagged {}'s repo".format(team_name))
# ... existing code ... try: commit = instance.repository.repo['HEAD'] except KeyError: # Log an error if we can't get a commit msg = "Unable to tag {}'s repo. Bad ref 'HEAD'. Is the repo empty?" logger.error(msg.format(team_name)) else: # Create a submission for the HEAD commit TeamSubmission.objects.create(teamclient=instance, commit=commit.id, name="ShellAI", submitter=None) logger.info("Tagged {}'s repo".format(team_name)) # ... rest of the code ...
596a29505351ec0e497cbe114a6e4d57d7cbada6
backoff/__init__.py
backoff/__init__.py
from backoff._decorator import on_predicate, on_exception from backoff._jitter import full_jitter, random_jitter from backoff._wait_gen import constant, expo, fibo, runtime __all__ = [ 'on_predicate', 'on_exception', 'constant', 'expo', 'fibo', 'runtime', 'full_jitter', 'random_jitter', ] __version__ = '2.1.0'
import importlib.metadata from backoff._decorator import on_exception, on_predicate from backoff._jitter import full_jitter, random_jitter from backoff._wait_gen import constant, expo, fibo, runtime __all__ = [ 'on_predicate', 'on_exception', 'constant', 'expo', 'fibo', 'runtime', 'full_jitter', 'random_jitter', ] __version__ = importlib.metadata.version("backoff")
Use importlib.metadata to set __version__
Use importlib.metadata to set __version__ This way we don't have to remember to update the version in two places every release. The version will only need to be set in pyproject.toml
Python
mit
litl/backoff
+ import importlib.metadata + - from backoff._decorator import on_predicate, on_exception + from backoff._decorator import on_exception, on_predicate from backoff._jitter import full_jitter, random_jitter from backoff._wait_gen import constant, expo, fibo, runtime __all__ = [ 'on_predicate', 'on_exception', 'constant', 'expo', 'fibo', 'runtime', 'full_jitter', 'random_jitter', ] - __version__ = '2.1.0' + __version__ = importlib.metadata.version("backoff")
Use importlib.metadata to set __version__
## Code Before: from backoff._decorator import on_predicate, on_exception from backoff._jitter import full_jitter, random_jitter from backoff._wait_gen import constant, expo, fibo, runtime __all__ = [ 'on_predicate', 'on_exception', 'constant', 'expo', 'fibo', 'runtime', 'full_jitter', 'random_jitter', ] __version__ = '2.1.0' ## Instruction: Use importlib.metadata to set __version__ ## Code After: import importlib.metadata from backoff._decorator import on_exception, on_predicate from backoff._jitter import full_jitter, random_jitter from backoff._wait_gen import constant, expo, fibo, runtime __all__ = [ 'on_predicate', 'on_exception', 'constant', 'expo', 'fibo', 'runtime', 'full_jitter', 'random_jitter', ] __version__ = importlib.metadata.version("backoff")
# ... existing code ... import importlib.metadata from backoff._decorator import on_exception, on_predicate from backoff._jitter import full_jitter, random_jitter # ... modified code ... __version__ = importlib.metadata.version("backoff") # ... rest of the code ...
354fb43cc95d68b06b85e8d1fa2426ca663ef8b9
common/__init__.py
common/__init__.py
VERSION = (0, 0, 0) __version__ = '.'.join(map(str, VERSION)) from django import template template.add_to_builtins('common.templatetags.common') template.add_to_builtins('common.templatetags.development')
VERSION = (0, 1, 0) __version__ = '.'.join(map(str, VERSION)) from django import template template.add_to_builtins('common.templatetags.common') template.add_to_builtins('common.templatetags.development') # Add db_name to options for use in model.Meta class import django.db.models.options as options options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('db_name',)
Add db_name to options for use in model.Meta class
Add db_name to options for use in model.Meta class
Python
bsd-3-clause
baskoopmans/djcommon,baskoopmans/djcommon,baskoopmans/djcommon
- VERSION = (0, 0, 0) + VERSION = (0, 1, 0) __version__ = '.'.join(map(str, VERSION)) - from django import template template.add_to_builtins('common.templatetags.common') template.add_to_builtins('common.templatetags.development') + + # Add db_name to options for use in model.Meta class + import django.db.models.options as options + options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('db_name',)
Add db_name to options for use in model.Meta class
## Code Before: VERSION = (0, 0, 0) __version__ = '.'.join(map(str, VERSION)) from django import template template.add_to_builtins('common.templatetags.common') template.add_to_builtins('common.templatetags.development') ## Instruction: Add db_name to options for use in model.Meta class ## Code After: VERSION = (0, 1, 0) __version__ = '.'.join(map(str, VERSION)) from django import template template.add_to_builtins('common.templatetags.common') template.add_to_builtins('common.templatetags.development') # Add db_name to options for use in model.Meta class import django.db.models.options as options options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('db_name',)
... VERSION = (0, 1, 0) __version__ = '.'.join(map(str, VERSION)) ... template.add_to_builtins('common.templatetags.development') # Add db_name to options for use in model.Meta class import django.db.models.options as options options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('db_name',) ...
3d64eb4a7438b6b4f46f1fdf7f47d530cb11b09c
spacy/tests/regression/test_issue2396.py
spacy/tests/regression/test_issue2396.py
from __future__ import unicode_literals from ..util import get_doc import pytest import numpy @pytest.mark.parametrize('sentence,matrix', [ ( 'She created a test for spacy', numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) def test_issue2396(EN, sentence, matrix): doc = EN(sentence) span = doc[:] assert (doc.get_lca_matrix() == matrix).all() assert (span.get_lca_matrix() == matrix).all()
from __future__ import unicode_literals from ..util import get_doc import pytest import numpy from numpy.testing import assert_array_equal @pytest.mark.parametrize('words,heads,matrix', [ ( 'She created a test for spacy'.split(), [1, 0, 1, -2, -1, -1], numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) def test_issue2396(en_vocab, words, heads, matrix): doc = get_doc(en_vocab, words=words, heads=heads) span = doc[:] assert_array_equal(doc.get_lca_matrix(), matrix) assert_array_equal(span.get_lca_matrix(), matrix)
Update get_lca_matrix test for develop
Update get_lca_matrix test for develop
Python
mit
explosion/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy
from __future__ import unicode_literals from ..util import get_doc import pytest import numpy + from numpy.testing import assert_array_equal + - @pytest.mark.parametrize('sentence,matrix', [ + @pytest.mark.parametrize('words,heads,matrix', [ ( - 'She created a test for spacy', + 'She created a test for spacy'.split(), + [1, 0, 1, -2, -1, -1], numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) - def test_issue2396(EN, sentence, matrix): - doc = EN(sentence) + def test_issue2396(en_vocab, words, heads, matrix): + doc = get_doc(en_vocab, words=words, heads=heads) + span = doc[:] - assert (doc.get_lca_matrix() == matrix).all() + assert_array_equal(doc.get_lca_matrix(), matrix) - assert (span.get_lca_matrix() == matrix).all() + assert_array_equal(span.get_lca_matrix(), matrix)
Update get_lca_matrix test for develop
## Code Before: from __future__ import unicode_literals from ..util import get_doc import pytest import numpy @pytest.mark.parametrize('sentence,matrix', [ ( 'She created a test for spacy', numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) def test_issue2396(EN, sentence, matrix): doc = EN(sentence) span = doc[:] assert (doc.get_lca_matrix() == matrix).all() assert (span.get_lca_matrix() == matrix).all() ## Instruction: Update get_lca_matrix test for develop ## Code After: from __future__ import unicode_literals from ..util import get_doc import pytest import numpy from numpy.testing import assert_array_equal @pytest.mark.parametrize('words,heads,matrix', [ ( 'She created a test for spacy'.split(), [1, 0, 1, -2, -1, -1], numpy.array([ [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 2, 3, 3, 3], [1, 1, 3, 3, 3, 3], [1, 1, 3, 3, 4, 4], [1, 1, 3, 3, 4, 5]], dtype=numpy.int32) ) ]) def test_issue2396(en_vocab, words, heads, matrix): doc = get_doc(en_vocab, words=words, heads=heads) span = doc[:] assert_array_equal(doc.get_lca_matrix(), matrix) assert_array_equal(span.get_lca_matrix(), matrix)
# ... existing code ... import numpy from numpy.testing import assert_array_equal @pytest.mark.parametrize('words,heads,matrix', [ ( 'She created a test for spacy'.split(), [1, 0, 1, -2, -1, -1], numpy.array([ # ... modified code ... ]) def test_issue2396(en_vocab, words, heads, matrix): doc = get_doc(en_vocab, words=words, heads=heads) span = doc[:] assert_array_equal(doc.get_lca_matrix(), matrix) assert_array_equal(span.get_lca_matrix(), matrix) # ... rest of the code ...
210c7b7fb421a7c083b9d292370b15c0ece17fa7
source/bark/__init__.py
source/bark/__init__.py
from .handler.distribute import Distribute #: Top level handler responsible for relaying all logs to other handlers. handle = Distribute()
from .handler.distribute import Distribute #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers handle = handler.handle
Correct handler reference variable name and add convenient accessors.
Correct handler reference variable name and add convenient accessors.
Python
apache-2.0
4degrees/mill,4degrees/sawmill
from .handler.distribute import Distribute #: Top level handler responsible for relaying all logs to other handlers. - handle = Distribute() + handler = Distribute() + handlers = handler.handlers + handle = handler.handle +
Correct handler reference variable name and add convenient accessors.
## Code Before: from .handler.distribute import Distribute #: Top level handler responsible for relaying all logs to other handlers. handle = Distribute() ## Instruction: Correct handler reference variable name and add convenient accessors. ## Code After: from .handler.distribute import Distribute #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers handle = handler.handle
... #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers handle = handler.handle ...
faf067ec4f5189a7a0b12fc78b62373a8f997ac8
scripts/migration/migrate_index_for_existing_files.py
scripts/migration/migrate_index_for_existing_files.py
import sys import logging from website.app import init_app from website.files.models.osfstorage import OsfStorageFile logger = logging.getLogger(__name__) def main(): init_app(routes=False) dry_run = 'dry' in sys.argv logger.warn('Current files will now be updated to be indexed if necessary') if dry_run: logger.warn('Dry_run mode') for file_ in OsfStorageFile.find(): logger.info('File with _id {0} and name {1} has been saved.'.format(file_._id, file_.name)) if not dry_run: file_.save() if __name__ == '__main__': main()
import sys import logging from website.app import init_app from website.search import search from website.files.models.osfstorage import OsfStorageFile logger = logging.getLogger(__name__) def main(): init_app(routes=False) dry_run = 'dry' in sys.argv logger.warn('Current files will now be updated to be indexed if necessary') if dry_run: logger.warn('Dry_run mode') for file_ in OsfStorageFile.find(): logger.info('File with _id {0} and name {1} has been saved.'.format(file_._id, file_.name)) if not dry_run: search.update_file(file_) if __name__ == '__main__': main()
Change migration to update_file rather than save it
Change migration to update_file rather than save it
Python
apache-2.0
billyhunt/osf.io,brianjgeiger/osf.io,zachjanicki/osf.io,brandonPurvis/osf.io,haoyuchen1992/osf.io,abought/osf.io,caseyrygt/osf.io,crcresearch/osf.io,mluo613/osf.io,caneruguz/osf.io,zamattiac/osf.io,danielneis/osf.io,leb2dg/osf.io,kwierman/osf.io,SSJohns/osf.io,aaxelb/osf.io,haoyuchen1992/osf.io,HalcyonChimera/osf.io,amyshi188/osf.io,rdhyee/osf.io,felliott/osf.io,saradbowman/osf.io,chennan47/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,GageGaskins/osf.io,leb2dg/osf.io,mattclark/osf.io,felliott/osf.io,leb2dg/osf.io,binoculars/osf.io,binoculars/osf.io,kch8qx/osf.io,KAsante95/osf.io,alexschiller/osf.io,samchrisinger/osf.io,CenterForOpenScience/osf.io,GageGaskins/osf.io,cslzchen/osf.io,caseyrollins/osf.io,mluke93/osf.io,alexschiller/osf.io,zachjanicki/osf.io,KAsante95/osf.io,danielneis/osf.io,emetsger/osf.io,mluke93/osf.io,haoyuchen1992/osf.io,emetsger/osf.io,jnayak1/osf.io,laurenrevere/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,acshi/osf.io,brandonPurvis/osf.io,HalcyonChimera/osf.io,jnayak1/osf.io,samchrisinger/osf.io,kch8qx/osf.io,mluo613/osf.io,samanehsan/osf.io,wearpants/osf.io,DanielSBrown/osf.io,hmoco/osf.io,caneruguz/osf.io,asanfilippo7/osf.io,baylee-d/osf.io,adlius/osf.io,Johnetordoff/osf.io,acshi/osf.io,Nesiehr/osf.io,alexschiller/osf.io,caseyrygt/osf.io,chrisseto/osf.io,abought/osf.io,aaxelb/osf.io,doublebits/osf.io,DanielSBrown/osf.io,caneruguz/osf.io,SSJohns/osf.io,GageGaskins/osf.io,emetsger/osf.io,felliott/osf.io,kch8qx/osf.io,TomHeatwole/osf.io,rdhyee/osf.io,Ghalko/osf.io,brandonPurvis/osf.io,monikagrabowska/osf.io,kch8qx/osf.io,doublebits/osf.io,ZobairAlijan/osf.io,Johnetordoff/osf.io,Ghalko/osf.io,acshi/osf.io,Johnetordoff/osf.io,brandonPurvis/osf.io,monikagrabowska/osf.io,crcresearch/osf.io,samanehsan/osf.io,laurenrevere/osf.io,wearpants/osf.io,samanehsan/osf.io,laurenrevere/osf.io,SSJohns/osf.io,pattisdr/osf.io,acshi/osf.io,felliott/osf.io,TomHeatwole/osf.io,danielneis/osf.io,monikagrabowska/osf.io,doublebits/osf.io,TomHeatwole/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,caseyrygt/osf.io,SSJohns/osf.io,ZobairAlijan/osf.io,ticklemepierce/osf.io,crcresearch/osf.io,brandonPurvis/osf.io,zamattiac/osf.io,mattclark/osf.io,asanfilippo7/osf.io,amyshi188/osf.io,emetsger/osf.io,mfraezz/osf.io,zachjanicki/osf.io,billyhunt/osf.io,jnayak1/osf.io,mluo613/osf.io,abought/osf.io,GageGaskins/osf.io,kch8qx/osf.io,erinspace/osf.io,doublebits/osf.io,hmoco/osf.io,monikagrabowska/osf.io,adlius/osf.io,KAsante95/osf.io,RomanZWang/osf.io,mluo613/osf.io,asanfilippo7/osf.io,icereval/osf.io,danielneis/osf.io,caseyrygt/osf.io,DanielSBrown/osf.io,sloria/osf.io,ZobairAlijan/osf.io,aaxelb/osf.io,cwisecarver/osf.io,chrisseto/osf.io,samanehsan/osf.io,chennan47/osf.io,zachjanicki/osf.io,adlius/osf.io,chrisseto/osf.io,doublebits/osf.io,RomanZWang/osf.io,abought/osf.io,cslzchen/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,KAsante95/osf.io,cwisecarver/osf.io,amyshi188/osf.io,Nesiehr/osf.io,ticklemepierce/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,amyshi188/osf.io,chennan47/osf.io,TomBaxter/osf.io,jnayak1/osf.io,ticklemepierce/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,samchrisinger/osf.io,ZobairAlijan/osf.io,saradbowman/osf.io,wearpants/osf.io,cslzchen/osf.io,adlius/osf.io,billyhunt/osf.io,alexschiller/osf.io,rdhyee/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,mluke93/osf.io,pattisdr/osf.io,alexschiller/osf.io,erinspace/osf.io,rdhyee/osf.io,RomanZWang/osf.io,GageGaskins/osf.io,samchrisinger/osf.io,RomanZWang/osf.io,RomanZWang/osf.io,mfraezz/osf.io,icereval/osf.io,Nesiehr/osf.io,caseyrollins/osf.io,binoculars/osf.io,KAsante95/osf.io,Ghalko/osf.io,Ghalko/osf.io,Nesiehr/osf.io,billyhunt/osf.io,ticklemepierce/osf.io,TomBaxter/osf.io,hmoco/osf.io,asanfilippo7/osf.io,cwisecarver/osf.io,baylee-d/osf.io,icereval/osf.io,haoyuchen1992/osf.io,kwierman/osf.io,DanielSBrown/osf.io,brianjgeiger/osf.io,TomHeatwole/osf.io,sloria/osf.io,mfraezz/osf.io,cslzchen/osf.io,hmoco/osf.io,zamattiac/osf.io,erinspace/osf.io,wearpants/osf.io,aaxelb/osf.io,mluke93/osf.io,sloria/osf.io,acshi/osf.io,TomBaxter/osf.io,cwisecarver/osf.io,kwierman/osf.io,caneruguz/osf.io,kwierman/osf.io,HalcyonChimera/osf.io,billyhunt/osf.io
import sys import logging from website.app import init_app + from website.search import search from website.files.models.osfstorage import OsfStorageFile logger = logging.getLogger(__name__) def main(): init_app(routes=False) dry_run = 'dry' in sys.argv logger.warn('Current files will now be updated to be indexed if necessary') if dry_run: logger.warn('Dry_run mode') for file_ in OsfStorageFile.find(): logger.info('File with _id {0} and name {1} has been saved.'.format(file_._id, file_.name)) if not dry_run: - file_.save() + search.update_file(file_) if __name__ == '__main__': main()
Change migration to update_file rather than save it
## Code Before: import sys import logging from website.app import init_app from website.files.models.osfstorage import OsfStorageFile logger = logging.getLogger(__name__) def main(): init_app(routes=False) dry_run = 'dry' in sys.argv logger.warn('Current files will now be updated to be indexed if necessary') if dry_run: logger.warn('Dry_run mode') for file_ in OsfStorageFile.find(): logger.info('File with _id {0} and name {1} has been saved.'.format(file_._id, file_.name)) if not dry_run: file_.save() if __name__ == '__main__': main() ## Instruction: Change migration to update_file rather than save it ## Code After: import sys import logging from website.app import init_app from website.search import search from website.files.models.osfstorage import OsfStorageFile logger = logging.getLogger(__name__) def main(): init_app(routes=False) dry_run = 'dry' in sys.argv logger.warn('Current files will now be updated to be indexed if necessary') if dry_run: logger.warn('Dry_run mode') for file_ in OsfStorageFile.find(): logger.info('File with _id {0} and name {1} has been saved.'.format(file_._id, file_.name)) if not dry_run: search.update_file(file_) if __name__ == '__main__': main()
# ... existing code ... from website.app import init_app from website.search import search from website.files.models.osfstorage import OsfStorageFile # ... modified code ... if not dry_run: search.update_file(file_) # ... rest of the code ...
44749393191aebf730c4dca17766fbdb713e636b
systempay/app.py
systempay/app.py
from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), # View for using PayPal as a payment method # url(r'^handle-ipn/', self.redirect_view.as_view(as_payment_method=True), # name='systempay-direct-payment'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication()
from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn/', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication()
Add missing handle ipn url
Add missing handle ipn url
Python
mit
bastien34/django-oscar-systempay,bastien34/django-oscar-systempay,dulaccc/django-oscar-systempay
from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView + handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), + url(r'^handle-ipn/', self.handle_ipn_view.as_view(), + name='handle-ipn'), - # View for using PayPal as a payment method - # url(r'^handle-ipn/', self.redirect_view.as_view(as_payment_method=True), - # name='systempay-direct-payment'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication()
Add missing handle ipn url
## Code Before: from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), # View for using PayPal as a payment method # url(r'^handle-ipn/', self.redirect_view.as_view(as_payment_method=True), # name='systempay-direct-payment'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication() ## Instruction: Add missing handle ipn url ## Code After: from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn/', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication()
// ... existing code ... secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN // ... modified code ... name='place-order'), url(r'^handle-ipn/', self.handle_ipn_view.as_view(), name='handle-ipn'), ) // ... rest of the code ...
0224877de121cb7cb850ef51a75c1c3f8c1cb105
kala.py
kala.py
import json import bottle from bottle_mongo import MongoPlugin app = bottle.Bottle() app.config.load_config('settings.ini') app.install(MongoPlugin( uri=app.config['mongodb.uri'], db=app.config['mongodb.db'], json_mongo=True)) def _get_json(name): result = bottle.request.query.get(name) return json.loads(result) if result else None @app.route('/<collection>') def get(mongodb, collection): filter_ = _get_json('filter') projection = _get_json('projection') skip = int(bottle.request.query.get('skip', 0)) limit = int(bottle.request.query.get('limit', 100)) sort = _get_json('sort') cursor = mongodb[collection].find( filter=filter_, projection=projection, skip=skip, limit=limit, sort=sort ) return {'results': [document for document in cursor]} if __name__ == '__main__': app.run()
import json import bottle from bottle_mongo import MongoPlugin app = bottle.Bottle() app.config.load_config('settings.ini') app.install(MongoPlugin( uri=app.config['mongodb.uri'], db=app.config['mongodb.db'], json_mongo=True)) def _get_json(name): result = bottle.request.query.get(name) return json.loads(result) if result else None @app.route('/<collection>') def get(mongodb, collection): filter_ = _get_json('filter') projection = _get_json('projection') skip = int(bottle.request.query.get('skip', 0)) limit = int(bottle.request.query.get('limit', 100)) sort = _get_json('sort') # Turns a JSON array of arrays to a list of tuples. sort = [tuple(field) for field in sort] if sort else None cursor = mongodb[collection].find( filter=filter_, projection=projection, skip=skip, limit=limit, sort=sort ) return {'results': [document for document in cursor]} if __name__ == '__main__': app.run()
Sort needs to be an array of arrays in the query string but a list of tuples in python.
Bugfix: Sort needs to be an array of arrays in the query string but a list of tuples in python.
Python
mit
damoxc/kala,cheng93/kala,cloudbuy/kala
import json import bottle from bottle_mongo import MongoPlugin app = bottle.Bottle() app.config.load_config('settings.ini') app.install(MongoPlugin( uri=app.config['mongodb.uri'], db=app.config['mongodb.db'], json_mongo=True)) def _get_json(name): result = bottle.request.query.get(name) return json.loads(result) if result else None @app.route('/<collection>') def get(mongodb, collection): filter_ = _get_json('filter') projection = _get_json('projection') skip = int(bottle.request.query.get('skip', 0)) limit = int(bottle.request.query.get('limit', 100)) sort = _get_json('sort') + # Turns a JSON array of arrays to a list of tuples. + sort = [tuple(field) for field in sort] if sort else None cursor = mongodb[collection].find( filter=filter_, projection=projection, skip=skip, limit=limit, sort=sort ) return {'results': [document for document in cursor]} if __name__ == '__main__': app.run()
Sort needs to be an array of arrays in the query string but a list of tuples in python.
## Code Before: import json import bottle from bottle_mongo import MongoPlugin app = bottle.Bottle() app.config.load_config('settings.ini') app.install(MongoPlugin( uri=app.config['mongodb.uri'], db=app.config['mongodb.db'], json_mongo=True)) def _get_json(name): result = bottle.request.query.get(name) return json.loads(result) if result else None @app.route('/<collection>') def get(mongodb, collection): filter_ = _get_json('filter') projection = _get_json('projection') skip = int(bottle.request.query.get('skip', 0)) limit = int(bottle.request.query.get('limit', 100)) sort = _get_json('sort') cursor = mongodb[collection].find( filter=filter_, projection=projection, skip=skip, limit=limit, sort=sort ) return {'results': [document for document in cursor]} if __name__ == '__main__': app.run() ## Instruction: Sort needs to be an array of arrays in the query string but a list of tuples in python. ## Code After: import json import bottle from bottle_mongo import MongoPlugin app = bottle.Bottle() app.config.load_config('settings.ini') app.install(MongoPlugin( uri=app.config['mongodb.uri'], db=app.config['mongodb.db'], json_mongo=True)) def _get_json(name): result = bottle.request.query.get(name) return json.loads(result) if result else None @app.route('/<collection>') def get(mongodb, collection): filter_ = _get_json('filter') projection = _get_json('projection') skip = int(bottle.request.query.get('skip', 0)) limit = int(bottle.request.query.get('limit', 100)) sort = _get_json('sort') # Turns a JSON array of arrays to a list of tuples. sort = [tuple(field) for field in sort] if sort else None cursor = mongodb[collection].find( filter=filter_, projection=projection, skip=skip, limit=limit, sort=sort ) return {'results': [document for document in cursor]} if __name__ == '__main__': app.run()
# ... existing code ... sort = _get_json('sort') # Turns a JSON array of arrays to a list of tuples. sort = [tuple(field) for field in sort] if sort else None # ... rest of the code ...
cbe07cd63d07f021ccd404cba2bcfe2a6933457b
tests/test_misc.py
tests/test_misc.py
import billboard import unittest from nose.tools import raises from requests.exceptions import ConnectionError import six class MiscTest(unittest.TestCase): @raises(ConnectionError) def test_timeout(self): """Checks that using a very small timeout prevents connection.""" billboard.ChartData('hot-100', timeout=1e-9) @raises(billboard.BillboardNotFoundException) def test_non_existent_chart(self): """Checks that requesting a non-existent chart fails.""" billboard.ChartData('does-not-exist') def test_unicode(self): """Checks that the Billboard website does not use Unicode characters.""" chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs')
import billboard import unittest from nose.tools import raises from requests.exceptions import ConnectionError import six class MiscTest(unittest.TestCase): @raises(ConnectionError) def test_timeout(self): """Checks that using a very small timeout prevents connection.""" billboard.ChartData('hot-100', timeout=1e-9) @raises(billboard.BillboardNotFoundException) def test_non_existent_chart(self): """Checks that requesting a non-existent chart fails.""" billboard.ChartData('does-not-exist') def test_unicode(self): """Checks that the Billboard website does not use Unicode characters.""" chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs') def test_charts(self): """Checks that the function for listing all charts returns reasonable results.""" charts = billboard.charts() self.assertTrue('hot-100' in charts) self.assertTrue(200 <= len(charts) <= 400)
Add test for tests function
Add test for tests function
Python
mit
guoguo12/billboard-charts,guoguo12/billboard-charts
import billboard import unittest from nose.tools import raises from requests.exceptions import ConnectionError import six class MiscTest(unittest.TestCase): @raises(ConnectionError) def test_timeout(self): """Checks that using a very small timeout prevents connection.""" billboard.ChartData('hot-100', timeout=1e-9) @raises(billboard.BillboardNotFoundException) def test_non_existent_chart(self): """Checks that requesting a non-existent chart fails.""" billboard.ChartData('does-not-exist') def test_unicode(self): """Checks that the Billboard website does not use Unicode characters.""" chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" - + def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs') + def test_charts(self): + """Checks that the function for listing all charts returns reasonable + results.""" + charts = billboard.charts() + self.assertTrue('hot-100' in charts) + self.assertTrue(200 <= len(charts) <= 400)
Add test for tests function
## Code Before: import billboard import unittest from nose.tools import raises from requests.exceptions import ConnectionError import six class MiscTest(unittest.TestCase): @raises(ConnectionError) def test_timeout(self): """Checks that using a very small timeout prevents connection.""" billboard.ChartData('hot-100', timeout=1e-9) @raises(billboard.BillboardNotFoundException) def test_non_existent_chart(self): """Checks that requesting a non-existent chart fails.""" billboard.ChartData('does-not-exist') def test_unicode(self): """Checks that the Billboard website does not use Unicode characters.""" chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs') ## Instruction: Add test for tests function ## Code After: import billboard import unittest from nose.tools import raises from requests.exceptions import ConnectionError import six class MiscTest(unittest.TestCase): @raises(ConnectionError) def test_timeout(self): """Checks that using a very small timeout prevents connection.""" billboard.ChartData('hot-100', timeout=1e-9) @raises(billboard.BillboardNotFoundException) def test_non_existent_chart(self): """Checks that requesting a non-existent chart fails.""" billboard.ChartData('does-not-exist') def test_unicode(self): """Checks that the Billboard website does not use Unicode characters.""" chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs') def test_charts(self): """Checks that the function for listing all charts returns reasonable results.""" charts = billboard.charts() self.assertTrue('hot-100' in charts) self.assertTrue(200 <= len(charts) <= 400)
... 'El Bano')) # With Unicode this should be "El Baño" def test_difficult_title_casing(self): ... def test_charts(self): """Checks that the function for listing all charts returns reasonable results.""" charts = billboard.charts() self.assertTrue('hot-100' in charts) self.assertTrue(200 <= len(charts) <= 400) ...
b6fc94d9c6b5015ad2dc882d454127d4b0a6ecee
django_foodbot/api/models.py
django_foodbot/api/models.py
from django.db import models class Menu(models.Model): day = models.CharField(max_length=10, blank=False, null=False) food = models.CharField(max_length=60, blank=False, null=False) meal = models.CharField(max_length=10, blank=False, null=False) option = models.IntegerField(null=False) week = models.IntegerField(null=False) class Meta: ordering = ('-week',) db_table = 'menu_table' def __unicode__(self): return u'%s %s' % (self.day, self.week) class Rating(models.Model): date = models.DateTimeField(auto_now_add=True) user_id = models.CharField(max_length=20) menu = models.ForeignKey(Menu, related_name='rating') rate = models.IntegerField(blank=False, null=False) comment = models.TextField(default='no comment', ) class Meta: ordering = ('-date',) db_table = 'rating' def __unicode__(self): return u'%s' % (self.date)
from django.db import models class Menu(models.Model): day = models.CharField(max_length=10, blank=False, null=False) food = models.CharField(max_length=120, blank=False, null=False) meal = models.CharField(max_length=10, blank=False, null=False) option = models.IntegerField(null=False) week = models.IntegerField(null=False) class Meta: ordering = ('-week',) db_table = 'menu_table' def __unicode__(self): return u'%s %s %s' % (self.day, self.week, self.meal) class Rating(models.Model): date = models.DateTimeField(auto_now_add=True) user_id = models.CharField(max_length=20) menu = models.ForeignKey(Menu, related_name='rating') rate = models.IntegerField(blank=False, null=False) comment = models.TextField(default='no comment', ) class Meta: ordering = ('-date',) db_table = 'rating' def __unicode__(self): return u'%s' % (self.date)
Increase character length for food
Increase character length for food
Python
mit
andela-kanyanwu/food-bot-review
from django.db import models class Menu(models.Model): day = models.CharField(max_length=10, blank=False, null=False) - food = models.CharField(max_length=60, blank=False, null=False) + food = models.CharField(max_length=120, blank=False, null=False) meal = models.CharField(max_length=10, blank=False, null=False) option = models.IntegerField(null=False) week = models.IntegerField(null=False) class Meta: ordering = ('-week',) db_table = 'menu_table' def __unicode__(self): - return u'%s %s' % (self.day, self.week) + return u'%s %s %s' % (self.day, self.week, self.meal) class Rating(models.Model): date = models.DateTimeField(auto_now_add=True) user_id = models.CharField(max_length=20) menu = models.ForeignKey(Menu, related_name='rating') rate = models.IntegerField(blank=False, null=False) comment = models.TextField(default='no comment', ) class Meta: ordering = ('-date',) db_table = 'rating' def __unicode__(self): return u'%s' % (self.date)
Increase character length for food
## Code Before: from django.db import models class Menu(models.Model): day = models.CharField(max_length=10, blank=False, null=False) food = models.CharField(max_length=60, blank=False, null=False) meal = models.CharField(max_length=10, blank=False, null=False) option = models.IntegerField(null=False) week = models.IntegerField(null=False) class Meta: ordering = ('-week',) db_table = 'menu_table' def __unicode__(self): return u'%s %s' % (self.day, self.week) class Rating(models.Model): date = models.DateTimeField(auto_now_add=True) user_id = models.CharField(max_length=20) menu = models.ForeignKey(Menu, related_name='rating') rate = models.IntegerField(blank=False, null=False) comment = models.TextField(default='no comment', ) class Meta: ordering = ('-date',) db_table = 'rating' def __unicode__(self): return u'%s' % (self.date) ## Instruction: Increase character length for food ## Code After: from django.db import models class Menu(models.Model): day = models.CharField(max_length=10, blank=False, null=False) food = models.CharField(max_length=120, blank=False, null=False) meal = models.CharField(max_length=10, blank=False, null=False) option = models.IntegerField(null=False) week = models.IntegerField(null=False) class Meta: ordering = ('-week',) db_table = 'menu_table' def __unicode__(self): return u'%s %s %s' % (self.day, self.week, self.meal) class Rating(models.Model): date = models.DateTimeField(auto_now_add=True) user_id = models.CharField(max_length=20) menu = models.ForeignKey(Menu, related_name='rating') rate = models.IntegerField(blank=False, null=False) comment = models.TextField(default='no comment', ) class Meta: ordering = ('-date',) db_table = 'rating' def __unicode__(self): return u'%s' % (self.date)
// ... existing code ... day = models.CharField(max_length=10, blank=False, null=False) food = models.CharField(max_length=120, blank=False, null=False) meal = models.CharField(max_length=10, blank=False, null=False) // ... modified code ... def __unicode__(self): return u'%s %s %s' % (self.day, self.week, self.meal) // ... rest of the code ...
20e293b49438a2428eee21bdc07799328a69ec48
dadd/worker/handlers.py
dadd/worker/handlers.py
import json import socket import requests from flask import request, jsonify from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info()) @app.route('/register/', methods=['POST']) def register_with_master(): register(app) return jsonify({'message': 'ok'}) def register(host, port): sess = requests.Session() if 'USERNAME' in app.config and 'PASSWORD' in app.config: sess.auth = (app.config['USERNAME'], app.config['PASSWORD']) sess.headers = {'content-type': 'application/json'} try: url = app.config['MASTER_URL'] + '/api/hosts/' resp = sess.post(url, data=json.dumps({ 'host': socket.getfqdn(), 'port': port })) if not resp.ok: app.logger.warning('Error registering with master: %s' % app.config['MASTER_URL']) except Exception as e: app.logger.warning('Connection Error: %s' % e)
import os import json import socket import requests from flask import request, jsonify, Response, abort from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info()) @app.route('/register/', methods=['POST']) def register_with_master(): register(app) return jsonify({'message': 'ok'}) def register(host, port): sess = requests.Session() if 'USERNAME' in app.config and 'PASSWORD' in app.config: sess.auth = (app.config['USERNAME'], app.config['PASSWORD']) sess.headers = {'content-type': 'application/json'} try: url = app.config['MASTER_URL'] + '/api/hosts/' resp = sess.post(url, data=json.dumps({ 'host': app.config.get('HOSTNAME', socket.getfqdn()), 'port': port })) if not resp.ok: app.logger.warning('Error registering with master: %s' % app.config['MASTER_URL']) except Exception as e: app.logger.warning('Connection Error: %s' % e) @app.route('/logs/<path>', methods=['GET']) def tail_log(path): if os.path.exists(path) and path.startswith('/tmp/'): return Response(open(path), content_type='text/plain') abort(404)
Allow setting the HOSTNAME reported to the master via an env var; Stub and endpoint for tailing the log of a process assuming you know the path.
Allow setting the HOSTNAME reported to the master via an env var; Stub and endpoint for tailing the log of a process assuming you know the path. I'd like to get this log processing a bit more automatic but I need to spend more time in Dadd's API.
Python
bsd-3-clause
ionrock/dadd,ionrock/dadd,ionrock/dadd,ionrock/dadd
+ import os import json import socket import requests - from flask import request, jsonify + from flask import request, jsonify, Response, abort from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info()) @app.route('/register/', methods=['POST']) def register_with_master(): register(app) return jsonify({'message': 'ok'}) def register(host, port): sess = requests.Session() if 'USERNAME' in app.config and 'PASSWORD' in app.config: sess.auth = (app.config['USERNAME'], app.config['PASSWORD']) sess.headers = {'content-type': 'application/json'} try: url = app.config['MASTER_URL'] + '/api/hosts/' resp = sess.post(url, data=json.dumps({ - 'host': socket.getfqdn(), 'port': port + 'host': app.config.get('HOSTNAME', socket.getfqdn()), + 'port': port })) if not resp.ok: app.logger.warning('Error registering with master: %s' % app.config['MASTER_URL']) except Exception as e: app.logger.warning('Connection Error: %s' % e) + + @app.route('/logs/<path>', methods=['GET']) + def tail_log(path): + if os.path.exists(path) and path.startswith('/tmp/'): + return Response(open(path), content_type='text/plain') + abort(404) +
Allow setting the HOSTNAME reported to the master via an env var; Stub and endpoint for tailing the log of a process assuming you know the path.
## Code Before: import json import socket import requests from flask import request, jsonify from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info()) @app.route('/register/', methods=['POST']) def register_with_master(): register(app) return jsonify({'message': 'ok'}) def register(host, port): sess = requests.Session() if 'USERNAME' in app.config and 'PASSWORD' in app.config: sess.auth = (app.config['USERNAME'], app.config['PASSWORD']) sess.headers = {'content-type': 'application/json'} try: url = app.config['MASTER_URL'] + '/api/hosts/' resp = sess.post(url, data=json.dumps({ 'host': socket.getfqdn(), 'port': port })) if not resp.ok: app.logger.warning('Error registering with master: %s' % app.config['MASTER_URL']) except Exception as e: app.logger.warning('Connection Error: %s' % e) ## Instruction: Allow setting the HOSTNAME reported to the master via an env var; Stub and endpoint for tailing the log of a process assuming you know the path. ## Code After: import os import json import socket import requests from flask import request, jsonify, Response, abort from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info()) @app.route('/register/', methods=['POST']) def register_with_master(): register(app) return jsonify({'message': 'ok'}) def register(host, port): sess = requests.Session() if 'USERNAME' in app.config and 'PASSWORD' in app.config: sess.auth = (app.config['USERNAME'], app.config['PASSWORD']) sess.headers = {'content-type': 'application/json'} try: url = app.config['MASTER_URL'] + '/api/hosts/' resp = sess.post(url, data=json.dumps({ 'host': app.config.get('HOSTNAME', socket.getfqdn()), 'port': port })) if not resp.ok: app.logger.warning('Error registering with master: %s' % app.config['MASTER_URL']) except Exception as e: app.logger.warning('Connection Error: %s' % e) @app.route('/logs/<path>', methods=['GET']) def tail_log(path): if os.path.exists(path) and path.startswith('/tmp/'): return Response(open(path), content_type='text/plain') abort(404)
# ... existing code ... import os import json # ... modified code ... from flask import request, jsonify, Response, abort ... resp = sess.post(url, data=json.dumps({ 'host': app.config.get('HOSTNAME', socket.getfqdn()), 'port': port })) ... app.logger.warning('Connection Error: %s' % e) @app.route('/logs/<path>', methods=['GET']) def tail_log(path): if os.path.exists(path) and path.startswith('/tmp/'): return Response(open(path), content_type='text/plain') abort(404) # ... rest of the code ...
422bb9ebfcff9826cf58d17a20df61cea21fdd77
app/supplier_constants.py
app/supplier_constants.py
KEY_DUNS_NUMBER = 'supplierDunsNumber' KEY_ORGANISATION_SIZE = 'supplierOrganisationSize' KEY_REGISTERED_NAME = 'supplierRegisteredName' KEY_REGISTRATION_BUILDING = 'supplierRegisteredBuilding' KEY_REGISTRATION_COUNTRY = 'supplierRegisteredCountry' KEY_REGISTRATION_NUMBER = 'supplierCompanyRegistrationNumber' KEY_REGISTRATION_POSTCODE = 'supplierRegisteredPostcode' KEY_REGISTRATION_TOWN = 'supplierRegisteredTown' KEY_TRADING_NAME = 'supplierTradingName' KEY_TRADING_STATUS = 'supplierTradingStatus' KEY_VAT_NUMBER = 'supplierVatNumber'
KEY_DUNS_NUMBER = 'supplierDunsNumber' KEY_ORGANISATION_SIZE = 'supplierOrganisationSize' KEY_REGISTERED_NAME = 'supplierRegisteredName' KEY_REGISTRATION_BUILDING = 'supplierRegisteredBuilding' KEY_REGISTRATION_COUNTRY = 'supplierRegisteredCountry' KEY_REGISTRATION_NUMBER = 'supplierCompanyRegistrationNumber' KEY_REGISTRATION_POSTCODE = 'supplierRegisteredPostcode' KEY_REGISTRATION_TOWN = 'supplierRegisteredTown' KEY_TRADING_NAME = 'supplierTradingName' KEY_TRADING_STATUS = 'supplierTradingStatus'
Remove VAT number from supplier constants
Remove VAT number from supplier constants
Python
mit
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
KEY_DUNS_NUMBER = 'supplierDunsNumber' KEY_ORGANISATION_SIZE = 'supplierOrganisationSize' KEY_REGISTERED_NAME = 'supplierRegisteredName' KEY_REGISTRATION_BUILDING = 'supplierRegisteredBuilding' KEY_REGISTRATION_COUNTRY = 'supplierRegisteredCountry' KEY_REGISTRATION_NUMBER = 'supplierCompanyRegistrationNumber' KEY_REGISTRATION_POSTCODE = 'supplierRegisteredPostcode' KEY_REGISTRATION_TOWN = 'supplierRegisteredTown' KEY_TRADING_NAME = 'supplierTradingName' KEY_TRADING_STATUS = 'supplierTradingStatus' - KEY_VAT_NUMBER = 'supplierVatNumber'
Remove VAT number from supplier constants
## Code Before: KEY_DUNS_NUMBER = 'supplierDunsNumber' KEY_ORGANISATION_SIZE = 'supplierOrganisationSize' KEY_REGISTERED_NAME = 'supplierRegisteredName' KEY_REGISTRATION_BUILDING = 'supplierRegisteredBuilding' KEY_REGISTRATION_COUNTRY = 'supplierRegisteredCountry' KEY_REGISTRATION_NUMBER = 'supplierCompanyRegistrationNumber' KEY_REGISTRATION_POSTCODE = 'supplierRegisteredPostcode' KEY_REGISTRATION_TOWN = 'supplierRegisteredTown' KEY_TRADING_NAME = 'supplierTradingName' KEY_TRADING_STATUS = 'supplierTradingStatus' KEY_VAT_NUMBER = 'supplierVatNumber' ## Instruction: Remove VAT number from supplier constants ## Code After: KEY_DUNS_NUMBER = 'supplierDunsNumber' KEY_ORGANISATION_SIZE = 'supplierOrganisationSize' KEY_REGISTERED_NAME = 'supplierRegisteredName' KEY_REGISTRATION_BUILDING = 'supplierRegisteredBuilding' KEY_REGISTRATION_COUNTRY = 'supplierRegisteredCountry' KEY_REGISTRATION_NUMBER = 'supplierCompanyRegistrationNumber' KEY_REGISTRATION_POSTCODE = 'supplierRegisteredPostcode' KEY_REGISTRATION_TOWN = 'supplierRegisteredTown' KEY_TRADING_NAME = 'supplierTradingName' KEY_TRADING_STATUS = 'supplierTradingStatus'
// ... existing code ... KEY_TRADING_STATUS = 'supplierTradingStatus' // ... rest of the code ...
d3bc714478c3f7a665b39dfb1b8d65e7bc59ccd0
utuputki-webui/utuputki/handlers/logout.py
utuputki-webui/utuputki/handlers/logout.py
from handlers.handlerbase import HandlerBase from db import db_session, Session class LogoutHandler(HandlerBase): def handle(self, packet_msg): # Remove session s = db_session() s.query(Session).filter_by(key=self.sock.sid).delete() s.commit() s.close() # Dump out log self.log.info("Logged out.") self.log.set_sid(None) # Deauthenticate & clear session ID self.sock.authenticated = False self.sock.sid = None
from handlers.handlerbase import HandlerBase from db import db_session, Session class LogoutHandler(HandlerBase): def handle(self, packet_msg): # Remove session s = db_session() s.query(Session).filter_by(key=self.sock.sid).delete() s.commit() s.close() # Dump out log self.log.info("Logged out.") self.log.set_sid(None) # Deauthenticate & clear session ID self.sock.authenticated = False self.sock.sid = None self.sock.uid = None self.sock.level = 0
Clear all session data from websocket obj
Clear all session data from websocket obj
Python
mit
katajakasa/utuputki2,katajakasa/utuputki2,katajakasa/utuputki2,katajakasa/utuputki2
from handlers.handlerbase import HandlerBase from db import db_session, Session class LogoutHandler(HandlerBase): def handle(self, packet_msg): # Remove session s = db_session() s.query(Session).filter_by(key=self.sock.sid).delete() s.commit() s.close() # Dump out log self.log.info("Logged out.") self.log.set_sid(None) # Deauthenticate & clear session ID self.sock.authenticated = False self.sock.sid = None + self.sock.uid = None + self.sock.level = 0
Clear all session data from websocket obj
## Code Before: from handlers.handlerbase import HandlerBase from db import db_session, Session class LogoutHandler(HandlerBase): def handle(self, packet_msg): # Remove session s = db_session() s.query(Session).filter_by(key=self.sock.sid).delete() s.commit() s.close() # Dump out log self.log.info("Logged out.") self.log.set_sid(None) # Deauthenticate & clear session ID self.sock.authenticated = False self.sock.sid = None ## Instruction: Clear all session data from websocket obj ## Code After: from handlers.handlerbase import HandlerBase from db import db_session, Session class LogoutHandler(HandlerBase): def handle(self, packet_msg): # Remove session s = db_session() s.query(Session).filter_by(key=self.sock.sid).delete() s.commit() s.close() # Dump out log self.log.info("Logged out.") self.log.set_sid(None) # Deauthenticate & clear session ID self.sock.authenticated = False self.sock.sid = None self.sock.uid = None self.sock.level = 0
... self.sock.sid = None self.sock.uid = None self.sock.level = 0 ...
bbf48a79539493fcade9b5cdb4b1c637b64961ee
tests/test_optimistic_strategy.py
tests/test_optimistic_strategy.py
from nose.tools import assert_true, assert_false from imagekit.cachefiles import ImageCacheFile from mock import Mock from .utils import create_image from django.core.files.storage import FileSystemStorage from imagekit.cachefiles.backends import Simple as SimpleCFBackend from imagekit.cachefiles.strategies import Optimistic as OptimisticStrategy class ImageGenerator(object): def generate(self): return create_image() def get_hash(self): return 'abc123' def get_image_cache_file(): storage = Mock(FileSystemStorage) backend = SimpleCFBackend() strategy = OptimisticStrategy() generator = ImageGenerator() return ImageCacheFile(generator, storage=storage, cachefile_backend=backend, cachefile_strategy=strategy) def test_no_io_on_bool(): """ When checking the truthiness of an ImageCacheFile, the storage shouldn't peform IO operations. """ file = get_image_cache_file() bool(file) assert_false(file.storage.exists.called) assert_false(file.storage.open.called)
from nose.tools import assert_true, assert_false from imagekit.cachefiles import ImageCacheFile from mock import Mock from .utils import create_image from django.core.files.storage import FileSystemStorage from imagekit.cachefiles.backends import Simple as SimpleCFBackend from imagekit.cachefiles.strategies import Optimistic as OptimisticStrategy class ImageGenerator(object): def generate(self): return create_image() def get_hash(self): return 'abc123' def get_image_cache_file(): storage = Mock(FileSystemStorage) backend = SimpleCFBackend() strategy = OptimisticStrategy() generator = ImageGenerator() return ImageCacheFile(generator, storage=storage, cachefile_backend=backend, cachefile_strategy=strategy) def test_no_io_on_bool(): """ When checking the truthiness of an ImageCacheFile, the storage shouldn't peform IO operations. """ file = get_image_cache_file() bool(file) assert_false(file.storage.exists.called) assert_false(file.storage.open.called) def test_no_io_on_url(): """ When getting the URL of an ImageCacheFile, the storage shouldn't be checked. """ file = get_image_cache_file() file.url assert_false(file.storage.exists.called) assert_false(file.storage.open.called)
Test that there isn't IO done when you get a URL
Test that there isn't IO done when you get a URL
Python
bsd-3-clause
FundedByMe/django-imagekit,tawanda/django-imagekit,FundedByMe/django-imagekit,tawanda/django-imagekit
from nose.tools import assert_true, assert_false from imagekit.cachefiles import ImageCacheFile from mock import Mock from .utils import create_image from django.core.files.storage import FileSystemStorage from imagekit.cachefiles.backends import Simple as SimpleCFBackend from imagekit.cachefiles.strategies import Optimistic as OptimisticStrategy class ImageGenerator(object): def generate(self): return create_image() def get_hash(self): return 'abc123' def get_image_cache_file(): storage = Mock(FileSystemStorage) backend = SimpleCFBackend() strategy = OptimisticStrategy() generator = ImageGenerator() return ImageCacheFile(generator, storage=storage, cachefile_backend=backend, cachefile_strategy=strategy) def test_no_io_on_bool(): """ When checking the truthiness of an ImageCacheFile, the storage shouldn't peform IO operations. """ file = get_image_cache_file() bool(file) assert_false(file.storage.exists.called) assert_false(file.storage.open.called) + + def test_no_io_on_url(): + """ + When getting the URL of an ImageCacheFile, the storage shouldn't be + checked. + + """ + file = get_image_cache_file() + file.url + assert_false(file.storage.exists.called) + assert_false(file.storage.open.called) +
Test that there isn't IO done when you get a URL
## Code Before: from nose.tools import assert_true, assert_false from imagekit.cachefiles import ImageCacheFile from mock import Mock from .utils import create_image from django.core.files.storage import FileSystemStorage from imagekit.cachefiles.backends import Simple as SimpleCFBackend from imagekit.cachefiles.strategies import Optimistic as OptimisticStrategy class ImageGenerator(object): def generate(self): return create_image() def get_hash(self): return 'abc123' def get_image_cache_file(): storage = Mock(FileSystemStorage) backend = SimpleCFBackend() strategy = OptimisticStrategy() generator = ImageGenerator() return ImageCacheFile(generator, storage=storage, cachefile_backend=backend, cachefile_strategy=strategy) def test_no_io_on_bool(): """ When checking the truthiness of an ImageCacheFile, the storage shouldn't peform IO operations. """ file = get_image_cache_file() bool(file) assert_false(file.storage.exists.called) assert_false(file.storage.open.called) ## Instruction: Test that there isn't IO done when you get a URL ## Code After: from nose.tools import assert_true, assert_false from imagekit.cachefiles import ImageCacheFile from mock import Mock from .utils import create_image from django.core.files.storage import FileSystemStorage from imagekit.cachefiles.backends import Simple as SimpleCFBackend from imagekit.cachefiles.strategies import Optimistic as OptimisticStrategy class ImageGenerator(object): def generate(self): return create_image() def get_hash(self): return 'abc123' def get_image_cache_file(): storage = Mock(FileSystemStorage) backend = SimpleCFBackend() strategy = OptimisticStrategy() generator = ImageGenerator() return ImageCacheFile(generator, storage=storage, cachefile_backend=backend, cachefile_strategy=strategy) def test_no_io_on_bool(): """ When checking the truthiness of an ImageCacheFile, the storage shouldn't peform IO operations. """ file = get_image_cache_file() bool(file) assert_false(file.storage.exists.called) assert_false(file.storage.open.called) def test_no_io_on_url(): """ When getting the URL of an ImageCacheFile, the storage shouldn't be checked. """ file = get_image_cache_file() file.url assert_false(file.storage.exists.called) assert_false(file.storage.open.called)
... assert_false(file.storage.open.called) def test_no_io_on_url(): """ When getting the URL of an ImageCacheFile, the storage shouldn't be checked. """ file = get_image_cache_file() file.url assert_false(file.storage.exists.called) assert_false(file.storage.open.called) ...
8e2596db204d2f6779280309aaa06d90872e9fb2
tests/test_bot_support.py
tests/test_bot_support.py
from __future__ import unicode_literals import pytest from .test_bot import TestBot class TestBotSupport(TestBot): @pytest.mark.parametrize('url,result', [ ('https://google.com', ['https://google.com']), ('google.com', ['google.com']), ('google.com/search?q=instabot', ['google.com/search?q=instabot']), ('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']), ('мвд.рф', ['мвд.рф']), ('https://мвд.рф', ['https://мвд.рф']), ('http://мвд.рф/news/', ['http://мвд.рф/news/']), ('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']), ]) def test_extract_urls(self, url, result): assert self.BOT.extract_urls(url) == result
from __future__ import unicode_literals import os import pytest from .test_bot import TestBot class TestBotSupport(TestBot): @pytest.mark.parametrize('url,result', [ ('https://google.com', ['https://google.com']), ('google.com', ['google.com']), ('google.com/search?q=instabot', ['google.com/search?q=instabot']), ('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']), ('мвд.рф', ['мвд.рф']), ('https://мвд.рф', ['https://мвд.рф']), ('http://мвд.рф/news/', ['http://мвд.рф/news/']), ('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']), ]) def test_extract_urls(self, url, result): assert self.BOT.extract_urls(url) == result def test_check_if_file_exist(self): test_file = open('test', 'w') assert self.BOT.check_if_file_exists('test') test_file.close() os.remove('test') def test_check_if_file_exist_fail(self): assert not self.BOT.check_if_file_exists('test')
Add test on check file if exist
Add test on check file if exist
Python
apache-2.0
instagrambot/instabot,ohld/instabot,instagrambot/instabot
from __future__ import unicode_literals + + import os import pytest from .test_bot import TestBot class TestBotSupport(TestBot): @pytest.mark.parametrize('url,result', [ ('https://google.com', ['https://google.com']), ('google.com', ['google.com']), ('google.com/search?q=instabot', ['google.com/search?q=instabot']), ('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']), ('мвд.рф', ['мвд.рф']), ('https://мвд.рф', ['https://мвд.рф']), ('http://мвд.рф/news/', ['http://мвд.рф/news/']), ('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']), ]) def test_extract_urls(self, url, result): assert self.BOT.extract_urls(url) == result + def test_check_if_file_exist(self): + test_file = open('test', 'w') + + assert self.BOT.check_if_file_exists('test') + + test_file.close() + os.remove('test') + + def test_check_if_file_exist_fail(self): + assert not self.BOT.check_if_file_exists('test') +
Add test on check file if exist
## Code Before: from __future__ import unicode_literals import pytest from .test_bot import TestBot class TestBotSupport(TestBot): @pytest.mark.parametrize('url,result', [ ('https://google.com', ['https://google.com']), ('google.com', ['google.com']), ('google.com/search?q=instabot', ['google.com/search?q=instabot']), ('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']), ('мвд.рф', ['мвд.рф']), ('https://мвд.рф', ['https://мвд.рф']), ('http://мвд.рф/news/', ['http://мвд.рф/news/']), ('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']), ]) def test_extract_urls(self, url, result): assert self.BOT.extract_urls(url) == result ## Instruction: Add test on check file if exist ## Code After: from __future__ import unicode_literals import os import pytest from .test_bot import TestBot class TestBotSupport(TestBot): @pytest.mark.parametrize('url,result', [ ('https://google.com', ['https://google.com']), ('google.com', ['google.com']), ('google.com/search?q=instabot', ['google.com/search?q=instabot']), ('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']), ('мвд.рф', ['мвд.рф']), ('https://мвд.рф', ['https://мвд.рф']), ('http://мвд.рф/news/', ['http://мвд.рф/news/']), ('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']), ]) def test_extract_urls(self, url, result): assert self.BOT.extract_urls(url) == result def test_check_if_file_exist(self): test_file = open('test', 'w') assert self.BOT.check_if_file_exists('test') test_file.close() os.remove('test') def test_check_if_file_exist_fail(self): assert not self.BOT.check_if_file_exists('test')
# ... existing code ... from __future__ import unicode_literals import os # ... modified code ... assert self.BOT.extract_urls(url) == result def test_check_if_file_exist(self): test_file = open('test', 'w') assert self.BOT.check_if_file_exists('test') test_file.close() os.remove('test') def test_check_if_file_exist_fail(self): assert not self.BOT.check_if_file_exists('test') # ... rest of the code ...
c31c54624d7a46dfd9df96e32d2e07246868aecc
tomviz/python/DefaultITKTransform.py
tomviz/python/DefaultITKTransform.py
def transform_scalars(dataset): """Define this method for Python operators that transform the input array.""" from tomviz import utils import numpy as np import itk # Get the current volume as a numpy array. array = utils.get_array(dataset) # Set up some ITK variables itk_image_type = itk.Image.F3 itk_converter = itk.PyBuffer[itk_image_type] # Read the image into ITK itk_image = itk_converter.GetImageFromArray(array) # ITK filter (I have no idea if this is right) filter = \ itk.ConfidenceConnectedImageFilter[itk_image_type,itk.Image.SS3].New() filter.SetInitialNeighborhoodRadius(3) filter.SetMultiplier(3) filter.SetNumberOfIterations(25) filter.SetReplaceValue(255) filter.SetSeed((24,65,37)) filter.SetInput(itk_image) filter.Update() # Get the image back from ITK (result is a numpy image) result = itk.PyBuffer[itk.Image.SS3].GetArrayFromImage(filter.GetOutput()) # This is where the transformed data is set, it will display in tomviz. utils.set_array(dataset, result)
import tomviz.operators class DefaultITKTransform(tomviz.operators.CancelableOperator): def transform_scalars(self, dataset): """Define this method for Python operators that transform the input array. This example uses an ITK filter to add 10 to each voxel value.""" # Try imports to make sure we have everything that is needed try: from tomviz import itkutils import itk except Exception as exc: print("Could not import necessary module(s)") raise exc self.progress.value = 0 self.progress.maximum = 100 # Add a try/except around the ITK portion. ITK exceptions are # passed up to the Python layer, so we can at least report what # went wrong with the script, e.g., unsupported image type. try: self.progress.value = 0 self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) self.progress.value = 30 self.progress.message = "Running filter" # ITK filter filter = itk.AddImageFilter[itk_input_image_type, # Input 1 itk_input_image_type, # Input 2 itk_input_image_type].New() # Output filter.SetInput1(itk_image) filter.SetConstant2(10) itkutils.observe_filter_progress(self, filter, 30, 70) try: filter.Update() except RuntimeError: # Exception thrown when ITK filter is aborted return self.progress.message = "Saving results" itkutils.set_array_from_itk_image(dataset, filter.GetOutput()) self.progress.value = 100 except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc
Change the ITK example to use a simpler ITK filter
Change the ITK example to use a simpler ITK filter
Python
bsd-3-clause
cjh1/tomviz,cryos/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,cjh1/tomviz,thewtex/tomviz,thewtex/tomviz,cryos/tomviz,mathturtle/tomviz,thewtex/tomviz,cjh1/tomviz,cryos/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,mathturtle/tomviz
+ import tomviz.operators - def transform_scalars(dataset): - """Define this method for Python operators that - transform the input array.""" - from tomviz import utils - import numpy as np - import itk - # Get the current volume as a numpy array. - array = utils.get_array(dataset) + class DefaultITKTransform(tomviz.operators.CancelableOperator): - # Set up some ITK variables - itk_image_type = itk.Image.F3 - itk_converter = itk.PyBuffer[itk_image_type] - # Read the image into ITK - itk_image = itk_converter.GetImageFromArray(array) + def transform_scalars(self, dataset): + """Define this method for Python operators that transform the input + array. This example uses an ITK filter to add 10 to each voxel value.""" + # Try imports to make sure we have everything that is needed + try: + from tomviz import itkutils + import itk + except Exception as exc: + print("Could not import necessary module(s)") + raise exc - # ITK filter (I have no idea if this is right) - filter = \ - itk.ConfidenceConnectedImageFilter[itk_image_type,itk.Image.SS3].New() - filter.SetInitialNeighborhoodRadius(3) - filter.SetMultiplier(3) - filter.SetNumberOfIterations(25) - filter.SetReplaceValue(255) - filter.SetSeed((24,65,37)) - filter.SetInput(itk_image) - filter.Update() - # Get the image back from ITK (result is a numpy image) - result = itk.PyBuffer[itk.Image.SS3].GetArrayFromImage(filter.GetOutput()) + self.progress.value = 0 + self.progress.maximum = 100 - # This is where the transformed data is set, it will display in tomviz. - utils.set_array(dataset, result) + # Add a try/except around the ITK portion. ITK exceptions are + # passed up to the Python layer, so we can at least report what + # went wrong with the script, e.g., unsupported image type. + try: + self.progress.value = 0 + self.progress.message = "Converting data to ITK image" + # Get the ITK image + itk_image = itkutils.convert_vtk_to_itk_image(dataset) + itk_input_image_type = type(itk_image) + self.progress.value = 30 + self.progress.message = "Running filter" + + # ITK filter + filter = itk.AddImageFilter[itk_input_image_type, # Input 1 + itk_input_image_type, # Input 2 + itk_input_image_type].New() # Output + filter.SetInput1(itk_image) + filter.SetConstant2(10) + itkutils.observe_filter_progress(self, filter, 30, 70) + + try: + filter.Update() + except RuntimeError: # Exception thrown when ITK filter is aborted + return + + self.progress.message = "Saving results" + + itkutils.set_array_from_itk_image(dataset, filter.GetOutput()) + + self.progress.value = 100 + except Exception as exc: + print("Problem encountered while running %s" % + self.__class__.__name__) + raise exc +
Change the ITK example to use a simpler ITK filter
## Code Before: def transform_scalars(dataset): """Define this method for Python operators that transform the input array.""" from tomviz import utils import numpy as np import itk # Get the current volume as a numpy array. array = utils.get_array(dataset) # Set up some ITK variables itk_image_type = itk.Image.F3 itk_converter = itk.PyBuffer[itk_image_type] # Read the image into ITK itk_image = itk_converter.GetImageFromArray(array) # ITK filter (I have no idea if this is right) filter = \ itk.ConfidenceConnectedImageFilter[itk_image_type,itk.Image.SS3].New() filter.SetInitialNeighborhoodRadius(3) filter.SetMultiplier(3) filter.SetNumberOfIterations(25) filter.SetReplaceValue(255) filter.SetSeed((24,65,37)) filter.SetInput(itk_image) filter.Update() # Get the image back from ITK (result is a numpy image) result = itk.PyBuffer[itk.Image.SS3].GetArrayFromImage(filter.GetOutput()) # This is where the transformed data is set, it will display in tomviz. utils.set_array(dataset, result) ## Instruction: Change the ITK example to use a simpler ITK filter ## Code After: import tomviz.operators class DefaultITKTransform(tomviz.operators.CancelableOperator): def transform_scalars(self, dataset): """Define this method for Python operators that transform the input array. This example uses an ITK filter to add 10 to each voxel value.""" # Try imports to make sure we have everything that is needed try: from tomviz import itkutils import itk except Exception as exc: print("Could not import necessary module(s)") raise exc self.progress.value = 0 self.progress.maximum = 100 # Add a try/except around the ITK portion. ITK exceptions are # passed up to the Python layer, so we can at least report what # went wrong with the script, e.g., unsupported image type. try: self.progress.value = 0 self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) self.progress.value = 30 self.progress.message = "Running filter" # ITK filter filter = itk.AddImageFilter[itk_input_image_type, # Input 1 itk_input_image_type, # Input 2 itk_input_image_type].New() # Output filter.SetInput1(itk_image) filter.SetConstant2(10) itkutils.observe_filter_progress(self, filter, 30, 70) try: filter.Update() except RuntimeError: # Exception thrown when ITK filter is aborted return self.progress.message = "Saving results" itkutils.set_array_from_itk_image(dataset, filter.GetOutput()) self.progress.value = 100 except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc
# ... existing code ... import tomviz.operators class DefaultITKTransform(tomviz.operators.CancelableOperator): def transform_scalars(self, dataset): """Define this method for Python operators that transform the input array. This example uses an ITK filter to add 10 to each voxel value.""" # Try imports to make sure we have everything that is needed try: from tomviz import itkutils import itk except Exception as exc: print("Could not import necessary module(s)") raise exc self.progress.value = 0 self.progress.maximum = 100 # Add a try/except around the ITK portion. ITK exceptions are # passed up to the Python layer, so we can at least report what # went wrong with the script, e.g., unsupported image type. try: self.progress.value = 0 self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) self.progress.value = 30 self.progress.message = "Running filter" # ITK filter filter = itk.AddImageFilter[itk_input_image_type, # Input 1 itk_input_image_type, # Input 2 itk_input_image_type].New() # Output filter.SetInput1(itk_image) filter.SetConstant2(10) itkutils.observe_filter_progress(self, filter, 30, 70) try: filter.Update() except RuntimeError: # Exception thrown when ITK filter is aborted return self.progress.message = "Saving results" itkutils.set_array_from_itk_image(dataset, filter.GetOutput()) self.progress.value = 100 except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc # ... rest of the code ...
e9862c50c1d71800602ca78bf9bdd8aad2def0a2
run.py
run.py
import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command)
import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True --is_crop ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command)
Add is_crop for celebA example
Add is_crop for celebA example
Python
mit
MustafaMustafa/WassersteinGAN-TensorFlow
import os tag = 'celebA_dcgan' dataset = 'celebA' - command = 'python main.py --dataset %s --is_train True ' \ + command = 'python main.py --dataset %s --is_train True --is_crop ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command)
Add is_crop for celebA example
## Code Before: import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command) ## Instruction: Add is_crop for celebA example ## Code After: import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True --is_crop ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command)
... command = 'python main.py --dataset %s --is_train True --is_crop ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) ...
3dda5003b3ce345a08369b15fc3447d2a4c7d1ad
examples/plotting_2d.py
examples/plotting_2d.py
from bluesky.examples import * from bluesky.standard_config import RE from matplotlib import pyplot as plt from xray_vision.backend.mpl.cross_section_2d import CrossSection import numpy as np import filestore.api as fsapi import time as ttime from filestore.handlers import NpyHandler fsapi.register_handler('npy', NpyHandler) def stepscan(motor, det): for i in np.linspace(-5, 5, 75): yield Msg('create') yield Msg('set', motor, i) yield Msg('trigger', det) yield Msg('read', motor) yield Msg('read', det) yield Msg('save') ic = LiveImage('det_2d') table_callback = LiveTable(fields=[motor._name, det_2d._name]) RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
from bluesky.examples import * from bluesky.tests.utils import setup_test_run_engine from matplotlib import pyplot as plt from xray_vision.backend.mpl.cross_section_2d import CrossSection import numpy as np import filestore.api as fsapi import time as ttime from filestore.handlers import NpyHandler fsapi.register_handler('npy', NpyHandler) def stepscan(motor, det): for i in np.linspace(-5, 5, 75): yield Msg('create') yield Msg('set', motor, i) yield Msg('trigger', det) yield Msg('read', motor) yield Msg('read', det) yield Msg('save') ic = LiveImage('det_2d') table_callback = LiveTable(fields=[motor._name, det_2d._name]) RE = setup_test_run_engine() RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
Set up RunEngine with required metadata.
FIX: Set up RunEngine with required metadata.
Python
bsd-3-clause
ericdill/bluesky,sameera2004/bluesky,sameera2004/bluesky,klauer/bluesky,klauer/bluesky,dchabot/bluesky,ericdill/bluesky,dchabot/bluesky
from bluesky.examples import * - from bluesky.standard_config import RE + from bluesky.tests.utils import setup_test_run_engine from matplotlib import pyplot as plt from xray_vision.backend.mpl.cross_section_2d import CrossSection import numpy as np import filestore.api as fsapi import time as ttime from filestore.handlers import NpyHandler fsapi.register_handler('npy', NpyHandler) def stepscan(motor, det): for i in np.linspace(-5, 5, 75): yield Msg('create') yield Msg('set', motor, i) yield Msg('trigger', det) yield Msg('read', motor) yield Msg('read', det) yield Msg('save') ic = LiveImage('det_2d') table_callback = LiveTable(fields=[motor._name, det_2d._name]) + RE = setup_test_run_engine() RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
Set up RunEngine with required metadata.
## Code Before: from bluesky.examples import * from bluesky.standard_config import RE from matplotlib import pyplot as plt from xray_vision.backend.mpl.cross_section_2d import CrossSection import numpy as np import filestore.api as fsapi import time as ttime from filestore.handlers import NpyHandler fsapi.register_handler('npy', NpyHandler) def stepscan(motor, det): for i in np.linspace(-5, 5, 75): yield Msg('create') yield Msg('set', motor, i) yield Msg('trigger', det) yield Msg('read', motor) yield Msg('read', det) yield Msg('save') ic = LiveImage('det_2d') table_callback = LiveTable(fields=[motor._name, det_2d._name]) RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i') ## Instruction: Set up RunEngine with required metadata. ## Code After: from bluesky.examples import * from bluesky.tests.utils import setup_test_run_engine from matplotlib import pyplot as plt from xray_vision.backend.mpl.cross_section_2d import CrossSection import numpy as np import filestore.api as fsapi import time as ttime from filestore.handlers import NpyHandler fsapi.register_handler('npy', NpyHandler) def stepscan(motor, det): for i in np.linspace(-5, 5, 75): yield Msg('create') yield Msg('set', motor, i) yield Msg('trigger', det) yield Msg('read', motor) yield Msg('read', det) yield Msg('save') ic = LiveImage('det_2d') table_callback = LiveTable(fields=[motor._name, det_2d._name]) RE = setup_test_run_engine() RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i')
// ... existing code ... from bluesky.examples import * from bluesky.tests.utils import setup_test_run_engine from matplotlib import pyplot as plt // ... modified code ... table_callback = LiveTable(fields=[motor._name, det_2d._name]) RE = setup_test_run_engine() RE(stepscan(motor, det_2d), subs={'event': ic, 'all': table_callback}, beamline_id='c08i') // ... rest of the code ...
1f6ba483902c59dc70d15ea1e33957ac6a874f01
freesound_datasets/local_settings.example.py
freesound_datasets/local_settings.example.py
FS_CLIENT_ID = 'FREESOUND_KEY' FS_CLIENT_SECRET = 'FREESOUND_SECRET' # Freesound keys for "login with" functionality # Get credentials at http://www.freesound.org/apiv2/apply # Set callback url to http://localhost:8000/social/complete/freesound/ SOCIAL_AUTH_FREESOUND_KEY = None SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET' # Google keys for "login with" functionality # Get credentials at https://console.developers.google.com # Set callback url to http://localhost:8000/social/complete/google-oauth2/ SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = None # (remove the part starting with the dot .) SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'GOOGLE_SECRET' # Facebook keys for "login with" functionality # See instructions in https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html # NOTE: might not work in localhost SOCIAL_AUTH_FACEBOOK_KEY = None SOCIAL_AUTH_FACEBOOK_SECRET = 'FACEBOOK_SECRET' # Github keys for "login with" functionality # Get credentials at https://github.com/settings/applications/new # Set callback url to http://localhost:8000/social/complete/github/ SOCIAL_AUTH_GITHUB_KEY = None SOCIAL_AUTH_GITHUB_SECRET = 'GITHUB_SECRET'
FS_CLIENT_ID = 'FREESOUND_KEY' FS_CLIENT_SECRET = 'FREESOUND_SECRET' # Freesound keys for "login with" functionality # Get credentials at http://www.freesound.org/apiv2/apply # Set callback url to http://localhost:8000/social/complete/freesound/ SOCIAL_AUTH_FREESOUND_KEY = None SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET'
Remove unused social auth keys
Remove unused social auth keys
Python
agpl-3.0
MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets
FS_CLIENT_ID = 'FREESOUND_KEY' FS_CLIENT_SECRET = 'FREESOUND_SECRET' # Freesound keys for "login with" functionality # Get credentials at http://www.freesound.org/apiv2/apply # Set callback url to http://localhost:8000/social/complete/freesound/ SOCIAL_AUTH_FREESOUND_KEY = None SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET' - # Google keys for "login with" functionality - # Get credentials at https://console.developers.google.com - # Set callback url to http://localhost:8000/social/complete/google-oauth2/ - SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = None # (remove the part starting with the dot .) - SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'GOOGLE_SECRET' - - # Facebook keys for "login with" functionality - # See instructions in https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html - # NOTE: might not work in localhost - SOCIAL_AUTH_FACEBOOK_KEY = None - SOCIAL_AUTH_FACEBOOK_SECRET = 'FACEBOOK_SECRET' - - # Github keys for "login with" functionality - # Get credentials at https://github.com/settings/applications/new - # Set callback url to http://localhost:8000/social/complete/github/ - SOCIAL_AUTH_GITHUB_KEY = None - SOCIAL_AUTH_GITHUB_SECRET = 'GITHUB_SECRET' -
Remove unused social auth keys
## Code Before: FS_CLIENT_ID = 'FREESOUND_KEY' FS_CLIENT_SECRET = 'FREESOUND_SECRET' # Freesound keys for "login with" functionality # Get credentials at http://www.freesound.org/apiv2/apply # Set callback url to http://localhost:8000/social/complete/freesound/ SOCIAL_AUTH_FREESOUND_KEY = None SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET' # Google keys for "login with" functionality # Get credentials at https://console.developers.google.com # Set callback url to http://localhost:8000/social/complete/google-oauth2/ SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = None # (remove the part starting with the dot .) SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'GOOGLE_SECRET' # Facebook keys for "login with" functionality # See instructions in https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html # NOTE: might not work in localhost SOCIAL_AUTH_FACEBOOK_KEY = None SOCIAL_AUTH_FACEBOOK_SECRET = 'FACEBOOK_SECRET' # Github keys for "login with" functionality # Get credentials at https://github.com/settings/applications/new # Set callback url to http://localhost:8000/social/complete/github/ SOCIAL_AUTH_GITHUB_KEY = None SOCIAL_AUTH_GITHUB_SECRET = 'GITHUB_SECRET' ## Instruction: Remove unused social auth keys ## Code After: FS_CLIENT_ID = 'FREESOUND_KEY' FS_CLIENT_SECRET = 'FREESOUND_SECRET' # Freesound keys for "login with" functionality # Get credentials at http://www.freesound.org/apiv2/apply # Set callback url to http://localhost:8000/social/complete/freesound/ SOCIAL_AUTH_FREESOUND_KEY = None SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET'
# ... existing code ... SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET' # ... rest of the code ...
563a905a48a5d4059463f25c5467a52a9d9c79c5
groove/timezone.py
groove/timezone.py
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day)
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) def datetime_aware(year, month, day, hour, minute, second): """ Return a datetime aware object with current local timezone. """ _datetime = datetime(year, month, day, hour, minute, second) return timezone.make_aware(_datetime, timezone.get_current_timezone())
Add function for creating a datetime aware object
Add function for creating a datetime aware object
Python
bsd-2-clause
funkbit/django-groove
from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) + + def datetime_aware(year, month, day, hour, minute, second): + """ + Return a datetime aware object with current local timezone. + """ + _datetime = datetime(year, month, day, hour, minute, second) + return timezone.make_aware(_datetime, timezone.get_current_timezone()) +
Add function for creating a datetime aware object
## Code Before: from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) ## Instruction: Add function for creating a datetime aware object ## Code After: from datetime import datetime, date from django.utils import timezone def datetime_midnight(year, month, day): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return timezone.make_aware(datetime(year, month, day), timezone.get_current_timezone()) def datetime_midnight_date(date_obj): """ Returns a timezone aware datetime object of a date at midnight, using the current timezone. """ return datetime_midnight(date_obj.year, date_obj.month, date_obj.day) def datetime_midnight_today(): """ Returns today at midnight as a timezone aware datetime object, using the current timezone. """ today = date.today() return datetime_midnight(today.year, today.month, today.day) def datetime_aware(year, month, day, hour, minute, second): """ Return a datetime aware object with current local timezone. """ _datetime = datetime(year, month, day, hour, minute, second) return timezone.make_aware(_datetime, timezone.get_current_timezone())
# ... existing code ... return datetime_midnight(today.year, today.month, today.day) def datetime_aware(year, month, day, hour, minute, second): """ Return a datetime aware object with current local timezone. """ _datetime = datetime(year, month, day, hour, minute, second) return timezone.make_aware(_datetime, timezone.get_current_timezone()) # ... rest of the code ...
bddab649c6684f09870983dca97c39eb30b62c06
djangobotcfg/status.py
djangobotcfg/status.py
from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth # authz = Authz( # forceBuild=True, # forceAllBuilds=True, # pingBuilder=True, # gracefulShutdown=True, # stopBuild=True, # stopAllBuilds=True, # cancelPendingBuild=True, # cleanShutdown=True, # ) def get_status(): return [ html.WebStatus( http_port = '8010', # authz = authz, order_console_by_time = True, revlink = 'http://code.djangoproject.com/changeset/%s', changecommentlink = ( r'\b#(\d+)\b', r'http://code.djangoproject.com/ticket/\1', r'Ticket \g<0>' ) ), words.IRC( host = 'irc.freenode.net', channels = ['#revsys'], nick = 'djangobuilds', notify_events = { 'successToFailure': True, 'failureToSuccess': True, } ) ]
from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth def get_status(): return [ html.WebStatus( http_port = '8010', # authz = authz, order_console_by_time = True, revlink = 'http://code.djangoproject.com/changeset/%s', changecommentlink = ( r'\b#(\d+)\b', r'http://code.djangoproject.com/ticket/\1', r'Ticket \g<0>' ) ), ]
Remove the IRC bot for now, and also the commented-out code.
Remove the IRC bot for now, and also the commented-out code.
Python
bsd-3-clause
hochanh/django-buildmaster,jacobian-archive/django-buildmaster
from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth - - # authz = Authz( - # forceBuild=True, - # forceAllBuilds=True, - # pingBuilder=True, - # gracefulShutdown=True, - # stopBuild=True, - # stopAllBuilds=True, - # cancelPendingBuild=True, - # cleanShutdown=True, - # ) def get_status(): return [ html.WebStatus( http_port = '8010', # authz = authz, order_console_by_time = True, revlink = 'http://code.djangoproject.com/changeset/%s', changecommentlink = ( r'\b#(\d+)\b', r'http://code.djangoproject.com/ticket/\1', r'Ticket \g<0>' ) ), - - words.IRC( - host = 'irc.freenode.net', - channels = ['#revsys'], - nick = 'djangobuilds', - notify_events = { - 'successToFailure': True, - 'failureToSuccess': True, - } - ) ]
Remove the IRC bot for now, and also the commented-out code.
## Code Before: from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth # authz = Authz( # forceBuild=True, # forceAllBuilds=True, # pingBuilder=True, # gracefulShutdown=True, # stopBuild=True, # stopAllBuilds=True, # cancelPendingBuild=True, # cleanShutdown=True, # ) def get_status(): return [ html.WebStatus( http_port = '8010', # authz = authz, order_console_by_time = True, revlink = 'http://code.djangoproject.com/changeset/%s', changecommentlink = ( r'\b#(\d+)\b', r'http://code.djangoproject.com/ticket/\1', r'Ticket \g<0>' ) ), words.IRC( host = 'irc.freenode.net', channels = ['#revsys'], nick = 'djangobuilds', notify_events = { 'successToFailure': True, 'failureToSuccess': True, } ) ] ## Instruction: Remove the IRC bot for now, and also the commented-out code. ## Code After: from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth def get_status(): return [ html.WebStatus( http_port = '8010', # authz = authz, order_console_by_time = True, revlink = 'http://code.djangoproject.com/changeset/%s', changecommentlink = ( r'\b#(\d+)\b', r'http://code.djangoproject.com/ticket/\1', r'Ticket \g<0>' ) ), ]
... from buildbot.status.web.auth import BasicAuth ... ), ] ...
47ddf999dd7ef8cd7600710ad6ad7611dd55a218
bin/testNetwork.py
bin/testNetwork.py
import subprocess import os from time import sleep env = {} HOME = os.environ.get("HOME", "/root") scannerConf = open(HOME+"/scanner.conf", "rt") while True: in_line = scannerConf.readline() if not in_line: break in_line = in_line[:-1] key, value = in_line.split("=") env[key] = value scannerConf.close() GATEWAY = '192.168.1.1' if env['GATEWAY']: GATEWAY = env['GATEWAY'] IFACE = 'wlan0' if env['IFACE']: IFACE = env['IFACE'] print("Testing GATEWAY=%s, IFACE=%s" % (GATEWAY, IFACE)) while True: ret = subprocess.call(['/bin/ping','-I', IFACE, '-nc4', GATEWAY]) if ret == 0: print("Network appears to be up") else: print("Network appears to be down, restarting...") ret = subprocess.call(['/sbin/ifdown', '--force', IFACE]) ret = subprocess.call(['/sbin/ifup', IFACE]) sleep(60)
import subprocess import os from time import sleep env = {} HOME = os.environ.get("HOME", "/root") scannerConf = open(HOME+"/scanner.conf", "rt") while True: in_line = scannerConf.readline() if not in_line: break in_line = in_line[:-1] key, value = in_line.split("=") env[key] = value scannerConf.close() GATEWAY = '192.168.1.1' if 'GATEWAY' in env: GATEWAY = env['GATEWAY'] IFACE = 'wlan0' if 'IFACE' in env: IFACE = env['IFACE'] print("Testing GATEWAY=%s, IFACE=%s" % (GATEWAY, IFACE)) while True: ret = subprocess.call(['/bin/ping','-I', IFACE, '-nc4', GATEWAY]) if ret == 0: print("Network appears to be up") else: print("Network appears to be down, restarting...") ret = subprocess.call(['/sbin/ifdown', '--force', IFACE]) ret = subprocess.call(['/sbin/ifup', IFACE]) sleep(60)
Change the config dictionary key validation
Change the config dictionary key validation
Python
apache-2.0
starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser
import subprocess import os from time import sleep env = {} HOME = os.environ.get("HOME", "/root") scannerConf = open(HOME+"/scanner.conf", "rt") while True: in_line = scannerConf.readline() if not in_line: break in_line = in_line[:-1] key, value = in_line.split("=") env[key] = value scannerConf.close() GATEWAY = '192.168.1.1' - if env['GATEWAY']: + if 'GATEWAY' in env: GATEWAY = env['GATEWAY'] IFACE = 'wlan0' - if env['IFACE']: + if 'IFACE' in env: IFACE = env['IFACE'] print("Testing GATEWAY=%s, IFACE=%s" % (GATEWAY, IFACE)) while True: ret = subprocess.call(['/bin/ping','-I', IFACE, '-nc4', GATEWAY]) if ret == 0: print("Network appears to be up") else: print("Network appears to be down, restarting...") ret = subprocess.call(['/sbin/ifdown', '--force', IFACE]) ret = subprocess.call(['/sbin/ifup', IFACE]) sleep(60)
Change the config dictionary key validation
## Code Before: import subprocess import os from time import sleep env = {} HOME = os.environ.get("HOME", "/root") scannerConf = open(HOME+"/scanner.conf", "rt") while True: in_line = scannerConf.readline() if not in_line: break in_line = in_line[:-1] key, value = in_line.split("=") env[key] = value scannerConf.close() GATEWAY = '192.168.1.1' if env['GATEWAY']: GATEWAY = env['GATEWAY'] IFACE = 'wlan0' if env['IFACE']: IFACE = env['IFACE'] print("Testing GATEWAY=%s, IFACE=%s" % (GATEWAY, IFACE)) while True: ret = subprocess.call(['/bin/ping','-I', IFACE, '-nc4', GATEWAY]) if ret == 0: print("Network appears to be up") else: print("Network appears to be down, restarting...") ret = subprocess.call(['/sbin/ifdown', '--force', IFACE]) ret = subprocess.call(['/sbin/ifup', IFACE]) sleep(60) ## Instruction: Change the config dictionary key validation ## Code After: import subprocess import os from time import sleep env = {} HOME = os.environ.get("HOME", "/root") scannerConf = open(HOME+"/scanner.conf", "rt") while True: in_line = scannerConf.readline() if not in_line: break in_line = in_line[:-1] key, value = in_line.split("=") env[key] = value scannerConf.close() GATEWAY = '192.168.1.1' if 'GATEWAY' in env: GATEWAY = env['GATEWAY'] IFACE = 'wlan0' if 'IFACE' in env: IFACE = env['IFACE'] print("Testing GATEWAY=%s, IFACE=%s" % (GATEWAY, IFACE)) while True: ret = subprocess.call(['/bin/ping','-I', IFACE, '-nc4', GATEWAY]) if ret == 0: print("Network appears to be up") else: print("Network appears to be down, restarting...") ret = subprocess.call(['/sbin/ifdown', '--force', IFACE]) ret = subprocess.call(['/sbin/ifup', IFACE]) sleep(60)
// ... existing code ... GATEWAY = '192.168.1.1' if 'GATEWAY' in env: GATEWAY = env['GATEWAY'] // ... modified code ... IFACE = 'wlan0' if 'IFACE' in env: IFACE = env['IFACE'] // ... rest of the code ...
47310125c53d80e4ff09af6616955ccb2d9e3bc8
conanfile.py
conanfile.py
from conans import ConanFile, CMake class ConanUsingSilicium(ConanFile): settings = "os", "compiler", "build_type", "arch" requires = "Boost/1.59.0@lasote/stable", "silicium/0.1@tyroxx/testing" generators = "cmake" default_options = "Boost:shared=True"
from conans import ConanFile, CMake class ConanUsingSilicium(ConanFile): settings = "os", "compiler", "build_type", "arch" requires = "silicium/0.1@tyroxx/testing" generators = "cmake" default_options = "Boost:shared=True"
Boost should be referenced automatically by silicium
Boost should be referenced automatically by silicium
Python
mit
TyRoXx/conan_using_silicium,TyRoXx/conan_using_silicium
from conans import ConanFile, CMake class ConanUsingSilicium(ConanFile): settings = "os", "compiler", "build_type", "arch" - requires = "Boost/1.59.0@lasote/stable", "silicium/0.1@tyroxx/testing" + requires = "silicium/0.1@tyroxx/testing" generators = "cmake" default_options = "Boost:shared=True"
Boost should be referenced automatically by silicium
## Code Before: from conans import ConanFile, CMake class ConanUsingSilicium(ConanFile): settings = "os", "compiler", "build_type", "arch" requires = "Boost/1.59.0@lasote/stable", "silicium/0.1@tyroxx/testing" generators = "cmake" default_options = "Boost:shared=True" ## Instruction: Boost should be referenced automatically by silicium ## Code After: from conans import ConanFile, CMake class ConanUsingSilicium(ConanFile): settings = "os", "compiler", "build_type", "arch" requires = "silicium/0.1@tyroxx/testing" generators = "cmake" default_options = "Boost:shared=True"
# ... existing code ... settings = "os", "compiler", "build_type", "arch" requires = "silicium/0.1@tyroxx/testing" generators = "cmake" # ... rest of the code ...
73a4aca6e9c0c4c9ef53e498319bf754c6bb8edb
rippl/rippl/urls.py
rippl/rippl/urls.py
"""rippl URL Configuration""" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from .registration.forms import RecaptchaRegView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/register/$', RecaptchaRegView.as_view()), url(r'^accounts/', include('registration.backends.simple.urls')), url(r'^$', TemplateView.as_view(template_name='index.html')), url(r'^mission_statement', TemplateView.as_view(template_name='mission_statement.html')), url(r'^legislature/', include('legislature.urls')), ]
"""rippl URL Configuration""" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from .registration.forms import RecaptchaRegView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/register/$', RecaptchaRegView.as_view()), url(r'^accounts/', include('registration.backends.simple.urls')), url(r'^$', TemplateView.as_view(template_name='index.html')), url( r'^mission_statement', TemplateView.as_view(template_name='mission_statement.html'), ), url(r'^legislature/', include('legislature.urls')), ]
Fix line length to pass CI
Fix line length to pass CI
Python
mit
gnmerritt/dailyrippl,gnmerritt/dailyrippl,gnmerritt/dailyrippl,gnmerritt/dailyrippl
"""rippl URL Configuration""" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from .registration.forms import RecaptchaRegView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/register/$', RecaptchaRegView.as_view()), url(r'^accounts/', include('registration.backends.simple.urls')), url(r'^$', TemplateView.as_view(template_name='index.html')), + url( + r'^mission_statement', - url(r'^mission_statement', TemplateView.as_view(template_name='mission_statement.html')), + TemplateView.as_view(template_name='mission_statement.html'), + ), url(r'^legislature/', include('legislature.urls')), ]
Fix line length to pass CI
## Code Before: """rippl URL Configuration""" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from .registration.forms import RecaptchaRegView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/register/$', RecaptchaRegView.as_view()), url(r'^accounts/', include('registration.backends.simple.urls')), url(r'^$', TemplateView.as_view(template_name='index.html')), url(r'^mission_statement', TemplateView.as_view(template_name='mission_statement.html')), url(r'^legislature/', include('legislature.urls')), ] ## Instruction: Fix line length to pass CI ## Code After: """rippl URL Configuration""" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from .registration.forms import RecaptchaRegView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/register/$', RecaptchaRegView.as_view()), url(r'^accounts/', include('registration.backends.simple.urls')), url(r'^$', TemplateView.as_view(template_name='index.html')), url( r'^mission_statement', TemplateView.as_view(template_name='mission_statement.html'), ), url(r'^legislature/', include('legislature.urls')), ]
// ... existing code ... url(r'^$', TemplateView.as_view(template_name='index.html')), url( r'^mission_statement', TemplateView.as_view(template_name='mission_statement.html'), ), // ... rest of the code ...
69e8798137ca63b78adf0c41582e89973d2ea129
create.py
create.py
import os import sys base_path = os.path.dirname(__file__) sys.path.append(base_path) one_up_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..')) sys.path.append(one_up_path) import model_creator import util_functions def create(text,score,prompt_string,model_path): model_path=util_functions.create_model_path(model_path) results = {'errors': [],'created' : False} try: e_set = model_creator.create_essay_set(text, score, prompt_string) except: results['errors'].append("essay set creation failed.") try: feature_ext, classifier = model_creator.extract_features_and_generate_model(e_set) except: results['errors'].append("feature extraction and model creation failed.") try: util_functions.create_directory(model_path) model_creator.dump_model_to_file(prompt_string, feature_ext, classifier, text, score, args.model_path) results['created']=True except: results['errors'].append("could not write model to: {0}".format(model_path)) return results def check(model_path): model_path=util_functions.create_model_path(model_path) try: with open(model_path) as f: pass except IOError as e: return False return True
import os import sys base_path = os.path.dirname(__file__) sys.path.append(base_path) one_up_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..')) sys.path.append(one_up_path) import model_creator import util_functions def create(text,score,prompt_string,model_path): model_path=util_functions.create_model_path(model_path) results = {'errors': [],'created' : False} try: e_set = model_creator.create_essay_set(text, score, prompt_string) except: results['errors'].append("essay set creation failed.") try: feature_ext, classifier = model_creator.extract_features_and_generate_model(e_set) except: results['errors'].append("feature extraction and model creation failed.") full_path=os.path.join(base_path,model_path) util_functions.create_directory(full_path) model_creator.dump_model_to_file(prompt_string, feature_ext, classifier, text, score, full_path) results['created']=True """ except: results['errors'].append("could not write model to: {0}".format(model_path)) """ return results def check(model_path): model_path=util_functions.create_model_path(model_path) try: with open(model_path) as f: pass except IOError as e: return False return True
Work on model file handling
Work on model file handling
Python
agpl-3.0
edx/ease,edx/ease
import os import sys base_path = os.path.dirname(__file__) sys.path.append(base_path) one_up_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..')) sys.path.append(one_up_path) import model_creator import util_functions def create(text,score,prompt_string,model_path): model_path=util_functions.create_model_path(model_path) results = {'errors': [],'created' : False} try: e_set = model_creator.create_essay_set(text, score, prompt_string) except: results['errors'].append("essay set creation failed.") try: feature_ext, classifier = model_creator.extract_features_and_generate_model(e_set) except: results['errors'].append("feature extraction and model creation failed.") - try: + + full_path=os.path.join(base_path,model_path) - util_functions.create_directory(model_path) + util_functions.create_directory(full_path) - model_creator.dump_model_to_file(prompt_string, feature_ext, classifier, text, score, args.model_path) + model_creator.dump_model_to_file(prompt_string, feature_ext, classifier, text, score, full_path) - results['created']=True + results['created']=True + """ except: results['errors'].append("could not write model to: {0}".format(model_path)) + """ return results def check(model_path): model_path=util_functions.create_model_path(model_path) try: with open(model_path) as f: pass except IOError as e: return False return True
Work on model file handling
## Code Before: import os import sys base_path = os.path.dirname(__file__) sys.path.append(base_path) one_up_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..')) sys.path.append(one_up_path) import model_creator import util_functions def create(text,score,prompt_string,model_path): model_path=util_functions.create_model_path(model_path) results = {'errors': [],'created' : False} try: e_set = model_creator.create_essay_set(text, score, prompt_string) except: results['errors'].append("essay set creation failed.") try: feature_ext, classifier = model_creator.extract_features_and_generate_model(e_set) except: results['errors'].append("feature extraction and model creation failed.") try: util_functions.create_directory(model_path) model_creator.dump_model_to_file(prompt_string, feature_ext, classifier, text, score, args.model_path) results['created']=True except: results['errors'].append("could not write model to: {0}".format(model_path)) return results def check(model_path): model_path=util_functions.create_model_path(model_path) try: with open(model_path) as f: pass except IOError as e: return False return True ## Instruction: Work on model file handling ## Code After: import os import sys base_path = os.path.dirname(__file__) sys.path.append(base_path) one_up_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..')) sys.path.append(one_up_path) import model_creator import util_functions def create(text,score,prompt_string,model_path): model_path=util_functions.create_model_path(model_path) results = {'errors': [],'created' : False} try: e_set = model_creator.create_essay_set(text, score, prompt_string) except: results['errors'].append("essay set creation failed.") try: feature_ext, classifier = model_creator.extract_features_and_generate_model(e_set) except: results['errors'].append("feature extraction and model creation failed.") full_path=os.path.join(base_path,model_path) util_functions.create_directory(full_path) model_creator.dump_model_to_file(prompt_string, feature_ext, classifier, text, score, full_path) results['created']=True """ except: results['errors'].append("could not write model to: {0}".format(model_path)) """ return results def check(model_path): model_path=util_functions.create_model_path(model_path) try: with open(model_path) as f: pass except IOError as e: return False return True
# ... existing code ... results['errors'].append("feature extraction and model creation failed.") full_path=os.path.join(base_path,model_path) util_functions.create_directory(full_path) model_creator.dump_model_to_file(prompt_string, feature_ext, classifier, text, score, full_path) results['created']=True """ except: # ... modified code ... results['errors'].append("could not write model to: {0}".format(model_path)) """ # ... rest of the code ...
574b4d95a48f4df676ed5f23f0c83a9df2bc241d
pydux/log_middleware.py
pydux/log_middleware.py
def log_middleware(store): """log all actions to console as they are dispatched""" def wrapper(next_): def log_dispatch(action): print('Dispatch Action:', action) return next_(action) return log_dispatch return wrapper
from __future__ import print_function """ logging middleware example """ def log_middleware(store): """log all actions to console as they are dispatched""" def wrapper(next_): def log_dispatch(action): print('Dispatch Action:', action) return next_(action) return log_dispatch return wrapper
Use from __future__ import for print function
Use from __future__ import for print function
Python
mit
usrlocalben/pydux
- + from __future__ import print_function + """ + logging middleware example + """ def log_middleware(store): """log all actions to console as they are dispatched""" def wrapper(next_): def log_dispatch(action): print('Dispatch Action:', action) return next_(action) return log_dispatch return wrapper
Use from __future__ import for print function
## Code Before: def log_middleware(store): """log all actions to console as they are dispatched""" def wrapper(next_): def log_dispatch(action): print('Dispatch Action:', action) return next_(action) return log_dispatch return wrapper ## Instruction: Use from __future__ import for print function ## Code After: from __future__ import print_function """ logging middleware example """ def log_middleware(store): """log all actions to console as they are dispatched""" def wrapper(next_): def log_dispatch(action): print('Dispatch Action:', action) return next_(action) return log_dispatch return wrapper
# ... existing code ... from __future__ import print_function """ logging middleware example """ # ... rest of the code ...
2f2ae3308256d2233e0363cb46ee88067da54b4b
modules/roles.py
modules/roles.py
import discord import shlex rolesTriggerString = '!role' # String to listen for as trigger async def parse_roles_command(message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i,x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is if len(msg) != 1: try: await client.add_roles(message.author,message.server.roles[role[0]]) except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." client.send_message(message.channel, msg) else: pass
import discord import shlex rolesTriggerString = '!role' # String to listen for as trigger async def parse_roles_command(message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i,x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author,role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign + " ." else: await client.add_roles(message.author,role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass
Add role removal and logic cleanup
Add role removal and logic cleanup
Python
mit
suclearnub/scubot
import discord import shlex rolesTriggerString = '!role' # String to listen for as trigger async def parse_roles_command(message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i,x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is + role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: + if role_to_assign in message.author.roles: + await client.remove_roles(message.author,role_to_assign) + msg = ":ok_hand: Removed you from " + role_to_assign + " ." + else: - await client.add_roles(message.author,message.server.roles[role[0]]) + await client.add_roles(message.author,role_to_assign) + msg = ":ok_hand: Added you to " + role_to_assign + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." - client.send_message(message.channel, msg) + await client.send_message(message.channel, msg) else: pass
Add role removal and logic cleanup
## Code Before: import discord import shlex rolesTriggerString = '!role' # String to listen for as trigger async def parse_roles_command(message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i,x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is if len(msg) != 1: try: await client.add_roles(message.author,message.server.roles[role[0]]) except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." client.send_message(message.channel, msg) else: pass ## Instruction: Add role removal and logic cleanup ## Code After: import discord import shlex rolesTriggerString = '!role' # String to listen for as trigger async def parse_roles_command(message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg = shlex.split(message.content) role = [i for i,x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: try: if role_to_assign in message.author.roles: await client.remove_roles(message.author,role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign + " ." else: await client.add_roles(message.author,role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign + " ." except discord.DiscordException: msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: pass
# ... existing code ... role = [i for i,x in enumerate(server_roles_str) if x == msg[1]] # Check where in the list the role is role_to_assign = message.server.roles[role[0]] if len(msg) != 1: # ... modified code ... try: if role_to_assign in message.author.roles: await client.remove_roles(message.author,role_to_assign) msg = ":ok_hand: Removed you from " + role_to_assign + " ." else: await client.add_roles(message.author,role_to_assign) msg = ":ok_hand: Added you to " + role_to_assign + " ." except discord.DiscordException: ... msg = "I'm sorry " + message.author.name + " ,I'm afraid I can't do that." await client.send_message(message.channel, msg) else: # ... rest of the code ...
719037cf20ae17e5fba71136cad1db7e8a47f703
spacy/lang/fi/examples.py
spacy/lang/fi/examples.py
from __future__ import unicode_literals """ Example sentences to test spaCy and its language models. >>> from spacy.lang.tr.examples import sentences >>> docs = nlp.pipe(sentences) """ sentences = [ "Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla." "Itseajavat autot siirtävät vakuutusriskin valmistajille." "San Francisco harkitsee jakelurobottien kieltämistä jalkakäytävillä." "Lontoo on iso kaupunki Iso-Britanniassa." ]
from __future__ import unicode_literals """ Example sentences to test spaCy and its language models. >>> from spacy.lang.fi.examples import sentences >>> docs = nlp.pipe(sentences) """ sentences = [ "Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla.", "Itseajavat autot siirtävät vakuutusriskin valmistajille.", "San Francisco harkitsee jakelurobottien kieltämistä jalkakäytävillä.", "Lontoo on iso kaupunki Iso-Britanniassa." ]
Update formatting and add missing commas
Update formatting and add missing commas
Python
mit
recognai/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy
from __future__ import unicode_literals """ Example sentences to test spaCy and its language models. - >>> from spacy.lang.tr.examples import sentences + >>> from spacy.lang.fi.examples import sentences >>> docs = nlp.pipe(sentences) """ sentences = [ - "Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla." + "Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla.", - "Itseajavat autot siirtävät vakuutusriskin valmistajille." + "Itseajavat autot siirtävät vakuutusriskin valmistajille.", - "San Francisco harkitsee jakelurobottien kieltämistä jalkakäytävillä." + "San Francisco harkitsee jakelurobottien kieltämistä jalkakäytävillä.", - "Lontoo on iso kaupunki Iso-Britanniassa." + "Lontoo on iso kaupunki Iso-Britanniassa." ]
Update formatting and add missing commas
## Code Before: from __future__ import unicode_literals """ Example sentences to test spaCy and its language models. >>> from spacy.lang.tr.examples import sentences >>> docs = nlp.pipe(sentences) """ sentences = [ "Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla." "Itseajavat autot siirtävät vakuutusriskin valmistajille." "San Francisco harkitsee jakelurobottien kieltämistä jalkakäytävillä." "Lontoo on iso kaupunki Iso-Britanniassa." ] ## Instruction: Update formatting and add missing commas ## Code After: from __future__ import unicode_literals """ Example sentences to test spaCy and its language models. >>> from spacy.lang.fi.examples import sentences >>> docs = nlp.pipe(sentences) """ sentences = [ "Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla.", "Itseajavat autot siirtävät vakuutusriskin valmistajille.", "San Francisco harkitsee jakelurobottien kieltämistä jalkakäytävillä.", "Lontoo on iso kaupunki Iso-Britanniassa." ]
// ... existing code ... Example sentences to test spaCy and its language models. >>> from spacy.lang.fi.examples import sentences >>> docs = nlp.pipe(sentences) // ... modified code ... sentences = [ "Apple harkitsee ostavansa startup-yrityksen UK:sta 1 miljardilla dollarilla.", "Itseajavat autot siirtävät vakuutusriskin valmistajille.", "San Francisco harkitsee jakelurobottien kieltämistä jalkakäytävillä.", "Lontoo on iso kaupunki Iso-Britanniassa." ] // ... rest of the code ...
37dc483fd381aa14eddddb13c991bbf647bb747b
data/global-configuration/packs/core-functions/module/node.py
data/global-configuration/packs/core-functions/module/node.py
from opsbro.evaluater import export_evaluater_function from opsbro.gossip import gossiper FUNCTION_GROUP = 'gossip' @export_evaluater_function(function_group=FUNCTION_GROUP) def is_in_group(group): """**is_in_group(group)** -> return True if the node have the group, False otherwise. * group: (string) group to check. <code> Example: is_in_group('linux') Returns: True </code> """ return gossiper.is_in_group(group)
from opsbro.evaluater import export_evaluater_function from opsbro.gossip import gossiper FUNCTION_GROUP = 'gossip' @export_evaluater_function(function_group=FUNCTION_GROUP) def is_in_group(group): """**is_in_group(group)** -> return True if the node have the group, False otherwise. * group: (string) group to check. <code> Example: is_in_group('linux') Returns: True </code> """ return gossiper.is_in_group(group) @export_evaluater_function(function_group=FUNCTION_GROUP) def is_in_defined_group(group): """**is_in_defined_group(group)** -> return True if the node have the group but was set in the configuration, not from discovery False otherwise. * group: (string) group to check. <code> Example: is_in_defined_group('linux') Returns: True </code> """ return gossiper.is_in_group(group)
Declare the is_in_defined_group function, even if it is an alias of the is_in_group
Enh: Declare the is_in_defined_group function, even if it is an alias of the is_in_group
Python
mit
naparuba/kunai,naparuba/kunai,naparuba/opsbro,naparuba/kunai,naparuba/kunai,naparuba/kunai,naparuba/opsbro,naparuba/opsbro,naparuba/kunai,naparuba/opsbro
from opsbro.evaluater import export_evaluater_function from opsbro.gossip import gossiper FUNCTION_GROUP = 'gossip' @export_evaluater_function(function_group=FUNCTION_GROUP) def is_in_group(group): """**is_in_group(group)** -> return True if the node have the group, False otherwise. * group: (string) group to check. <code> Example: is_in_group('linux') Returns: True </code> """ return gossiper.is_in_group(group) + + @export_evaluater_function(function_group=FUNCTION_GROUP) + def is_in_defined_group(group): + """**is_in_defined_group(group)** -> return True if the node have the group but was set in the configuration, not from discovery False otherwise. + + * group: (string) group to check. + + + <code> + Example: + is_in_defined_group('linux') + Returns: + True + </code> + """ + return gossiper.is_in_group(group) +
Declare the is_in_defined_group function, even if it is an alias of the is_in_group
## Code Before: from opsbro.evaluater import export_evaluater_function from opsbro.gossip import gossiper FUNCTION_GROUP = 'gossip' @export_evaluater_function(function_group=FUNCTION_GROUP) def is_in_group(group): """**is_in_group(group)** -> return True if the node have the group, False otherwise. * group: (string) group to check. <code> Example: is_in_group('linux') Returns: True </code> """ return gossiper.is_in_group(group) ## Instruction: Declare the is_in_defined_group function, even if it is an alias of the is_in_group ## Code After: from opsbro.evaluater import export_evaluater_function from opsbro.gossip import gossiper FUNCTION_GROUP = 'gossip' @export_evaluater_function(function_group=FUNCTION_GROUP) def is_in_group(group): """**is_in_group(group)** -> return True if the node have the group, False otherwise. * group: (string) group to check. <code> Example: is_in_group('linux') Returns: True </code> """ return gossiper.is_in_group(group) @export_evaluater_function(function_group=FUNCTION_GROUP) def is_in_defined_group(group): """**is_in_defined_group(group)** -> return True if the node have the group but was set in the configuration, not from discovery False otherwise. * group: (string) group to check. <code> Example: is_in_defined_group('linux') Returns: True </code> """ return gossiper.is_in_group(group)
# ... existing code ... return gossiper.is_in_group(group) @export_evaluater_function(function_group=FUNCTION_GROUP) def is_in_defined_group(group): """**is_in_defined_group(group)** -> return True if the node have the group but was set in the configuration, not from discovery False otherwise. * group: (string) group to check. <code> Example: is_in_defined_group('linux') Returns: True </code> """ return gossiper.is_in_group(group) # ... rest of the code ...
e90afe565a4d54e7fb81b4fbd29d44525b81aa89
data_structs/queue.py
data_structs/queue.py
''' Linear queue ''' class Queue: def __init__(self): self.items = list() def is_Empty(self): return self.items == [] def size(self): return len(self.items) def set(self, item): self.Queue.insert(0, item) def get(self): return self.items.pop() def main(): pass if __name__ == '__main__': main()
''' Linear queue ''' class Queue: def __init__(self, items=[]): self.items = items def is_Empty(self): return self.items == [] def size(self): return len(self.items) def enqueue(self, item): self.Queue.insert(0, item) def dequeue(self): return self.items.pop() def main(): pass if __name__ == '__main__': main()
Add default values and changed names for getter and setter
LinearQueue: Add default values and changed names for getter and setter
Python
apache-2.0
fedusia/python
''' Linear queue ''' class Queue: - def __init__(self): + def __init__(self, items=[]): - self.items = list() + self.items = items def is_Empty(self): return self.items == [] def size(self): return len(self.items) - def set(self, item): + def enqueue(self, item): self.Queue.insert(0, item) - def get(self): + def dequeue(self): return self.items.pop() def main(): pass if __name__ == '__main__': main()
Add default values and changed names for getter and setter
## Code Before: ''' Linear queue ''' class Queue: def __init__(self): self.items = list() def is_Empty(self): return self.items == [] def size(self): return len(self.items) def set(self, item): self.Queue.insert(0, item) def get(self): return self.items.pop() def main(): pass if __name__ == '__main__': main() ## Instruction: Add default values and changed names for getter and setter ## Code After: ''' Linear queue ''' class Queue: def __init__(self, items=[]): self.items = items def is_Empty(self): return self.items == [] def size(self): return len(self.items) def enqueue(self, item): self.Queue.insert(0, item) def dequeue(self): return self.items.pop() def main(): pass if __name__ == '__main__': main()
// ... existing code ... class Queue: def __init__(self, items=[]): self.items = items // ... modified code ... def enqueue(self, item): self.Queue.insert(0, item) ... def dequeue(self): return self.items.pop() // ... rest of the code ...
20e8ef6bd68100a70b9d50013630ff71d8b7ec94
changes/artifacts/__init__.py
changes/artifacts/__init__.py
from __future__ import absolute_import, print_function from .manager import Manager from .coverage import CoverageHandler from .xunit import XunitHandler manager = Manager() manager.register(CoverageHandler, ['coverage.xml']) manager.register(XunitHandler, ['xunit.xml', 'junit.xml'])
from __future__ import absolute_import, print_function from .manager import Manager from .coverage import CoverageHandler from .xunit import XunitHandler manager = Manager() manager.register(CoverageHandler, ['coverage.xml', '*.coverage.xml']) manager.register(XunitHandler, ['xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml'])
Support wildcard matches on coverage/junit results
Support wildcard matches on coverage/junit results
Python
apache-2.0
dropbox/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes
from __future__ import absolute_import, print_function from .manager import Manager from .coverage import CoverageHandler from .xunit import XunitHandler manager = Manager() - manager.register(CoverageHandler, ['coverage.xml']) + manager.register(CoverageHandler, ['coverage.xml', '*.coverage.xml']) - manager.register(XunitHandler, ['xunit.xml', 'junit.xml']) + manager.register(XunitHandler, ['xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml'])
Support wildcard matches on coverage/junit results
## Code Before: from __future__ import absolute_import, print_function from .manager import Manager from .coverage import CoverageHandler from .xunit import XunitHandler manager = Manager() manager.register(CoverageHandler, ['coverage.xml']) manager.register(XunitHandler, ['xunit.xml', 'junit.xml']) ## Instruction: Support wildcard matches on coverage/junit results ## Code After: from __future__ import absolute_import, print_function from .manager import Manager from .coverage import CoverageHandler from .xunit import XunitHandler manager = Manager() manager.register(CoverageHandler, ['coverage.xml', '*.coverage.xml']) manager.register(XunitHandler, ['xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml'])
... manager = Manager() manager.register(CoverageHandler, ['coverage.xml', '*.coverage.xml']) manager.register(XunitHandler, ['xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml']) ...
5bad3f45bdca436515b416bbcfb45ca53b46ca2a
application/lomadee/data_importer.py
application/lomadee/data_importer.py
from django.conf import settings from urllib.parse import urljoin, urlencode class ComputerDataImporter(object): def __init__(self): pass def build_api_url(self, **kwargs): api_url = urljoin(settings.LOMADEE_API_URL, settings.LOMADEE_APP_TOKEN) # Specific path to 'Computer' category url = urljoin(api_url, 'offer/_category/6424') kwargs['sourceId'] = settings.LOMADEE_SOURCE_ID return '{}?{}'.format(url, urlencode(kwargs))
from django.conf import settings from urllib.parse import urljoin, urlencode import requests class ComputerDataImporter(object): def __init__(self): pass def build_api_url(self, **kwargs): api_url = urljoin(settings.LOMADEE_API_URL, settings.LOMADEE_APP_TOKEN) # Specific path to 'Computer' category url = urljoin('{}/'.format(api_url), 'offer/_category/6424') kwargs['sourceId'] = settings.LOMADEE_SOURCE_ID kwargs['size'] = 100 return '{}?{}'.format(url, urlencode(kwargs)) def get_data(self, url=None): if not url: url = self.build_api_url() data = requests.get(url).json() if data['requestInfo']['status'] != 'OK': return False final_data = [] final_data.extend(data['offers']) pagination = data['pagination'] # Get only 3 pages. To get all pages use: # if pagination['page'] < pagination['totalPage'] if pagination['page'] < 3: next_page_data = self.get_data( self.build_api_url(page=pagination['page'] + 1) ) final_data.extend(next_page_data) return final_data
Add get_data method to data importer
Add get_data method to data importer Signed-off-by: Matheus Fernandes <[email protected]>
Python
mit
msfernandes/facebook-chatbot
from django.conf import settings from urllib.parse import urljoin, urlencode + import requests class ComputerDataImporter(object): def __init__(self): pass def build_api_url(self, **kwargs): api_url = urljoin(settings.LOMADEE_API_URL, settings.LOMADEE_APP_TOKEN) # Specific path to 'Computer' category - url = urljoin(api_url, 'offer/_category/6424') + url = urljoin('{}/'.format(api_url), 'offer/_category/6424') kwargs['sourceId'] = settings.LOMADEE_SOURCE_ID + kwargs['size'] = 100 return '{}?{}'.format(url, urlencode(kwargs)) + def get_data(self, url=None): + if not url: + url = self.build_api_url() + + data = requests.get(url).json() + if data['requestInfo']['status'] != 'OK': + return False + + final_data = [] + final_data.extend(data['offers']) + pagination = data['pagination'] + + # Get only 3 pages. To get all pages use: + # if pagination['page'] < pagination['totalPage'] + if pagination['page'] < 3: + next_page_data = self.get_data( + self.build_api_url(page=pagination['page'] + 1) + ) + final_data.extend(next_page_data) + return final_data +
Add get_data method to data importer
## Code Before: from django.conf import settings from urllib.parse import urljoin, urlencode class ComputerDataImporter(object): def __init__(self): pass def build_api_url(self, **kwargs): api_url = urljoin(settings.LOMADEE_API_URL, settings.LOMADEE_APP_TOKEN) # Specific path to 'Computer' category url = urljoin(api_url, 'offer/_category/6424') kwargs['sourceId'] = settings.LOMADEE_SOURCE_ID return '{}?{}'.format(url, urlencode(kwargs)) ## Instruction: Add get_data method to data importer ## Code After: from django.conf import settings from urllib.parse import urljoin, urlencode import requests class ComputerDataImporter(object): def __init__(self): pass def build_api_url(self, **kwargs): api_url = urljoin(settings.LOMADEE_API_URL, settings.LOMADEE_APP_TOKEN) # Specific path to 'Computer' category url = urljoin('{}/'.format(api_url), 'offer/_category/6424') kwargs['sourceId'] = settings.LOMADEE_SOURCE_ID kwargs['size'] = 100 return '{}?{}'.format(url, urlencode(kwargs)) def get_data(self, url=None): if not url: url = self.build_api_url() data = requests.get(url).json() if data['requestInfo']['status'] != 'OK': return False final_data = [] final_data.extend(data['offers']) pagination = data['pagination'] # Get only 3 pages. To get all pages use: # if pagination['page'] < pagination['totalPage'] if pagination['page'] < 3: next_page_data = self.get_data( self.build_api_url(page=pagination['page'] + 1) ) final_data.extend(next_page_data) return final_data
// ... existing code ... from urllib.parse import urljoin, urlencode import requests // ... modified code ... # Specific path to 'Computer' category url = urljoin('{}/'.format(api_url), 'offer/_category/6424') kwargs['sourceId'] = settings.LOMADEE_SOURCE_ID kwargs['size'] = 100 ... return '{}?{}'.format(url, urlencode(kwargs)) def get_data(self, url=None): if not url: url = self.build_api_url() data = requests.get(url).json() if data['requestInfo']['status'] != 'OK': return False final_data = [] final_data.extend(data['offers']) pagination = data['pagination'] # Get only 3 pages. To get all pages use: # if pagination['page'] < pagination['totalPage'] if pagination['page'] < 3: next_page_data = self.get_data( self.build_api_url(page=pagination['page'] + 1) ) final_data.extend(next_page_data) return final_data // ... rest of the code ...
a7bea68d4e904a27c53d08d37093ac5ed2c033f0
utilities/StartPages.py
utilities/StartPages.py
import os import re import sys import json from __common__code__ import CreateFile from __tmpl__ import Prompt class PromptClass(Prompt.ErrPrompt): def InitInput(self): print ("Please input URL(s), use EOF to finish. \n(CTRL+D. if not work for Windows, try CTRL+Z)") def main(): prompt = PromptClass() cfgfile = CreateFile('StartPage.json', 'cfg', TransferredMeaning = True, Prompt = True) URL = [] IllegalChars = r"[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\-\.\_\~\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]" try: prompt.InitInput() while True: tmp = raw_input() if re.search(IllegalChars, tmp): prompt.IllegalURL() URL.append(tmp) except EOFError: prompt.Exit() json.dump(URL, cfgfile) cfgfile.close() return if __name__ == '__main__': main() else: raise EnvironmentError("Please do not import this script as a module!")
import re import sys import json from __common__code__ import CreateFile from __tmpl__ import Prompt class PromptClass(Prompt.ErrPrompt): def InitInput(self): print ("Please input URL(s), use EOF to finish. \n(CTRL+D. if not work for Windows, try CTRL+Z)") def main(): prompt = PromptClass() cfgfile = CreateFile('StartPage.json', 'cfg', TransferredMeaning = True, Prompt = True) if not cfgfile: prompt.Exit() sys.exit(False) URL = [] IllegalChars = r"[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\-\.\_\~\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]" try: prompt.InitInput() while True: tmp = raw_input() if re.search(IllegalChars, tmp): prompt.IllegalURL() URL.append(tmp) except EOFError: prompt.Exit() json.dump(URL, cfgfile) cfgfile.close() return if __name__ == '__main__': main() else: raise EnvironmentError("Please do not import this script as a module!")
Fix bug: continue running when fail to open file
Fix bug: continue running when fail to open file
Python
mit
nday-dev/Spider-Framework
- import os import re import sys import json from __common__code__ import CreateFile from __tmpl__ import Prompt class PromptClass(Prompt.ErrPrompt): def InitInput(self): print ("Please input URL(s), use EOF to finish. \n(CTRL+D. if not work for Windows, try CTRL+Z)") def main(): prompt = PromptClass() cfgfile = CreateFile('StartPage.json', 'cfg', TransferredMeaning = True, Prompt = True) + if not cfgfile: + prompt.Exit() + sys.exit(False) URL = [] IllegalChars = r"[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\-\.\_\~\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]" try: prompt.InitInput() while True: tmp = raw_input() if re.search(IllegalChars, tmp): prompt.IllegalURL() URL.append(tmp) except EOFError: prompt.Exit() json.dump(URL, cfgfile) cfgfile.close() return if __name__ == '__main__': main() else: raise EnvironmentError("Please do not import this script as a module!")
Fix bug: continue running when fail to open file
## Code Before: import os import re import sys import json from __common__code__ import CreateFile from __tmpl__ import Prompt class PromptClass(Prompt.ErrPrompt): def InitInput(self): print ("Please input URL(s), use EOF to finish. \n(CTRL+D. if not work for Windows, try CTRL+Z)") def main(): prompt = PromptClass() cfgfile = CreateFile('StartPage.json', 'cfg', TransferredMeaning = True, Prompt = True) URL = [] IllegalChars = r"[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\-\.\_\~\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]" try: prompt.InitInput() while True: tmp = raw_input() if re.search(IllegalChars, tmp): prompt.IllegalURL() URL.append(tmp) except EOFError: prompt.Exit() json.dump(URL, cfgfile) cfgfile.close() return if __name__ == '__main__': main() else: raise EnvironmentError("Please do not import this script as a module!") ## Instruction: Fix bug: continue running when fail to open file ## Code After: import re import sys import json from __common__code__ import CreateFile from __tmpl__ import Prompt class PromptClass(Prompt.ErrPrompt): def InitInput(self): print ("Please input URL(s), use EOF to finish. \n(CTRL+D. if not work for Windows, try CTRL+Z)") def main(): prompt = PromptClass() cfgfile = CreateFile('StartPage.json', 'cfg', TransferredMeaning = True, Prompt = True) if not cfgfile: prompt.Exit() sys.exit(False) URL = [] IllegalChars = r"[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\-\.\_\~\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]" try: prompt.InitInput() while True: tmp = raw_input() if re.search(IllegalChars, tmp): prompt.IllegalURL() URL.append(tmp) except EOFError: prompt.Exit() json.dump(URL, cfgfile) cfgfile.close() return if __name__ == '__main__': main() else: raise EnvironmentError("Please do not import this script as a module!")
... import re ... cfgfile = CreateFile('StartPage.json', 'cfg', TransferredMeaning = True, Prompt = True) if not cfgfile: prompt.Exit() sys.exit(False) URL = [] ...
1b9c4935b2edf6601c2d75d8a2d318266de2d456
circuits/tools/__init__.py
circuits/tools/__init__.py
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def graph(x): s = StringIO() d = 0 i = 0 done = False stack = [] visited = set() children = list(x.components) while not done: if x not in visited: if d: s.write("%s%s\n" % (" " * d, "|")) s.write("%s%s%s\n" % (" " * d, "|-", x)) else: s.write(" .%s\n" % x) if x.components: d += 1 visited.add(x) if i < len(children): x = children[i] i += 1 if x.components: stack.append((i, children)) children = list(x.components) i = 0 else: if stack: i, children = stack.pop() d -= 1 else: done = True return s.getvalue()
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def graph(x): s = StringIO() d = 0 i = 0 done = False stack = [] visited = set() children = list(x.components) while not done: if x not in visited: if d: s.write("%s%s\n" % (" " * d, "|")) s.write("%s%s%s\n" % (" " * d, "|-", x)) else: s.write(" .%s\n" % x) if x.components: d += 1 visited.add(x) if i < len(children): x = children[i] i += 1 if x.components: stack.append((i, d, children)) children = list(x.components) i = 0 else: if stack: i, d, children = stack.pop() else: done = True return s.getvalue()
Store the depth (d) on the stack and restore when backtracking
tools: Store the depth (d) on the stack and restore when backtracking
Python
mit
treemo/circuits,treemo/circuits,eriol/circuits,treemo/circuits,eriol/circuits,nizox/circuits,eriol/circuits
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def graph(x): s = StringIO() d = 0 i = 0 done = False stack = [] visited = set() children = list(x.components) while not done: if x not in visited: if d: s.write("%s%s\n" % (" " * d, "|")) s.write("%s%s%s\n" % (" " * d, "|-", x)) else: s.write(" .%s\n" % x) if x.components: d += 1 visited.add(x) if i < len(children): x = children[i] i += 1 if x.components: - stack.append((i, children)) + stack.append((i, d, children)) children = list(x.components) i = 0 else: if stack: - i, children = stack.pop() + i, d, children = stack.pop() - d -= 1 else: done = True return s.getvalue()
Store the depth (d) on the stack and restore when backtracking
## Code Before: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def graph(x): s = StringIO() d = 0 i = 0 done = False stack = [] visited = set() children = list(x.components) while not done: if x not in visited: if d: s.write("%s%s\n" % (" " * d, "|")) s.write("%s%s%s\n" % (" " * d, "|-", x)) else: s.write(" .%s\n" % x) if x.components: d += 1 visited.add(x) if i < len(children): x = children[i] i += 1 if x.components: stack.append((i, children)) children = list(x.components) i = 0 else: if stack: i, children = stack.pop() d -= 1 else: done = True return s.getvalue() ## Instruction: Store the depth (d) on the stack and restore when backtracking ## Code After: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def graph(x): s = StringIO() d = 0 i = 0 done = False stack = [] visited = set() children = list(x.components) while not done: if x not in visited: if d: s.write("%s%s\n" % (" " * d, "|")) s.write("%s%s%s\n" % (" " * d, "|-", x)) else: s.write(" .%s\n" % x) if x.components: d += 1 visited.add(x) if i < len(children): x = children[i] i += 1 if x.components: stack.append((i, d, children)) children = list(x.components) i = 0 else: if stack: i, d, children = stack.pop() else: done = True return s.getvalue()
// ... existing code ... if x.components: stack.append((i, d, children)) children = list(x.components) // ... modified code ... if stack: i, d, children = stack.pop() else: // ... rest of the code ...
64d6a44ecbbaa7d8ac2c79bd95827ced66254bcf
fireplace/carddata/minions/warlock.py
fireplace/carddata/minions/warlock.py
import random from ..card import * # Blood Imp class CS2_059(Card): def endTurn(self): if self.game.currentPlayer is self.owner: if self.owner.field: random.choice(self.owner.field).buff("CS2_059o") class CS2_059o(Card): health = 1 # Felguard class EX1_301(Card): def activate(self): self.owner.loseMana(1) # Succubus class EX1_306(Card): activate = discard(1) # Doomguard class EX1_310(Card): activate = discard(2) # Pit Lord class EX1_313(Card): def activate(self): self.owner.hero.damage(5) # Flame Imp class EX1_319(Card): def activate(self): self.owner.hero.damage(3)
import random from ..card import * # Blood Imp class CS2_059(Card): def endTurn(self): if self.game.currentPlayer is self.owner: if self.owner.field: random.choice(self.owner.field).buff("CS2_059o") class CS2_059o(Card): health = 1 # Felguard class EX1_301(Card): def activate(self): self.owner.loseMana(1) # Succubus class EX1_306(Card): activate = discard(1) # Doomguard class EX1_310(Card): activate = discard(2) # Pit Lord class EX1_313(Card): def activate(self): self.owner.hero.damage(5) # Flame Imp class EX1_319(Card): def activate(self): self.owner.hero.damage(3) # Lord Jaraxxus class EX1_323(Card): def activate(self): self.removeFromField() self.owner.setHero("EX1_323h")
IMPLEMENT JARAXXUS, EREDAR LORD OF THE BURNING LEGION
IMPLEMENT JARAXXUS, EREDAR LORD OF THE BURNING LEGION
Python
agpl-3.0
butozerca/fireplace,jleclanche/fireplace,amw2104/fireplace,NightKev/fireplace,liujimj/fireplace,amw2104/fireplace,smallnamespace/fireplace,butozerca/fireplace,oftc-ftw/fireplace,beheh/fireplace,Ragowit/fireplace,Meerkov/fireplace,Meerkov/fireplace,oftc-ftw/fireplace,liujimj/fireplace,smallnamespace/fireplace,Ragowit/fireplace
import random from ..card import * # Blood Imp class CS2_059(Card): def endTurn(self): if self.game.currentPlayer is self.owner: if self.owner.field: random.choice(self.owner.field).buff("CS2_059o") class CS2_059o(Card): health = 1 # Felguard class EX1_301(Card): def activate(self): self.owner.loseMana(1) # Succubus class EX1_306(Card): activate = discard(1) # Doomguard class EX1_310(Card): activate = discard(2) # Pit Lord class EX1_313(Card): def activate(self): self.owner.hero.damage(5) # Flame Imp class EX1_319(Card): def activate(self): self.owner.hero.damage(3) + + # Lord Jaraxxus + class EX1_323(Card): + def activate(self): + self.removeFromField() + self.owner.setHero("EX1_323h") +
IMPLEMENT JARAXXUS, EREDAR LORD OF THE BURNING LEGION
## Code Before: import random from ..card import * # Blood Imp class CS2_059(Card): def endTurn(self): if self.game.currentPlayer is self.owner: if self.owner.field: random.choice(self.owner.field).buff("CS2_059o") class CS2_059o(Card): health = 1 # Felguard class EX1_301(Card): def activate(self): self.owner.loseMana(1) # Succubus class EX1_306(Card): activate = discard(1) # Doomguard class EX1_310(Card): activate = discard(2) # Pit Lord class EX1_313(Card): def activate(self): self.owner.hero.damage(5) # Flame Imp class EX1_319(Card): def activate(self): self.owner.hero.damage(3) ## Instruction: IMPLEMENT JARAXXUS, EREDAR LORD OF THE BURNING LEGION ## Code After: import random from ..card import * # Blood Imp class CS2_059(Card): def endTurn(self): if self.game.currentPlayer is self.owner: if self.owner.field: random.choice(self.owner.field).buff("CS2_059o") class CS2_059o(Card): health = 1 # Felguard class EX1_301(Card): def activate(self): self.owner.loseMana(1) # Succubus class EX1_306(Card): activate = discard(1) # Doomguard class EX1_310(Card): activate = discard(2) # Pit Lord class EX1_313(Card): def activate(self): self.owner.hero.damage(5) # Flame Imp class EX1_319(Card): def activate(self): self.owner.hero.damage(3) # Lord Jaraxxus class EX1_323(Card): def activate(self): self.removeFromField() self.owner.setHero("EX1_323h")
// ... existing code ... self.owner.hero.damage(3) # Lord Jaraxxus class EX1_323(Card): def activate(self): self.removeFromField() self.owner.setHero("EX1_323h") // ... rest of the code ...
0b6d5b0d10974842a0e52904d9793bfa4313ffb0
src/api/v1/watchers/__init__.py
src/api/v1/watchers/__init__.py
def filter_namespaces(data, user, _message): if user["role"] != "administrator": if isinstance(data, list): for item in data: if "members" not in item or user["username"] not in item["members"]: data.remove(item) return data else: if "members" not in data or user["username"] not in data["members"]: return None else: return data def filter_metrics(data, user, message): if "body" in message and "name" in message["body"]: if ("involvedObject" in data and "name" in data["involvedObject"] and data["involvedObject"]["name"] == message["body"]["name"]): return data else: return None else: return data return data
def filter_namespaces(data, user, _message): if user["role"] != "administrator": if isinstance(data, list): for item in data: if "members" not in item or user["username"] not in item["members"]: data.remove(item) return data else: if "members" not in data or user["username"] not in data["members"]: return None return data def filter_metrics(data, user, message): if "body" in message and "name" in message["body"]: if ("involvedObject" in data and "name" in data["involvedObject"] and data["involvedObject"]["name"] == message["body"]["name"]): return data else: return None else: return data return data
Fix user role filtered namespace
Fix user role filtered namespace
Python
apache-2.0
ElasticBox/elastickube,ElasticBox/elastickube,ElasticBox/elastickube,ElasticBox/elastickube,ElasticBox/elastickube
def filter_namespaces(data, user, _message): if user["role"] != "administrator": if isinstance(data, list): for item in data: if "members" not in item or user["username"] not in item["members"]: data.remove(item) return data else: if "members" not in data or user["username"] not in data["members"]: return None - else: - return data + return data def filter_metrics(data, user, message): if "body" in message and "name" in message["body"]: if ("involvedObject" in data and "name" in data["involvedObject"] and data["involvedObject"]["name"] == message["body"]["name"]): return data else: return None else: return data return data
Fix user role filtered namespace
## Code Before: def filter_namespaces(data, user, _message): if user["role"] != "administrator": if isinstance(data, list): for item in data: if "members" not in item or user["username"] not in item["members"]: data.remove(item) return data else: if "members" not in data or user["username"] not in data["members"]: return None else: return data def filter_metrics(data, user, message): if "body" in message and "name" in message["body"]: if ("involvedObject" in data and "name" in data["involvedObject"] and data["involvedObject"]["name"] == message["body"]["name"]): return data else: return None else: return data return data ## Instruction: Fix user role filtered namespace ## Code After: def filter_namespaces(data, user, _message): if user["role"] != "administrator": if isinstance(data, list): for item in data: if "members" not in item or user["username"] not in item["members"]: data.remove(item) return data else: if "members" not in data or user["username"] not in data["members"]: return None return data def filter_metrics(data, user, message): if "body" in message and "name" in message["body"]: if ("involvedObject" in data and "name" in data["involvedObject"] and data["involvedObject"]["name"] == message["body"]["name"]): return data else: return None else: return data return data
// ... existing code ... return None return data // ... rest of the code ...