commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
93ba327a3198c587d791aeb1d285f6e7f339df20
app/grandchallenge/archives/models.py
app/grandchallenge/archives/models.py
from django.db import models from grandchallenge.core.models import UUIDModel from grandchallenge.cases.models import Image from grandchallenge.patients.models import Patient class Archive(UUIDModel): """ Model for archive. Contains a collection of images """ name = models.CharField(max_length=255, default="Unnamed Archive") images = models.ManyToManyField(Image) def __str__(self): return f"<{self.__class__.__name__} {self.name}>" def delete(self, *args, **kwargs): # Remove all related patients and other models via cascading Patient.objects.filter(study__image__archive__id=self.id).delete() super().delete(*args, **kwargs)
from django.db import models from grandchallenge.core.models import UUIDModel from grandchallenge.cases.models import Image from grandchallenge.patients.models import Patient class Archive(UUIDModel): """ Model for archive. Contains a collection of images """ name = models.CharField(max_length=255, default="Unnamed Archive") images = models.ManyToManyField(Image) def __str__(self): return f"<{self.__class__.__name__} {self.name}>" def delete(self, *args, **kwargs): # Remove all related patients and other models via cascading Patient.objects.filter(study__image__archive__id=self.id).delete( *args, **kwargs ) super().delete(*args, **kwargs)
Add args and kwargs to delete method
Add args and kwargs to delete method
Python
apache-2.0
comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django
--- +++ @@ -18,5 +18,7 @@ def delete(self, *args, **kwargs): # Remove all related patients and other models via cascading - Patient.objects.filter(study__image__archive__id=self.id).delete() + Patient.objects.filter(study__image__archive__id=self.id).delete( + *args, **kwargs + ) super().delete(*args, **kwargs)
056c2922bd8304d054915bca10c9510148d96398
isAccessedInFunction.py
isAccessedInFunction.py
#! /usr/bin/env python import subprocess, sys, re try: classfile = sys.argv[1] functionRE = re.compile(sys.argv[2]) toSearch = re.compile(sys.argv[3]) except (re.error, IndexError) as e: print("""usage: %s classfile functionregex searchregex Will disassemble classfile, then search for searchregex in every function matching functionregex. If searchregex is found, returns 0. If searchregex is not found, but a function matchung functionregex, returns 1 Else returns 2 """ % sys.argv[0]) sys.exit(3) #display out put line by line proc = subprocess.Popen(['javap', '-p', '-c', sys.argv[1]],stdout=subprocess.PIPE) insideWantedFunction = False foundWantedFunction = False foundWantedStringInWantedFunction = False for line in iter(proc.stdout.readline,''): if not insideWantedFunction: if functionRE.search(line): insideWantedFunction = True foundWantedFunction = True else: if line.strip() == "": insideWantedFunction = False continue if toSearch.search(line): foundWantedStringInWantedFunction = True if foundWantedStringInWantedFunction: sys.exit(0) elif foundWantedFunction: sys.exit(1) else: sys.exit(2)
#! /usr/bin/env python import subprocess, sys, re try: classfile = sys.argv[1] functionRE = re.compile(sys.argv[2]) toSearch = re.compile(sys.argv[3]) except (re.error, IndexError) as e: print("""usage: %s classfile functionregex searchregex Will disassemble classfile, then search for searchregex in every function matching functionregex. If searchregex is found, returns 0. If searchregex is not found, but a function matchung functionregex, returns 1 Else returns 2 """ % sys.argv[0]) sys.exit(3) #display out put line by line proc = subprocess.Popen(['javap', '-p', '-c', sys.argv[1]],stdout=subprocess.PIPE) insideWantedFunction = False foundWantedFunction = False foundWantedStringInWantedFunction = False for line in iter(proc.stdout.readline,''): if not insideWantedFunction: if len(line) >= 3 and line[0:2] == ' ' and line[2] != ' ' \ and functionRE.search(line): insideWantedFunction = True foundWantedFunction = True else: if line.strip() == "": insideWantedFunction = False continue if toSearch.search(line): foundWantedStringInWantedFunction = True if foundWantedStringInWantedFunction: sys.exit(0) elif foundWantedFunction: sys.exit(1) else: sys.exit(2)
Improve detection of function start.
Improve detection of function start.
Python
apache-2.0
FAU-Inf2/AuDoscore,FAU-Inf2/AuDoscore
--- +++ @@ -26,7 +26,8 @@ foundWantedStringInWantedFunction = False for line in iter(proc.stdout.readline,''): if not insideWantedFunction: - if functionRE.search(line): + if len(line) >= 3 and line[0:2] == ' ' and line[2] != ' ' \ + and functionRE.search(line): insideWantedFunction = True foundWantedFunction = True else:
f1754acb58fe9088e90692f5200babff3fa49bdf
src/zeit/cms/tests/test_celery.py
src/zeit/cms/tests/test_celery.py
import datetime import zeit.cms.celery import zeit.cms.testing @zeit.cms.celery.CELERY.task() def task(context, datetime): pass class CeleryTaskTest(zeit.cms.testing.ZeitCmsTestCase): def test_registering_task_without_json_serializable_arguments_raises(self): now = datetime.datetime.now() with self.assertRaises(TypeError): task.delay(self.repository['testcontent'], datetime=now) with self.assertRaises(TypeError): task.apply_async( (self.repository['testcontent'],), {'datetime': now}, task_id=now, countdown=now) def test_registering_task_with_json_serializable_argument_passes(self): with self.assertNothingRaised(): task.delay('http://xml.zeit.de/testcontent', datetime='2016-01-01 12:00:00') task.apply_async( ('http://xml.zeit.de/testcontent',), {'datetime': '2016-01-01 12:00:00'}, task_id=1, countdown=30)
import datetime import zeit.cms.celery import zeit.cms.testing @zeit.cms.celery.CELERY.task() def dummy_task(context, datetime): """Dummy task to test our framework.""" class CeleryTaskTest(zeit.cms.testing.ZeitCmsTestCase): """Testing ..celery.TransactionAwareTask.""" def test_registering_task_without_json_serializable_arguments_raises(self): now = datetime.datetime.now() with self.assertRaises(TypeError): dummy_task.delay(self.repository['testcontent'], datetime=now) with self.assertRaises(TypeError): dummy_task.apply_async( (self.repository['testcontent'],), {'datetime': now}, task_id=now, countdown=now) def test_registering_task_with_json_serializable_argument_passes(self): with self.assertNothingRaised(): dummy_task.delay('http://xml.zeit.de/testcontent', datetime='2016-01-01 12:00:00') dummy_task.apply_async( ('http://xml.zeit.de/testcontent',), {'datetime': '2016-01-01 12:00:00'}, task_id=1, countdown=30)
Improve naming and add docstrings.
ZON-3409: Improve naming and add docstrings.
Python
bsd-3-clause
ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms
--- +++ @@ -4,26 +4,27 @@ @zeit.cms.celery.CELERY.task() -def task(context, datetime): - pass +def dummy_task(context, datetime): + """Dummy task to test our framework.""" class CeleryTaskTest(zeit.cms.testing.ZeitCmsTestCase): + """Testing ..celery.TransactionAwareTask.""" def test_registering_task_without_json_serializable_arguments_raises(self): now = datetime.datetime.now() with self.assertRaises(TypeError): - task.delay(self.repository['testcontent'], datetime=now) + dummy_task.delay(self.repository['testcontent'], datetime=now) with self.assertRaises(TypeError): - task.apply_async( + dummy_task.apply_async( (self.repository['testcontent'],), {'datetime': now}, task_id=now, countdown=now) def test_registering_task_with_json_serializable_argument_passes(self): with self.assertNothingRaised(): - task.delay('http://xml.zeit.de/testcontent', - datetime='2016-01-01 12:00:00') - task.apply_async( + dummy_task.delay('http://xml.zeit.de/testcontent', + datetime='2016-01-01 12:00:00') + dummy_task.apply_async( ('http://xml.zeit.de/testcontent',), {'datetime': '2016-01-01 12:00:00'}, task_id=1, countdown=30)
ea287daca69d0385c2792cd0021a0b1a23fb912b
helpers/datadog_reporting.py
helpers/datadog_reporting.py
import os import yaml from dogapi import dog_stats_api, dog_http_api def setup(): """ Initialize connection to datadog during locust startup. Reads the datadog api key from (in order): 1) An environment variable named DATADOG_API_KEY 2) the DATADOG_API_KEY of a yaml file at 2a) the environment variable ANSIBLE_VARS 2b) /edx/app/edx_ansible/server-vars.yaml """ api_key = os.environ.get('DATADOG_API_KEY') if api_key is None: server_vars_path = os.environ.get('ANSIBLE_VARS', '/edx/app/edx_ansible/server-vars.yaml') server_vars = yaml.safe_load(server_vars_path) api_key = server_vars.get('DATADOG_API_KEY') # By default use the statsd agent dog_stats_api.start( statsd=True, api_key=api_key, )
import os import yaml from dogapi import dog_stats_api, dog_http_api def setup(): """ Initialize connection to datadog during locust startup. Reads the datadog api key from (in order): 1) An environment variable named DATADOG_API_KEY 2) the DATADOG_API_KEY of a yaml file at 2a) the environment variable ANSIBLE_VARS 2b) /edx/app/edx_ansible/server-vars.yaml """ api_key = os.environ.get('DATADOG_API_KEY') if api_key is None: server_vars_path = os.environ.get('ANSIBLE_VARS', '/edx/app/edx_ansible/server-vars.yml') with open(server_vars_path, 'r') as server_vars_file: server_vars = yaml.safe_load(server_vars_file) api_key = server_vars.get('DATADOG_API_KEY') # By default use the statsd agent dog_stats_api.start( statsd=True, api_key=api_key, )
Fix reading of API key from yaml file.
Fix reading of API key from yaml file.
Python
apache-2.0
edx/edx-load-tests,edx/edx-load-tests,edx/edx-load-tests,edx/edx-load-tests
--- +++ @@ -18,8 +18,9 @@ api_key = os.environ.get('DATADOG_API_KEY') if api_key is None: - server_vars_path = os.environ.get('ANSIBLE_VARS', '/edx/app/edx_ansible/server-vars.yaml') - server_vars = yaml.safe_load(server_vars_path) + server_vars_path = os.environ.get('ANSIBLE_VARS', '/edx/app/edx_ansible/server-vars.yml') + with open(server_vars_path, 'r') as server_vars_file: + server_vars = yaml.safe_load(server_vars_file) api_key = server_vars.get('DATADOG_API_KEY') # By default use the statsd agent
8548822ed0755a17cc3dc95cac582683a1ffb11c
linguist/models/base.py
linguist/models/base.py
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from .. import settings @python_2_unicode_compatible class Translation(models.Model): """ A Translation. """ identifier = models.CharField( max_length=100, verbose_name=_('identifier'), help_text=_('The registered model identifier.')) object_id = models.IntegerField( verbose_name=_('The object ID'), help_text=_('The object ID of this translation')) language = models.CharField( max_length=10, verbose_name=_('locale'), choices=settings.SUPPORTED_LANGUAGES, default=settings.DEFAULT_LANGUAGE, help_text=_('The language for this translation')) field_name = models.CharField( max_length=100, verbose_name=_('field name'), help_text=_('The model field name for this translation.')) content = models.TextField( verbose_name=_('content'), null=True, help_text=_('The translated content for the field.')) class Meta: abstract = True app_label = 'linguist' verbose_name = _('translation') verbose_name_plural = _('translations') unique_together = (('identifier', 'object_id', 'language', 'field_name'),) def __str__(self): return '%s:%d:%s:%s' % ( self.identifier, self.object_id, self.field_name, self.language)
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from .. import settings @python_2_unicode_compatible class Translation(models.Model): """ A Translation. """ identifier = models.CharField( max_length=100, verbose_name=_('identifier'), help_text=_('The registered model identifier.')) object_id = models.IntegerField( verbose_name=_('The object ID'), help_text=_('The object ID of this translation')) language = models.CharField( max_length=10, verbose_name=_('locale'), choices=settings.SUPPORTED_LANGUAGES, default=settings.DEFAULT_LANGUAGE, help_text=_('The language for this translation')) field_name = models.CharField( max_length=100, verbose_name=_('field name'), help_text=_('The model field name for this translation.')) field_value = models.TextField( verbose_name=_('field value'), null=True, help_text=_('The translated content for the field.')) class Meta: abstract = True app_label = 'linguist' verbose_name = _('translation') verbose_name_plural = _('translations') unique_together = (('identifier', 'object_id', 'language', 'field_name'),) def __str__(self): return '%s:%d:%s:%s' % ( self.identifier, self.object_id, self.field_name, self.language)
Rename content field to field_value.
Rename content field to field_value.
Python
mit
ulule/django-linguist
--- +++ @@ -32,8 +32,8 @@ verbose_name=_('field name'), help_text=_('The model field name for this translation.')) - content = models.TextField( - verbose_name=_('content'), + field_value = models.TextField( + verbose_name=_('field value'), null=True, help_text=_('The translated content for the field.'))
b7fd4b9db379fc9bc28f22f6608c804e9f08e181
oonib/input/handlers.py
oonib/input/handlers.py
import glob import json import os import yaml from oonib.handlers import OONIBHandler from oonib import config class InputDescHandler(OONIBHandler): def get(self, inputID): #XXX return the input descriptor # see oonib.md in ooni-spec bn = os.path.basename(inputID) + ".desc" try: f = open(os.path.join(config.main.input_dir, bn)) a = {} inputDesc = yaml.safe_load(f) a['id'] = inputID a['name'] = inputDesc['name'] a['description'] = inputDesc['description'] self.write(json.dumps(a)) except Exception: log.err("No Input Descriptor found for id %s" % inputID) class InputListHandler(OONIBHandler): def get(self): path = os.path.abspath(config.main.input_dir) + "/*.desc" inputnames = map(os.path.basename, glob.iglob(path)) inputList = [] for inputname in inputnames: f = open(os.path.join(config.main.input_dir, inputname)) d = yaml.safe_load(f) inputList.append({ 'id': inputname, 'name': d['name'], 'description': d['description'] }) f.close() self.write(json.dumps(inputList))
import glob import json import os import yaml from oonib.handlers import OONIBHandler from oonib import config, log class InputDescHandler(OONIBHandler): def get(self, inputID): bn = os.path.basename(inputID) + ".desc" try: f = open(os.path.join(config.main.input_dir, bn)) a = {} inputDesc = yaml.safe_load(f) for k in ['name', 'description', 'version', 'author', 'date']: a[k] = inputDesc[k] self.write(json.dumps(a)) except IOError: log.err("No Input Descriptor found for id %s" % inputID) except Exception, e: log.err("Invalid Input Descriptor found for id %s" % inputID) class InputListHandler(OONIBHandler): def get(self): path = os.path.abspath(config.main.input_dir) + "/*.desc" inputnames = map(os.path.basename, glob.iglob(path)) inputList = [] for inputname in inputnames: f = open(os.path.join(config.main.input_dir, inputname)) d = yaml.safe_load(f) inputList.append({ 'id': inputname, 'name': d['name'], 'description': d['description'] }) f.close() self.write(json.dumps(inputList))
Implement input API as spec'd in oonib.md
Implement input API as spec'd in oonib.md
Python
bsd-2-clause
DoNotUseThisCodeJUSTFORKS/ooni-backend,DoNotUseThisCodeJUSTFORKS/ooni-backend,dstufft/ooni-backend,dstufft/ooni-backend
--- +++ @@ -1,28 +1,25 @@ import glob import json import os - import yaml from oonib.handlers import OONIBHandler - -from oonib import config +from oonib import config, log class InputDescHandler(OONIBHandler): def get(self, inputID): - #XXX return the input descriptor - # see oonib.md in ooni-spec bn = os.path.basename(inputID) + ".desc" try: f = open(os.path.join(config.main.input_dir, bn)) a = {} inputDesc = yaml.safe_load(f) - a['id'] = inputID - a['name'] = inputDesc['name'] - a['description'] = inputDesc['description'] + for k in ['name', 'description', 'version', 'author', 'date']: + a[k] = inputDesc[k] self.write(json.dumps(a)) - except Exception: + except IOError: log.err("No Input Descriptor found for id %s" % inputID) + except Exception, e: + log.err("Invalid Input Descriptor found for id %s" % inputID) class InputListHandler(OONIBHandler): def get(self):
e85102e3c5e76c0e695aef2eb14ba973fb0da660
lobster/commands/elk.py
lobster/commands/elk.py
from lobster.core.command import Command class Elk_Update(Command): @property def help(self): return 'update Kibana objects' def setup(self, argparser): pass def run(self, args): args.config.elk.update_kibana() class Elk_Cleanup(Command): @property def help(self): return 'delete Elasticsearch indices and Kibana objects' def setup(self, argparser): pass def run(self, args): args.config.elk.cleanup()
from lobster.core.command import Command class ElkUpdate(Command): @property def help(self): return 'update Kibana objects' def setup(self, argparser): pass def run(self, args): args.config.elk.update_kibana() class ElkCleanup(Command): @property def help(self): return 'delete Elasticsearch indices and Kibana objects' def setup(self, argparser): pass def run(self, args): args.config.elk.cleanup()
Change class names to CamelCase
Change class names to CamelCase
Python
mit
matz-e/lobster,matz-e/lobster,matz-e/lobster
--- +++ @@ -1,7 +1,7 @@ from lobster.core.command import Command -class Elk_Update(Command): +class ElkUpdate(Command): @property def help(self): return 'update Kibana objects' @@ -13,7 +13,7 @@ args.config.elk.update_kibana() -class Elk_Cleanup(Command): +class ElkCleanup(Command): @property def help(self): return 'delete Elasticsearch indices and Kibana objects'
8ecc24ab865ff9dec647fe69d78af0a63f0a902a
nap/rest/models.py
nap/rest/models.py
from __future__ import unicode_literals from .. import http from .publisher import Publisher from django.db import transaction from django.shortcuts import get_object_or_404 class ModelPublisher(Publisher): '''A Publisher with useful methods to publish Models''' @property def model(self): '''By default, we try to get the model from our serialiser''' # XXX Should this call get_serialiser? return self.serialiser._meta.model # Auto-build serialiser from model class? def get_object_list(self): return self.model.objects.all() def get_object(self, object_id): return get_object_or_404(self.get_object_list(), pk=object_id) def list_post_default(self, request, **kwargs): data = self.get_request_data() serialiser = self.get_serialiser() serialiser_kwargs = self.get_serialiser_kwargs() try: with transaction.atomic(): obj = serialiser.object_inflate(data, **serialiser_kwargs) except ValueError as e: return http.BadRequest(str(e)) return self.render_single_object(obj, serialiser)
from __future__ import unicode_literals from .. import http from ..shortcuts import get_object_or_404 from .publisher import Publisher from django.db import transaction class ModelPublisher(Publisher): '''A Publisher with useful methods to publish Models''' @property def model(self): '''By default, we try to get the model from our serialiser''' # XXX Should this call get_serialiser? return self.serialiser._meta.model # Auto-build serialiser from model class? def get_object_list(self): return self.model.objects.all() def get_object(self, object_id): return get_object_or_404(self.get_object_list(), pk=object_id) def list_post_default(self, request, **kwargs): data = self.get_request_data() serialiser = self.get_serialiser() serialiser_kwargs = self.get_serialiser_kwargs() try: with transaction.atomic(): obj = serialiser.object_inflate(data, **serialiser_kwargs) except ValueError as e: return http.BadRequest(str(e)) return self.render_single_object(obj, serialiser)
Use our own get_object_or_404 for ModelPublisher.get_object
Use our own get_object_or_404 for ModelPublisher.get_object
Python
bsd-3-clause
MarkusH/django-nap,limbera/django-nap
--- +++ @@ -1,10 +1,10 @@ from __future__ import unicode_literals from .. import http +from ..shortcuts import get_object_or_404 from .publisher import Publisher from django.db import transaction -from django.shortcuts import get_object_or_404 class ModelPublisher(Publisher):
1599d4ed14fb3d7c7e551c9f6ce3f86d9df17cbd
mammoth/writers/html.py
mammoth/writers/html.py
from __future__ import unicode_literals from .abc import Writer import cgi class HtmlWriter(Writer): def __init__(self): self._fragments = [] def text(self, text): self._fragments.append(_escape_html(text)) def start(self, name, attributes=None): attribute_string = _generate_attribute_string(attributes) self._fragments.append("<{0}{1}>".format(name, attribute_string)) def end(self, name): self._fragments.append("</{0}>".format(name)) def self_closing(self, name, attributes=None): attribute_string = _generate_attribute_string(attributes) self._fragments.append("<{0}{1} />".format(name, attribute_string)) def append(self, html): self._fragments.append(html) def as_string(self): return "".join(self._fragments) def _escape_html(text): return cgi.escape(text, quote=True) def _generate_attribute_string(attributes): if attributes is None: return "" else: return "".join( ' {0}="{1}"'.format(key, _escape_html(attributes[key])) for key in sorted(attributes) )
from __future__ import unicode_literals from xml.sax.saxutils import escape from .abc import Writer class HtmlWriter(Writer): def __init__(self): self._fragments = [] def text(self, text): self._fragments.append(_escape_html(text)) def start(self, name, attributes=None): attribute_string = _generate_attribute_string(attributes) self._fragments.append("<{0}{1}>".format(name, attribute_string)) def end(self, name): self._fragments.append("</{0}>".format(name)) def self_closing(self, name, attributes=None): attribute_string = _generate_attribute_string(attributes) self._fragments.append("<{0}{1} />".format(name, attribute_string)) def append(self, html): self._fragments.append(html) def as_string(self): return "".join(self._fragments) def _escape_html(text): return escape(text, {'"': "&quot;"}) def _generate_attribute_string(attributes): if attributes is None: return "" else: return "".join( ' {0}="{1}"'.format(key, _escape_html(attributes[key])) for key in sorted(attributes) )
Use xml.sax.saxutils.escape instead of deprecated cgi.escape
Use xml.sax.saxutils.escape instead of deprecated cgi.escape ``` /usr/local/lib/python3.6/dist-packages/mammoth/writers/html.py:34: DeprecationWarning: cgi.escape is deprecated, use html.escape instead return cgi.escape(text, quote=True) ```
Python
bsd-2-clause
mwilliamson/python-mammoth
--- +++ @@ -1,8 +1,7 @@ from __future__ import unicode_literals +from xml.sax.saxutils import escape from .abc import Writer - -import cgi class HtmlWriter(Writer): @@ -31,7 +30,7 @@ def _escape_html(text): - return cgi.escape(text, quote=True) + return escape(text, {'"': "&quot;"}) def _generate_attribute_string(attributes):
7c91429412119f887e611c5f6a52a5ebc32a99b0
tof_server/map_model.py
tof_server/map_model.py
"""Model for handling operations on map data""" import json def persist_map(map_data, metadata, cursor, player_id): """Method for persisting map data""" serialized_map_data = json.dumps(map_data) map_sql = """INSERT INTO maps (download_code, map_hash, player_id) VALUES (%s, %s, %s)""" cursor.execute(map_sql, (metadata['code'], metadata['hash'], player_id)) last_id_sql = "SELECT LAST_INSERT_ID()" cursor.execute(last_id_sql) last_id = cursor.fetchone() map_data_sql = "INSERT INTO maps_data (map_id, json) VALUES (%s, %s)" cursor.execute(map_data_sql, (last_id[0], serialized_map_data)) def find_map(map_code, cursor): """Method for retrieving map data""" map_code_sql = "SELECT id FROM maps WHERE download_code = %s" cursor.execute(map_code_sql, (map_code,)) map_id = cursor.fetchone() if not map_id: return None map_data_sql = "SELECT json FROM maps_data WHERE map_id = %s" cursor.execute(map_data_sql, (map_id[0],)) map_data = cursor.fetchone() return json.loads(map_data[0])
"""Model for handling operations on map data""" import json def persist_map(map_data, metadata, cursor, player_id): """Method for persisting map data""" serialized_map_data = json.dumps(map_data) map_sql = """INSERT INTO maps (download_code, map_hash, player_id) VALUES (%s, %s, %s)""" cursor.execute(map_sql, (metadata['code'], metadata['hash'], player_id)) last_id_sql = "SELECT LAST_INSERT_ID()" cursor.execute(last_id_sql) last_id = cursor.fetchone() map_data_sql = "INSERT INTO maps_data (map_id, json) VALUES (%s, %s)" cursor.execute(map_data_sql, (last_id[0], serialized_map_data)) def find_map(map_code, cursor): """Method for retrieving map data""" map_code_sql = "SELECT id FROM maps WHERE download_code = %s" cursor.execute(map_code_sql, (map_code.upper(),)) map_id = cursor.fetchone() if not map_id: return None map_data_sql = "SELECT json FROM maps_data WHERE map_id = %s" cursor.execute(map_data_sql, (map_id[0],)) map_data = cursor.fetchone() return json.loads(map_data[0])
Change map download code to be case insensitive
Change map download code to be case insensitive
Python
mit
P1X-in/Tanks-of-Freedom-Server
--- +++ @@ -23,7 +23,7 @@ def find_map(map_code, cursor): """Method for retrieving map data""" map_code_sql = "SELECT id FROM maps WHERE download_code = %s" - cursor.execute(map_code_sql, (map_code,)) + cursor.execute(map_code_sql, (map_code.upper(),)) map_id = cursor.fetchone() if not map_id:
bb190d54324e15ed6ce99845047228eaef5e57cb
test_core.py
test_core.py
#!/usr/bin/env python from ookoobah import core from ookoobah import utils game = core.Game() utils.populate_grid_from_string(game.grid, """ ###### #>..\# #.#..# #....# #.\./# ###### """) game.start() for n in range(10): print utils.dump_grid_to_string(game.grid, game.ball) game.step()
#!/usr/bin/env python from ookoobah import core from ookoobah import utils game = core.Game() utils.populate_grid_from_string(game.grid, """ ###### #>..\# #.#..# #....# #.\./# ###### """) game.start() print "hit <enter> to render next; ^C to abort" while True: print utils.dump_grid_to_string(game.grid, game.ball) game.step() raw_input()
Make the core dumper interactive
test: Make the core dumper interactive
Python
mit
vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah
--- +++ @@ -15,6 +15,8 @@ """) game.start() -for n in range(10): +print "hit <enter> to render next; ^C to abort" +while True: print utils.dump_grid_to_string(game.grid, game.ball) game.step() + raw_input()
7f2d9b94bdcbfb90870591d7cb497bb0aa2ac069
test/test_yeast.py
test/test_yeast.py
import unittest from yeast_harness import * class TestYeast(unittest.TestCase): def test_single_c_source(self): mk = Makefile( spores=SporeFile( sources=CSourceFile('tree'), products='static_lib', path='tree'), name='Makefile') mk.create() mk.create_spores() mk.create_sources() self.assertEqual(mk.make(), 0) self.assertEqual(mk.make('-q'), 0)
import unittest from yeast_harness import * class TestYeast(unittest.TestCase): def test_single_c_source(self): mk = Makefile( spores=SporeFile( sources=CSourceFile('tree'), products='static_lib', path='tree'), name='Makefile') mk.create() mk.create_spores() mk.create_sources() self.assertEqual(mk.make(), 0) self.assertEqual(mk.make('-q'), 0) def test_large_source_tree(self): make_sources = lambda: [CSourceFile('tree') for _ in range(10)] make_spore = lambda: SporeFile( sources=make_sources(), products='static_lib', path='tree') mk = Makefile( spores=[make_spore() for _ in range(10)], name='Makefile') mk.create() mk.create_spores() mk.create_sources()
Create initial test case for large tree
Create initial test case for large tree
Python
mit
sjanhunen/yeast,sjanhunen/moss,sjanhunen/gnumake-molds,sjanhunen/moss
--- +++ @@ -17,3 +17,19 @@ mk.create_sources() self.assertEqual(mk.make(), 0) self.assertEqual(mk.make('-q'), 0) + + def test_large_source_tree(self): + + make_sources = lambda: [CSourceFile('tree') for _ in range(10)] + make_spore = lambda: SporeFile( + sources=make_sources(), + products='static_lib', + path='tree') + + mk = Makefile( + spores=[make_spore() for _ in range(10)], + name='Makefile') + + mk.create() + mk.create_spores() + mk.create_sources()
77d0fe3daec4f6e4f9166dcd32943b21384a2073
tests/test_core.py
tests/test_core.py
from grazer.core import crawler from bs4 import BeautifulSoup def test_extract_links(): text = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> </body> </html> """ bs = BeautifulSoup(text, "html.parser") links = crawler.extract_links(bs) expected = ["http://example.com/elsie", "http://example.com/lacie", "http://example.com/tillie"] assert links == expected def test_link_trimmer(): result = crawler.trim_link("http://example.com/lacie", "http://example.com") assert result == "/lacie"
from grazer.core import crawler from bs4 import BeautifulSoup def test_extract_links(): text = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> </body> </html> """ bs = BeautifulSoup(text, "html.parser") links = crawler.extract_links(bs) expected = ["http://example.com/elsie", "http://example.com/lacie", "http://example.com/tillie"] assert links == expected def test_link_trimmer(): result = crawler.trim_link("http://example.com/lacie", "http://example.com") assert result == "/lacie" def test_trim_link_without_trailing_slash(): result = crawler.trim_link("http://example.com", "http://example.com") assert result == "http://example.com"
Test to validate trimming scenario
Test to validate trimming scenario
Python
mit
CodersOfTheNight/verata
--- +++ @@ -30,3 +30,8 @@ def test_link_trimmer(): result = crawler.trim_link("http://example.com/lacie", "http://example.com") assert result == "/lacie" + + +def test_trim_link_without_trailing_slash(): + result = crawler.trim_link("http://example.com", "http://example.com") + assert result == "http://example.com"
3f5ac069710679201cb0a3a041a0ca75186c9e03
version.py
version.py
major = 0 minor=0 patch=16 branch="master" timestamp=1376507917.4
major = 0 minor=0 patch=17 branch="master" timestamp=1376509025.95
Tag commit for v0.0.17-master generated by gitmake.py
Tag commit for v0.0.17-master generated by gitmake.py
Python
mit
ryansturmer/gitmake
--- +++ @@ -1,5 +1,5 @@ major = 0 minor=0 -patch=16 +patch=17 branch="master" -timestamp=1376507917.4 +timestamp=1376509025.95
fdc23d97064220e1042bcf7a7cb9714f476c4219
busstops/management/commands/import_operators.py
busstops/management/commands/import_operators.py
""" Usage: ./manage.py import_operators < NOC_db.csv """ from busstops.management.import_from_csv import ImportFromCSVCommand from busstops.models import Operator class Command(ImportFromCSVCommand): @staticmethod def get_region_id(region_id): if region_id in ('ADMIN', 'Admin', ''): return 'GB' elif region_id in ('SC', 'YO', 'WA', 'LO'): return region_id[0] return region_id @classmethod def handle_row(cls, row): "Given a CSV row (a list), returns an Operator object" operator_id = row['NOCCODE'].replace('=', '') if operator_id == 'TVSR': return None if row['OperatorPublicName'] in ('First', 'Arriva', 'Stagecoach') \ or row['OperatorPublicName'].startswith('inc.') \ or row['OperatorPublicName'].startswith('formerly'): name = row['RefNm'] elif row['OperatorPublicName'] != '': name = row['OperatorPublicName'] else: name = row['OpNm'] name = name.replace('\'', u'\u2019') # Fancy apostrophe operator = Operator.objects.update_or_create( id=operator_id, defaults=dict( name=name.strip(), vehicle_mode=row['Mode'].lower().replace('ct operator', 'community transport').replace('drt', 'demand responsive transport'), region_id=cls.get_region_id(row['TLRegOwn']), ) ) return operator
""" Usage: ./manage.py import_operators < NOC_db.csv """ from busstops.management.import_from_csv import ImportFromCSVCommand from busstops.models import Operator class Command(ImportFromCSVCommand): @staticmethod def get_region_id(region_id): if region_id in ('ADMIN', 'Admin', ''): return 'GB' elif region_id in ('SC', 'YO', 'WA', 'LO'): return region_id[0] return region_id @classmethod def handle_row(cls, row): "Given a CSV row (a list), returns an Operator object" if row['Duplicate'] != 'OK': return None operator_id = row['NOCCODE'].replace('=', '') if operator_id == 'TVSR': return None if row['OperatorPublicName'] in ('First', 'Arriva', 'Stagecoach') \ or row['OperatorPublicName'].startswith('inc.') \ or row['OperatorPublicName'].startswith('formerly'): name = row['RefNm'] elif row['OperatorPublicName'] != '': name = row['OperatorPublicName'] else: name = row['OpNm'] name = name.replace('\'', u'\u2019') # Fancy apostrophe operator = Operator.objects.update_or_create( id=operator_id, defaults=dict( name=name.strip(), vehicle_mode=row['Mode'].lower().replace('ct operator', 'community transport').replace('drt', 'demand responsive transport'), region_id=cls.get_region_id(row['TLRegOwn']), ) ) return operator
Stop importing clearly duplicate operators (like the First Manchester operator without a name)
Stop importing clearly duplicate operators (like the First Manchester operator without a name)
Python
mpl-2.0
jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk
--- +++ @@ -22,6 +22,9 @@ @classmethod def handle_row(cls, row): "Given a CSV row (a list), returns an Operator object" + if row['Duplicate'] != 'OK': + return None + operator_id = row['NOCCODE'].replace('=', '') if operator_id == 'TVSR':
4f27be336a58d0bba66a4f7ab57126d9dd734ab9
talks/views.py
talks/views.py
from django.shortcuts import render, get_object_or_404 from config.utils import get_active_event from .models import Talk def list_talks(request): event = get_active_event() talks = event.talks.prefetch_related( 'applicants', 'applicants__user', 'skill_level', 'sponsor', ).order_by('-keynote', 'title') # Temporary hack to let only admins & committee members see the talks user = request.user permitted = user.is_authenticated and (user.is_superuser or user.is_talk_committee_member()) if not permitted: talks = event.talks.none() return render(request, 'talks/list_talks.html', { "talks": talks, }) def view_talk(request, slug): event = get_active_event() talk = get_object_or_404(Talk, slug=slug, event=event) return render(request, 'talks/view_talk.html', { 'talk': talk})
from django.shortcuts import render, get_object_or_404 from config.utils import get_active_event from .models import Talk def list_talks(request): event = get_active_event() talks = event.talks.prefetch_related( 'applicants', 'applicants__user', 'skill_level', 'sponsor', ).order_by('-keynote', 'title') return render(request, 'talks/list_talks.html', { "talks": talks, }) def view_talk(request, slug): event = get_active_event() talk = get_object_or_404(Talk, slug=slug, event=event) return render(request, 'talks/view_talk.html', { 'talk': talk})
Revert "Temporarily make talks visible only to committee"
Revert "Temporarily make talks visible only to committee" This reverts commit 57050b7025acb3de66024fe01255849a5ba5f1fc.
Python
bsd-3-clause
WebCampZg/conference-web,WebCampZg/conference-web,WebCampZg/conference-web
--- +++ @@ -14,12 +14,6 @@ 'sponsor', ).order_by('-keynote', 'title') - # Temporary hack to let only admins & committee members see the talks - user = request.user - permitted = user.is_authenticated and (user.is_superuser or user.is_talk_committee_member()) - if not permitted: - talks = event.talks.none() - return render(request, 'talks/list_talks.html', { "talks": talks, })
2161910a53604bdc48027c5c4e71f9af4228cbaa
keras/backend/common.py
keras/backend/common.py
import numpy as np # the type of float to use throughout the session. _FLOATX = 'float32' _EPSILON = 10e-8 def epsilon(): return _EPSILON def set_epsilon(e): global _EPSILON _EPSILON = e def floatx(): return _FLOATX def set_floatx(floatx): global _FLOATX if floatx not in {'float32', 'float64'}: raise Exception('Unknown floatx type: ' + str(floatx)) if isinstance(floatx, unicode): floatx = floatx.encode('ascii') _FLOATX = floatx def cast_to_floatx(x): '''Cast a Numpy array to floatx. ''' return np.asarray(x, dtype=_FLOATX)
import numpy as np # the type of float to use throughout the session. _FLOATX = 'float32' _EPSILON = 10e-8 def epsilon(): return _EPSILON def set_epsilon(e): global _EPSILON _EPSILON = e def floatx(): return _FLOATX def set_floatx(floatx): global _FLOATX if floatx not in {'float32', 'float64'}: raise Exception('Unknown floatx type: ' + str(floatx)) floatx = floatx.encode('ascii') _FLOATX = floatx def cast_to_floatx(x): '''Cast a Numpy array to floatx. ''' return np.asarray(x, dtype=_FLOATX)
Fix floatx encoding on Python3
Fix floatx encoding on Python3
Python
apache-2.0
keras-team/keras,nebw/keras,daviddiazvico/keras,kemaswill/keras,DeepGnosis/keras,keras-team/keras,dolaameng/keras,relh/keras,kuza55/keras
--- +++ @@ -22,8 +22,7 @@ global _FLOATX if floatx not in {'float32', 'float64'}: raise Exception('Unknown floatx type: ' + str(floatx)) - if isinstance(floatx, unicode): - floatx = floatx.encode('ascii') + floatx = floatx.encode('ascii') _FLOATX = floatx
5bb7cc09df33debb46eba17d12f078f043131db0
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: try: list_of_footprints = src_plugin.FootprintEnumerate(libpath) except UnicodeDecodeError: pass except Exception as e: print(libpath) raise e
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: try: list_of_footprints = src_plugin.FootprintEnumerate(libpath) except UnicodeDecodeError: # pcbnew python modules (at least git-7d6230a and v4.x) have an issue # with loading unicode paths # https://bugs.launchpad.net/kicad/+bug/1740881 pass except Exception as e: print(libpath) raise e
Document kicad python unicode bug
Document kicad python unicode bug
Python
mit
monostable/haskell-kicad-data,monostable/haskell-kicad-data,kasbah/haskell-kicad-data
--- +++ @@ -19,6 +19,9 @@ try: list_of_footprints = src_plugin.FootprintEnumerate(libpath) except UnicodeDecodeError: + # pcbnew python modules (at least git-7d6230a and v4.x) have an issue + # with loading unicode paths + # https://bugs.launchpad.net/kicad/+bug/1740881 pass except Exception as e: print(libpath)
ce42ab724ad8a76dd04e24e4df6d20d96255989f
kitchen/lib/__init__.py
kitchen/lib/__init__.py
import os import json from kitchen.settings import KITCHEN_LOCATION def load_data(data_type): retval = [] nodes_dir = os.path.join(KITCHEN_LOCATION, data_type) if not os.path.isdir(nodes_dir): raise IOError('Invalid data type or kitchen location. Check your settings.') for filename in os.listdir(nodes_dir): if filename.endswith('.json'): entry = {'name': filename[:-5]} f = open(os.path.join(nodes_dir, filename), 'r') entry['data'] = json.load(f) f.close() retval.append(entry) return retval
import os import json from kitchen.settings import KITCHEN_LOCATION def load_data(data_type): retval = [] nodes_dir = os.path.join(KITCHEN_LOCATION, data_type) if not os.path.isdir(nodes_dir): raise IOError('Invalid data type or kitchen location. Check your settings.') for filename in os.listdir(nodes_dir): if filename.endswith('.json'): entry = {'name': filename[:-5]} f = open(os.path.join(nodes_dir, filename), 'r') entry['data'] = json.load(f) f.close() retval.append(entry) return sort_list_by_data_key(retval, 'chef_environment') def sort_list_by_data_key(old_list, key): return sorted(old_list, key=lambda k: k['data'][key])
Allow list to be sorted by a key in the node's data
Allow list to be sorted by a key in the node's data
Python
apache-2.0
edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen
--- +++ @@ -15,5 +15,7 @@ entry['data'] = json.load(f) f.close() retval.append(entry) - return retval + return sort_list_by_data_key(retval, 'chef_environment') +def sort_list_by_data_key(old_list, key): + return sorted(old_list, key=lambda k: k['data'][key])
74a3fe9d83c3ccf2f6972277df3a34c47bc06c26
slave/skia_slave_scripts/run_gyp.py
slave/skia_slave_scripts/run_gyp.py
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run GYP to generate project files. """ from build_step import BuildStep import sys class RunGYP(BuildStep): def _Run(self): self._flavor_utils.RunGYP() if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(RunGYP))
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run GYP to generate project files. """ from build_step import BuildStep import sys class RunGYP(BuildStep): def __init__(self, timeout=15000, no_output_timeout=10000, **kwargs): super(RunGYP, self).__init__(timeout=timeout, no_output_timeout=no_output_timeout, **kwargs) def _Run(self): self._flavor_utils.RunGYP() if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(RunGYP))
Increase timeout for RunGYP step BUG=skia:1631 (SkipBuildbotRuns)
Increase timeout for RunGYP step BUG=skia:1631 (SkipBuildbotRuns) git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@11229 2bbb7eff-a529-9590-31e7-b0007b416f81
Python
bsd-3-clause
Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot
--- +++ @@ -10,6 +10,12 @@ class RunGYP(BuildStep): + def __init__(self, timeout=15000, no_output_timeout=10000, + **kwargs): + super(RunGYP, self).__init__(timeout=timeout, + no_output_timeout=no_output_timeout, + **kwargs) + def _Run(self): self._flavor_utils.RunGYP()
96ef8f3f2c81822df635a373496d2f638178f85a
backend/project_name/settings/test.py
backend/project_name/settings/test.py
from .base import * # noqa SECRET_KEY = "test" DATABASES = { "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": base_dir_join("db.sqlite3"),} } STATIC_ROOT = "staticfiles" STATIC_URL = "/static/" MEDIA_ROOT = "mediafiles" MEDIA_URL = "/media/" DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSystemStorage" STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage" # Speed up password hashing PASSWORD_HASHERS = [ "django.contrib.auth.hashers.MD5PasswordHasher", ] # Celery CELERY_TASK_ALWAYS_EAGER = True CELERY_TASK_EAGER_PROPAGATES = True
from .base import * # noqa SECRET_KEY = "test" DATABASES = { "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": base_dir_join("db.sqlite3"),} } STATIC_ROOT = base_dir_join('staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = base_dir_join('mediafiles') MEDIA_URL = '/media/' DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSystemStorage" STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage" # Speed up password hashing PASSWORD_HASHERS = [ "django.contrib.auth.hashers.MD5PasswordHasher", ] # Celery CELERY_TASK_ALWAYS_EAGER = True CELERY_TASK_EAGER_PROPAGATES = True
Revert "Fix ci build by adjust static root and media root path"
Revert "Fix ci build by adjust static root and media root path" This reverts commit e502c906
Python
mit
vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate
--- +++ @@ -7,11 +7,11 @@ "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": base_dir_join("db.sqlite3"),} } -STATIC_ROOT = "staticfiles" -STATIC_URL = "/static/" +STATIC_ROOT = base_dir_join('staticfiles') +STATIC_URL = '/static/' -MEDIA_ROOT = "mediafiles" -MEDIA_URL = "/media/" +MEDIA_ROOT = base_dir_join('mediafiles') +MEDIA_URL = '/media/' DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSystemStorage" STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage"
f365c36cb726f6ace05cf05f1a11635337963270
src/nodeconductor_saltstack/sharepoint/extension.py
src/nodeconductor_saltstack/sharepoint/extension.py
from nodeconductor.core import NodeConductorExtension class SharepointExtension(NodeConductorExtension): @staticmethod def django_app(): return 'nodeconductor_saltstack.sharepoint' @staticmethod def rest_urls(): from .urls import register_in return register_in @staticmethod def celery_tasks(): from datetime import timedelta return { 'sharepoint-sync-tenants': { 'task': 'nodeconductor.sharepoint.sync_tenants', 'schedule': timedelta(minutes=30), 'args': () }, }
from nodeconductor.core import NodeConductorExtension class SharepointExtension(NodeConductorExtension): @staticmethod def django_app(): return 'nodeconductor_saltstack.sharepoint' @staticmethod def rest_urls(): from .urls import register_in return register_in @staticmethod def celery_tasks(): from datetime import timedelta return { 'sharepoint-sync-tenants': { 'task': 'nodeconductor.sharepoint.sync_tenants', 'schedule': timedelta(minutes=10), 'args': () }, }
Increase default sync frequency for SP
Increase default sync frequency for SP
Python
mit
opennode/nodeconductor-saltstack
--- +++ @@ -18,7 +18,7 @@ return { 'sharepoint-sync-tenants': { 'task': 'nodeconductor.sharepoint.sync_tenants', - 'schedule': timedelta(minutes=30), + 'schedule': timedelta(minutes=10), 'args': () }, }
74c770b8b457b14a297193e0cd8e9d5bb6b4b031
utils/retry.py
utils/retry.py
import time import urllib2 import socket from google.appengine.api import datastore_errors from google.appengine.runtime import apiproxy_errors MAX_ATTEMPTS = 10 def retry(func, *args, **kwargs): for attempt in range(MAX_ATTEMPTS): if attempt: seconds = min(300, 2 ** attempt) print "Attempt %d of %d will start in %d seconds." % ( attempt + 1, MAX_ATTEMPTS, seconds) time.sleep(seconds) try: return func(*args, **kwargs) except (datastore_errors.Timeout, apiproxy_errors.Error, urllib2.URLError, socket.error), error: print type(error) print error if attempt + 1 >= MAX_ATTEMPTS: raise def retry_objects(func, objects): if not objects: return print "Trying to %s %d objects (%s to %s)" % ( func.__name__, len(objects), objects[0].key().name(), objects[-1].key().name()) return retry(func, objects)
import logging import time import urllib2 import socket from google.appengine.api import datastore_errors from google.appengine.runtime import apiproxy_errors MAX_ATTEMPTS = 10 def retry(func, *args, **kwargs): for attempt in range(MAX_ATTEMPTS): if attempt: seconds = min(300, 2 ** attempt) logging.info("Attempt %d of %d will start in %d seconds." % ( attempt + 1, MAX_ATTEMPTS, seconds)) time.sleep(seconds) try: return func(*args, **kwargs) except (datastore_errors.Timeout, apiproxy_errors.Error, urllib2.URLError, socket.error), error: logging.error(type(error)) logging.error(str(error)) if attempt + 1 >= MAX_ATTEMPTS: raise def retry_objects(func, objects): if not objects: return logging.info("Trying to %s %d objects (%s to %s)" % ( func.__name__, len(objects), objects[0].key().name(), objects[-1].key().name())) return retry(func, objects)
Use logging module for debug messages, not stdout.
Use logging module for debug messages, not stdout.
Python
mit
jcrocholl/nxdom,jcrocholl/nxdom
--- +++ @@ -1,3 +1,4 @@ +import logging import time import urllib2 import socket @@ -12,15 +13,15 @@ for attempt in range(MAX_ATTEMPTS): if attempt: seconds = min(300, 2 ** attempt) - print "Attempt %d of %d will start in %d seconds." % ( - attempt + 1, MAX_ATTEMPTS, seconds) + logging.info("Attempt %d of %d will start in %d seconds." % ( + attempt + 1, MAX_ATTEMPTS, seconds)) time.sleep(seconds) try: return func(*args, **kwargs) except (datastore_errors.Timeout, apiproxy_errors.Error, urllib2.URLError, socket.error), error: - print type(error) - print error + logging.error(type(error)) + logging.error(str(error)) if attempt + 1 >= MAX_ATTEMPTS: raise @@ -28,7 +29,7 @@ def retry_objects(func, objects): if not objects: return - print "Trying to %s %d objects (%s to %s)" % ( + logging.info("Trying to %s %d objects (%s to %s)" % ( func.__name__, len(objects), - objects[0].key().name(), objects[-1].key().name()) + objects[0].key().name(), objects[-1].key().name())) return retry(func, objects)
b2d121a2ee8750afd0f4d527c80371bd501f841c
neo/io/nixio_fr.py
neo/io/nixio_fr.py
from neo.io.basefromrawio import BaseFromRaw from neo.rawio.nixrawio import NIXRawIO # This class subjects to limitations when there are multiple asymmetric blocks class NixIO(NIXRawIO, BaseFromRaw): name = 'NIX IO' _prefered_signal_group_mode = 'group-by-same-units' _prefered_units_group_mode = 'split-all' def __init__(self, filename): NIXRawIO.__init__(self, filename) BaseFromRaw.__init__(self, filename) def read_block(self, block_index=0, lazy=False, signal_group_mode=None, units_group_mode=None, load_waveforms=False): bl = super().read_block(block_index, lazy, signal_group_mode, units_group_mode, load_waveforms) for chx in bl.channel_indexes: if "nix_name" in chx.annotations: nixname = chx.annotations["nix_name"] chx.annotations["nix_name"] = nixname[0] return bl def __enter__(self): return self def __exit__(self, *args): self.header = None self.file.close()
from neo.io.basefromrawio import BaseFromRaw from neo.rawio.nixrawio import NIXRawIO # This class subjects to limitations when there are multiple asymmetric blocks class NixIO(NIXRawIO, BaseFromRaw): name = 'NIX IO' _prefered_signal_group_mode = 'group-by-same-units' _prefered_units_group_mode = 'split-all' def __init__(self, filename): NIXRawIO.__init__(self, filename) BaseFromRaw.__init__(self, filename) def read_block(self, block_index=0, lazy=False, signal_group_mode=None, units_group_mode=None, load_waveforms=False): bl = super(NixIO, self).read_block(block_index, lazy, signal_group_mode, units_group_mode, load_waveforms) for chx in bl.channel_indexes: if "nix_name" in chx.annotations: nixname = chx.annotations["nix_name"] chx.annotations["nix_name"] = nixname[0] return bl def __enter__(self): return self def __exit__(self, *args): self.header = None self.file.close()
Use Python2 compatible super() call
[nixio] Use Python2 compatible super() call
Python
bsd-3-clause
NeuralEnsemble/python-neo,JuliaSprenger/python-neo,samuelgarcia/python-neo,INM-6/python-neo,rgerkin/python-neo,apdavison/python-neo
--- +++ @@ -17,8 +17,10 @@ def read_block(self, block_index=0, lazy=False, signal_group_mode=None, units_group_mode=None, load_waveforms=False): - bl = super().read_block(block_index, lazy, signal_group_mode, - units_group_mode, load_waveforms) + bl = super(NixIO, self).read_block(block_index, lazy, + signal_group_mode, + units_group_mode, + load_waveforms) for chx in bl.channel_indexes: if "nix_name" in chx.annotations: nixname = chx.annotations["nix_name"]
0c67cff030592cd44023444a5f10eef6570bfdf0
odinweb/testing.py
odinweb/testing.py
""" Testing Helpers ~~~~~~~~~~~~~~~ Collection of Mocks and Tools for testing APIs. """ from odin.codecs import json_codec from odinweb.constants import Method class MockRequest(object): """ Mocked Request object """ def __init__(self, query=None, post=None, headers=None, method=Method.GET, body='', host='127.0.0.1', request_codec=None, response_codec=None): self.GET = query or {} self.POST = post or {} self.headers = headers or {} self.method = method self.body = body self.host = host self.request_codec = request_codec or json_codec self.response_codec = response_codec or json_codec
""" Testing Helpers ~~~~~~~~~~~~~~~ Collection of Mocks and Tools for testing APIs. """ from typing import Dict, Any from odin.codecs import json_codec try: from urllib.parse import urlparse, parse_qs except ImportError: from urlparse import urlparse, parse_qs from odinweb.constants import Method class MockRequest(object): """ Mocked Request object. This can be treated as a template of a request """ @classmethod def from_uri(cls, uri, post=None, headers=None, method=Method.GET, body='', request_codec=None, response_codec=None): # type: (str, Dict[str, str], Dict[str, str], Method, str, Any, Any) -> MockRequest scheme, netloc, path, params, query, fragment = urlparse(uri) return cls(scheme, netloc, path, parse_qs(query), post, headers, method, body, request_codec, response_codec) def __init__(self, scheme='http', host='127.0.0.1', path=None, query=None, headers=None, method=Method.GET, post=None, body='', request_codec=None, response_codec=None): # type: (str, str, str, Dict[str, str], Dict[str, str], Dict[str, str], Method, str, Any, Any) -> MockRequest self.scheme = scheme self.host = host self.path = path self.GET = query or {} self.headers = headers or {} self.method = method self.POST = post or {} self.body = body self.request_codec = request_codec or json_codec self.response_codec = response_codec or json_codec
Expand Mock Request to include path and built in URL parsing.
Expand Mock Request to include path and built in URL parsing.
Python
bsd-3-clause
python-odin/odinweb,python-odin/odinweb
--- +++ @@ -5,22 +5,40 @@ Collection of Mocks and Tools for testing APIs. """ +from typing import Dict, Any + from odin.codecs import json_codec +try: + from urllib.parse import urlparse, parse_qs +except ImportError: + from urlparse import urlparse, parse_qs from odinweb.constants import Method class MockRequest(object): """ - Mocked Request object + Mocked Request object. + + This can be treated as a template of a request """ - def __init__(self, query=None, post=None, headers=None, method=Method.GET, body='', host='127.0.0.1', + @classmethod + def from_uri(cls, uri, post=None, headers=None, method=Method.GET, body='', request_codec=None, response_codec=None): + # type: (str, Dict[str, str], Dict[str, str], Method, str, Any, Any) -> MockRequest + scheme, netloc, path, params, query, fragment = urlparse(uri) + return cls(scheme, netloc, path, parse_qs(query), post, headers, method, body, request_codec, response_codec) + + def __init__(self, scheme='http', host='127.0.0.1', path=None, query=None, headers=None, method=Method.GET, + post=None, body='', request_codec=None, response_codec=None): + # type: (str, str, str, Dict[str, str], Dict[str, str], Dict[str, str], Method, str, Any, Any) -> MockRequest + self.scheme = scheme + self.host = host + self.path = path self.GET = query or {} - self.POST = post or {} self.headers = headers or {} self.method = method + self.POST = post or {} self.body = body - self.host = host self.request_codec = request_codec or json_codec self.response_codec = response_codec or json_codec
8da30d3752fd6a056891960aa2892bcd8001c79b
lintreview/processor.py
lintreview/processor.py
import logging import lintreview.tools as tools from lintreview.diff import DiffCollection from lintreview.review import Problems from lintreview.review import Review log = logging.getLogger(__name__) class Processor(object): def __init__(self, client, number, head, target_path): self._client = client self._number = number self._head = head self._target_path = target_path self._changes = None self._problems = Problems(target_path) self._review = Review(client, number) def load_changes(self): log.info('Loading pull request patches from github.') files = self._client.pull_requests.list_files(self._number) pull_request_patches = files.all() self._changes = DiffCollection(pull_request_patches) self._problems.set_changes(self._changes) def run_tools(self, repo_config): if not self._changes: raise RuntimeError('No loaded changes, cannot run tools. ' 'Try calling load_changes first.') files_to_check = self._changes.get_files(append_base=self._target_path) tools.run( repo_config, self._problems, files_to_check, self._target_path) def publish(self, wait_time=0): self._problems.limit_to_changes() self._review.publish(self._problems, self._head, wait_time)
import logging import lintreview.tools as tools from lintreview.diff import DiffCollection from lintreview.review import Problems from lintreview.review import Review log = logging.getLogger(__name__) class Processor(object): def __init__(self, client, number, head, target_path): self._client = client self._number = number self._head = head self._target_path = target_path self._changes = None self._problems = Problems(target_path) self._review = Review(client, number) def load_changes(self): log.info('Loading pull request patches from github.') files = self._client.pull_requests.list_files(self._number) pull_request_patches = files.all() self._changes = DiffCollection(pull_request_patches) self._problems.set_changes(self._changes) def run_tools(self, repo_config): if self._changes is None: raise RuntimeError('No loaded changes, cannot run tools. ' 'Try calling load_changes first.') files_to_check = self._changes.get_files(append_base=self._target_path) tools.run( repo_config, self._problems, files_to_check, self._target_path) def publish(self, wait_time=0): self._problems.limit_to_changes() self._review.publish(self._problems, self._head, wait_time)
Make check against None instead of falsey things.
Make check against None instead of falsey things.
Python
mit
markstory/lint-review,markstory/lint-review,adrianmoisey/lint-review,zoidbergwill/lint-review,zoidbergwill/lint-review,adrianmoisey/lint-review,zoidbergwill/lint-review,markstory/lint-review
--- +++ @@ -27,7 +27,7 @@ self._problems.set_changes(self._changes) def run_tools(self, repo_config): - if not self._changes: + if self._changes is None: raise RuntimeError('No loaded changes, cannot run tools. ' 'Try calling load_changes first.') files_to_check = self._changes.get_files(append_base=self._target_path)
f62ccee6bffa4dff9047a2f4b7499412dd3e2fb1
tomviz/python/SwapAxes.py
tomviz/python/SwapAxes.py
def transform(dataset, axis1, axis2): """Swap two axes in a dataset""" data_py = dataset.active_scalars dataset.active_scalars = data_py.swapaxes(axis1, axis2)
def transform(dataset, axis1, axis2): """Swap two axes in a dataset""" import numpy as np data_py = dataset.active_scalars swapped = data_py.swapaxes(axis1, axis2) dataset.active_scalars = np.asfortranarray(swapped)
Convert array back to fortran before setting
Convert array back to fortran before setting Unfortunately, it looks like numpy.ndarray.swapaxes converts the ordering from Fortran to C. When this happens, a warning message will be printed to the console later that a conversion to Fortran ordering is required. Instead of printing the warning, just convert it back to Fortran ordering ourselves. We already know that this operator unfortunately converts the ordering to C. Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
Python
bsd-3-clause
OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz
--- +++ @@ -1,5 +1,8 @@ def transform(dataset, axis1, axis2): """Swap two axes in a dataset""" + import numpy as np + data_py = dataset.active_scalars - dataset.active_scalars = data_py.swapaxes(axis1, axis2) + swapped = data_py.swapaxes(axis1, axis2) + dataset.active_scalars = np.asfortranarray(swapped)
5558b19b46fbe1db6f25b227ac581095fedcff2e
us_ignite/maps/views.py
us_ignite/maps/views.py
import json from django.core.serializers.json import DjangoJSONEncoder from django.http import HttpResponse from django.template.response import TemplateResponse from us_ignite.maps.models import Location def location_list(request): """Shows a list of locations in a map.""" object_list = Location.published.select_related('category').all() context = { 'object_list': object_list, } return TemplateResponse(request, 'maps/object_list.html', context) def _get_content(name, website): if not website: return name return u'<div><h2><a href="%s">%s</a></h2></div>' % (website, name) def _get_location_data(location): return { 'latitude': location.position.latitude, 'longitude': location.position.longitude, 'name': location.name, 'website': location.website, 'category': location.category.name, 'image': location.get_image_url(), 'content': _get_content(location.name, location.website), } def location_list_json(request): """Returns the locations in JSON format""" object_list = Location.published.select_related('category').all() dict_list = [_get_location_data(l) for l in object_list] response = 'map.render(%s)' % json.dumps(dict_list, cls=DjangoJSONEncoder) return HttpResponse(response, content_type='application/javascript')
from django.template.response import TemplateResponse from us_ignite.common.response import json_response from us_ignite.maps.models import Location def location_list(request): """Shows a list of locations in a map.""" object_list = Location.published.select_related('category').all() context = { 'object_list': object_list, } return TemplateResponse(request, 'maps/object_list.html', context) def _get_content(name, website): if not website: return name return u'<div><h2><a href="%s">%s</a></h2></div>' % (website, name) def _get_location_data(location): return { 'latitude': location.position.latitude, 'longitude': location.position.longitude, 'name': location.name, 'website': location.website, 'category': location.category.name, 'image': location.get_image_url(), 'content': _get_content(location.name, location.website), } def location_list_json(request): """Returns the locations in JSON format""" object_list = Location.published.select_related('category').all() dict_list = [_get_location_data(l) for l in object_list] return json_response(dict_list, callback='map.render')
Update ``maps`` to use the ``json_response`` function.
Update ``maps`` to use the ``json_response`` function.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
--- +++ @@ -1,9 +1,6 @@ -import json - -from django.core.serializers.json import DjangoJSONEncoder -from django.http import HttpResponse from django.template.response import TemplateResponse +from us_ignite.common.response import json_response from us_ignite.maps.models import Location @@ -38,5 +35,4 @@ """Returns the locations in JSON format""" object_list = Location.published.select_related('category').all() dict_list = [_get_location_data(l) for l in object_list] - response = 'map.render(%s)' % json.dumps(dict_list, cls=DjangoJSONEncoder) - return HttpResponse(response, content_type='application/javascript') + return json_response(dict_list, callback='map.render')
497b0c8e9581cee76398c18c78ea8eb4362ef5b2
project/editorial/views/__init__.py
project/editorial/views/__init__.py
from braces.views import UserPassesTestMixin class CustomUserTest(UserPassesTestMixin): """User must be a member of this organization to view this content. This also requires that a user be logged in, so it's not needed to use this with LoginRequiredMixin. """ def test_func(self, user): """"User must be a super""" if user.is_superuser(): # Superuser can use all views return True if not user.is_authenticated(): # No logged in user; this will redirect to login page return False return self.test_user(user)
from braces.views import UserPassesTestMixin class CustomUserTest(UserPassesTestMixin): """User must be a member of this organization to view this content. This also requires that a user be logged in, so it's not needed to use this with LoginRequiredMixin. """ def test_func(self, user): """"User must be a super""" if user.is_superuser: # Superuser can use all views return True if not user.is_authenticated(): # No logged in user; this will redirect to login page return False return self.test_user(user)
Fix API call for is-superuser.
Fix API call for is-superuser.
Python
mit
ProjectFacet/facet,ProjectFacet/facet,ProjectFacet/facet,ProjectFacet/facet,ProjectFacet/facet
--- +++ @@ -11,7 +11,7 @@ def test_func(self, user): """"User must be a super""" - if user.is_superuser(): + if user.is_superuser: # Superuser can use all views return True
89f631bcaa4a48a4f65989975031efbbbd59e522
l10n_ch_mis_reports/__manifest__.py
l10n_ch_mis_reports/__manifest__.py
# Copyright 2018 Camptocamp SA # Copyright 2015 Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Switzerland - MIS reports', 'summary': 'Specific MIS reports for switzerland localization', 'version': '11.0.1.0.0', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Localization', 'website': 'https://github.com/OCA/l10n-switzerland', 'license': 'AGPL-3', 'depends': [ 'l10n_ch', 'mis_builder', 'l10n_ch_account_tags', ], 'data': [ 'data/mis_report_style.xml', 'data/mis_report.xml', 'data/mis_report_kpi.xml', ], }
# Copyright 2018 Camptocamp SA # Copyright 2015 Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Switzerland - MIS reports', 'summary': 'Specific MIS reports for switzerland localization', 'version': '11.0.1.1.0', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Localization', 'website': 'https://github.com/OCA/l10n-switzerland', 'license': 'AGPL-3', 'depends': [ 'l10n_ch', 'mis_builder_budget', 'l10n_ch_account_tags', ], 'data': [ 'data/mis_report_style.xml', 'data/mis_report.xml', 'data/mis_report_kpi.xml', ], }
Fix dependency to mis_builder_budget to remove runbot warning
Fix dependency to mis_builder_budget to remove runbot warning
Python
agpl-3.0
brain-tec/l10n-switzerland,brain-tec/l10n-switzerland,brain-tec/l10n-switzerland
--- +++ @@ -5,14 +5,14 @@ { 'name': 'Switzerland - MIS reports', 'summary': 'Specific MIS reports for switzerland localization', - 'version': '11.0.1.0.0', + 'version': '11.0.1.1.0', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Localization', 'website': 'https://github.com/OCA/l10n-switzerland', 'license': 'AGPL-3', 'depends': [ 'l10n_ch', - 'mis_builder', + 'mis_builder_budget', 'l10n_ch_account_tags', ], 'data': [
9bdf9455344b83fc28c5ecceafba82036bb2c75d
foodsaving/management/tests/test_makemessages.py
foodsaving/management/tests/test_makemessages.py
from unittest.mock import patch from django.test import TestCase from ..commands.makemessages import Command as MakeMessagesCommand from django_jinja.management.commands.makemessages import Command as DjangoJinjaMakeMessagesCommand makemessages = MakeMessagesCommand django_jinja_makemessages = DjangoJinjaMakeMessagesCommand class CustomMakeMessagesTest(TestCase): def test_update_options(self): options = { 'locale': [], } modified_options = MakeMessagesCommand.update_options(**options) self.assertIn('jinja', modified_options['extensions']) self.assertIn('en', modified_options['locale']) options['extensions'] = ['py'] modified_options_with_initial_extension = MakeMessagesCommand.update_options(**options) self.assertIn('jinja', modified_options_with_initial_extension['extensions']) @patch(__name__ + '.django_jinja_makemessages.handle') @patch(__name__ + '.makemessages.update_options', return_value={}) def test_handle(self, mock1, mock2): MakeMessagesCommand.handle(MakeMessagesCommand()) assert MakeMessagesCommand.update_options.called assert DjangoJinjaMakeMessagesCommand.handle.called
from unittest.mock import patch from django.test import TestCase from ..commands.makemessages import Command as MakeMessagesCommand from django_jinja.management.commands.makemessages import Command as DjangoJinjaMakeMessagesCommand makemessages = MakeMessagesCommand django_jinja_makemessages = DjangoJinjaMakeMessagesCommand class CustomMakeMessagesTest(TestCase): def test_update_options(self): options = { 'locale': [], } modified_options = MakeMessagesCommand.update_options(**options) self.assertIn('jinja2', modified_options['extensions']) self.assertIn('en', modified_options['locale']) @patch(__name__ + '.django_jinja_makemessages.handle') @patch(__name__ + '.makemessages.update_options', return_value={}) def test_handle(self, mock1, mock2): MakeMessagesCommand.handle(MakeMessagesCommand()) assert MakeMessagesCommand.update_options.called assert DjangoJinjaMakeMessagesCommand.handle.called
Fix makemessages test to look for jinja2
Fix makemessages test to look for jinja2
Python
agpl-3.0
yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend
--- +++ @@ -15,12 +15,8 @@ } modified_options = MakeMessagesCommand.update_options(**options) - self.assertIn('jinja', modified_options['extensions']) + self.assertIn('jinja2', modified_options['extensions']) self.assertIn('en', modified_options['locale']) - - options['extensions'] = ['py'] - modified_options_with_initial_extension = MakeMessagesCommand.update_options(**options) - self.assertIn('jinja', modified_options_with_initial_extension['extensions']) @patch(__name__ + '.django_jinja_makemessages.handle') @patch(__name__ + '.makemessages.update_options', return_value={})
b6308afbc33f80b621e68c3d2b635fe64666c51a
wcontrol/conf/config.py
wcontrol/conf/config.py
import os basedir = os.path.abspath(os.path.dirname(__file__)) # forms wtf config WTF_CSRF_ENABLED = True SECRET_KEY = 'impossible-to-guess' # sqlalchemy database config SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db') SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository') SQLALCHEMY_TRACK_MODIFICATIONS = False # oauth google config OAUTH_CREDENTIALS = { 'google': { 'id': os.environ.get('WEIGHT_CONTROL_OAUTH_GOOGLE_ID'), 'secret': os.environ.get('WEIGHT_CONTROL_OAUTH_GOOGLE_SECRET') }, 'facebook': { 'id': os.environ.get('WEIGHT_CONTROL_OAUTH_FACEBOOK_ID'), 'secret': os.environ.get('WEIGHT_CONTROL_OAUTH_FACEBOOK_SECRET') } } # measurements MEASUREMENTS = [ (1, 'Weight'), (2, 'BMI'), (3, 'Fat'), (4, 'Muscle'), (5, 'Viceral Fat'), (6, 'Basal Metabolic Rate'), (7, 'Body Age') ]
import os basedir = os.path.abspath(os.path.dirname(__file__)) # forms wtf config WTF_CSRF_ENABLED = True SECRET_KEY = 'impossible-to-guess' # sqlalchemy database config SQLALCHEMY_DATABASE_URI = os.environ.get('WCONTROL_DB', 'sqlite:///wcontrol/db/app.db') SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository') SQLALCHEMY_TRACK_MODIFICATIONS = False # oauth google config OAUTH_CREDENTIALS = { 'google': { 'id': os.environ.get('WEIGHT_CONTROL_OAUTH_GOOGLE_ID'), 'secret': os.environ.get('WEIGHT_CONTROL_OAUTH_GOOGLE_SECRET') }, 'facebook': { 'id': os.environ.get('WEIGHT_CONTROL_OAUTH_FACEBOOK_ID'), 'secret': os.environ.get('WEIGHT_CONTROL_OAUTH_FACEBOOK_SECRET') } } # measurements MEASUREMENTS = [ (1, 'Weight'), (2, 'BMI'), (3, 'Fat'), (4, 'Muscle'), (5, 'Viceral Fat'), (6, 'Basal Metabolic Rate'), (7, 'Body Age') ]
Use a env var to get DB path
Use a env var to get DB path
Python
mit
pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control
--- +++ @@ -6,7 +6,8 @@ SECRET_KEY = 'impossible-to-guess' # sqlalchemy database config -SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db') +SQLALCHEMY_DATABASE_URI = os.environ.get('WCONTROL_DB', + 'sqlite:///wcontrol/db/app.db') SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository') SQLALCHEMY_TRACK_MODIFICATIONS = False
58d3efa146f006fe518b02234b4eb0d6708cecc8
examples/web_ws.py
examples/web_ws.py
#!/usr/bin/env python3 """Example for aiohttp.web websocket server """ import os from aiohttp import web WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html') async def wshandler(request): resp = web.WebSocketResponse() available = resp.can_prepare(request) if not available: with open(WS_FILE, 'rb') as fp: return web.Response(body=fp.read(), content_type='text/html') await resp.prepare(request) try: print('Someone joined.') for ws in request.app['sockets']: await ws.send_str('Someone joined') request.app['sockets'].append(resp) async for msg in resp: if msg.type == web.WSMsgType.TEXT: for ws in request.app['sockets']: if ws is not resp: await ws.send_str(msg.data) else: return resp return resp finally: request.app['sockets'].remove(resp) print('Someone disconnected.') for ws in request.app['sockets']: await ws.send_str('Someone disconnected.') async def on_shutdown(app): for ws in app['sockets']: await ws.close() def init(): app = web.Application() app['sockets'] = [] app.router.add_get('/', wshandler) app.on_shutdown.append(on_shutdown) return app web.run_app(init())
#!/usr/bin/env python3 """Example for aiohttp.web websocket server """ import os from aiohttp import web WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html') async def wshandler(request): resp = web.WebSocketResponse() available = resp.can_prepare(request) if not available: with open(WS_FILE, 'rb') as fp: return web.Response(body=fp.read(), content_type='text/html') await resp.prepare(request) await resp.send_str('Welcome!!!') try: print('Someone joined.') for ws in request.app['sockets']: await ws.send_str('Someone joined') request.app['sockets'].append(resp) async for msg in resp: if msg.type == web.WSMsgType.TEXT: for ws in request.app['sockets']: if ws is not resp: await ws.send_str(msg.data) else: return resp return resp finally: request.app['sockets'].remove(resp) print('Someone disconnected.') for ws in request.app['sockets']: await ws.send_str('Someone disconnected.') async def on_shutdown(app): for ws in app['sockets']: await ws.close() def init(): app = web.Application() app['sockets'] = [] app.router.add_get('/', wshandler) app.on_shutdown.append(on_shutdown) return app web.run_app(init())
Send welcome message at very first of communication channel
Send welcome message at very first of communication channel
Python
apache-2.0
rutsky/aiohttp,arthurdarcet/aiohttp,arthurdarcet/aiohttp,KeepSafe/aiohttp,rutsky/aiohttp,KeepSafe/aiohttp,KeepSafe/aiohttp,rutsky/aiohttp,arthurdarcet/aiohttp
--- +++ @@ -18,6 +18,8 @@ return web.Response(body=fp.read(), content_type='text/html') await resp.prepare(request) + + await resp.send_str('Welcome!!!') try: print('Someone joined.')
2c914f6e438906296860983a01e593ab1f9a5cd7
CloudSQLReplicator/google/cloud/pontem/sql/replicator/__init__.py
CloudSQLReplicator/google/cloud/pontem/sql/replicator/__init__.py
# Copyright 2018 The Pontem Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Pontem SQL Replicator.""" __version__ = '0.0.1' __package_name__ = 'cloudsql-replicator'
# Copyright 2018 The Pontem Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Pontem SQL Replicator.""" __version__ = '0.0.1' __package_name__ = 'cloudsql-replication'
Update the UA used in CloudSQLReplicator
Update the UA used in CloudSQLReplicator
Python
apache-2.0
GoogleCloudPlatform/pontem,GoogleCloudPlatform/pontem
--- +++ @@ -15,4 +15,5 @@ """Pontem SQL Replicator.""" __version__ = '0.0.1' -__package_name__ = 'cloudsql-replicator' +__package_name__ = 'cloudsql-replication' +
5dbea33ce9d2b2d9354a8e86e271c087723dc748
events/cms_plugins.py
events/cms_plugins.py
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool import datetime from django.utils.translation import ugettext as _ from events.models import CalendarEventsPlugin as CalendarEventsPluginModel from events.models import AllEventsPlugin as AllEventsPluginModel from events.models import Event class CalendarEventsPlugin(CMSPluginBase): model = CalendarEventsPluginModel name = _("Events (from one calendar)") render_template = "events/plugin.html" module = _("TheHerk") def render(self, context, instance, placeholder): events = Event.objects.filter(calendar__id=instance.calendar).filter(end__gte=datetime.date.today()).order_by('start')[:instance.number_to_show] context.update({ 'instance': instance, 'events': events, 'placeholder': placeholder, }) return context class AllEventsPlugin(CMSPluginBase): model = AllEventsPluginModel name = _("Events (all calendars)") render_template = "events/plugin.html" module = _("TheHerk") def render(self, context, instance, placeholder): events = Event.objects.filter(end__gte=datetime.date.today()).order_by('start')[:instance.number_to_show] context.update({ 'instance': instance, 'events': events, 'placeholder': placeholder, }) return context plugin_pool.register_plugin(CalendarEventsPlugin) plugin_pool.register_plugin(AllEventsPlugin)
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool import datetime from django.utils.translation import ugettext as _ from events.models import CalendarEventsPlugin as CalendarEventsPluginModel from events.models import AllEventsPlugin as AllEventsPluginModel from events.models import Event class CalendarEventsPlugin(CMSPluginBase): model = CalendarEventsPluginModel name = _("Events (from one calendar)") render_template = "events/plugin.html" module = _("TheHerk") def render(self, context, instance, placeholder): events = Event.objects.filter(calendar__id=instance.calendar.id).filter(end__gte=datetime.date.today()).order_by('start')[:instance.number_to_show] context.update({ 'instance': instance, 'events': events, 'placeholder': placeholder, }) return context class AllEventsPlugin(CMSPluginBase): model = AllEventsPluginModel name = _("Events (all calendars)") render_template = "events/plugin.html" module = _("TheHerk") def render(self, context, instance, placeholder): events = Event.objects.filter(end__gte=datetime.date.today()).order_by('start')[:instance.number_to_show] context.update({ 'instance': instance, 'events': events, 'placeholder': placeholder, }) return context plugin_pool.register_plugin(CalendarEventsPlugin) plugin_pool.register_plugin(AllEventsPlugin)
Update context for one calendar
Update context for one calendar
Python
bsd-3-clause
theherk/django-theherk-events
--- +++ @@ -14,7 +14,7 @@ module = _("TheHerk") def render(self, context, instance, placeholder): - events = Event.objects.filter(calendar__id=instance.calendar).filter(end__gte=datetime.date.today()).order_by('start')[:instance.number_to_show] + events = Event.objects.filter(calendar__id=instance.calendar.id).filter(end__gte=datetime.date.today()).order_by('start')[:instance.number_to_show] context.update({ 'instance': instance, 'events': events,
5a4e9d19f75bb02dc359099931310c7e6dd1ac99
web/extras/contentment/components/folder/controller.py
web/extras/contentment/components/folder/controller.py
# encoding: utf-8 """Basic folder controller. Additional views on asset contents. """ import datetime from web.extras.contentment.api import action, view from web.extras.contentment.components.asset.controller import AssetController log = __import__('logging').getLogger(__name__) __all__ = ['FolderController'] class FolderController(AssetController): @view("Details", "A detailed contents view.") def view_details(self, sort=None): return 'details', None @view("Event Attachments", "A list of events and their attachments.") def view_attachments(self, year=None, sort="starts"): if year is None: year = datetime.datetime.now().year year = int(year) years = [] for i in self.asset.contents: if not hasattr(i, 'starts'): continue if i.starts is None: continue years.append(i.starts.year) years = sorted(list(set(years))) filter_range = (datetime.datetime(year, 1, 1, 0, 0, 0), datetime.datetime(year+1, 1, 1, 0, 0, 0)) return 'nested', dict(years=years, year=year, filter_range=filter_range, sort=sort)
# encoding: utf-8 """Basic folder controller. Additional views on asset contents. """ import datetime from web.extras.contentment.api import action, view from web.extras.contentment.components.asset.controller import AssetController log = __import__('logging').getLogger(__name__) __all__ = ['FolderController'] class FolderController(AssetController): @view("Details", "A detailed contents view.") def view_details(self, sort=None): return 'details', None @view("Event Attachments", "A list of events and their attachments.") def view_attachments(self, year=None, sort="starts"): if year is None: year = datetime.datetime.now().year year = int(year) years = [] for i in self.asset.contents: if not hasattr(i, 'starts'): continue if i.starts is None: continue years.append(i.starts.year) years = sorted(list(set(years))) if year > max(years): year = years[-1] elif year < min(years): yeare = years[0] filter_range = (datetime.datetime(year, 1, 1, 0, 0, 0), datetime.datetime(year+1, 1, 1, 0, 0, 0)) return 'nested', dict(years=years, year=year, filter_range=filter_range, sort=sort)
Change default year to maximal available year, not current year.
Change default year to maximal available year, not current year.
Python
mit
marrow/contentment,marrow/contentment
--- +++ @@ -36,6 +36,12 @@ years = sorted(list(set(years))) + if year > max(years): + year = years[-1] + + elif year < min(years): + yeare = years[0] + filter_range = (datetime.datetime(year, 1, 1, 0, 0, 0), datetime.datetime(year+1, 1, 1, 0, 0, 0)) return 'nested', dict(years=years, year=year, filter_range=filter_range, sort=sort)
a4f03e82b72287027a57101fe67f7fc26d312801
url_shortener/__init__.py
url_shortener/__init__.py
# -*- coding: utf-8 -*- from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('url_shortener.default_config') app.config.from_envvar('URL_SHORTENER_CONFIGURATION') db = SQLAlchemy(app)
# -*- coding: utf-8 -*- from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('url_shortener.default_config') """ From http://flask-sqlalchemy.pocoo.org/2.1/config/: "SQLALCHEMY_TRACK_MODIFICATIONS - If set to True, Flask-SQLAlchemy will track modifications of objects and emit signals. The default is None, which enables tracking but issues a warning that it will be disabled by default in the future. This requires extra memory and should be disabled if not needed." This application uses SQLAlchemy event system, so this value is set to False """ app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config.from_envvar('URL_SHORTENER_CONFIGURATION') db = SQLAlchemy(app)
Set SQLALCHEMY_TRACK_MODIFICATIONS option to False
Set SQLALCHEMY_TRACK_MODIFICATIONS option to False This commit adds code responsible for setting SQLALCHEMY_TRACK_MODIFICATION option to False. This option is provided by Flask-SQLAlchemy extension and relates to event system provided by this extension. This project uses event system provided by SQLAlchemy library, not by Flask-SQLAlchemy, so this option should be disabled for better performance.
Python
mit
piotr-rusin/url-shortener,piotr-rusin/url-shortener
--- +++ @@ -6,5 +6,18 @@ app = Flask(__name__) app.config.from_object('url_shortener.default_config') +""" +From http://flask-sqlalchemy.pocoo.org/2.1/config/: + +"SQLALCHEMY_TRACK_MODIFICATIONS - If set to True, Flask-SQLAlchemy +will track modifications of objects and emit signals. The default is +None, which enables tracking but issues a warning that it will be +disabled by default in the future. This requires extra memory and +should be disabled if not needed." + +This application uses SQLAlchemy event system, so this value is set +to False +""" +app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config.from_envvar('URL_SHORTENER_CONFIGURATION') db = SQLAlchemy(app)
d9f26a1d2831546517aec163a447dcf83cc80701
decisiontree/tests/urls.py
decisiontree/tests/urls.py
from django.conf.urls import include from django.contrib import admin admin.autodiscover() urlpatterns = [ (r'^admin/', include(admin.site.urls)), (r'^account/', include('rapidsms.urls.login_logout')), (r'^scheduler/', include('rapidsms.contrib.scheduler.urls')), (r'^tree/', include('decisiontree.urls')), ]
from django.conf.urls import include from django.contrib import admin admin.autodiscover() urlpatterns = [ (r'^admin/', include(admin.site.urls)), (r'^account/', include('rapidsms.urls.login_logout')), (r'^tree/', include('decisiontree.urls')), ]
Remove reference to the scheduler, which was removed.
Remove reference to the scheduler, which was removed.
Python
bsd-3-clause
caktus/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app
--- +++ @@ -8,6 +8,5 @@ urlpatterns = [ (r'^admin/', include(admin.site.urls)), (r'^account/', include('rapidsms.urls.login_logout')), - (r'^scheduler/', include('rapidsms.contrib.scheduler.urls')), (r'^tree/', include('decisiontree.urls')), ]
61b4f72045ea683a83a358d5d66bd32f7711598b
services/serializers.py
services/serializers.py
from rest_framework import serializers from .models import Service, Category, ServicePhoto class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name', 'photo', 'order') class ServicePhotoSerializer(serializers.ModelSerializer): """ """ class Meta: model = ServicePhoto fields = ('id', 'photo') class ServiceSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from semillas_backend.users.serializers import UserSerializer JSONRenderer().render(UserSerializer(user_instance).data) """ category = CategorySerializer() photos = ServicePhotoSerializer(many=True) class Meta: model = Service fields = ('id', 'title', 'date', 'description', 'category', 'photos')
from rest_framework import serializers from .models import Service, Category, ServicePhoto from semillas_backend.users.serializers import UserSerializer class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name', 'photo', 'order') class ServicePhotoSerializer(serializers.ModelSerializer): """ """ class Meta: model = ServicePhoto fields = ('id', 'photo') class ServiceSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from semillas_backend.users.serializers import UserSerializer JSONRenderer().render(UserSerializer(user_instance).data) """ category = CategorySerializer() photos = ServicePhotoSerializer(many=True) author = UserSerializer() class Meta: model = Service fields = ('id', 'title', 'date', 'description', 'author', 'category', 'photos')
Add user serialized to ServiceSerializer
Add user serialized to ServiceSerializer
Python
mit
Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform
--- +++ @@ -1,6 +1,7 @@ from rest_framework import serializers from .models import Service, Category, ServicePhoto +from semillas_backend.users.serializers import UserSerializer class CategorySerializer(serializers.ModelSerializer): @@ -26,6 +27,7 @@ """ category = CategorySerializer() photos = ServicePhotoSerializer(many=True) + author = UserSerializer() class Meta: model = Service - fields = ('id', 'title', 'date', 'description', 'category', 'photos') + fields = ('id', 'title', 'date', 'description', 'author', 'category', 'photos')
b5a43a7fdfc69abfa687d2b31a2add0d52ed5235
motobot/core_plugins/ctcp.py
motobot/core_plugins/ctcp.py
from motobot import match, Notice, Eat, __VERSION__ from time import strftime, localtime @match(r'\x01(.+)\x01', priority=Priority.max) def ctcp_match(bot, context, message, match): mapping = { 'VERSION': 'MotoBot Version ' + __VERSION__, 'FINGER': 'Oh you dirty man!', 'TIME': strftime('%a %b %d %H:%M:%S', localtime()), 'PING': message } try: ctcp_req = match.group(1) reply = ctcp_response[ctcp_req] return reply, Notice(context.nick), Eat except KeyError: return None
from motobot import match, Notice, Eat, Priority, __VERSION__ from time import strftime, localtime @match(r'\x01(.+)\x01', priority=Priority.max) def ctcp_match(bot, context, message, match): ctcp_response = { 'VERSION': 'MotoBot Version ' + __VERSION__, 'FINGER': 'Oh you dirty man!', 'TIME': strftime('%a %b %d %H:%M:%S', localtime()), 'PING': message } try: ctcp_req = match.group(1) reply = ctcp_response[ctcp_req] return reply, Notice(context.nick), Eat except KeyError: return None
Fix CTCP import and naming bug
Fix CTCP import and naming bug
Python
mit
Motoko11/MotoBot
--- +++ @@ -1,10 +1,10 @@ -from motobot import match, Notice, Eat, __VERSION__ +from motobot import match, Notice, Eat, Priority, __VERSION__ from time import strftime, localtime @match(r'\x01(.+)\x01', priority=Priority.max) def ctcp_match(bot, context, message, match): - mapping = { + ctcp_response = { 'VERSION': 'MotoBot Version ' + __VERSION__, 'FINGER': 'Oh you dirty man!', 'TIME': strftime('%a %b %d %H:%M:%S', localtime()),
54c46aaafe5b99b4da01911b4133dfaace7f6a43
_priorityQ.py
_priorityQ.py
import bin_heap as bh class Priority(object): """docstring for priority""" def __init__(self): self.bin_heap = bh def insert(self, item, rank): bh.push(item, rank) def pop(self): item = self.bin_heap.pop() return item def peek(self, item): return item
import bin_heap as bh class Priority(object): """docstring for priority""" def __init__(self): self.bin_heap = bh() def insert(self, item, rank): bh.push(item, rank) def pop(self): item = self.bin_heap.pop() return item def peek(self, item): return item
Fix typo; bin_heap will now properly instate
Fix typo; bin_heap will now properly instate
Python
mit
jwarren116/data-structures
--- +++ @@ -4,7 +4,7 @@ class Priority(object): """docstring for priority""" def __init__(self): - self.bin_heap = bh + self.bin_heap = bh() def insert(self, item, rank): bh.push(item, rank)
376fcbd76bb2f0de3c738ac66ac5526b6685d18a
plim/extensions.py
plim/extensions.py
from docutils.core import publish_parts import coffeescript from scss import Scss from stylus import Stylus from .util import as_unicode def rst_to_html(source): # This code was taken from http://wiki.python.org/moin/ReStructuredText # You may also be interested in http://www.tele3.cz/jbar/rest/about.html html = publish_parts(source=source, writer_name='html') return html['html_body'] def coffee_to_js(source): return as_unicode('<script>{js}</script>').format(js=coffeescript.compile(source)) def scss_to_css(source): css = Scss().compile(source).strip() return as_unicode('<style>{css}</style>').format(css=css) def stylus_to_css(source): compiler = Stylus(plugins={'nib':{}}) return as_unicode('<style>{css}</style>').format(css=compiler.compile(source).strip())
from docutils.core import publish_parts import coffeescript from scss import Scss from stylus import Stylus from .util import as_unicode def rst_to_html(source): # This code was taken from http://wiki.python.org/moin/ReStructuredText # You may also be interested in http://www.tele3.cz/jbar/rest/about.html html = publish_parts(source=source, writer_name='html') return html['html_body'] def coffee_to_js(source): return as_unicode('<script>{js}</script>').format(js=coffeescript.compile(source)) def scss_to_css(source): css = Scss().compile(source).strip() return as_unicode('<style>{css}</style>').format(css=css) def stylus_to_css(source): compiler = Stylus() return as_unicode('<style>{css}</style>').format(css=compiler.compile(source).strip())
Fix execjs.ProgramError: Error: Cannot find module 'nib' for -stylus
Fix execjs.ProgramError: Error: Cannot find module 'nib' for -stylus
Python
mit
kxxoling/Plim
--- +++ @@ -24,5 +24,5 @@ def stylus_to_css(source): - compiler = Stylus(plugins={'nib':{}}) + compiler = Stylus() return as_unicode('<style>{css}</style>').format(css=compiler.compile(source).strip())
db1c0183b3d42c611eaefa77f4b3bc4f33cb8267
django_classified/admin.py
django_classified/admin.py
# -*- coding:utf-8 -*- from django.contrib import admin from sorl.thumbnail.admin import AdminImageMixin from .models import Section, Group, Item, Image, Area class ImageInline(AdminImageMixin, admin.StackedInline): model = Image extra = 5 class ItemAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',), } list_display = ('title', 'group', 'area', 'user', 'is_active', 'posted', 'updated') list_filter = ('area', 'group', 'is_active', 'posted',) search_fields = ('title', 'user__email') inlines = [ImageInline] class GroupAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',), } list_display = ('title', 'slug', 'section', 'count') list_filter = ('section',) search_fields = ('title', 'section__title') class SectionAdmin(admin.ModelAdmin): list_display = ('title',) class AreaAdmin(admin.ModelAdmin): list_display = ( 'title', ) prepopulated_fields = {'slug': ('title',)} admin.site.register(Area, AreaAdmin) admin.site.register(Section, SectionAdmin) admin.site.register(Group, GroupAdmin) admin.site.register(Item, ItemAdmin)
# -*- coding:utf-8 -*- from django.contrib import admin from sorl.thumbnail.admin import AdminImageMixin from .models import Section, Group, Item, Image, Area class ImageInline(AdminImageMixin, admin.StackedInline): model = Image extra = 5 class ItemAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',), } list_display = ('title', 'group', 'area', 'user', 'is_active', 'posted', 'updated') list_filter = ('area', 'group', 'is_active', 'posted',) search_fields = ('title', 'description', 'user__email') inlines = [ImageInline] class GroupAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',), } list_display = ('title', 'slug', 'section', 'count') list_filter = ('section',) search_fields = ('title', 'section__title') class SectionAdmin(admin.ModelAdmin): list_display = ('title',) class AreaAdmin(admin.ModelAdmin): list_display = ( 'title', ) prepopulated_fields = {'slug': ('title',)} admin.site.register(Area, AreaAdmin) admin.site.register(Section, SectionAdmin) admin.site.register(Group, GroupAdmin) admin.site.register(Item, ItemAdmin)
Allow to search items by description.
Allow to search items by description.
Python
mit
inoks/dcf,inoks/dcf
--- +++ @@ -14,7 +14,7 @@ prepopulated_fields = {'slug': ('title',), } list_display = ('title', 'group', 'area', 'user', 'is_active', 'posted', 'updated') list_filter = ('area', 'group', 'is_active', 'posted',) - search_fields = ('title', 'user__email') + search_fields = ('title', 'description', 'user__email') inlines = [ImageInline]
33448ac669e192143655560dd52299e7069585ac
django_token/middleware.py
django_token/middleware.py
from django import http from django.contrib import auth from django.core import exceptions class TokenMiddleware(object): """ Middleware that authenticates against a token in the http authorization header. """ get_response = None def __init__(self, get_response=None): self.get_response = get_response def __call__(self, request): if not self.get_response: return exceptions.ImproperlyConfigured( 'Middleware called without proper initialization') self.process_request(request) return self.get_response(request) def process_request(self, request): auth_header = request.META.get('HTTP_AUTHORIZATION', b'') auth_header = auth_header.partition(b' ') if auth_header[0].lower() != b'token': return None # If they specified an invalid token, let them know. if not auth_header[2]: return http.HttpResponseBadRequest("Improperly formatted token") user = auth.authenticate(token=auth_header[2]) if user: request.user = user
from django import http from django.contrib import auth from django.core import exceptions class TokenMiddleware(object): """ Middleware that authenticates against a token in the http authorization header. """ get_response = None def __init__(self, get_response=None): self.get_response = get_response def __call__(self, request): if not self.get_response: return exceptions.ImproperlyConfigured( 'Middleware called without proper initialization') self.process_request(request) return self.get_response(request) def process_request(self, request): auth_header = str(request.META.get('HTTP_AUTHORIZATION', '')).partition(' ') if auth_header[0].lower() != 'token': return None # If they specified an invalid token, let them know. if not auth_header[2]: return http.HttpResponseBadRequest("Improperly formatted token") user = auth.authenticate(token=auth_header[2]) if user: request.user = user
Fix for byte literals compatibility.
Fix for byte literals compatibility.
Python
mit
jasonbeverage/django-token
--- +++ @@ -23,10 +23,9 @@ return self.get_response(request) def process_request(self, request): - auth_header = request.META.get('HTTP_AUTHORIZATION', b'') - auth_header = auth_header.partition(b' ') + auth_header = str(request.META.get('HTTP_AUTHORIZATION', '')).partition(' ') - if auth_header[0].lower() != b'token': + if auth_header[0].lower() != 'token': return None # If they specified an invalid token, let them know.
b929573e051f84ecc15020889fde6f6d798daa18
pmxbot/__init__.py
pmxbot/__init__.py
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab from __future__ import absolute_import import socket import logging from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'localhost', server_port = 6667, use_ssl = False, password = None, silent_bot = False, log_channels = [], other_channels = [], places = ['London', 'Tokyo', 'New York'], feed_interval = 15, # minutes feeds = [dict( name = 'pmxbot bitbucket', channel = '#inane', linkurl = 'http://bitbucket.org/yougov/pmxbot', url = 'http://bitbucket.org/yougov/pmxbot', ), ], librarypaste = 'http://paste.jaraco.com', ) config['logs URL'] = 'http://' + socket.getfqdn() config['log level'] = logging.INFO "The config object"
# -*- coding: utf-8 -*- # vim:ts=4:sw=4:noexpandtab from __future__ import absolute_import import socket import logging as _logging from .dictlib import ConfigDict config = ConfigDict( bot_nickname = 'pmxbot', database = 'sqlite:pmxbot.sqlite', server_host = 'localhost', server_port = 6667, use_ssl = False, password = None, silent_bot = False, log_channels = [], other_channels = [], places = ['London', 'Tokyo', 'New York'], feed_interval = 15, # minutes feeds = [dict( name = 'pmxbot bitbucket', channel = '#inane', linkurl = 'http://bitbucket.org/yougov/pmxbot', url = 'http://bitbucket.org/yougov/pmxbot', ), ], librarypaste = 'http://paste.jaraco.com', ) config['logs URL'] = 'http://' + socket.getfqdn() config['log level'] = _logging.INFO "The config object"
Fix issue with conflated pmxbot.logging
Fix issue with conflated pmxbot.logging
Python
mit
yougov/pmxbot,yougov/pmxbot,yougov/pmxbot
--- +++ @@ -4,7 +4,7 @@ from __future__ import absolute_import import socket -import logging +import logging as _logging from .dictlib import ConfigDict @@ -30,6 +30,6 @@ librarypaste = 'http://paste.jaraco.com', ) config['logs URL'] = 'http://' + socket.getfqdn() -config['log level'] = logging.INFO +config['log level'] = _logging.INFO "The config object"
108c11d5187f7ec4647351c924df8cd881020b8a
falmer/matte/views.py
falmer/matte/views.py
from rest_framework import views, serializers from rest_framework.decorators import permission_classes from rest_framework.parsers import FileUploadParser from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from falmer.content.serializers import WagtailImageSerializer from falmer.matte.models import MatteImage class MatteUploadSerializer(serializers.Serializer): source = serializers.IntegerField() file = serializers.FileField() def create(self, validated_data): image = MatteImage.objects.create( internal_source=validated_data['source'], file=validated_data['file'], file_size=validated_data['file'].size, uploaded_by_user=validated_data['user'] ) return image class Image(views.APIView): # parser_classes = (FileUploadParser, ) @permission_classes((IsAuthenticated,)) def put(self, request): image = MatteUploadSerializer(data=request.data) if image.is_valid(): image = image.save(user=request.user) return Response({ 'ok': True, 'data': WagtailImageSerializer(instance=image).data }, status=200)
from rest_framework import views, serializers from rest_framework.decorators import permission_classes from rest_framework.parsers import FileUploadParser from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from falmer.content.serializers import WagtailImageSerializer from falmer.matte.models import MatteImage class MatteUploadSerializer(serializers.Serializer): source = serializers.IntegerField() file = serializers.FileField() def create(self, validated_data): image = MatteImage.objects.create( internal_source=validated_data['source'], file=validated_data['file'], file_size=validated_data['file'].size, uploaded_by_user=validated_data['user'] ) return image class Image(views.APIView): # parser_classes = (FileUploadParser, ) @permission_classes((IsAuthenticated,)) def put(self, request): image = MatteUploadSerializer(data=request.data) if image.is_valid(): image = image.save(user=request.user) return Response({ 'ok': True, 'data': WagtailImageSerializer(instance=image).data }, status=200) else: print('file upload issue', image.errors) return Response({ 'ok': False, 'errors': image.errors }, status=400)
Return error for image upload
Return error for image upload
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
--- +++ @@ -37,3 +37,9 @@ 'ok': True, 'data': WagtailImageSerializer(instance=image).data }, status=200) + else: + print('file upload issue', image.errors) + return Response({ + 'ok': False, + 'errors': image.errors + }, status=400)
17cc0e9ab4f32e74c9a03124e38628c0f6640f40
nodeconductor/quotas/serializers.py
nodeconductor/quotas/serializers.py
from rest_framework import serializers from nodeconductor.quotas import models, utils from nodeconductor.core.serializers import GenericRelatedField class QuotaSerializer(serializers.HyperlinkedModelSerializer): scope = GenericRelatedField(related_models=utils.get_models_with_quotas(), read_only=True) class Meta(object): model = models.Quota fields = ('url', 'uuid', 'name', 'limit', 'usage', 'scope') read_only_fields = ('uuid', 'name') lookup_field = 'uuid' # TODO: cleanup after migration to drf 3 def validate(self, attrs): from nodeconductor.structure.serializers import fix_non_nullable_attrs return fix_non_nullable_attrs(attrs)
from rest_framework import serializers from nodeconductor.quotas import models, utils from nodeconductor.core.serializers import GenericRelatedField class QuotaSerializer(serializers.HyperlinkedModelSerializer): scope = GenericRelatedField(related_models=utils.get_models_with_quotas(), read_only=True) class Meta(object): model = models.Quota fields = ('url', 'uuid', 'name', 'limit', 'usage', 'scope') read_only_fields = ('uuid', 'name', 'scope', 'usage') lookup_field = 'uuid' # TODO: cleanup after migration to drf 3 def validate(self, attrs): from nodeconductor.structure.serializers import fix_non_nullable_attrs return fix_non_nullable_attrs(attrs)
Make quota usage read only (nc-263)
Make quota usage read only (nc-263)
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
--- +++ @@ -10,7 +10,7 @@ class Meta(object): model = models.Quota fields = ('url', 'uuid', 'name', 'limit', 'usage', 'scope') - read_only_fields = ('uuid', 'name') + read_only_fields = ('uuid', 'name', 'scope', 'usage') lookup_field = 'uuid' # TODO: cleanup after migration to drf 3
2e9b87a7409f1995f96867270361f23a9fc3d1ab
flaskext/clevercss.py
flaskext/clevercss.py
# -*- coding: utf-8 -*- """ flaskext.clevercss ~~~~~~~~~~~~~ A small Flask extension that makes it easy to use cleverCSS with your Flask application. :copyright: (c) 2010 by Steve Losh. :copyright: (c) 2011 by Sujan Shakya. :license: MIT, see LICENSE for more details. """ 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()
# -*- coding: utf-8 -*- """ flaskext.clevercss ~~~~~~~~~~~~~ A small Flask extension that makes it easy to use cleverCSS with your Flask application. :copyright: (c) 2010 by Steve Losh. :copyright: (c) 2011 by Sujan Shakya. :license: MIT, see LICENSE for more details. """ 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
--- +++ @@ -18,7 +18,7 @@ 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):
ac31a10d00508ddd354d9c30055d2955b306d516
duct/protocol/sflow/protocol/utils.py
duct/protocol/sflow/protocol/utils.py
import struct, socket def unpack_address(u): addrtype = u.unpack_uint() if self.addrtype == 1: self.address = u.unpack_fopaque(4) if self.addrtype == 2: self.address = u.unpack_fopaque(16) return self.address class IPv4Address(object): def __init__(self, addr_int): self.addr_int = addr_int self.na = struct.pack(b'!L', addr_int) def __str__(self): return socket.inet_ntoa(self.na) def asString(self): return str(self) def __repr__(self): return "<IPv4Address ip=\"%s\">" % str(self)
import struct, socket def unpack_address(u): addrtype = u.unpack_uint() if addrtype == 1: address = u.unpack_fopaque(4) if addrtype == 2: address = u.unpack_fopaque(16) return address class IPv4Address(object): def __init__(self, addr_int): self.addr_int = addr_int self.na = struct.pack(b'!L', addr_int) def __str__(self): return socket.inet_ntoa(self.na) def asString(self): return str(self) def __repr__(self): return "<IPv4Address ip=\"%s\">" % str(self)
Fix bad transposition of utility function in sflow
Fix bad transposition of utility function in sflow
Python
mit
ducted/duct,ducted/duct,ducted/duct,ducted/duct
--- +++ @@ -4,13 +4,13 @@ def unpack_address(u): addrtype = u.unpack_uint() - if self.addrtype == 1: - self.address = u.unpack_fopaque(4) + if addrtype == 1: + address = u.unpack_fopaque(4) - if self.addrtype == 2: - self.address = u.unpack_fopaque(16) + if addrtype == 2: + address = u.unpack_fopaque(16) - return self.address + return address class IPv4Address(object): def __init__(self, addr_int):
2045856aa66cef7b81d9e617fd29fc9ca19276d7
pwned/src/pwned.py
pwned/src/pwned.py
import hashlib, sys, urllib.request def main(): hash = hashlib.sha1(bytes(sys.argv[1], "utf-8")) digest = hash.hexdigest().upper() url = f"https://api.pwnedpasswords.com/range/{digest[:5]}" request = urllib.request.Request(url, headers={"User-Agent":"API-Programming-Exercise"}) page = urllib.request.urlopen(request) data = (page.read().decode('utf-8').split()) for i in data: tmp = i.split(":") if digest[:5] + tmp[0] == digest: print(f"{sys.argv[1]} was found") print(f"Hash {digest}, {tmp[1]} occurrences") if __name__ == "__main__": main()
import hashlib, sys, urllib.request def main(): hash = hashlib.sha1(bytes(sys.argv[1], "utf-8")) digest = hash.hexdigest().upper() url = f"https://api.pwnedpasswords.com/range/{digest[:5]}" request = urllib.request.Request(url, headers={"User-Agent":"API-Programming-Exercise"}) page = urllib.request.urlopen(request) data = (page.read().decode('utf-8').split()) for i in data: tmp = i.split(":") if digest[:5] + tmp[0] == digest: print(f"{sys.argv[1]} was found") print(f"Hash {digest}, {tmp[1]} occurrences") else: print(f"Password {sys.argv[1]} was not found") if __name__ == "__main__": main()
Add output when password is not found
Add output when password is not found
Python
agpl-3.0
0x424D/crappy,0x424D/crappy
--- +++ @@ -15,6 +15,8 @@ if digest[:5] + tmp[0] == digest: print(f"{sys.argv[1]} was found") print(f"Hash {digest}, {tmp[1]} occurrences") + else: + print(f"Password {sys.argv[1]} was not found") if __name__ == "__main__": main()
9fb302a4e8d5d69fa4c9727c72f7953f26d1f13f
SyncOnSave.py
SyncOnSave.py
import sublime, sublime_plugin import subprocess import threading DEBUG = False # Base rsync command template: rsync -arv <local> <remote> base_cmd = "rsync -arv {0} {1}" class SyncOnSaveCommand(sublime_plugin.EventListener): def on_post_save(self, view): """ Sync directory containing the current directory after saving. """ synced_dirs = sublime.load_settings("SyncOnSave.sublime-settings").get("synced_dirs") file_name = view.file_name() for synced_dir in synced_dirs.keys(): if file_name.startswith(synced_dir): # Current file is in a synced directory. remote = synced_dirs[synced_dir]["remote"] cmd = base_cmd.format(synced_dir, remote) if DEBUG: print cmd # Execute rsync in a new thread, to avoid noticeable network lag on save. thread = threading.Thread(target=subprocess.call, args=(cmd,), kwargs={"shell": True}) thread.daemon = True thread.start()
from __future__ import print_function import sublime, sublime_plugin import subprocess import threading DEBUG = False # Base rsync command template: rsync -arv <local> <remote> base_cmd = "rsync -arv {0} {1}" class SyncOnSaveCommand(sublime_plugin.EventListener): def on_post_save(self, view): """ Sync directory containing the current directory after saving. """ synced_dirs = sublime.load_settings("SyncOnSave.sublime-settings").get("synced_dirs") file_name = view.file_name() for synced_dir in synced_dirs.keys(): if file_name.startswith(synced_dir): # Current file is in a synced directory. remote = synced_dirs[synced_dir]["remote"] cmd = base_cmd.format(synced_dir, remote) if DEBUG: print(cmd) # Execute rsync in a new thread, to avoid noticeable network lag on save. thread = threading.Thread(target=subprocess.call, args=(cmd,), kwargs={"shell": True}) thread.daemon = True thread.start()
Add Sublime Text 3 support
Add Sublime Text 3 support
Python
mit
aldld/SyncOnSave
--- +++ @@ -1,3 +1,5 @@ +from __future__ import print_function + import sublime, sublime_plugin import subprocess import threading @@ -21,7 +23,7 @@ cmd = base_cmd.format(synced_dir, remote) if DEBUG: - print cmd + print(cmd) # Execute rsync in a new thread, to avoid noticeable network lag on save. thread = threading.Thread(target=subprocess.call, args=(cmd,), kwargs={"shell": True})
34c38e0cfe5e880e678704c4d473f082787fca64
rest_framework/authtoken/management/commands/drf_create_token.py
rest_framework/authtoken/management/commands/drf_create_token.py
from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from rest_framework.authtoken.models import Token UserModel = get_user_model() class Command(BaseCommand): help = 'Create DRF Token for a given user' def create_user_token(self, username): user = UserModel._default_manager.get_by_natural_key(username) token = Token.objects.get_or_create(user=user) return token[0] def add_arguments(self, parser): parser.add_argument('username', type=str, nargs='+') def handle(self, *args, **options): username = options['username'] try: token = self.create_user_token(username) except UserModel.DoesNotExist: print('Cannot create the Token: user {0} does not exist'.format( username )) print('Generated token {0} for user {1}'.format(token.key, username))
from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand, CommandError from rest_framework.authtoken.models import Token UserModel = get_user_model() class Command(BaseCommand): help = 'Create DRF Token for a given user' def create_user_token(self, username): user = UserModel._default_manager.get_by_natural_key(username) token = Token.objects.get_or_create(user=user) return token[0] def add_arguments(self, parser): parser.add_argument('username', type=str, nargs='+') def handle(self, *args, **options): username = options['username'] try: token = self.create_user_token(username) except UserModel.DoesNotExist: raise CommandError( 'Cannot create the Token: user {0} does not exist'.format( username) ) self.stdout.write( 'Generated token {0} for user {1}'.format(token.key, username))
Use self.sdtout and CommandError to print output
Use self.sdtout and CommandError to print output
Python
bsd-2-clause
dmwyatt/django-rest-framework,ossanna16/django-rest-framework,jpadilla/django-rest-framework,tomchristie/django-rest-framework,jpadilla/django-rest-framework,kgeorgy/django-rest-framework,kgeorgy/django-rest-framework,tomchristie/django-rest-framework,tomchristie/django-rest-framework,ossanna16/django-rest-framework,jpadilla/django-rest-framework,kgeorgy/django-rest-framework,ossanna16/django-rest-framework,davesque/django-rest-framework,davesque/django-rest-framework,davesque/django-rest-framework,dmwyatt/django-rest-framework,dmwyatt/django-rest-framework
--- +++ @@ -1,5 +1,5 @@ from django.contrib.auth import get_user_model -from django.core.management.base import BaseCommand +from django.core.management.base import BaseCommand, CommandError from rest_framework.authtoken.models import Token @@ -23,7 +23,9 @@ try: token = self.create_user_token(username) except UserModel.DoesNotExist: - print('Cannot create the Token: user {0} does not exist'.format( - username - )) - print('Generated token {0} for user {1}'.format(token.key, username)) + raise CommandError( + 'Cannot create the Token: user {0} does not exist'.format( + username) + ) + self.stdout.write( + 'Generated token {0} for user {1}'.format(token.key, username))
f7f3907da8ec31cafaec3d7e82755cfa344ed60e
performance/web.py
performance/web.py
class Request: GET = 'get' POST = 'post' def __init__(self, url, type, data=None): self.url = url self.type = type self.data = data class RequestData: def __init__(self, data=None): self.data = data def for_type(self, type=Request.GET): if type is Request.GET: return data
import requests from time import time class Client: def __init__(self): pass class Request: GET = 'get' POST = 'post' def __init__(self, url, type, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) self.started = time() response = getattr(requests, self.type)( url=self.url, data=data ) self.finished = time() self.status_code = response.status_code except AttributeError: raise RequestTypeError(type=self.type) def get_response_time(self): try: return self.finished - self.started except AttributeError: raise RequestTimeError class RequestData: def __init__(self, data=None): self.data = data def for_type(self, type=Request.GET): if type is Request.GET: return data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s".' % self.type class RequestTimeError(Exception): pass
Create Error-classes, Client class and do function for Request
Create Error-classes, Client class and do function for Request
Python
mit
BakeCode/performance-testing,BakeCode/performance-testing
--- +++ @@ -1,3 +1,12 @@ +import requests +from time import time + + +class Client: + def __init__(self): + pass + + class Request: GET = 'get' POST = 'post' @@ -7,6 +16,27 @@ self.type = type self.data = data + def do(self): + try: + data = '' + if isinstance(self.data, RequestData): + data = self.data.for_type(type=self.type) + self.started = time() + response = getattr(requests, self.type)( + url=self.url, + data=data + ) + self.finished = time() + self.status_code = response.status_code + except AttributeError: + raise RequestTypeError(type=self.type) + + def get_response_time(self): + try: + return self.finished - self.started + except AttributeError: + raise RequestTimeError + class RequestData: def __init__(self, data=None): @@ -15,3 +45,15 @@ def for_type(self, type=Request.GET): if type is Request.GET: return data + + +class RequestTypeError(Exception): + def __init__(self, type): + self.type = type + + def __str__(self): + return 'Invalid request type "%s".' % self.type + + +class RequestTimeError(Exception): + pass
112d12aa4622b77a55f0f90b6c0cb7c3ac3d407e
CommandException.py
CommandException.py
class CommandException(Exception): """ This custom exception can be thrown by commands when something goes wrong during execution. The parameter is a message sent to the source that called the command (a channel or a user) """ def __init__(self, displayMessage=None, shouldLogError=True): """ Create a new CommandException, to be thrown when something goes wrong during Command execution :param displayMessage: An optional message to display to the IRC chat the bot is in :param shouldLogError: Whether this exception should be logged to the program log. This is useful if it's a problem that needs to be solved, but can be set to False if it's a user input error """ self.displayMessage = displayMessage self.shouldLogError = shouldLogError def __str__(self): return self.displayMessage class CommandInputException(CommandException): """ This custom exception can be raised when the input to some module or command is invalid or can't be parsed. It is a more specific implementation of the CommandException, that doesn't log itself to the logfile """ def __init__(self, displayMessage): """ Create a new InputException. The display message will be shown to the user :param displayMessage: The message to show to the user that called the command. This message should explain how the input should be correctly formatted """ super(CommandException, self).__init__(displayMessage, False)
class CommandException(Exception): """ This custom exception can be thrown by commands when something goes wrong during execution. The parameter is a message sent to the source that called the command (a channel or a user) """ def __init__(self, displayMessage=None, shouldLogError=True): """ Create a new CommandException, to be thrown when something goes wrong during Command execution :param displayMessage: An optional message to display to the IRC chat the bot is in :param shouldLogError: Whether this exception should be logged to the program log. This is useful if it's a problem that needs to be solved, but can be set to False if it's a user input error """ self.displayMessage = displayMessage self.shouldLogError = shouldLogError def __str__(self): return self.displayMessage class CommandInputException(CommandException): """ This custom exception can be raised when the input to some module or command is invalid or can't be parsed. It is a more specific implementation of the CommandException, that doesn't log itself to the logfile """ def __init__(self, displayMessage): """ Create a new InputException. The display message will be shown to the user :param displayMessage: The message to show to the user that called the command. This message should explain how the input should be correctly formatted """ super(CommandInputException, self).__init__(displayMessage, False)
Fix wrong class in 'super()' call
Fix wrong class in 'super()' call Oops
Python
mit
Didero/DideRobot
--- +++ @@ -28,4 +28,4 @@ Create a new InputException. The display message will be shown to the user :param displayMessage: The message to show to the user that called the command. This message should explain how the input should be correctly formatted """ - super(CommandException, self).__init__(displayMessage, False) + super(CommandInputException, self).__init__(displayMessage, False)
7c6a128b707db738d0a89c2897b35ed7d783ade0
plugins/basic_info_plugin.py
plugins/basic_info_plugin.py
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): name = 'BasicInfoPlugin' short_description = 'Basic info:' default = True description = textwrap.dedent(''' This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes ''') def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# unprintable'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.printable for x in s))) result += str(table) + '\n' return result
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): name = 'BasicInfoPlugin' short_description = 'Basic info:' default = True description = textwrap.dedent(''' This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes ''') def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# Punct.', '# Control'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) result += str(table) + '\n' return result
Add punctuation to basic info
Add punctuation to basic info
Python
mit
Sakartu/stringinfo
--- +++ @@ -22,9 +22,9 @@ if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() - table.field_names = ['Length', '# Digits', '# Alpha', '# unprintable'] + table.field_names = ['Length', '# Digits', '# Alpha', '# Punct.', '# Control'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), - sum(x in string.printable for x in s))) + sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) result += str(table) + '\n' return result
c1f63f381b167d6bfe701a36e998727cf4ed3bec
client/software/resources/modules/hardware_auto_find.py
client/software/resources/modules/hardware_auto_find.py
#I got this code on http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python #So, yeah. I didn't wrote this code :-P import sys import glob import serial def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/tty[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/tty.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result if __name__ == '__main__': print(serial_ports())
#I got this code on http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python #So, yeah. I didn't wrote this code :-P import sys import glob import serial def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" # ports = glob.glob('/dev/tty[A-Za-z]*') ports = glob.glob('/dev/ttyUSB[A-Za-z0-9]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/tty.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result if __name__ == '__main__': print(serial_ports())
Make hardware search only on USB on Ubuntu Linux
Make hardware search only on USB on Ubuntu Linux
Python
mit
MU-Software/Project_Musica_for_Contest
--- +++ @@ -16,7 +16,8 @@ ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" - ports = glob.glob('/dev/tty[A-Za-z]*') + # ports = glob.glob('/dev/tty[A-Za-z]*') + ports = glob.glob('/dev/ttyUSB[A-Za-z0-9]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/tty.*') else:
171144db2109e4bbe357b44ca37ad5578e1c3996
config.py
config.py
FFMPEG_PATH = '/usr/local/bin/ffmpeg' VIDEO_CODEC = 'h264' # used with ffprobe to detect whether or not we need to encode VIDEO_ENCODER = 'h264_omx' AUDIO_CODEC = 'aac' # used with ffprobe to detect whether or not we need to encode AUDIO_ENCODER = 'aac' BITRATE = '2500k' INPUT_EXTS = ['.mkv'] OUTPUT_EXT = '.mp4'
FFMPEG_PATH = '/usr/local/bin/ffmpeg' VIDEO_CODEC = 'h264' # used with ffprobe to detect whether or not we need to encode VIDEO_ENCODER = 'h264_omx' AUDIO_CODEC = 'aac' # used with ffprobe to detect whether or not we need to encode AUDIO_ENCODER = 'aac' BITRATE = '2500k' INPUT_EXTS = ['.mkv', '.mp4'] OUTPUT_EXT = '.mp4'
Add mp4 as input ext
Add mp4 as input ext
Python
mit
danielbreves/auto_encoder
--- +++ @@ -8,5 +8,5 @@ BITRATE = '2500k' -INPUT_EXTS = ['.mkv'] +INPUT_EXTS = ['.mkv', '.mp4'] OUTPUT_EXT = '.mp4'
1bd344a3ccda43f4ac1d4b94b1a18fc816c9b6ae
slurmscale/jobs/jobs.py
slurmscale/jobs/jobs.py
"""Get info about jobs running on this cluster.""" import pyslurm from job import Job class Jobs(object): """A service object to inspect jobs.""" @property def _jobs(self): """Fetch fresh data.""" return pyslurm.job().get() def list(self): """List the current jobs on the cluster.""" current_jobs = self._jobs return [Job(current_jobs[j]) for j in current_jobs]
"""Get info about jobs running on this cluster.""" import pyslurm from job import Job class Jobs(object): """A service object to inspect jobs.""" @property def _jobs(self): """Fetch fresh data.""" return pyslurm.job().get() def list(self, states=None): """ List the current jobs on the cluster. :type states: List of ``str`` :param states: Filter jobs in the given states. Available states are ``PENDING``, ``RUNNING``, ``CANCELLED``, ``CONFIGURING``, ``COMPLETING``, ``COMPLETED``, ``FAILED``, ``TIMEOUT``, ``PREEMPTED``, ``NODE_FAIL`` and ``SPECIAL_EXIT``. :rtype: List of ``Job`` :return: A list of current cluster jobs, possibly filtered by supplied states. """ current_jobs = self._jobs jobs = [] if states: for i in current_jobs: if current_jobs[i].get('job_state', '') in states: jobs.append(Job(current_jobs[i])) else: jobs = [Job(current_jobs[j]) for j in current_jobs] return jobs
Add ability to filter job list by job state
Add ability to filter job list by job state
Python
mit
afgane/slurmscale,afgane/slurmscale
--- +++ @@ -12,7 +12,26 @@ """Fetch fresh data.""" return pyslurm.job().get() - def list(self): - """List the current jobs on the cluster.""" + def list(self, states=None): + """ + List the current jobs on the cluster. + + :type states: List of ``str`` + :param states: Filter jobs in the given states. Available states are + ``PENDING``, ``RUNNING``, ``CANCELLED``, ``CONFIGURING``, + ``COMPLETING``, ``COMPLETED``, ``FAILED``, ``TIMEOUT``, + ``PREEMPTED``, ``NODE_FAIL`` and ``SPECIAL_EXIT``. + + :rtype: List of ``Job`` + :return: A list of current cluster jobs, possibly filtered by supplied + states. + """ current_jobs = self._jobs - return [Job(current_jobs[j]) for j in current_jobs] + jobs = [] + if states: + for i in current_jobs: + if current_jobs[i].get('job_state', '') in states: + jobs.append(Job(current_jobs[i])) + else: + jobs = [Job(current_jobs[j]) for j in current_jobs] + return jobs
d3f73b55dc68ec18fb5f4c43dcff59f3766d752f
mica/starcheck/__init__.py
mica/starcheck/__init__.py
from .starcheck import get_starcheck_catalog, main, get_mp_dir
from .starcheck import get_starcheck_catalog, get_starcheck_catalog_at_date, main, get_mp_dir
Add get_starcheck_catalog_at_date to top level items in mica.starcheck
Add get_starcheck_catalog_at_date to top level items in mica.starcheck
Python
bsd-3-clause
sot/mica,sot/mica
--- +++ @@ -1 +1 @@ -from .starcheck import get_starcheck_catalog, main, get_mp_dir +from .starcheck import get_starcheck_catalog, get_starcheck_catalog_at_date, main, get_mp_dir
20d1cd153d54f2eab88197c76c201ed5e7814536
modules/urbandictionary.py
modules/urbandictionary.py
"""Looks up a term from urban dictionary @package ppbot @syntax ud <word> """ import requests import json from modules import * class Urbandictionary(Module): def __init__(self, *args, **kwargs): """Constructor""" Module.__init__(self, kwargs=kwargs) self.url = "http://www.urbandictionary.com/iphone/search/define?term=%s" def _register_events(self): """Register module commands.""" self.add_command('ud') def ud(self, event): """Action to react/respond to user calls.""" if self.num_args >= 1: word = '%20'.join(event['args']) r = requests.get(self.url % (word)) ur = json.loads(r.text) try: definition = ur['list'][0] definition['definition'] = definition['definition'].replace("\r", " ").replace("\n", " ") definition['example'] = definition['example'].replace("\r", " ").replace("\n", " ") message = "%(word)s (%(thumbs_up)d/%(thumbs_down)d): %(definition)s (ex: %(example)s)" % (definition) self.msg(event['target'], message[:450]) except KeyError: self.msg(event['target'], 'Could find word "%s"' % ' '.join(event['args'])) else: self.syntax_message(event['nick'], '.ud <word>')
"""Looks up a term from urban dictionary @package ppbot @syntax ud <word> """ import requests import json from modules import * class Urbandictionary(Module): def __init__(self, *args, **kwargs): """Constructor""" Module.__init__(self, kwargs=kwargs) self.url = "http://www.urbandictionary.com/iphone/search/define?term=%s" def _register_events(self): """Register module commands.""" self.add_command('ud') def ud(self, event): """Action to react/respond to user calls.""" if self.num_args >= 1: word = '%20'.join(event['args']) r = requests.get(self.url % (word)) ur = json.loads(r.text) try: definition = ur['list'][0] definition['definition'] = definition['definition'].replace("\r", " ").replace("\n", " ") definition['example'] = definition['example'].replace("\r", " ").replace("\n", " ") message = "%(word)s (%(thumbs_up)d/%(thumbs_down)d): %(definition)s (ex: %(example)s)" % (definition) self.msg(event['target'], message[:450]) except (IndexError, KeyError) as e: self.msg(event['target'], 'Could find word "%s"' % ' '.join(event['args'])) else: self.syntax_message(event['nick'], '.ud <word>')
Fix another exception for ud when def isn't found
Fix another exception for ud when def isn't found
Python
mit
billyvg/piebot
--- +++ @@ -35,7 +35,7 @@ definition['example'] = definition['example'].replace("\r", " ").replace("\n", " ") message = "%(word)s (%(thumbs_up)d/%(thumbs_down)d): %(definition)s (ex: %(example)s)" % (definition) self.msg(event['target'], message[:450]) - except KeyError: + except (IndexError, KeyError) as e: self.msg(event['target'], 'Could find word "%s"' % ' '.join(event['args'])) else: self.syntax_message(event['nick'], '.ud <word>')
137b834f166eea13781311b1f050f0eaf2e1d610
podcasts/management/commands/updatepodcasts.py
podcasts/management/commands/updatepodcasts.py
from django.core.management import BaseCommand from podcasts.models import Podcast class Command(BaseCommand): help = 'Initialize podcasts with data from their RSS feeds' def handle(self, *args, **kwargs): for podcast in Podcast.objects.all(): podcast.update()
from django.core.management import BaseCommand from optparse import make_option from podcasts.models import Podcast class Command(BaseCommand): help = 'Initialize podcasts with data from their RSS feeds' option_list = BaseCommand.option_list + ( make_option( '--only-new', action='store_true', dest='only_new', default=False, help='Only update new podcasts' ), ) def handle(self, *args, **options): for podcast in Podcast.objects.all(): if options['only_new'] and podcast.title != "": continue podcast.update()
Make it optional to only update metadata of new podcasts
Make it optional to only update metadata of new podcasts
Python
mit
matachi/sputnik,matachi/sputnik,matachi/sputnik,matachi/sputnik
--- +++ @@ -1,10 +1,22 @@ from django.core.management import BaseCommand +from optparse import make_option from podcasts.models import Podcast class Command(BaseCommand): help = 'Initialize podcasts with data from their RSS feeds' + option_list = BaseCommand.option_list + ( + make_option( + '--only-new', + action='store_true', + dest='only_new', + default=False, + help='Only update new podcasts' + ), + ) - def handle(self, *args, **kwargs): + def handle(self, *args, **options): for podcast in Podcast.objects.all(): + if options['only_new'] and podcast.title != "": + continue podcast.update()
06122b26a944455576b41501cae6fb73af1bf901
post/tests/urls.py
post/tests/urls.py
from django.conf.urls import patterns, include urlpatterns = patterns( (r'^jmbo/', include('jmbo.urls')), (r'^comments/', include('django.contrib.comments.urls')), (r'^post/', include('post.urls')), )
from django.conf.urls import patterns, include urlpatterns = patterns( '', (r'^jmbo/', include('jmbo.urls')), (r'^comments/', include('django.contrib.comments.urls')), (r'^post/', include('post.urls')), )
Use correct url pattern format
Use correct url pattern format
Python
bsd-3-clause
praekelt/jmbo-post,praekelt/jmbo-post
--- +++ @@ -2,6 +2,7 @@ urlpatterns = patterns( + '', (r'^jmbo/', include('jmbo.urls')), (r'^comments/', include('django.contrib.comments.urls')), (r'^post/', include('post.urls')),
aee157ce27aa4f00a798b87e07583dc795265eb4
methodAndKnottiness/reliability.py
methodAndKnottiness/reliability.py
import sys count = 0 for line in sys.stdin: if count == 0: B = int(line) elif count == 1: N = int(line) else: c, r = line.rstrip().split(' ') cost = int(c) reliability = float(r) count+=1 print("Fin")
import sys, math count = 0 cost=[] reliability=[] # Read input. Budget, number of machines, cost and reliability for line in sys.stdin: if count == 0: B = int(line) elif count == 1: N = int(line) else: c, r = line.rstrip().split(' ') cost.append(int(c)) reliability.append(float(r)) count+=1 M = [[0 for i in range(B)] for i in range(N)] for i in range(B): M[0][i]=1 print(cost) #for i in range(1,N): for i in range(1,3): for b in range(0,B): max = 0 # break for k in range(0, math.floor(b/cost[i])): m = M[i-1][b-k*cost[i]]*(1-reliability[i])**k if m > max: max = m print("new max",max) print("Budget:", B) print("Number machines:", N) # print("\nIterated Version:") # print(M[0:3]) print("Fin")
Save point, got code written but need to figure out the base probabilities
Save point, got code written but need to figure out the base probabilities
Python
mit
scrasmussen/ProsaicOeuvre,scrasmussen/ProsaicOeuvre,scrasmussen/ProsaicOeuvre
--- +++ @@ -1,6 +1,10 @@ -import sys +import sys, math count = 0 +cost=[] +reliability=[] + +# Read input. Budget, number of machines, cost and reliability for line in sys.stdin: if count == 0: B = int(line) @@ -8,10 +12,31 @@ N = int(line) else: c, r = line.rstrip().split(' ') - cost = int(c) - reliability = float(r) - + cost.append(int(c)) + reliability.append(float(r)) + count+=1 +M = [[0 for i in range(B)] for i in range(N)] +for i in range(B): + M[0][i]=1 + + +print(cost) +#for i in range(1,N): +for i in range(1,3): + for b in range(0,B): + max = 0 + # break + for k in range(0, math.floor(b/cost[i])): + m = M[i-1][b-k*cost[i]]*(1-reliability[i])**k + if m > max: + max = m + print("new max",max) + +print("Budget:", B) +print("Number machines:", N) +# print("\nIterated Version:") +# print(M[0:3]) print("Fin")
56ff6b21e9530edf823a9ff178b4b24702df4ace
badgus/urls.py
badgus/urls.py
from django.conf import settings from django.conf.urls.defaults import * from .profiles import urls as profiles_urls from django.views.generic.simple import direct_to_template from django.contrib import admin admin.autodiscover() import badger badger.autodiscover() from funfactory import monkeypatches monkeypatches.patch() from badger import Progress #from badger_multiplayer.models import Badge, Award, Nomination from badger.models import Badge, Award urlpatterns = patterns('', url(r'^$', 'badger.views.home', name='home'), (r'^notification/', include('notification.urls')), (r'^badges/', include('badger_multiplayer.urls')), (r'^badges/', include('badger.urls')), (r'^browserid/', include('django_browserid.urls')), (r'^profiles/', include(profiles_urls)), (r'^accounts/', include('django.contrib.auth.urls')), (r'^admin/', include(admin.site.urls)), ) ## In DEBUG mode, serve media files through Django. if settings.DEBUG: # Remove leading and trailing slashes so the regex matches. media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
from django.conf import settings from django.conf.urls.defaults import * from .profiles import urls as profiles_urls from django.views.generic.simple import direct_to_template from funfactory import monkeypatches monkeypatches.patch() import badger badger.autodiscover() from django.contrib import admin admin.autodiscover() from badger import Progress #from badger_multiplayer.models import Badge, Award, Nomination from badger.models import Badge, Award urlpatterns = patterns('', url(r'^$', 'badger.views.home', name='home'), (r'^notification/', include('notification.urls')), (r'^badges/', include('badger_multiplayer.urls')), (r'^badges/', include('badger.urls')), (r'^browserid/', include('django_browserid.urls')), (r'^profiles/', include(profiles_urls)), (r'^accounts/', include('django.contrib.auth.urls')), (r'^admin/', include(admin.site.urls)), ) ## In DEBUG mode, serve media files through Django. if settings.DEBUG: # Remove leading and trailing slashes so the regex matches. media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
Change the monkey patching order
Change the monkey patching order
Python
bsd-3-clause
lmorchard/badg.us,deepankverma/badges.mozilla.org,mozilla/badges.mozilla.org,lmorchard/badg.us,deepankverma/badges.mozilla.org,lmorchard/badg.us,mozilla/badg.us,mozilla/badges.mozilla.org,mozilla/badg.us,mozilla/badges.mozilla.org,lmorchard/badg.us,mozilla/badg.us,deepankverma/badges.mozilla.org,deepankverma/badges.mozilla.org,mozilla/badges.mozilla.org
--- +++ @@ -5,14 +5,14 @@ from django.views.generic.simple import direct_to_template -from django.contrib import admin -admin.autodiscover() +from funfactory import monkeypatches +monkeypatches.patch() import badger badger.autodiscover() -from funfactory import monkeypatches -monkeypatches.patch() +from django.contrib import admin +admin.autodiscover() from badger import Progress #from badger_multiplayer.models import Badge, Award, Nomination
a6dd8aee6a3b6272372532a19fba3d830d40612a
neo/test/io/test_axonio.py
neo/test/io/test_axonio.py
# encoding: utf-8 """ Tests of io.axonio """ try: import unittest2 as unittest except ImportError: import unittest from neo.io import AxonIO from neo.test.io.common_io_test import BaseTestIO class TestAxonIO(BaseTestIO, unittest.TestCase): files_to_test = ['File_axon_1.abf', 'File_axon_2.abf', 'File_axon_3.abf', 'File_axon_4.abf',] files_to_download = files_to_test ioclass = AxonIO if __name__ == "__main__": unittest.main()
# encoding: utf-8 """ Tests of io.axonio """ try: import unittest2 as unittest except ImportError: import unittest from neo.io import AxonIO from neo.test.io.common_io_test import BaseTestIO class TestAxonIO(BaseTestIO, unittest.TestCase): files_to_test = ['File_axon_1.abf', 'File_axon_2.abf', 'File_axon_3.abf', 'File_axon_4.abf', 'File_axon_5.abf', 'File_axon_6.abf', ] files_to_download = files_to_test ioclass = AxonIO if __name__ == "__main__": unittest.main()
Test with file from Jackub
Test with file from Jackub git-svn-id: 0eea5547755d67006ec5687992a7464f0ad96b59@379 acbc63fc-6c75-0410-9d68-8fa99cba188a
Python
bsd-3-clause
SummitKwan/python-neo,mschmidt87/python-neo,rgerkin/python-neo,jakobj/python-neo,CINPLA/python-neo,apdavison/python-neo,theunissenlab/python-neo,samuelgarcia/python-neo,guangxingli/python-neo,mgr0dzicki/python-neo,JuliaSprenger/python-neo,NeuralEnsemble/python-neo,npyoung/python-neo,INM-6/python-neo,tclose/python-neo,tkf/neo,amchagas/python-neo,Blackfynn/python-neo
--- +++ @@ -16,7 +16,12 @@ files_to_test = ['File_axon_1.abf', 'File_axon_2.abf', 'File_axon_3.abf', - 'File_axon_4.abf',] + 'File_axon_4.abf', + 'File_axon_5.abf', + 'File_axon_6.abf', + + + ] files_to_download = files_to_test ioclass = AxonIO
99a1ce2ecee6dd761113515da5c89b8c7da5537f
Python/Algorithm.py
Python/Algorithm.py
class Algorithm: """ Algorithm Class Base class for the page substitution algorithms. """ def __init__(self, input = []): """ Algorithm Constructor. Parameters ---------- input : list A list containing the the input page swap. """ if not input: #If the list is empty throw an exception. raise ValueError("The list must not be empty") #throws the exception. self.blocks = input[0] #Store the page frames size. self.pages = input[1:] #Store the pages to swap. self.missingPages = self.blocks #Count the lack of pages. def removeChuncks(self, list, start, stop): """ Remove a piece of a list. Parameters ---------- list : list The list to delete the elements start : int start point. stop : int stop point. """ del list[start:stop] #Delete range def preparePageFrame(self): """ Prepare the page frames. Returns ------- list The list with initialized Page frames """ pageFrame = [self.pages[x] for x in range(0, self.blocks)] #Create the page frame with elements passed by the user. self.removeChuncks(self.pages, 0, self.blocks) #Remove part of the list that is on the page frame return pageFrame #Return the list
class Algorithm: """ Algorithm Class Base class for the page substitution algorithms. """ def __init__(self, input = []): """ Algorithm Constructor. Parameters ---------- input : list A list containing the the input page swap. """ if not input: #If the list is empty throw an exception. raise ValueError("The list must not be empty") #throws the exception. self.blocks = input[0] #Store the page frames size. self.pages = input[1:] #Store the pages to swap. self.missingPages = self.blocks #Count the lack of pages. def removeChuncks(self, list, start, stop): """ Remove a piece of a list. Parameters ---------- list : list The list to delete the elements start : int start point. stop : int stop point. """ del list[start:stop] #Delete range def preparePageFrame(self): """ Prepare the page frames. Returns ------- list The list with initialized Page frames """ pageFrame = [None] * self.blocks #Create the page frame with elements passed by the user. iterator = 0 for i in range(0, len(self.pages)): if self.pages[i] not in pageFrame: pageFrame[iterator] = self.pages[i] iterator = iterator + 1 if iterator == self.blocks: self.removeChuncks(self.pages, 0, i) #Remove part of the list that is on the page frame break return pageFrame #Return the list
Fix logic error under preparePageFrames
Fix logic error under preparePageFrames
Python
mit
caiomcg/OS-PageSubstitution
--- +++ @@ -43,6 +43,14 @@ list The list with initialized Page frames """ - pageFrame = [self.pages[x] for x in range(0, self.blocks)] #Create the page frame with elements passed by the user. - self.removeChuncks(self.pages, 0, self.blocks) #Remove part of the list that is on the page frame + pageFrame = [None] * self.blocks #Create the page frame with elements passed by the user. + iterator = 0 + for i in range(0, len(self.pages)): + if self.pages[i] not in pageFrame: + pageFrame[iterator] = self.pages[i] + iterator = iterator + 1 + if iterator == self.blocks: + self.removeChuncks(self.pages, 0, i) #Remove part of the list that is on the page frame + break + return pageFrame #Return the list
81cf4bc40fd23ba8e93b0e4bc96eff8e866c014b
redis_commands/parse.py
redis_commands/parse.py
#!/usr/bin/python # -*- coding: utf-8 -*- import lxml.etree, lxml.html import re url = "http://redis.io" output = "output.txt" f = open(output, "w"); tree = lxml.html.parse("download/raw.dat").getroot() commands = tree.find_class("command") data = {} for command in commands: for row in command.findall('a'): command_url = "%s/%s" % (url, row.get('href')) for sibling in command.itersiblings(): usage = "" for command_args in command.findall('span'): usage = "Usage: %s %s" % (row.text, command_args.text.replace(' ', '').replace('\n', ' ').strip()) summary = "%s<br>%s" % (sibling.text, usage) data[command_url] = (row.text, summary) for command_url in data.keys(): command, summary = data[command_url] summary = unicode(summary).encode("utf-8") f.write("\t".join([str(command), # title "", # namespace command_url, # url summary, # description "", # synopsis "", # details "", # type "" # lang ]) ) f.write("\n") f.close()
#!/usr/bin/python # -*- coding: utf-8 -*- import lxml.etree, lxml.html import re url = "http://redis.io" output = "output.txt" f = open(output, "w"); tree = lxml.html.parse("download/raw.dat").getroot() commands = tree.find_class("command") data = {} for command in commands: for row in command.findall('a'): command_url = "%s%s" % (url, row.get('href')) for sibling in command.itersiblings(): usage = "" for command_args in command.findall('span'): usage = "Usage: %s %s" % (row.text, command_args.text.replace(' ', '').replace('\n', ' ').strip()) summary = "%s<br>%s" % (sibling.text, usage) data[command_url] = (row.text, summary) for command_url in data.keys(): command, summary = data[command_url] summary = unicode(summary).encode("utf-8") f.write("\t".join([str(command), # title "", # namespace command_url, # url summary, # description "", # synopsis "", # details "", # type "" # lang ]) ) f.write("\n") f.close()
Remove double slashes in the Redis commands urls
Remove double slashes in the Redis commands urls
Python
apache-2.0
souravbadami/zeroclickinfo-fathead,p12tic/zeroclickinfo-fathead,samskeller/zeroclickinfo-fathead,rasikapohankar/zeroclickinfo-fathead,thinker3197/zeroclickinfo-fathead,thinker3197/zeroclickinfo-fathead,souravbadami/zeroclickinfo-fathead,rasikapohankar/zeroclickinfo-fathead,p12tic/zeroclickinfo-fathead,nikhilsingh291/zeroclickinfo-fathead,dankolbrs/zeroclickinfo-fathead,p12tic/zeroclickinfo-fathead,rasikapohankar/zeroclickinfo-fathead,samskeller/zeroclickinfo-fathead,p12tic/zeroclickinfo-fathead,samskeller/zeroclickinfo-fathead,thinker3197/zeroclickinfo-fathead,rasikapohankar/zeroclickinfo-fathead,souravbadami/zeroclickinfo-fathead,nikhilsingh291/zeroclickinfo-fathead,dankolbrs/zeroclickinfo-fathead,rasikapohankar/zeroclickinfo-fathead,p12tic/zeroclickinfo-fathead,samskeller/zeroclickinfo-fathead,souravbadami/zeroclickinfo-fathead,p12tic/zeroclickinfo-fathead,thinker3197/zeroclickinfo-fathead,nikhilsingh291/zeroclickinfo-fathead,souravbadami/zeroclickinfo-fathead,dankolbrs/zeroclickinfo-fathead,samskeller/zeroclickinfo-fathead,nikhilsingh291/zeroclickinfo-fathead,dankolbrs/zeroclickinfo-fathead,samskeller/zeroclickinfo-fathead,dankolbrs/zeroclickinfo-fathead,nikhilsingh291/zeroclickinfo-fathead,thinker3197/zeroclickinfo-fathead,souravbadami/zeroclickinfo-fathead,dankolbrs/zeroclickinfo-fathead,nikhilsingh291/zeroclickinfo-fathead,rasikapohankar/zeroclickinfo-fathead,thinker3197/zeroclickinfo-fathead
--- +++ @@ -17,7 +17,7 @@ for command in commands: for row in command.findall('a'): - command_url = "%s/%s" % (url, row.get('href')) + command_url = "%s%s" % (url, row.get('href')) for sibling in command.itersiblings(): usage = ""
b499cf14eeb3d793a06d74c5eb2f581d49a9926e
jupyter_kernel/magics/python_magic.py
jupyter_kernel/magics/python_magic.py
# Copyright (c) Calico Development Team. # Distributed under the terms of the Modified BSD License. # http://calicoproject.org/ from jupyter_kernel import Magic, option class PythonMagic(Magic): env = {} def line_python(self, *args): """%python CODE - evaluate code as Python""" code = " ".join(args) self.retval = self.eval(code) def eval(self, code): try: return eval(code.strip(), self.env) except: try: exec code.strip() in self.env except Exception as exc: return "Error: " + str(exc) if "retval" in self.env: return self.env["retval"] @option( "-e", "--eval_output", action="store_true", default=False, help="Use the retval value from the Python cell as code in the kernel language." ) def cell_python(self, eval_output=False): """%%python - evaluate contents of cell as Python""" if self.code.strip(): if eval_output: self.eval(self.code) self.code = str(self.env["retval"]) if "retval" in self.env else "" self.retval = None self.evaluate = True else: self.retval = self.eval(self.code) self.evaluate = False def post_process(self, retval): if retval: return retval else: return self.retval def register_magics(kernel): kernel.register_magics(PythonMagic)
# Copyright (c) Calico Development Team. # Distributed under the terms of the Modified BSD License. # http://calicoproject.org/ from jupyter_kernel import Magic, option class PythonMagic(Magic): env = {} def line_python(self, *args): """%python CODE - evaluate code as Python""" code = " ".join(args) self.retval = self.eval(code) def eval(self, code): try: return eval(code.strip(), self.env) except: try: exec(code.strip(), self.env) except Exception as exc: return "Error: " + str(exc) if "retval" in self.env: return self.env["retval"] @option( "-e", "--eval_output", action="store_true", default=False, help="Use the retval value from the Python cell as code in the kernel language." ) def cell_python(self, eval_output=False): """%%python - evaluate contents of cell as Python""" if self.code.strip(): if eval_output: self.eval(self.code) self.code = str(self.env["retval"]) if "retval" in self.env else "" self.retval = None self.evaluate = True else: self.retval = self.eval(self.code) self.evaluate = False def post_process(self, retval): if retval: return retval else: return self.retval def register_magics(kernel): kernel.register_magics(PythonMagic)
Use Python2/3 compatible form of exec
Use Python2/3 compatible form of exec
Python
bsd-3-clause
Calysto/metakernel
--- +++ @@ -17,7 +17,7 @@ return eval(code.strip(), self.env) except: try: - exec code.strip() in self.env + exec(code.strip(), self.env) except Exception as exc: return "Error: " + str(exc) if "retval" in self.env:
01b9d47976dd68a3fe9ae2656e423a03edb5187d
examples/source.py
examples/source.py
"""Test client that connects and sends infinite data.""" import sys from tulip import * def dprint(*args): print('source:', *args, file=sys.stderr) class Client(Protocol): data = b'x'*16*1024 def connection_made(self, tr): dprint('connecting to', tr.get_extra_info('addr')) self.tr = tr self.lost = False self.loop = get_event_loop() self.waiter = Future() self.write_some_data() def write_some_data(self): dprint('writing', len(self.data), 'bytes') self.tr.write(self.data) if not self.lost: self.loop.call_soon(self.write_some_data) def connection_lost(self, exc): dprint('lost connection', repr(exc)) self.lost = True self.waiter.set_result(None) @coroutine def start(loop): tr, pr = yield from loop.create_connection(Client, 'localhost', 1111) dprint('tr =', tr) dprint('pr =', pr) res = yield from pr.waiter return res def main(): loop = get_event_loop() loop.run_until_complete(start(loop)) if __name__ == '__main__': main()
"""Test client that connects and sends infinite data.""" import sys from tulip import * def dprint(*args): print('source:', *args, file=sys.stderr) class Client(Protocol): data = b'x'*16*1024 def connection_made(self, tr): dprint('connecting to', tr.get_extra_info('addr')) self.tr = tr self.lost = False self.loop = get_event_loop() self.waiter = Future() self.write_some_data() def write_some_data(self): if self.lost: dprint('lost already') return dprint('writing', len(self.data), 'bytes') self.tr.write(self.data) self.loop.call_soon(self.write_some_data) def connection_lost(self, exc): dprint('lost connection', repr(exc)) self.lost = True self.waiter.set_result(None) @coroutine def start(loop): tr, pr = yield from loop.create_connection(Client, 'localhost', 1111) dprint('tr =', tr) dprint('pr =', pr) res = yield from pr.waiter return res def main(): loop = get_event_loop() loop.run_until_complete(start(loop)) if __name__ == '__main__': main()
Fix logic around lost connection.
Fix logic around lost connection.
Python
apache-2.0
leetreveil/tulip,overcastcloud/trollius,leetreveil/tulip,overcastcloud/trollius,leetreveil/tulip,overcastcloud/trollius
--- +++ @@ -20,10 +20,12 @@ self.write_some_data() def write_some_data(self): + if self.lost: + dprint('lost already') + return dprint('writing', len(self.data), 'bytes') self.tr.write(self.data) - if not self.lost: - self.loop.call_soon(self.write_some_data) + self.loop.call_soon(self.write_some_data) def connection_lost(self, exc): dprint('lost connection', repr(exc))
9ce7de86b7d9c1e9288fa5c09f97414516cabc63
corehq/apps/reports/filters/urls.py
corehq/apps/reports/filters/urls.py
from django.conf.urls import url from .api import ( EmwfOptionsView, CaseListFilterOptions, DeviceLogUsers, DeviceLogIds, MobileWorkersOptionsView, ReassignCaseOptions, ) from .location import LocationGroupFilterOptions urlpatterns = [ url(r'^emwf_options/$', EmwfOptionsView.as_view(), name='emwf_options'), url(r'^users_options/$', MobileWorkersOptionsView.as_view(), name=MobileWorkersOptionsView.urlname), url(r'^new_emwf_options/$', LocationRestrictedEmwfOptions.as_view(), name='new_emwf_options'), url(r'^case_list_options/$', CaseListFilterOptions.as_view(), name='case_list_options'), url(r'^reassign_case_options/$', ReassignCaseOptions.as_view(), name='reassign_case_options'), url(r'^grouplocationfilter_options/$', LocationGroupFilterOptions.as_view(), name='grouplocationfilter_options' ), url(r'^device_log_users/$', DeviceLogUsers.as_view(), name='device_log_users'), url(r'^device_log_ids/$', DeviceLogIds.as_view(), name='device_log_ids'), ]
from django.conf.urls import url from .api import ( EmwfOptionsView, CaseListFilterOptions, DeviceLogUsers, DeviceLogIds, MobileWorkersOptionsView, ReassignCaseOptions, ) from .location import LocationGroupFilterOptions urlpatterns = [ url(r'^emwf_options/$', EmwfOptionsView.as_view(), name='emwf_options'), url(r'^users_options/$', MobileWorkersOptionsView.as_view(), name=MobileWorkersOptionsView.urlname), url(r'^case_list_options/$', CaseListFilterOptions.as_view(), name='case_list_options'), url(r'^reassign_case_options/$', ReassignCaseOptions.as_view(), name='reassign_case_options'), url(r'^grouplocationfilter_options/$', LocationGroupFilterOptions.as_view(), name='grouplocationfilter_options' ), url(r'^device_log_users/$', DeviceLogUsers.as_view(), name='device_log_users'), url(r'^device_log_ids/$', DeviceLogIds.as_view(), name='device_log_ids'), ]
Fix bad merge and formatting
Fix bad merge and formatting
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -11,14 +11,13 @@ from .location import LocationGroupFilterOptions urlpatterns = [ - url(r'^emwf_options/$', EmwfOptionsView.as_view(), name='emwf_options'), - url(r'^users_options/$', MobileWorkersOptionsView.as_view(), name=MobileWorkersOptionsView.urlname), - url(r'^new_emwf_options/$', LocationRestrictedEmwfOptions.as_view(), name='new_emwf_options'), - url(r'^case_list_options/$', CaseListFilterOptions.as_view(), name='case_list_options'), - url(r'^reassign_case_options/$', ReassignCaseOptions.as_view(), name='reassign_case_options'), - url(r'^grouplocationfilter_options/$', LocationGroupFilterOptions.as_view(), - name='grouplocationfilter_options' - ), - url(r'^device_log_users/$', DeviceLogUsers.as_view(), name='device_log_users'), - url(r'^device_log_ids/$', DeviceLogIds.as_view(), name='device_log_ids'), + url(r'^emwf_options/$', EmwfOptionsView.as_view(), name='emwf_options'), + url(r'^users_options/$', MobileWorkersOptionsView.as_view(), name=MobileWorkersOptionsView.urlname), + url(r'^case_list_options/$', CaseListFilterOptions.as_view(), name='case_list_options'), + url(r'^reassign_case_options/$', ReassignCaseOptions.as_view(), name='reassign_case_options'), + url(r'^grouplocationfilter_options/$', LocationGroupFilterOptions.as_view(), + name='grouplocationfilter_options' + ), + url(r'^device_log_users/$', DeviceLogUsers.as_view(), name='device_log_users'), + url(r'^device_log_ids/$', DeviceLogIds.as_view(), name='device_log_ids'), ]
7186faebdb22f4aacffb2e0603fe6918f6b89ee7
rrd_data_source.py
rrd_data_source.py
class RRDDataSource(object): name = "" data_source_type = "" heartbeat = "" temp_value = 0 def __init__(self, name, data_source_type, heartbeat): self.name = name self.data_source_type = data_source_type self.heartbeat = heartbeat
class RRDDataSource(object): name = "" data_source_type = "" heartbeat = "" temp_value = 0 def __init__(self, name, data_source_type, heartbeat, temp_value=None): self.name = name self.data_source_type = data_source_type self.heartbeat = heartbeat self.temp_value = temp_value
Add temp_value (optional) parameter to RRDDataSource constructor.
Add temp_value (optional) parameter to RRDDataSource constructor.
Python
mit
netgroup/OSHI-monitoring,StefanoSalsano/OSHI-monitoring,ferrarimarco/OSHI-monitoring,StefanoSalsano/OSHI-monitoring,netgroup/OSHI-monitoring,ferrarimarco/OSHI-monitoring
--- +++ @@ -4,7 +4,8 @@ heartbeat = "" temp_value = 0 - def __init__(self, name, data_source_type, heartbeat): + def __init__(self, name, data_source_type, heartbeat, temp_value=None): self.name = name self.data_source_type = data_source_type self.heartbeat = heartbeat + self.temp_value = temp_value
ff65a3e1b0f061100a20462dea4f654b02707a6f
fig/cli/command.py
fig/cli/command.py
from docker import Client import logging import os import re import yaml from ..project import Project from .docopt_command import DocoptCommand from .formatter import Formatter from .utils import cached_property log = logging.getLogger(__name__) class Command(DocoptCommand): @cached_property def client(self): if os.environ.get('DOCKER_URL'): return Client(os.environ['DOCKER_URL']) else: return Client() @cached_property def project(self): config = yaml.load(open('fig.yml')) return Project.from_config(self.project_name, config, self.client) @cached_property def project_name(self): project = os.path.basename(os.getcwd()) project = re.sub(r'[^a-zA-Z0-9]', '', project) if not project: project = 'default' return project @cached_property def formatter(self): return Formatter()
from docker import Client import logging import os import re import yaml import socket from ..project import Project from .docopt_command import DocoptCommand from .formatter import Formatter from .utils import cached_property from .errors import UserError log = logging.getLogger(__name__) class Command(DocoptCommand): @cached_property def client(self): if os.environ.get('DOCKER_URL'): return Client(os.environ['DOCKER_URL']) socket_path = '/var/run/docker.sock' tcp_host = '127.0.0.1' tcp_port = 4243 if os.path.exists(socket_path): return Client('unix://%s' % socket_path) try: s = socket.socket() s.connect((tcp_host, tcp_port)) s.close() return Client('http://%s:%s' % (tcp_host, tcp_port)) except: pass raise UserError(""" Couldn't find Docker daemon - tried %s and %s:%s. If it's running elsewhere, specify a url with DOCKER_URL. """ % (socket_path, tcp_host, tcp_port)) @cached_property def project(self): config = yaml.load(open('fig.yml')) return Project.from_config(self.project_name, config, self.client) @cached_property def project_name(self): project = os.path.basename(os.getcwd()) project = re.sub(r'[^a-zA-Z0-9]', '', project) if not project: project = 'default' return project @cached_property def formatter(self): return Formatter()
Check default socket and localhost:4243 for Docker daemon
Check default socket and localhost:4243 for Docker daemon
Python
apache-2.0
MSakamaki/compose,alexisbellido/docker.github.io,prologic/compose,KevinGreene/compose,phiroict/docker,calou/compose,rillig/docker.github.io,docker/docker.github.io,phiroict/docker,vlajos/compose,ekristen/compose,JimGalasyn/docker.github.io,albers/compose,zhangspook/compose,charleswhchan/compose,talolard/compose,nhumrich/compose,mrfuxi/compose,rillig/docker.github.io,saada/compose,rgbkrk/compose,ggtools/compose,michael-k/docker-compose,anweiss/docker.github.io,joaofnfernandes/docker.github.io,kikkomep/compose,joaofnfernandes/docker.github.io,funkyfuture/docker-compose,Katlean/fig,menglingwei/denverdino.github.io,abesto/fig,heroku/fig,josephpage/compose,menglingwei/denverdino.github.io,browning/compose,ralphtheninja/compose,bsmr-docker/compose,tangkun75/compose,cclauss/compose,sanscontext/docker.github.io,thaJeztah/compose,ouziel-slama/compose,gtrdotmcs/compose,BSWANG/denverdino.github.io,docker-zh/docker.github.io,bdwill/docker.github.io,thaJeztah/docker.github.io,sanscontext/docker.github.io,vdemeester/compose,bfirsh/fig,gdevillele/docker.github.io,zhangspook/compose,menglingwei/denverdino.github.io,Yelp/docker-compose,jonaseck2/compose,sanscontext/docker.github.io,tiry/compose,menglingwei/denverdino.github.io,bcicen/fig,ChrisChinchilla/compose,thieman/compose,ouziel-slama/compose,ekristen/compose,danix800/docker.github.io,sdurrheimer/compose,goloveychuk/compose,aduermael/docker.github.io,denverdino/docker.github.io,Dakno/compose,sebglazebrook/compose,troy0820/docker.github.io,ZJaffee/compose,dilgerma/compose,shin-/compose,lukemarsden/compose,dockerhn/compose,ain/compose,dnephin/compose,docker/docker.github.io,aanand/fig,simonista/compose,vlajos/compose,docker-zh/docker.github.io,noironetworks/compose,genki/compose,xydinesh/compose,aduermael/docker.github.io,brunocascio/compose,viranch/compose,funkyfuture/docker-compose,bobphill/compose,mohitsoni/compose,benhamill/compose,denverdino/denverdino.github.io,sdurrheimer/compose,anweiss/docker.github.io,alexisbellido/docker.github.io,mbailey/compose,jrabbit/compose,shubheksha/docker.github.io,shakamunyi/fig,denverdino/docker.github.io,phiroict/docker,bdwill/docker.github.io,jiekechoo/compose,danix800/docker.github.io,docker-zh/docker.github.io,xydinesh/compose,mbailey/compose,phiroict/docker,talolard/compose,jeanpralo/compose,bsmr-docker/compose,thaJeztah/docker.github.io,DoubleMalt/compose,LuisBosquez/docker.github.io,BSWANG/denverdino.github.io,JimGalasyn/docker.github.io,hypriot/compose,dopry/compose,jzwlqx/denverdino.github.io,KalleDK/compose,schmunk42/compose,kojiromike/compose,joeuo/docker.github.io,thaJeztah/docker.github.io,viranch/compose,gdevillele/docker.github.io,kojiromike/compose,ain/compose,sebglazebrook/compose,tiry/compose,dopry/compose,au-phiware/compose,BSWANG/denverdino.github.io,phiroict/docker,bdwill/docker.github.io,JimGalasyn/docker.github.io,mark-adams/compose,qzio/compose,mdaue/compose,alexisbellido/docker.github.io,dnephin/compose,marcusmartins/compose,jorgeLuizChaves/compose,troy0820/docker.github.io,shubheksha/docker.github.io,jessekl/compose,pspierce/compose,alunduil/fig,twitherspoon/compose,andrewgee/compose,aanand/fig,screwgoth/compose,jzwlqx/denverdino.github.io,londoncalling/docker.github.io,j-fuentes/compose,joaofnfernandes/docker.github.io,danix800/docker.github.io,mdaue/compose,troy0820/docker.github.io,Chouser/compose,amitsaha/compose,tpounds/compose,thaJeztah/docker.github.io,mosquito/docker-compose,cgvarela/compose,lmesz/compose,ggtools/compose,KevinGreene/compose,LuisBosquez/docker.github.io,JimGalasyn/docker.github.io,pspierce/compose,shubheksha/docker.github.io,screwgoth/compose,runcom/compose,philwrenn/compose,TheDataShed/compose,gtrdotmcs/compose,kikkomep/compose,mnuessler/compose,ph-One/compose,jzwlqx/denverdino.github.io,schmunk42/compose,rillig/docker.github.io,mindaugasrukas/compose,Katlean/fig,BSWANG/denverdino.github.io,unodba/compose,glogiotatidis/compose,shubheksha/docker.github.io,d2bit/compose,nerro/compose,moxiegirl/compose,jiekechoo/compose,alexisbellido/docker.github.io,troy0820/docker.github.io,mrfuxi/compose,alexandrev/compose,denverdino/docker.github.io,uvgroovy/compose,heroku/fig,jzwlqx/denverdino.github.io,RobertNorthard/compose,jgrowl/compose,shin-/docker.github.io,swoopla/compose,prologic/compose,shin-/docker.github.io,unodba/compose,Dakno/compose,JimGalasyn/docker.github.io,LuisBosquez/docker.github.io,denverdino/denverdino.github.io,LuisBosquez/docker.github.io,docker-zh/docker.github.io,thaJeztah/compose,tpounds/compose,iamluc/compose,ionrock/compose,shakamunyi/fig,nerro/compose,uvgroovy/compose,brunocascio/compose,thieman/compose,ph-One/compose,lmesz/compose,gdevillele/docker.github.io,docker/docker.github.io,anweiss/docker.github.io,benhamill/compose,anweiss/docker.github.io,ionrock/compose,joeuo/docker.github.io,BSWANG/denverdino.github.io,londoncalling/docker.github.io,mchasal/compose,denverdino/denverdino.github.io,joeuo/docker.github.io,mark-adams/compose,browning/compose,noironetworks/compose,bdwill/docker.github.io,runcom/compose,charleswhchan/compose,shin-/docker.github.io,ralphtheninja/compose,menglingwei/denverdino.github.io,aduermael/docker.github.io,alexisbellido/docker.github.io,genki/compose,alexandrev/compose,londoncalling/docker.github.io,amitsaha/compose,hypriot/compose,iamluc/compose,rillig/docker.github.io,denverdino/docker.github.io,jeanpralo/compose,j-fuentes/compose,alunduil/fig,feelobot/compose,joeuo/docker.github.io,Yelp/docker-compose,denverdino/denverdino.github.io,mindaugasrukas/compose,swoopla/compose,marcusmartins/compose,shin-/docker.github.io,dilgerma/compose,GM-Alex/compose,londoncalling/docker.github.io,mnuessler/compose,bbirand/compose,rgbkrk/compose,bcicen/fig,TomasTomecek/compose,qzio/compose,denverdino/denverdino.github.io,johnstep/docker.github.io,denverdino/docker.github.io,DoubleMalt/compose,denverdino/compose,KalleDK/compose,michael-k/docker-compose,calou/compose,simonista/compose,bdwill/docker.github.io,aduermael/docker.github.io,GM-Alex/compose,LuisBosquez/docker.github.io,d2bit/compose,dbdd4us/compose,VinceBarresi/compose,TheDataShed/compose,jorgeLuizChaves/compose,andrewgee/compose,mosquito/docker-compose,goloveychuk/compose,mohitsoni/compose,Chouser/compose,docker-zh/docker.github.io,mnowster/compose,johnstep/docker.github.io,albers/compose,hoogenm/compose,lukemarsden/compose,cclauss/compose,anweiss/docker.github.io,artemkaint/compose,bbirand/compose,saada/compose,twitherspoon/compose,shin-/docker.github.io,rstacruz/compose,nhumrich/compose,hoogenm/compose,philwrenn/compose,ChrisChinchilla/compose,danix800/docker.github.io,rstacruz/compose,mchasal/compose,ZJaffee/compose,dbdd4us/compose,shubheksha/docker.github.io,joaofnfernandes/docker.github.io,joeuo/docker.github.io,jrabbit/compose,moxiegirl/compose,heroku/fig,docker/docker.github.io,tangkun75/compose,glogiotatidis/compose,josephpage/compose,jessekl/compose,gdevillele/docker.github.io,johnstep/docker.github.io,joaofnfernandes/docker.github.io,bcicen/fig,feelobot/compose,docker/docker.github.io,artemkaint/compose,johnstep/docker.github.io,au-phiware/compose,jonaseck2/compose,jzwlqx/denverdino.github.io,MSakamaki/compose,bobphill/compose,vdemeester/compose,bfirsh/fig,TomasTomecek/compose,sanscontext/docker.github.io,jgrowl/compose,sanscontext/docker.github.io,cgvarela/compose,thaJeztah/docker.github.io,dockerhn/compose,londoncalling/docker.github.io,johnstep/docker.github.io,shin-/compose,VinceBarresi/compose,abesto/fig,RobertNorthard/compose,gdevillele/docker.github.io,denverdino/compose,mnowster/compose
--- +++ @@ -3,11 +3,13 @@ import os import re import yaml +import socket from ..project import Project from .docopt_command import DocoptCommand from .formatter import Formatter from .utils import cached_property +from .errors import UserError log = logging.getLogger(__name__) @@ -16,8 +18,26 @@ def client(self): if os.environ.get('DOCKER_URL'): return Client(os.environ['DOCKER_URL']) - else: - return Client() + + socket_path = '/var/run/docker.sock' + tcp_host = '127.0.0.1' + tcp_port = 4243 + + if os.path.exists(socket_path): + return Client('unix://%s' % socket_path) + + try: + s = socket.socket() + s.connect((tcp_host, tcp_port)) + s.close() + return Client('http://%s:%s' % (tcp_host, tcp_port)) + except: + pass + + raise UserError(""" + Couldn't find Docker daemon - tried %s and %s:%s. + If it's running elsewhere, specify a url with DOCKER_URL. + """ % (socket_path, tcp_host, tcp_port)) @cached_property def project(self):
036a89ce97d8160fe6b4cb10a95f3cf9e8a855ff
Lib/test/test_openpty.py
Lib/test/test_openpty.py
# Test to see if openpty works. (But don't worry if it isn't available.) import os from test.test_support import verbose, TestFailed, TestSkipped try: if verbose: print "Calling os.openpty()" master, slave = os.openpty() if verbose: print "(master, slave) = (%d, %d)"%(master, slave) except AttributeError: raise TestSkipped, "No openpty() available." if not os.isatty(master): raise TestFailed, "Master-end of pty is not a terminal." if not os.isatty(slave): raise TestFailed, "Slave-end of pty is not a terminal." os.write(slave, 'Ping!') print os.read(master, 1024)
# Test to see if openpty works. (But don't worry if it isn't available.) import os from test.test_support import verbose, TestFailed, TestSkipped try: if verbose: print "Calling os.openpty()" master, slave = os.openpty() if verbose: print "(master, slave) = (%d, %d)"%(master, slave) except AttributeError: raise TestSkipped, "No openpty() available." if not os.isatty(slave): raise TestFailed, "Slave-end of pty is not a terminal." os.write(slave, 'Ping!') print os.read(master, 1024)
Remove bogus test; the master is not a terminal on Solaris and HP-UX.
Remove bogus test; the master is not a terminal on Solaris and HP-UX.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -12,8 +12,6 @@ except AttributeError: raise TestSkipped, "No openpty() available." -if not os.isatty(master): - raise TestFailed, "Master-end of pty is not a terminal." if not os.isatty(slave): raise TestFailed, "Slave-end of pty is not a terminal."
301f22b9b2de2a27dd2e3faa27ccb9c70266e938
pybossa/api/project_stats.py
pybossa/api/project_stats.py
# -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2015 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PYBOSSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PYBOSSA. If not, see <http://www.gnu.org/licenses/>. """ PYBOSSA api module for exposing domain object ProjectStats via an API. """ from flask import request from pybossa.model.project_stats import ProjectStats from api_base import APIBase class ProjectStatsAPI(APIBase): """Class for domain object ProjectStats.""" __class__ = ProjectStats def _select_attributes(self, stats_data): if request.args.get('full'): return stats_data stats_data['info'].pop('hours_stats', None) stats_data['info'].pop('dates_stats', None) stats_data['info'].pop('users_stats', None) return stats_data
# -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2015 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PYBOSSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PYBOSSA. If not, see <http://www.gnu.org/licenses/>. """ PYBOSSA api module for exposing domain object ProjectStats via an API. """ import copy from flask import request from pybossa.model.project_stats import ProjectStats from api_base import APIBase class ProjectStatsAPI(APIBase): """Class for domain object ProjectStats.""" __class__ = ProjectStats def _select_attributes(self, stats_data): if not request.args.get('full'): tmp = copy.deepcopy(stats_data) tmp['info'].pop('hours_stats', None) tmp['info'].pop('dates_stats', None) tmp['info'].pop('users_stats', None) return tmp return stats_data
Fix _select_attributes from project api
Fix _select_attributes from project api
Python
agpl-3.0
PyBossa/pybossa,PyBossa/pybossa,Scifabric/pybossa,Scifabric/pybossa
--- +++ @@ -18,6 +18,7 @@ """ PYBOSSA api module for exposing domain object ProjectStats via an API. """ +import copy from flask import request from pybossa.model.project_stats import ProjectStats from api_base import APIBase @@ -30,9 +31,10 @@ __class__ = ProjectStats def _select_attributes(self, stats_data): - if request.args.get('full'): - return stats_data - stats_data['info'].pop('hours_stats', None) - stats_data['info'].pop('dates_stats', None) - stats_data['info'].pop('users_stats', None) + if not request.args.get('full'): + tmp = copy.deepcopy(stats_data) + tmp['info'].pop('hours_stats', None) + tmp['info'].pop('dates_stats', None) + tmp['info'].pop('users_stats', None) + return tmp return stats_data
88da3432dc0676cbe74c0d9f170fbd6f18f97f8a
examples/tornado_server.py
examples/tornado_server.py
from tornado import ioloop, web from jsonrpcserver import method, async_dispatch as dispatch @method async def ping(): return "pong" class MainHandler(web.RequestHandler): async def post(self): request = self.request.body.decode() response = await dispatch(request) print(response) if response.wanted: self.write(str(response)) app = web.Application([(r"/", MainHandler)]) if __name__ == "__main__": app.listen(5000) ioloop.IOLoop.current().start()
from tornado import ioloop, web from jsonrpcserver import method, async_dispatch as dispatch @method async def ping() -> str: return "pong" class MainHandler(web.RequestHandler): async def post(self) -> None: request = self.request.body.decode() response = await dispatch(request) if response.wanted: self.write(str(response)) app = web.Application([(r"/", MainHandler)]) if __name__ == "__main__": app.listen(5000) ioloop.IOLoop.current().start()
Remove unwanted print statement from example
Remove unwanted print statement from example
Python
mit
bcb/jsonrpcserver
--- +++ @@ -3,15 +3,14 @@ @method -async def ping(): +async def ping() -> str: return "pong" class MainHandler(web.RequestHandler): - async def post(self): + async def post(self) -> None: request = self.request.body.decode() response = await dispatch(request) - print(response) if response.wanted: self.write(str(response))
0605e11672b76aa9582ed8024006b524f90d0c79
tools/pinboost_debugme.py
tools/pinboost_debugme.py
#!/usr/bin/env python import sys, os, tempfile pid = int(sys.argv[1]) mytid = int(sys.argv[2]) # FIXME: optionally attach GDB to each thread since GDB won't find Pintool threads by itself #for tid in os.listdir('/proc/%d/task' % pid): # tid = int(tid) # print "Starting screen with GDB for thread %d; resume using screen -r gdb-%d" % (tid, tid) # os.system('screen -d -m -S gdb-%d -- gdb $SNIPER_ROOT/pin_kit/intel64/bin/pinbin %d' % (tid, tid)) cmdfile = '/tmp/gdbcmd-%d' % mytid open(cmdfile, 'w').write('''\ # Continue execution past the sleep in pinboost_debugme() and into the real exception continue # Show a backtrace at the exception backtrace ''') print print "[PINBOOST] Starting screen session with GDB attached to thread %d; resume using" % mytid print "# screen -r gdb-%d" % mytid os.system('screen -d -m -S gdb-%d -- gdb -command=%s $SNIPER_ROOT/pin_kit/intel64/bin/pinbin %d' % (mytid, cmdfile, mytid))
#!/usr/bin/env python import sys, os, tempfile pid = int(sys.argv[1]) mytid = int(sys.argv[2]) # FIXME: optionally attach GDB to each thread since GDB won't find Pintool threads by itself #for tid in os.listdir('/proc/%d/task' % pid): # tid = int(tid) # print >> sys.stderr, "Starting screen with GDB for thread %d; resume using screen -r gdb-%d" % (tid, tid) # os.system('screen -d -m -S gdb-%d -- gdb $SNIPER_ROOT/pin_kit/intel64/bin/pinbin %d' % (tid, tid)) cmdfile = '/tmp/gdbcmd-%d' % mytid open(cmdfile, 'w').write('''\ # Continue execution past the sleep in pinboost_debugme() and into the real exception continue # Show a backtrace at the exception backtrace ''') print >> sys.stderr print >> sys.stderr, "[PINBOOST] Starting screen session with GDB attached to thread %d; resume using" % mytid print >> sys.stderr, "# screen -r gdb-%d" % mytid os.system('screen -d -m -S gdb-%d -- gdb -command=%s $SNIPER_ROOT/pin_kit/intel64/bin/pinbin %d' % (mytid, cmdfile, mytid))
Write GDB debug session information to stderr, as stdout will be redirected to a log file
[pinboost] Write GDB debug session information to stderr, as stdout will be redirected to a log file
Python
mit
abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper
--- +++ @@ -8,7 +8,7 @@ # FIXME: optionally attach GDB to each thread since GDB won't find Pintool threads by itself #for tid in os.listdir('/proc/%d/task' % pid): # tid = int(tid) -# print "Starting screen with GDB for thread %d; resume using screen -r gdb-%d" % (tid, tid) +# print >> sys.stderr, "Starting screen with GDB for thread %d; resume using screen -r gdb-%d" % (tid, tid) # os.system('screen -d -m -S gdb-%d -- gdb $SNIPER_ROOT/pin_kit/intel64/bin/pinbin %d' % (tid, tid)) cmdfile = '/tmp/gdbcmd-%d' % mytid @@ -19,8 +19,8 @@ backtrace ''') -print -print "[PINBOOST] Starting screen session with GDB attached to thread %d; resume using" % mytid -print "# screen -r gdb-%d" % mytid +print >> sys.stderr +print >> sys.stderr, "[PINBOOST] Starting screen session with GDB attached to thread %d; resume using" % mytid +print >> sys.stderr, "# screen -r gdb-%d" % mytid os.system('screen -d -m -S gdb-%d -- gdb -command=%s $SNIPER_ROOT/pin_kit/intel64/bin/pinbin %d' % (mytid, cmdfile, mytid))
91825c1883d0d95c593707a1f3f9d4f85b9154f1
instana/options.py
instana/options.py
import logging class Options(object): service = '' agent_host = '' agent_port = 0 log_level = logging.ERROR def __init__(self, **kwds): self.__dict__.update(kwds)
import logging class Options(object): service = '' agent_host = '' agent_port = 0 log_level = logging.WARN def __init__(self, **kwds): self.__dict__.update(kwds)
Switch default log level to WARN
Switch default log level to WARN
Python
mit
instana/python-sensor,instana/python-sensor
--- +++ @@ -5,7 +5,7 @@ service = '' agent_host = '' agent_port = 0 - log_level = logging.ERROR + log_level = logging.WARN def __init__(self, **kwds): self.__dict__.update(kwds)
e44f4ce0db6c56309107bc7280ac4e2b41616ab2
modules/git/git.py
modules/git/git.py
import os import os.path import subprocess from module import Module class git(Module): def __init__(self, scrap): super(git, self).__init__(scrap) scrap.register_event("git", "msg", self.distribute) self.register_cmd("version", self.git_version) self.register_cmd("update", self.update) def git_version(self, server, event, bot): c = server["connection"] if not os.path.exists(".git"): c.privmsg(event.target, "Scrappy not running from a git repo") else: ver = subprocess.check_output(["git", "describe", "--always"]) c.privmsg(event.target, "Scrappy git version: %s" % ver.strip()) def update(self, server, event, bot): c = server["connection"] if not os.path.exists(".git"): c.privmsg(event.target, "Scrappy not running from a git repo") else: self.git_version(server, event, bot) os.system("git pull") c.privmsg(event.target, "Scrappy updated! You may need to %sreboot." % server["cmdchar"]) self.git_version(server, event, bot)
import os import os.path import subprocess from module import Module class git(Module): def __init__(self, scrap): super(git, self).__init__(scrap) scrap.register_event("git", "msg", self.distribute) self.register_cmd("version", self.git_version) self.register_cmd("update", self.update) def git_version(self, server, event, bot): c = server["connection"] if not os.path.exists(".git"): c.privmsg(event.target, "Scrappy not running from a git repo") else: ver = subprocess.check_output(["git", "describe", "--always"]) c.privmsg(event.target, "Scrappy git version: %s" % ver.strip()) def update(self, server, event, bot): c = server["connection"] if not os.path.exists(".git"): c.privmsg(event.target, "Scrappy not running from a git repo") else: output = subprocess.check_output(["git", "pull"]) if "up-to-date" in output: c.privmsg(event.target, "Scrappy is already the latest version") else: c.privmsg(event.target, "Scrappy updated! You may need to %sreboot." % server["cmdchar"]) self.git_version(server, event, bot)
Use subprocess to update, seems silly to use both subprocess and os.systemm in the same module. update also reports if the version hasn't changed.
Use subprocess to update, seems silly to use both subprocess and os.systemm in the same module. update also reports if the version hasn't changed.
Python
mit
tcoppi/scrappy,johnmiked15/scrappy,johnmiked15/scrappy,tcoppi/scrappy
--- +++ @@ -26,10 +26,12 @@ if not os.path.exists(".git"): c.privmsg(event.target, "Scrappy not running from a git repo") else: - self.git_version(server, event, bot) - os.system("git pull") - c.privmsg(event.target, "Scrappy updated! You may need to %sreboot." % server["cmdchar"]) - self.git_version(server, event, bot) + output = subprocess.check_output(["git", "pull"]) + if "up-to-date" in output: + c.privmsg(event.target, "Scrappy is already the latest version") + else: + c.privmsg(event.target, "Scrappy updated! You may need to %sreboot." % server["cmdchar"]) + self.git_version(server, event, bot)
d5b0234cca1bbab1a0bd20091df44380aca71ee8
tslearn/tests/test_svm.py
tslearn/tests/test_svm.py
import numpy as np from tslearn.metrics import cdist_gak from tslearn.svm import TimeSeriesSVC __author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr' def test_svm_gak(): n, sz, d = 15, 10, 3 rng = np.random.RandomState(0) time_series = rng.randn(n, sz, d) labels = rng.randint(low=0, high=2, size=n) gamma = 10. gak_km = TimeSeriesSVC(kernel="gak", gamma=gamma) sklearn_X, _ = gak_km._preprocess_sklearn(time_series, labels, fit_time=True) cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.)) np.testing.assert_allclose(sklearn_X, cdist_mat)
import numpy as np from tslearn.metrics import cdist_gak from tslearn.svm import TimeSeriesSVC, TimeSeriesSVR __author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr' def test_gamma_value_svm(): n, sz, d = 5, 10, 3 rng = np.random.RandomState(0) time_series = rng.randn(n, sz, d) labels = rng.randint(low=0, high=2, size=n) gamma = 10. for ModelClass in [TimeSeriesSVC, TimeSeriesSVR]: gak_model = ModelClass(kernel="gak", gamma=gamma) sklearn_X, _ = gak_model._preprocess_sklearn(time_series, labels, fit_time=True) cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.)) np.testing.assert_allclose(sklearn_X, cdist_mat)
Change test name and test SVR too
Change test name and test SVR too
Python
bsd-2-clause
rtavenar/tslearn
--- +++ @@ -1,22 +1,24 @@ import numpy as np from tslearn.metrics import cdist_gak -from tslearn.svm import TimeSeriesSVC +from tslearn.svm import TimeSeriesSVC, TimeSeriesSVR __author__ = 'Romain Tavenard romain.tavenard[at]univ-rennes2.fr' -def test_svm_gak(): - n, sz, d = 15, 10, 3 +def test_gamma_value_svm(): + n, sz, d = 5, 10, 3 rng = np.random.RandomState(0) time_series = rng.randn(n, sz, d) labels = rng.randint(low=0, high=2, size=n) gamma = 10. - gak_km = TimeSeriesSVC(kernel="gak", gamma=gamma) - sklearn_X, _ = gak_km._preprocess_sklearn(time_series, labels, - fit_time=True) + for ModelClass in [TimeSeriesSVC, TimeSeriesSVR]: + gak_model = ModelClass(kernel="gak", gamma=gamma) + sklearn_X, _ = gak_model._preprocess_sklearn(time_series, + labels, + fit_time=True) - cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.)) + cdist_mat = cdist_gak(time_series, sigma=np.sqrt(gamma / 2.)) - np.testing.assert_allclose(sklearn_X, cdist_mat) + np.testing.assert_allclose(sklearn_X, cdist_mat)
e731c3a4a8590f5cddd23fd2f9af265749f08a38
code_snippets/guides-agentchecks-methods.py
code_snippets/guides-agentchecks-methods.py
self.gauge( ... ) # Sample a gauge metric self.increment( ... ) # Increment a counter metric self.decrement( ... ) # Decrement a counter metric self.histogram( ... ) # Sample a histogram metric self.rate( ... ) # Sample a point, with the rate calculated at the end of the check
self.gauge( ... ) # Sample a gauge metric self.increment( ... ) # Increment a counter metric self.decrement( ... ) # Decrement a counter metric self.histogram( ... ) # Sample a histogram metric self.rate( ... ) # Sample a point, with the rate calculated at the end of the check self.count( ... ) # Sample a raw count metric self.monotonic_count( ... ) # Sample an increasing counter metric
Document AgentCheck count and monotonic_count methods
Document AgentCheck count and monotonic_count methods
Python
bsd-3-clause
inokappa/documentation,macobo/documentation,macobo/documentation,jhotta/documentation,jhotta/documentation,inokappa/documentation,macobo/documentation,macobo/documentation,inokappa/documentation,jhotta/documentation,jhotta/documentation,jhotta/documentation,jhotta/documentation,inokappa/documentation,inokappa/documentation,macobo/documentation
--- +++ @@ -7,3 +7,7 @@ self.histogram( ... ) # Sample a histogram metric self.rate( ... ) # Sample a point, with the rate calculated at the end of the check + +self.count( ... ) # Sample a raw count metric + +self.monotonic_count( ... ) # Sample an increasing counter metric
6da466984143d2a9176870583ca5dba8d1b9764c
test/integration/test_graylogapi.py
test/integration/test_graylogapi.py
import pytest from pygraylog.pygraylog import graylogapi def test_get(): api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two', username = 'Zack', password = 'Zack') res = api._get() expected = { 'one': 'two' } assert res == expected def test_post(): api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two', username = 'Zack', password = 'Zack') with pytest.raises(NotImplementedError): api._post() def test_put(): api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two', username = 'Zack', password = 'Zack') with pytest.raises(NotImplementedError): api._put() def test_delete(): api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two', username = 'Zack', password = 'Zack') with pytest.raises(NotImplementedError): api._delete()
import pytest from pygraylog.pygraylog import graylogapi def test_get(): api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two', username = 'Zack', password = 'Zack') res = api._get() expected = "{\"one\": \"two\"}\n" assert res == expected def test_post(): api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two', username = 'Zack', password = 'Zack') with pytest.raises(NotImplementedError): api._post() def test_put(): api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two', username = 'Zack', password = 'Zack') with pytest.raises(NotImplementedError): api._put() def test_delete(): api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two', username = 'Zack', password = 'Zack') with pytest.raises(NotImplementedError): api._delete()
Modify test to reflect that api returns string response.
Modify test to reflect that api returns string response.
Python
apache-2.0
zmallen/pygraylog
--- +++ @@ -6,9 +6,7 @@ username = 'Zack', password = 'Zack') res = api._get() - expected = { - 'one': 'two' - } + expected = "{\"one\": \"two\"}\n" assert res == expected def test_post():
4ba0b5fe7f31d4353e9c091b03df7324d1c20e88
heat/common/pluginutils.py
heat/common/pluginutils.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_log import log as logging LOG = logging.getLogger(__name__) def log_fail_msg(manager, entrypoint, exception): LOG.warning('Encountered exception while loading %(module_name)s: ' '"%(message)s". Not using %(name)s.', {'module_name': entrypoint.module_name, 'message': exception.message, 'name': entrypoint.name})
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_log import log as logging import six LOG = logging.getLogger(__name__) def log_fail_msg(manager, entrypoint, exception): LOG.warning('Encountered exception while loading %(module_name)s: ' '"%(message)s". Not using %(name)s.', {'module_name': entrypoint.module_name, 'message': getattr(exception, 'message', six.text_type(exception)), 'name': entrypoint.name})
Fix no message attribute in exception
Fix no message attribute in exception For py35, message attribute in exception seems removed. We should directly get the string message from exception object if message attribute not presented. And since get message attribute already been deprecated. We should remove sopport on exception.message after we fully jump to py35. Partial-Bug: #1704725 Change-Id: I3970aa7c161aa82d179779f1a2f46405d5b0dddb
Python
apache-2.0
noironetworks/heat,noironetworks/heat,openstack/heat,openstack/heat
--- +++ @@ -12,6 +12,7 @@ # under the License. from oslo_log import log as logging +import six LOG = logging.getLogger(__name__) @@ -21,5 +22,6 @@ LOG.warning('Encountered exception while loading %(module_name)s: ' '"%(message)s". Not using %(name)s.', {'module_name': entrypoint.module_name, - 'message': exception.message, + 'message': getattr(exception, 'message', + six.text_type(exception)), 'name': entrypoint.name})
dd63394499c7c629033e76afa0196dfe48547da2
corehq/messaging/smsbackends/tropo/models.py
corehq/messaging/smsbackends/tropo/models.py
from urllib import urlencode from urllib2 import urlopen from corehq.apps.sms.util import clean_phone_number from corehq.apps.sms.models import SQLSMSBackend from dimagi.ext.couchdbkit import * from corehq.messaging.smsbackends.tropo.forms import TropoBackendForm from django.conf import settings class SQLTropoBackend(SQLSMSBackend): class Meta: app_label = 'sms' proxy = True @classmethod def get_available_extra_fields(cls): return [ 'messaging_token', ] @classmethod def get_api_id(cls): return 'TROPO' @classmethod def get_generic_name(cls): return "Tropo" @classmethod def get_form_class(cls): return TropoBackendForm def get_sms_rate_limit(self): return 60 def send(self, msg, *args, **kwargs): phone_number = clean_phone_number(msg.phone_number) text = msg.text.encode('utf-8') config = self.config params = urlencode({ 'action': 'create', 'token': config.messaging_token, 'numberToDial': phone_number, 'msg': text, '_send_sms': 'true', }) url = 'https://api.tropo.com/1.0/sessions?%s' % params response = urlopen(url, timeout=settings.SMS_GATEWAY_TIMEOUT).read() return response
from urllib import urlencode from urllib2 import urlopen from corehq.apps.sms.util import clean_phone_number from corehq.apps.sms.models import SQLSMSBackend from dimagi.ext.couchdbkit import * from corehq.messaging.smsbackends.tropo.forms import TropoBackendForm from django.conf import settings class SQLTropoBackend(SQLSMSBackend): class Meta: app_label = 'sms' proxy = True @classmethod def get_available_extra_fields(cls): return [ 'messaging_token', ] @classmethod def get_api_id(cls): return 'TROPO' @classmethod def get_generic_name(cls): return "Tropo" @classmethod def get_form_class(cls): return TropoBackendForm def get_sms_rate_limit(self): return 60 @classmethod def get_opt_in_keywords(cls): return ['START'] @classmethod def get_opt_out_keywords(cls): return ['STOP'] def send(self, msg, *args, **kwargs): phone_number = clean_phone_number(msg.phone_number) text = msg.text.encode('utf-8') config = self.config params = urlencode({ 'action': 'create', 'token': config.messaging_token, 'numberToDial': phone_number, 'msg': text, '_send_sms': 'true', }) url = 'https://api.tropo.com/1.0/sessions?%s' % params response = urlopen(url, timeout=settings.SMS_GATEWAY_TIMEOUT).read() return response
Add opt in/out keywords for tropo
Add opt in/out keywords for tropo
Python
bsd-3-clause
dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
--- +++ @@ -33,6 +33,14 @@ def get_sms_rate_limit(self): return 60 + @classmethod + def get_opt_in_keywords(cls): + return ['START'] + + @classmethod + def get_opt_out_keywords(cls): + return ['STOP'] + def send(self, msg, *args, **kwargs): phone_number = clean_phone_number(msg.phone_number) text = msg.text.encode('utf-8')
ed48c19844ee4f78c897c26555bdba9977a9a6ac
bluebottle/test/test_runner.py
bluebottle/test/test_runner.py
from django.test.runner import DiscoverRunner from django.db import connection from tenant_schemas.utils import get_tenant_model from bluebottle.test.utils import InitProjectDataMixin class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin): def setup_databases(self, *args, **kwargs): result = super(MultiTenantRunner, self).setup_databases(*args, **kwargs) # Create secondary tenant connection.set_schema_to_public() tenant_domain = 'testserver2' tenant2 = get_tenant_model()( domain_url=tenant_domain, schema_name='test2', client_name='test2') tenant2.save( verbosity=self.verbosity) # Add basic data for tenant connection.set_tenant(tenant2) self.init_projects() # Create main tenant connection.set_schema_to_public() tenant_domain = 'testserver' tenant = get_tenant_model()( domain_url=tenant_domain, schema_name='test', client_name='test') tenant.save( verbosity=self.verbosity) connection.set_tenant(tenant) return result
from django.test.runner import DiscoverRunner from django.db import connection from tenant_schemas.utils import get_tenant_model from bluebottle.test.utils import InitProjectDataMixin class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin): def setup_databases(self, *args, **kwargs): result = super(MultiTenantRunner, self).setup_databases(*args, **kwargs) # Create secondary tenant connection.set_schema_to_public() tenant_domain = 'testserver2' tenant2, _created = get_tenant_model().objects.get_or_create( domain_url=tenant_domain, schema_name='test2', client_name='test2') tenant2.save( verbosity=self.verbosity) # Add basic data for tenant connection.set_tenant(tenant2) self.init_projects() # Create main tenant connection.set_schema_to_public() tenant_domain = 'testserver' tenant, _created = get_tenant_model().objects.get_or_create( domain_url=tenant_domain, schema_name='test', client_name='test') tenant.save( verbosity=self.verbosity) connection.set_tenant(tenant) return result
Make it possible to run tests with --keepdb
Make it possible to run tests with --keepdb
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
--- +++ @@ -13,7 +13,7 @@ # Create secondary tenant connection.set_schema_to_public() tenant_domain = 'testserver2' - tenant2 = get_tenant_model()( + tenant2, _created = get_tenant_model().objects.get_or_create( domain_url=tenant_domain, schema_name='test2', client_name='test2') @@ -28,7 +28,8 @@ # Create main tenant connection.set_schema_to_public() tenant_domain = 'testserver' - tenant = get_tenant_model()( + + tenant, _created = get_tenant_model().objects.get_or_create( domain_url=tenant_domain, schema_name='test', client_name='test')
25395cbd3536c1bc2ee1a6bc44a34ea7fc5b2a13
src/priestLogger.py
src/priestLogger.py
import logging from logging.handlers import TimedRotatingFileHandler class PriestLogger: def __init__(self): logHandler = TimedRotatingFileHandler("C:\\lucas\\PriestPy\\Dropbox\\logs\\HowToPriest",when="midnight",backupCount=365) logFormatter = logging.Formatter('%(asctime)s - %(message)s') logHandler.setFormatter( logFormatter ) self.logger = logging.getLogger( 'H2PLogger' ) self.logger.addHandler( logHandler ) self.logger.setLevel( logging.INFO ) def log(self, message): self.logger.info(message.channel.name + ' - ' + message.author.name+': ' + message.content)
import logging from logging.handlers import TimedRotatingFileHandler from time import sleep class PriestLogger: def __init__(self): logHandler = TimedRotatingFileHandler("C:\\lucas\\PriestPy\\Dropbox\\logs\\HowToPriest",when="midnight",backupCount=365) logFormatter = logging.Formatter('%(asctime)s - %(message)s') logHandler.setFormatter( logFormatter ) self.logger = logging.getLogger( 'H2PLogger' ) self.logger.addHandler( logHandler ) self.logger.setLevel( logging.INFO ) def log(self, message): sent = false while not sent: try: self.logger.info(message.channel.name + ' - ' + message.author.name+': ' + message.content) sent = true except: sleep(0.2)
Fix for conflict in opening file
Fix for conflict in opening file
Python
mit
lgkern/PriestPy
--- +++ @@ -1,5 +1,6 @@ import logging from logging.handlers import TimedRotatingFileHandler +from time import sleep class PriestLogger: @@ -12,4 +13,11 @@ self.logger.setLevel( logging.INFO ) def log(self, message): - self.logger.info(message.channel.name + ' - ' + message.author.name+': ' + message.content) + sent = false + while not sent: + try: + self.logger.info(message.channel.name + ' - ' + message.author.name+': ' + message.content) + sent = true + except: + sleep(0.2) +
7e0ef4ba74bf2d6ea93f49d88c58378e7a1f9106
fabfile.py
fabfile.py
from fusionbox.fabric_helpers import * env.roledefs = { 'dev': ['dev.fusionbox.com'], } env.project_name = 'django-widgy' env.short_name = 'widgy' env.tld = '' def stage_with_docs(pip=False, migrate=False, syncdb=False, branch=None): stage(pip=pip, migrate=migrate, syncdb=syncdb, branch=branch) with cd('/var/www/%s%s/doc' % (env.project_name, env.tld)): with virtualenv(env.short_name): run("make html") stage = roles('dev')(stage) dstage = roles('dev')(stage_with_docs)
from fusionbox.fabric_helpers import * env.roledefs = { 'dev': ['dev.fusionbox.com'], } env.project_name = 'django-widgy' env.short_name = 'widgy' env.tld = '' _stage = stage def stage(pip=False, migrate=False, syncdb=False, branch=None): _stage(pip=pip, migrate=migrate, syncdb=syncdb, branch=branch) with cd('/var/www/%s%s/doc' % (env.project_name, env.tld)): with virtualenv(env.short_name): run("make html") stage = roles('dev')(stage)
Make this one role, stage
Make this one role, stage
Python
apache-2.0
j00bar/django-widgy,j00bar/django-widgy,j00bar/django-widgy
--- +++ @@ -9,11 +9,11 @@ env.tld = '' -def stage_with_docs(pip=False, migrate=False, syncdb=False, branch=None): - stage(pip=pip, migrate=migrate, syncdb=syncdb, branch=branch) +_stage = stage +def stage(pip=False, migrate=False, syncdb=False, branch=None): + _stage(pip=pip, migrate=migrate, syncdb=syncdb, branch=branch) with cd('/var/www/%s%s/doc' % (env.project_name, env.tld)): with virtualenv(env.short_name): run("make html") stage = roles('dev')(stage) -dstage = roles('dev')(stage_with_docs)
78af66131240f79e43fba811cb8769b1911fa013
services/fitbit.py
services/fitbit.py
import foauth.providers class Fitbit(foauth.providers.OAuth1): # General info about the provider provider_url = 'https://www.fitbit.com/' docs_url = 'https://dev.fitbit.com/' category = 'Fitness' # URLs to interact with the API request_token_url = 'https://api.fitbit.com/oauth/request_token' authorize_url = 'https://www.fitbit.com/oauth/authorize' access_token_url = 'https://api.fitbit.com/oauth/access_token' api_domain = 'api.fitbit.com' available_permissions = [ (None, 'read and write your fitness data'), ] def get_user_id(self, key): r = self.api(key, self.api_domain, u'/1/user/-/profile.json') return r.json()[u'user'][u'encodedId']
import requests import foauth.providers class Fitbit(foauth.providers.OAuth2): # General info about the provider provider_url = 'https://www.fitbit.com/' docs_url = 'https://dev.fitbit.com/' category = 'Fitness' # URLs to interact with the API authorize_url = 'https://www.fitbit.com/oauth2/authorize' access_token_url = 'https://api.fitbit.com/oauth2/token' api_domain = 'api.fitbit.com' available_permissions = [ (None, 'read and write your user profile'), ('activity', 'read and write your activity data'), ('heartrate', 'read and write your heart rate'), ('location', 'read and write your location'), ('nutrition', 'read and write your nutrition information'), ('settings', 'manage your account and device settings'), ('sleep', 'read and write to your sleep logs'), ('social', 'manage your friends'), ('weight', 'read and write your weight information'), ] def __init__(self, *args, **kwargs): super(Fitbit, self).__init__(*args, **kwargs) self.auth = (self.client_id, self.client_secret) def get_authorize_params(self, redirect_uri, scopes): # Always request profile info, in order to get the user ID scopes.append('profile') return super(Fitbit, self).get_authorize_params(redirect_uri, scopes) def get_access_token_response(self, redirect_uri, data): # Need a custom request here in order to include state return requests.post(self.get_access_token_url(), { 'client_id': self.client_id, 'client_secret': self.client_secret, 'grant_type': 'authorization_code', 'code': data['code'], 'redirect_uri': redirect_uri, 'state': data['state'], }, verify=self.verify, auth=self.auth) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/1/user/-/profile.json') return r.json()[u'user'][u'encodedId']
Upgrade Fitbit to OAuth 2.0
Upgrade Fitbit to OAuth 2.0
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
--- +++ @@ -1,21 +1,50 @@ +import requests + import foauth.providers -class Fitbit(foauth.providers.OAuth1): +class Fitbit(foauth.providers.OAuth2): # General info about the provider provider_url = 'https://www.fitbit.com/' docs_url = 'https://dev.fitbit.com/' category = 'Fitness' # URLs to interact with the API - request_token_url = 'https://api.fitbit.com/oauth/request_token' - authorize_url = 'https://www.fitbit.com/oauth/authorize' - access_token_url = 'https://api.fitbit.com/oauth/access_token' + authorize_url = 'https://www.fitbit.com/oauth2/authorize' + access_token_url = 'https://api.fitbit.com/oauth2/token' api_domain = 'api.fitbit.com' available_permissions = [ - (None, 'read and write your fitness data'), + (None, 'read and write your user profile'), + ('activity', 'read and write your activity data'), + ('heartrate', 'read and write your heart rate'), + ('location', 'read and write your location'), + ('nutrition', 'read and write your nutrition information'), + ('settings', 'manage your account and device settings'), + ('sleep', 'read and write to your sleep logs'), + ('social', 'manage your friends'), + ('weight', 'read and write your weight information'), ] + + def __init__(self, *args, **kwargs): + super(Fitbit, self).__init__(*args, **kwargs) + self.auth = (self.client_id, self.client_secret) + + def get_authorize_params(self, redirect_uri, scopes): + # Always request profile info, in order to get the user ID + scopes.append('profile') + return super(Fitbit, self).get_authorize_params(redirect_uri, scopes) + + def get_access_token_response(self, redirect_uri, data): + # Need a custom request here in order to include state + return requests.post(self.get_access_token_url(), { + 'client_id': self.client_id, + 'client_secret': self.client_secret, + 'grant_type': 'authorization_code', + 'code': data['code'], + 'redirect_uri': redirect_uri, + 'state': data['state'], + }, verify=self.verify, auth=self.auth) def get_user_id(self, key): r = self.api(key, self.api_domain, u'/1/user/-/profile.json')
20bc9544830f329c07c8f80e2f38a7fc9fdb3245
tests/unit/utils/test_yamldumper.py
tests/unit/utils/test_yamldumper.py
# -*- coding: utf-8 -*- ''' Unit tests for salt.utils.yamldumper ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt Libs import salt.utils.yamldumper # Import Salt Testing Libs from tests.support.unit import TestCase, skipIf from tests.support.mock import NO_MOCK, NO_MOCK_REASON @skipIf(NO_MOCK, NO_MOCK_REASON) class YamlDumperTestCase(TestCase): ''' TestCase for salt.utils.yamlloader module ''' def test_yaml_dump(self): ''' Test yaml.dump a dict ''' data = {'foo': 'bar'} assert salt.utils.yamldumper.dump(data) == '{!!python/unicode \'foo\': !!python/unicode \'bar\'}\n' assert salt.utils.yamldumper.dump(data, default_flow_style=False) == '!!python/unicode \'foo\': !!python/unicode \'bar\'\n' def test_yaml_safe_dump(self): ''' Test yaml.safe_dump a dict ''' data = {'foo': 'bar'} assert salt.utils.yamldumper.safe_dump(data) == '{foo: bar}\n' assert salt.utils.yamldumper.safe_dump(data, default_flow_style=False) == 'foo: bar\n'
# -*- coding: utf-8 -*- ''' Unit tests for salt.utils.yamldumper ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt Libs import salt.utils.yamldumper # Import Salt Testing Libs from tests.support.unit import TestCase, skipIf from tests.support.mock import NO_MOCK, NO_MOCK_REASON @skipIf(NO_MOCK, NO_MOCK_REASON) class YamlDumperTestCase(TestCase): ''' TestCase for salt.utils.yamldumper module ''' def test_yaml_dump(self): ''' Test yaml.dump a dict ''' data = {'foo': 'bar'} assert salt.utils.yamldumper.dump(data) == '{!!python/unicode \'foo\': !!python/unicode \'bar\'}\n' assert salt.utils.yamldumper.dump(data, default_flow_style=False) == '!!python/unicode \'foo\': !!python/unicode \'bar\'\n' def test_yaml_safe_dump(self): ''' Test yaml.safe_dump a dict ''' data = {'foo': 'bar'} assert salt.utils.yamldumper.safe_dump(data) == '{foo: bar}\n' assert salt.utils.yamldumper.safe_dump(data, default_flow_style=False) == 'foo: bar\n'
Update docs for yamldumper test
Update docs for yamldumper test
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -17,7 +17,7 @@ @skipIf(NO_MOCK, NO_MOCK_REASON) class YamlDumperTestCase(TestCase): ''' - TestCase for salt.utils.yamlloader module + TestCase for salt.utils.yamldumper module ''' def test_yaml_dump(self): '''
936021e0a7b2f23935f4580c5140c1292a37cf82
runbot_pylint/__openerp__.py
runbot_pylint/__openerp__.py
{ 'name': 'Runbot Pylint', 'category': 'Website', 'summary': 'Runbot', 'version': '1.0', 'description': "Runbot", 'author': 'OpenERP SA', 'depends': ['runbot'], 'external_dependencies': { }, 'data': [ "view/runbot_pylint_view.xml" ], 'installable': True, }
{ 'name': 'Runbot Pylint', 'category': 'Website', 'summary': 'Runbot', 'version': '1.0', 'description': "Runbot", 'author': 'OpenERP SA', 'depends': ['runbot'], 'external_dependencies': { 'bin': ['pylint'], }, 'data': [ "view/runbot_pylint_view.xml" ], 'installable': True, }
Add external depedencies to pylint bin
Add external depedencies to pylint bin
Python
agpl-3.0
amoya-dx/runbot-addons
--- +++ @@ -7,6 +7,7 @@ 'author': 'OpenERP SA', 'depends': ['runbot'], 'external_dependencies': { + 'bin': ['pylint'], }, 'data': [ "view/runbot_pylint_view.xml"
2823efda9d6ec2a14606c9e22ef8085f111d8842
isort/pylama_isort.py
isort/pylama_isort.py
import os import sys from contextlib import contextmanager from typing import Any, Dict, List from pylama.lint import Linter as BaseLinter from . import api @contextmanager def supress_stdout(): stdout = sys.stdout with open(os.devnull, "w") as devnull: sys.stdout = devnull yield sys.stdout = stdout class Linter(BaseLinter): def allow(self, path: str) -> bool: """Determine if this path should be linted.""" return path.endswith(".py") def run(self, path: str, **meta: Any) -> List[Dict[str, Any]]: """Lint the file. Return an array of error dicts if appropriate.""" with supress_stdout(): if api.check_file(path, check=True): return [ {"lnum": 0, "col": 0, "text": "Incorrectly sorted imports.", "type": "ISORT"} ] else: return []
import os import sys from contextlib import contextmanager from typing import Any, Dict, List from pylama.lint import Linter as BaseLinter from . import api @contextmanager def supress_stdout(): stdout = sys.stdout with open(os.devnull, "w") as devnull: sys.stdout = devnull yield sys.stdout = stdout class Linter(BaseLinter): def allow(self, path: str) -> bool: """Determine if this path should be linted.""" return path.endswith(".py") def run(self, path: str, **meta: Any) -> List[Dict[str, Any]]: """Lint the file. Return an array of error dicts if appropriate.""" with supress_stdout(): if api.check_file(path): return [ {"lnum": 0, "col": 0, "text": "Incorrectly sorted imports.", "type": "ISORT"} ] else: return []
Fix pylama isort integration not to include check=True redundly
Fix pylama isort integration not to include check=True redundly
Python
mit
PyCQA/isort,PyCQA/isort
--- +++ @@ -25,7 +25,7 @@ def run(self, path: str, **meta: Any) -> List[Dict[str, Any]]: """Lint the file. Return an array of error dicts if appropriate.""" with supress_stdout(): - if api.check_file(path, check=True): + if api.check_file(path): return [ {"lnum": 0, "col": 0, "text": "Incorrectly sorted imports.", "type": "ISORT"} ]
c52e8e27d7b245722e10887dc97440481d0871f4
scraper/political_parties.py
scraper/political_parties.py
import re import requests import lxml.html from parliament.models import PoliticalParty def create_parties(): url = 'https://www.tweedekamer.nl/kamerleden/fracties' page = requests.get(url) tree = lxml.html.fromstring(page.content) rows = tree.xpath("//ul[@class='reset grouped-list']/li/a") for row in rows: columns = row.text.split('-') if len(columns) > 1: name = columns[0].strip() name_short = columns[1] name_short = re.sub(r'\(.+?\)', '', name_short).strip() else: name = columns[0] name = re.sub(r'\(.+?\)', '', name).strip() name_short = name # print('name: ' + name) # print('short: ' + name_short) if PoliticalParty.find_party(name): print('WARNING: party already exists!') else: party = PoliticalParty.objects.create(name=name, name_short=name_short) party.update_info('nl', 'nl') party.save() print('created: ' + str(party))
import re import requests import lxml.html from parliament.models import PoliticalParty def create_parties(): url = 'https://www.tweedekamer.nl/kamerleden/fracties' page = requests.get(url) tree = lxml.html.fromstring(page.content) rows = tree.xpath("//ul[@class='reset grouped-list']/li/a") for row in rows: columns = row.text.split('-') if len(columns) > 1: name = columns[0].strip() name_short = columns[1] name_short = re.sub(r'\(.+?\)', '', name_short).strip() else: name = columns[0] name = re.sub(r'\(.+?\)', '', name).strip() name_short = name # print('name: ' + name) # print('short: ' + name_short) party = PoliticalParty.find_party(name) if party: print('WARNING: party already exists!') else: party = PoliticalParty.objects.create(name=name, name_short=name_short) print('created: ' + str(party)) party.update_info('nl', 'nl') party.save()
Update party info after creation
Update party info after creation
Python
mit
openkamer/openkamer,openkamer/openkamer,openkamer/openkamer,openkamer/openkamer
--- +++ @@ -24,10 +24,11 @@ name_short = name # print('name: ' + name) # print('short: ' + name_short) - if PoliticalParty.find_party(name): + party = PoliticalParty.find_party(name) + if party: print('WARNING: party already exists!') else: party = PoliticalParty.objects.create(name=name, name_short=name_short) - party.update_info('nl', 'nl') - party.save() print('created: ' + str(party)) + party.update_info('nl', 'nl') + party.save()
01cc82642273af950caedba471ed4cc9e788b615
alapage/urls.py
alapage/urls.py
# -*- coding: utf-8 -*- from django.conf.urls import url from alapage.views import HomepageView, PageView, PagesmapView urlpatterns = [] urlpatterns.append( url(r'^sitemap/$', PagesmapView.as_view(), name="alapage-map")) #urlpatterns.append(url(r'^alapage/wizard/$', PageWizardView.as_view(), name="alapage-wizard")) #urlpatterns.append(url(r'^alapage/wizard/post/$', AddPagePostView.as_view(), name="alapage-wizard-post")) urlpatterns.append( url(r'^(?P<url>.*?)$', PageView.as_view(), name="page-view")) urlpatterns.append(url(r'^', HomepageView.as_view(), name="home-view"))
from django.conf.urls import url from alapage.views import HomepageView, PageView, PagesmapView urlpatterns = [ url(r'^sitemap/?$', PagesmapView.as_view(), name="alapage-map"), url(r'^(?P<url>.*?)?$', PageView.as_view(), name="page-view"), url(r'^', HomepageView.as_view(), name="home-view"), ]
Fix url regex for no trailing slash
Fix url regex for no trailing slash
Python
mit
synw/django-alapage,synw/django-alapage,synw/django-alapage
--- +++ @@ -1,15 +1,9 @@ -# -*- coding: utf-8 -*- - from django.conf.urls import url from alapage.views import HomepageView, PageView, PagesmapView -urlpatterns = [] - -urlpatterns.append( - url(r'^sitemap/$', PagesmapView.as_view(), name="alapage-map")) -#urlpatterns.append(url(r'^alapage/wizard/$', PageWizardView.as_view(), name="alapage-wizard")) -#urlpatterns.append(url(r'^alapage/wizard/post/$', AddPagePostView.as_view(), name="alapage-wizard-post")) -urlpatterns.append( - url(r'^(?P<url>.*?)$', PageView.as_view(), name="page-view")) -urlpatterns.append(url(r'^', HomepageView.as_view(), name="home-view")) +urlpatterns = [ + url(r'^sitemap/?$', PagesmapView.as_view(), name="alapage-map"), + url(r'^(?P<url>.*?)?$', PageView.as_view(), name="page-view"), + url(r'^', HomepageView.as_view(), name="home-view"), +]
491d2ad7cea58597e15b095b94930b6ff1dbf4d2
createdb.py
createdb.py
from chalice.extensions import db from chalice import init_app from chalice.blog.models import Tag, Post from chalice.auth.models import User if __name__ == '__main__': app = init_app() with app.test_request_context(): db.create_all() post = Post( 'This is a title', 'The classic hello world here.') post.tags = ['rant', 'programming'] db.session.add(post) user = User('andrimar', 'testpass') db.session.add(user) db.session.commit() print 'Initialized an empty db using the following connection string: %s' % app.config['SQLALCHEMY_DATABASE_URI']
from chalice.extensions import db from chalice import init_app from chalice.blog.models import Tag, Post from chalice.auth.models import User if __name__ == '__main__': app = init_app() with app.test_request_context(): db.create_all() user = User(app.config['CHALICE_USER'], app.config['CHALICE_PASS']) db.session.add(user) db.session.commit() print 'Initialized a db using the following connection string: %s' % app.config['SQLALCHEMY_DATABASE_URI']
Remove dummy post from created.py script. Initial user now taken from config.
Remove dummy post from created.py script. Initial user now taken from config.
Python
bsd-2-clause
andrimarjonsson/chalice,andrimarjonsson/chalice
--- +++ @@ -7,10 +7,7 @@ app = init_app() with app.test_request_context(): db.create_all() - post = Post( 'This is a title', 'The classic hello world here.') - post.tags = ['rant', 'programming'] - db.session.add(post) - user = User('andrimar', 'testpass') + user = User(app.config['CHALICE_USER'], app.config['CHALICE_PASS']) db.session.add(user) db.session.commit() - print 'Initialized an empty db using the following connection string: %s' % app.config['SQLALCHEMY_DATABASE_URI'] + print 'Initialized a db using the following connection string: %s' % app.config['SQLALCHEMY_DATABASE_URI']
e8422ac65a4557257d9697b8dfcb538a02e5f6f0
pixelated/common/__init__.py
pixelated/common/__init__.py
import ssl import logging from logging.handlers import SysLogHandler from threading import Timer logger = logging.getLogger('pixelated.startup') def init_logging(name, level=logging.INFO, config_file=None): global logger logger_name = 'pixelated.%s' % name logging.basicConfig(level=level) if config_file: logging.config.fileConfig(config_file) else: formatter = logging.Formatter('%(asctime)s %(name)s: %(levelname)s %(message)s', '%b %e %H:%M:%S') syslog = SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_DAEMON) syslog.setFormatter(formatter) logger.addHandler(syslog) logger.name = logger_name logger.info('Initialized logging') def latest_available_ssl_version(): return ssl.PROTOCOL_TLSv1 class Watchdog: def __init__(self, timeout, userHandler=None, args=[]): self.timeout = timeout self.handler = userHandler if userHandler is not None else self.defaultHandler self.timer = Timer(self.timeout, self.handler, args=args) self.timer.daemon = True self.timer.start() def reset(self): self.timer.cancel() self.timer = Timer(self.timeout, self.handler) def stop(self): self.timer.cancel() def defaultHandler(self): raise self
import ssl import logging from logging.handlers import SysLogHandler from threading import Timer logger = logging.getLogger('pixelated.startup') def init_logging(name, level=logging.INFO, config_file=None): global logger logger_name = 'pixelated.%s' % name logging.basicConfig(level=level) if config_file: logging.config.fileConfig(config_file) else: formatter = logging.Formatter('%(asctime)s %(name)s: %(levelname)s %(message)s', '%b %e %H:%M:%S') syslog = SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_DAEMON) syslog.setFormatter(formatter) logger.addHandler(syslog) logger.name = logger_name logger.info('Initialized logging') def latest_available_ssl_version(): try: return ssl.PROTOCOL_TLSv1_2 except AttributeError: return ssl.PROTOCOL_TLSv1 class Watchdog: def __init__(self, timeout, userHandler=None, args=[]): self.timeout = timeout self.handler = userHandler if userHandler is not None else self.defaultHandler self.timer = Timer(self.timeout, self.handler, args=args) self.timer.daemon = True self.timer.start() def reset(self): self.timer.cancel() self.timer = Timer(self.timeout, self.handler) def stop(self): self.timer.cancel() def defaultHandler(self): raise self
Revert "Downgraded SSL version to TLS 1 until we have the requests library fixed"
Revert "Downgraded SSL version to TLS 1 until we have the requests library fixed" - TLS1.2 does not work on older pythons (like on MacOSX) but it works as intended on current linux versions so enable it if possible This reverts commit 666630f2a01bdeb7becc3cd3b324c076eaf1567d. Conflicts: pixelated/common/__init__.py
Python
agpl-3.0
pixelated-project/pixelated-dispatcher,pixelated-project/pixelated-dispatcher,pixelated/pixelated-dispatcher,pixelated/pixelated-dispatcher,pixelated/pixelated-dispatcher,pixelated-project/pixelated-dispatcher
--- +++ @@ -24,7 +24,10 @@ def latest_available_ssl_version(): - return ssl.PROTOCOL_TLSv1 + try: + return ssl.PROTOCOL_TLSv1_2 + except AttributeError: + return ssl.PROTOCOL_TLSv1 class Watchdog:
d7ea84800b89255137300b8e8d83b4b6abfc30b2
src/oscar/apps/voucher/receivers.py
src/oscar/apps/voucher/receivers.py
from oscar.apps.basket import signals def track_voucher_addition(basket, voucher, **kwargs): voucher.num_basket_additions += 1 voucher.save() def track_voucher_removal(basket, voucher, **kwargs): voucher.num_basket_additions -= 1 voucher.save() signals.voucher_addition.connect(track_voucher_addition) signals.voucher_removal.connect(track_voucher_removal)
from django.db.models import F from oscar.apps.basket import signals def track_voucher_addition(basket, voucher, **kwargs): voucher.num_basket_additions += 1 voucher.__class__._default_manager.filter(pk=voucher.pk).update( num_basket_additions=F('num_basket_additions') + 1, ) def track_voucher_removal(basket, voucher, **kwargs): voucher.num_basket_additions -= 1 voucher.__class__._default_manager.filter(pk=voucher.pk).update( num_basket_additions=F('num_basket_additions') - 1, ) signals.voucher_addition.connect(track_voucher_addition) signals.voucher_removal.connect(track_voucher_removal)
Fix race condition when tracking num_basket_additions on a voucher
Fix race condition when tracking num_basket_additions on a voucher
Python
bsd-3-clause
jmt4/django-oscar,mexeniz/django-oscar,michaelkuty/django-oscar,pasqualguerrero/django-oscar,binarydud/django-oscar,saadatqadri/django-oscar,jmt4/django-oscar,michaelkuty/django-oscar,nickpack/django-oscar,pasqualguerrero/django-oscar,okfish/django-oscar,sasha0/django-oscar,okfish/django-oscar,sasha0/django-oscar,bnprk/django-oscar,anentropic/django-oscar,solarissmoke/django-oscar,amirrpp/django-oscar,solarissmoke/django-oscar,dongguangming/django-oscar,amirrpp/django-oscar,django-oscar/django-oscar,anentropic/django-oscar,saadatqadri/django-oscar,lijoantony/django-oscar,pasqualguerrero/django-oscar,sasha0/django-oscar,jmt4/django-oscar,anentropic/django-oscar,jlmadurga/django-oscar,lijoantony/django-oscar,lijoantony/django-oscar,Bogh/django-oscar,vovanbo/django-oscar,spartonia/django-oscar,eddiep1101/django-oscar,monikasulik/django-oscar,taedori81/django-oscar,amirrpp/django-oscar,sasha0/django-oscar,faratro/django-oscar,eddiep1101/django-oscar,django-oscar/django-oscar,vovanbo/django-oscar,michaelkuty/django-oscar,sonofatailor/django-oscar,MatthewWilkes/django-oscar,taedori81/django-oscar,lijoantony/django-oscar,pdonadeo/django-oscar,pdonadeo/django-oscar,binarydud/django-oscar,spartonia/django-oscar,michaelkuty/django-oscar,bnprk/django-oscar,binarydud/django-oscar,MatthewWilkes/django-oscar,WillisXChen/django-oscar,MatthewWilkes/django-oscar,monikasulik/django-oscar,WadeYuChen/django-oscar,WadeYuChen/django-oscar,thechampanurag/django-oscar,WadeYuChen/django-oscar,itbabu/django-oscar,QLGu/django-oscar,sonofatailor/django-oscar,anentropic/django-oscar,thechampanurag/django-oscar,QLGu/django-oscar,nfletton/django-oscar,jmt4/django-oscar,jlmadurga/django-oscar,MatthewWilkes/django-oscar,john-parton/django-oscar,john-parton/django-oscar,kapari/django-oscar,kapari/django-oscar,itbabu/django-oscar,Jannes123/django-oscar,okfish/django-oscar,ka7eh/django-oscar,rocopartners/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,Jannes123/django-oscar,saadatqadri/django-oscar,bnprk/django-oscar,faratro/django-oscar,mexeniz/django-oscar,jlmadurga/django-oscar,mexeniz/django-oscar,Bogh/django-oscar,binarydud/django-oscar,itbabu/django-oscar,taedori81/django-oscar,nfletton/django-oscar,bschuon/django-oscar,pdonadeo/django-oscar,Jannes123/django-oscar,dongguangming/django-oscar,jlmadurga/django-oscar,itbabu/django-oscar,pasqualguerrero/django-oscar,Jannes123/django-oscar,Bogh/django-oscar,bschuon/django-oscar,rocopartners/django-oscar,spartonia/django-oscar,faratro/django-oscar,bschuon/django-oscar,rocopartners/django-oscar,dongguangming/django-oscar,monikasulik/django-oscar,nickpack/django-oscar,nickpack/django-oscar,bschuon/django-oscar,bnprk/django-oscar,saadatqadri/django-oscar,nfletton/django-oscar,nickpack/django-oscar,nfletton/django-oscar,QLGu/django-oscar,eddiep1101/django-oscar,WillisXChen/django-oscar,faratro/django-oscar,thechampanurag/django-oscar,dongguangming/django-oscar,Bogh/django-oscar,QLGu/django-oscar,monikasulik/django-oscar,ka7eh/django-oscar,john-parton/django-oscar,WadeYuChen/django-oscar,ka7eh/django-oscar,taedori81/django-oscar,eddiep1101/django-oscar,WillisXChen/django-oscar,WillisXChen/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,thechampanurag/django-oscar,pdonadeo/django-oscar,john-parton/django-oscar,kapari/django-oscar,solarissmoke/django-oscar,kapari/django-oscar,rocopartners/django-oscar,amirrpp/django-oscar,mexeniz/django-oscar,vovanbo/django-oscar,vovanbo/django-oscar,WillisXChen/django-oscar,ka7eh/django-oscar,solarissmoke/django-oscar,WillisXChen/django-oscar,spartonia/django-oscar,okfish/django-oscar
--- +++ @@ -1,14 +1,19 @@ +from django.db.models import F from oscar.apps.basket import signals def track_voucher_addition(basket, voucher, **kwargs): voucher.num_basket_additions += 1 - voucher.save() + voucher.__class__._default_manager.filter(pk=voucher.pk).update( + num_basket_additions=F('num_basket_additions') + 1, + ) def track_voucher_removal(basket, voucher, **kwargs): voucher.num_basket_additions -= 1 - voucher.save() + voucher.__class__._default_manager.filter(pk=voucher.pk).update( + num_basket_additions=F('num_basket_additions') - 1, + ) signals.voucher_addition.connect(track_voucher_addition)
691dae3963d049664605084438714b2850bd0933
linter.py
linter.py
# # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Markus Liljedahl # Copyright (c) 2017 Markus Liljedahl # # License: MIT # """This module exports the AnsibleLint plugin class.""" from SublimeLinter.lint import Linter, util class AnsibleLint(Linter): """Provides an interface to ansible-lint.""" # ansbile-lint verison requirements check version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 3.0.1' # linter settings cmd = ('ansible-lint', '${args}', '${file}') regex = r'.+:(?P<line>\d+): \[(?P<error>.z+)\] (?P<message>.+)' # -p generate non-multi-line, pep8 compatible output multiline = False # ansible-lint does not support column number word_re = False line_col_base = (1, 1) tempfile_suffix = 'yml' error_stream = util.STREAM_STDOUT defaults = { 'selector': 'source.ansible', 'args': '-p' }
# # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Markus Liljedahl # Copyright (c) 2017 Markus Liljedahl # # License: MIT # """This module exports the AnsibleLint plugin class.""" from SublimeLinter.lint import Linter, util class AnsibleLint(Linter): """Provides an interface to ansible-lint.""" # ansbile-lint verison requirements check version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 3.0.1' # linter settings cmd = ('ansible-lint', '${args}', '@') regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)' # -p generate non-multi-line, pep8 compatible output multiline = False # ansible-lint does not support column number word_re = False line_col_base = (1, 1) tempfile_suffix = 'yml' error_stream = util.STREAM_STDOUT defaults = { 'selector': 'source.ansible', 'args': '--nocolor -p', '--exclude= +': ['.galaxy'], } inline_overrides = ['exclude']
Update to support SublimeLinter 4
Update to support SublimeLinter 4
Python
mit
mliljedahl/SublimeLinter-contrib-ansible-lint
--- +++ @@ -22,8 +22,8 @@ version_requirement = '>= 3.0.1' # linter settings - cmd = ('ansible-lint', '${args}', '${file}') - regex = r'.+:(?P<line>\d+): \[(?P<error>.z+)\] (?P<message>.+)' + cmd = ('ansible-lint', '${args}', '@') + regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)' # -p generate non-multi-line, pep8 compatible output multiline = False @@ -33,7 +33,10 @@ tempfile_suffix = 'yml' error_stream = util.STREAM_STDOUT + defaults = { 'selector': 'source.ansible', - 'args': '-p' + 'args': '--nocolor -p', + '--exclude= +': ['.galaxy'], } + inline_overrides = ['exclude']
84597d8b8135af36056f968d10699c206dd06942
adapter/terminal.py
adapter/terminal.py
import os import socket import subprocess import string import logging log = logging.getLogger('terminal') class Terminal: def __init__(self, tty, socket): self.tty = tty self.socket = socket def __del__(self): self.socket.close() TIMEOUT = 1 # Timeout in seconds for child opening a socket and sending the tty name def create(): socket_path = '/tmp/vscode-lldb-%d.sock' % os.getpid() try: os.unlink(socket_path) except OSError: pass ls = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) ls.bind(socket_path) ls.listen(1) subprocess.Popen(['x-terminal-emulator', '-e', 'bash -c "tty | nc -U %s -q -1"' % socket_path]); try: ls.settimeout(TIMEOUT) conn, addr = ls.accept() os.unlink(socket_path) conn.settimeout(TIMEOUT) data = '' while True: data += conn.recv(32) lines = string.split(data, '\n') if len(lines) > 1: return Terminal(lines[0], conn) except (OSError, socket.timeout): raise Exception('Failed to create a new terminal')
import os import socket import subprocess import string import logging log = logging.getLogger('terminal') class Terminal: def __init__(self, tty, socket): self.tty = tty self.socket = socket def __del__(self): self.socket.close() TIMEOUT = 3 # Timeout in seconds for child opening a socket and sending the tty name def create(): ls = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ls.bind(('127.0.0.1', 0)) ls.listen(1) addr, port = ls.getsockname() # Open a TCP connection, send output of `tty`, wait till the socket gets closed from our end command = 'exec 3<>/dev/tcp/127.0.0.1/%d; tty >&3; read <&3' % port subprocess.Popen(['x-terminal-emulator', '-e', 'bash -c "%s"' % command]); try: ls.settimeout(TIMEOUT) conn, addr = ls.accept() conn.settimeout(TIMEOUT) output = '' while True: data = conn.recv(32) if len(data) == 0: reason = 'connection aborted' break log.info('received %s', data) output += data lines = string.split(output, '\n') if len(lines) > 1: return Terminal(lines[0], conn) except (OSError, socket.timeout): reason = 'timeout' raise Exception('Failed to create a new terminal: %s' % reason)
Use bash's built-in tcp support, drop dependency on netcat.
Use bash's built-in tcp support, drop dependency on netcat.
Python
mit
vadimcn/vscode-lldb,vadimcn/vscode-lldb,NeroProtagonist/vscode-lldb,NeroProtagonist/vscode-lldb,NeroProtagonist/vscode-lldb,vadimcn/vscode-lldb,NeroProtagonist/vscode-lldb,vadimcn/vscode-lldb,NeroProtagonist/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb
--- +++ @@ -14,29 +14,33 @@ def __del__(self): self.socket.close() -TIMEOUT = 1 # Timeout in seconds for child opening a socket and sending the tty name +TIMEOUT = 3 # Timeout in seconds for child opening a socket and sending the tty name def create(): - socket_path = '/tmp/vscode-lldb-%d.sock' % os.getpid() - try: os.unlink(socket_path) - except OSError: pass - ls = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - ls.bind(socket_path) + ls = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + ls.bind(('127.0.0.1', 0)) ls.listen(1) - subprocess.Popen(['x-terminal-emulator', '-e', 'bash -c "tty | nc -U %s -q -1"' % socket_path]); + addr, port = ls.getsockname() + # Open a TCP connection, send output of `tty`, wait till the socket gets closed from our end + command = 'exec 3<>/dev/tcp/127.0.0.1/%d; tty >&3; read <&3' % port + subprocess.Popen(['x-terminal-emulator', '-e', 'bash -c "%s"' % command]); try: ls.settimeout(TIMEOUT) conn, addr = ls.accept() - os.unlink(socket_path) - conn.settimeout(TIMEOUT) - data = '' + output = '' while True: - data += conn.recv(32) - lines = string.split(data, '\n') + data = conn.recv(32) + if len(data) == 0: + reason = 'connection aborted' + break + log.info('received %s', data) + output += data + lines = string.split(output, '\n') if len(lines) > 1: return Terminal(lines[0], conn) + except (OSError, socket.timeout): + reason = 'timeout' - except (OSError, socket.timeout): - raise Exception('Failed to create a new terminal') + raise Exception('Failed to create a new terminal: %s' % reason)
a27a525650571b6f3756edf7f0fdf82d724f22d3
performance/web.py
performance/web.py
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) started = time() response = getattr(requests, self.type)( url=self.url, data=data ) finished = time() return finished - started except AttributeError: raise RequestTypeError(type=self.type) class RequestData: def __init__(self, data=None): self.data = data def for_type(self, type=Request.GET): if type is Request.GET: return data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) started = time() response = getattr(requests, self.type)( url=self.url, data=data ) finished = time() return finished - started except AttributeError: raise RequestTypeError(type=self.type) class RequestData: def __init__(self, data=None): self.data = data def get_converted(self, type=Request.GET): if type is Request.GET: return self.data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type
Update function name and return value
Update function name and return value
Python
mit
BakeCode/performance-testing,BakeCode/performance-testing
--- +++ @@ -38,9 +38,9 @@ def __init__(self, data=None): self.data = data - def for_type(self, type=Request.GET): + def get_converted(self, type=Request.GET): if type is Request.GET: - return data + return self.data class RequestTypeError(Exception):
a3dd19f7825bcbc65c666dc5e45af1084c061a12
{{cookiecutter.extension_name}}/{{cookiecutter.extension_name}}/__init__.py
{{cookiecutter.extension_name}}/{{cookiecutter.extension_name}}/__init__.py
from IPython.display import display import json # Running `npm run build` will create static resources in the static # directory of this Python package (and create that directory if necessary). def _jupyter_labextension_paths(): return [{ 'name': '{{cookiecutter.extension_name}}', 'src': 'static', }] def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'static', 'dest': '{{cookiecutter.extension_name}}', 'require': '{{cookiecutter.extension_name}}/extension' }] # A display function that can be used within a notebook. E.g.: # from {{cookiecutter.extension_name}} import {{cookiecutter.mime_short_name}} # {{cookiecutter.mime_short_name}}(data) def {{cookiecutter.mime_short_name}}(data): bundle = { '{{cookiecutter.mime_type}}': data, # 'application/json': data, 'text/plain': json.dumps(data, indent=4) } display(bundle, raw=True)
from IPython.display import display, JSON import json # Running `npm run build` will create static resources in the static # directory of this Python package (and create that directory if necessary). def _jupyter_labextension_paths(): return [{ 'name': '{{cookiecutter.extension_name}}', 'src': 'static', }] def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'static', 'dest': '{{cookiecutter.extension_name}}', 'require': '{{cookiecutter.extension_name}}/extension' }] # A display class that can be used within a notebook. E.g.: # from {{cookiecutter.extension_name}} import {{cookiecutter.mime_short_name}} # {{cookiecutter.mime_short_name}}(data) class {{cookiecutter.mime_short_name}}(JSON): @property def data(self): return self._data @data.setter def data(self, data): if isinstance(data, str): data = json.loads(data) self._data = data def _ipython_display_(self): bundle = { '{{cookiecutter.mime_type}}': self.data, 'text/plain': '<{{cookiecutter.extension_name}}.{{cookiecutter.mime_short_name}} object>' } display(bundle, raw=True)
Use sub-class of IPython.display.JSON vs. display function
Use sub-class of IPython.display.JSON vs. display function
Python
cc0-1.0
gnestor/mimerender-cookiecutter,jupyterlab/mimerender-cookiecutter,jupyterlab/mimerender-cookiecutter,gnestor/mimerender-cookiecutter
--- +++ @@ -1,4 +1,4 @@ -from IPython.display import display +from IPython.display import display, JSON import json @@ -21,14 +21,25 @@ }] -# A display function that can be used within a notebook. E.g.: +# A display class that can be used within a notebook. E.g.: # from {{cookiecutter.extension_name}} import {{cookiecutter.mime_short_name}} # {{cookiecutter.mime_short_name}}(data) + +class {{cookiecutter.mime_short_name}}(JSON): -def {{cookiecutter.mime_short_name}}(data): - bundle = { - '{{cookiecutter.mime_type}}': data, - # 'application/json': data, - 'text/plain': json.dumps(data, indent=4) - } - display(bundle, raw=True) + @property + def data(self): + return self._data + + @data.setter + def data(self, data): + if isinstance(data, str): + data = json.loads(data) + self._data = data + + def _ipython_display_(self): + bundle = { + '{{cookiecutter.mime_type}}': self.data, + 'text/plain': '<{{cookiecutter.extension_name}}.{{cookiecutter.mime_short_name}} object>' + } + display(bundle, raw=True)
9d6975b2a07315d7fe907ed332300409d226085c
flycam.py
flycam.py
import capture from picamera import PiCamera import time def image_cap_loop(camera, status=None): """Set image parameters, capture image, set wait time, repeat""" resolution = (854, 480) camera.rotation = 90 latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) day = 100000 # image size when light is good if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) # status = capture.shutdown(camera) image_cap_loop(camera, status) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main()
import capture from picamera import PiCamera import time def image_cap_loop(camera, status=None): """Set image parameters, capture image, set wait time, repeat""" resolution = (854, 480) camera.rotation = 90 latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) day = 150000 # image size when light is good if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) # status = capture.shutdown(camera) image_cap_loop(camera, status) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main()
Adjust image size to 150k.
Adjust image size to 150k.
Python
mit
gnfrazier/YardCam
--- +++ @@ -12,7 +12,7 @@ status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) - day = 100000 # image size when light is good + day = 150000 # image size when light is good if size > day: wait = 60 else: