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
e97a1ed2015db2eb2d5fe6abe15af6d9020c16d9
mbuild/tests/test_box.py
mbuild/tests/test_box.py
import pytest import numpy as np import mbuild as mb from mbuild.tests.base_test import BaseTest class TestBox(BaseTest): def test_init_lengths(self): box = mb.Box(lengths=np.ones(3)) assert np.array_equal(box.lengths, np.ones(3)) assert np.array_equal(box.mins, np.zeros(3)) assert np.array_equal(box.maxs, np.ones(3)) def test_init_bounds(self): box = mb.Box(mins=np.zeros(3), maxs=np.ones(3)) assert np.array_equal(box.lengths, np.ones(3)) assert np.array_equal(box.mins, np.zeros(3)) assert np.array_equal(box.maxs, np.ones(3)) def test_scale(self): box = mb.Box(lengths=np.ones(3)) scaling_factors = np.array([3, 4, 5]) box.scale(scaling_factors) assert np.array_equal(box.lengths, scaling_factors) assert np.array_equal(box.mins, (np.ones(3) / 2) - (scaling_factors / 2)) assert np.array_equal(box.maxs, (scaling_factors / 2) + (np.ones(3) / 2)) def test_center(self): box = mb.Box(lengths=np.ones(3)) box.center() assert np.array_equal(box.lengths, np.ones(3)) assert np.array_equal(box.mins, np.ones(3) * -0.5) assert np.array_equal(box.maxs, np.ones(3) * 0.5)
import pytest import numpy as np import mbuild as mb from mbuild.tests.base_test import BaseTest class TestBox(BaseTest): def test_init_lengths(self): box = mb.Box(lengths=np.ones(3)) assert np.array_equal(box.lengths, np.ones(3)) assert np.array_equal(box.mins, np.zeros(3)) assert np.array_equal(box.maxs, np.ones(3)) def test_init_bounds(self): box = mb.Box(mins=np.zeros(3), maxs=np.ones(3)) assert np.array_equal(box.lengths, np.ones(3)) assert np.array_equal(box.mins, np.zeros(3)) assert np.array_equal(box.maxs, np.ones(3))
Remove box tests for non-existant functionality
Remove box tests for non-existant functionality
Python
mit
ctk3b/mbuild,iModels/mbuild,iModels/mbuild,ctk3b/mbuild,tcmoore3/mbuild,tcmoore3/mbuild,summeraz/mbuild,summeraz/mbuild
--- +++ @@ -17,18 +17,3 @@ assert np.array_equal(box.lengths, np.ones(3)) assert np.array_equal(box.mins, np.zeros(3)) assert np.array_equal(box.maxs, np.ones(3)) - - def test_scale(self): - box = mb.Box(lengths=np.ones(3)) - scaling_factors = np.array([3, 4, 5]) - box.scale(scaling_factors) - assert np.array_equal(box.lengths, scaling_factors) - assert np.array_equal(box.mins, (np.ones(3) / 2) - (scaling_factors / 2)) - assert np.array_equal(box.maxs, (scaling_factors / 2) + (np.ones(3) / 2)) - - def test_center(self): - box = mb.Box(lengths=np.ones(3)) - box.center() - assert np.array_equal(box.lengths, np.ones(3)) - assert np.array_equal(box.mins, np.ones(3) * -0.5) - assert np.array_equal(box.maxs, np.ones(3) * 0.5)
c63a4b469fae66668214da3b963c03cead99d16d
real_estate_agency/real_estate_agency/views.py
real_estate_agency/real_estate_agency/views.py
from django.shortcuts import render, render_to_response from django.template import RequestContext from new_buildings.models import Builder, ResidentalComplex, NewApartment from new_buildings.forms import SearchForm from feedback.models import Feedback def corporation_benefit_plan(request): return render(request, 'corporation_benefit_plan.html') def index(request): # Only 4 requests to DB feedbacks = Feedback.objects.all()[:4].prefetch_related( 'bought').prefetch_related( 'bought__type_of_complex').prefetch_related('social_media_links') context = { 'feedbacks': feedbacks, 'form': SearchForm, } return render(request, 'index.html', context, ) def privacy_policy(request): return render(request, 'privacy_policy.html') def thanks(request): return render(request, 'thanks.html')
from django.shortcuts import render, render_to_response from django.template import RequestContext from new_buildings.models import Builder, ResidentalComplex, NewApartment from new_buildings.forms import SearchForm from feedback.models import Feedback def corporation_benefit_plan(request): return render(request, 'corporation_benefit_plan.html') def index(request): # Only 4 requests to DB feedbacks = Feedback.objects.all()[:4].prefetch_related( 'bought').prefetch_related( 'bought__type_of_complex').prefetch_related('social_media_links') residental_complexes = ResidentalComplex.objects.filter( is_popular=True) context = { 'feedbacks': feedbacks, 'form': SearchForm, 'residental_complexes': residental_complexes, } return render(request, 'index.html', context, ) def privacy_policy(request): return render(request, 'privacy_policy.html') def thanks(request): return render(request, 'thanks.html')
Add pupular RC objects to index view.
Add pupular RC objects to index view. Earlier they was at context processor.
Python
mit
Dybov/real_estate_agency,Dybov/real_estate_agency,Dybov/real_estate_agency
--- +++ @@ -15,9 +15,12 @@ feedbacks = Feedback.objects.all()[:4].prefetch_related( 'bought').prefetch_related( 'bought__type_of_complex').prefetch_related('social_media_links') + residental_complexes = ResidentalComplex.objects.filter( + is_popular=True) context = { 'feedbacks': feedbacks, 'form': SearchForm, + 'residental_complexes': residental_complexes, } return render(request, 'index.html',
84341e0d5f0f1b902c2a334f40cddb29e10a1f16
mozillians/users/cron.py
mozillians/users/cron.py
from django.conf import settings import cronjobs from celery.task.sets import TaskSet from elasticutils.contrib.django import get_es from mozillians.users.tasks import index_objects from mozillians.users.models import UserProfile, UserProfileMappingType @cronjobs.register def index_all_profiles(): # Get an es object, delete index and re-create it es = get_es(timeout=settings.ES_INDEXING_TIMEOUT) mappings = {'mappings': {UserProfileMappingType.get_mapping_type_name(): UserProfileMappingType.get_mapping()}} def _recreate_index(index): es.indices.delete(index=index, ignore=[400, 404]) es.indices.create(index, body=mappings) _recreate_index(settings.ES_INDEXES['default']) _recreate_index(settings.ES_INDEXES['public']) # mozillians index ids = UserProfile.objects.complete().values_list('id', flat=True) ts = [index_objects.subtask(kwargs={'mapping_type': UserProfileMappingType, 'ids': ids, 'chunk_size': 150, 'public_index': False})] # public index ts += [index_objects.subtask(kwargs={'mapping_type': UserProfileMappingType, 'ids': ids, 'chunk_size': 150, 'public_index': True})] TaskSet(ts).apply_async()
from django.conf import settings import cronjobs from celery.task.sets import TaskSet from celeryutils import chunked from elasticutils.contrib.django import get_es from mozillians.users.tasks import index_objects from mozillians.users.models import UserProfile, UserProfileMappingType @cronjobs.register def index_all_profiles(): # Get an es object, delete index and re-create it es = get_es(timeout=settings.ES_INDEXING_TIMEOUT) mappings = {'mappings': {UserProfileMappingType.get_mapping_type_name(): UserProfileMappingType.get_mapping()}} def _recreate_index(index): es.indices.delete(index=index, ignore=[400, 404]) es.indices.create(index, body=mappings) _recreate_index(settings.ES_INDEXES['default']) _recreate_index(settings.ES_INDEXES['public']) # mozillians index ids = UserProfile.objects.complete().values_list('id', flat=True) ts = [index_objects.subtask(args=[UserProfileMappingType, chunk, 150, False]) for chunk in chunked(sorted(list(ids)), 150)] # public index ts += [index_objects.subtask(args=[UserProfileMappingType, chunk, 150, True]) for chunk in chunked(sorted(list(ids)), 150)] TaskSet(ts).apply_async()
Index profiles in chunks and not altogether.
Index profiles in chunks and not altogether.
Python
bsd-3-clause
johngian/mozillians,akatsoulas/mozillians,akarki15/mozillians,johngian/mozillians,hoosteeno/mozillians,mozilla/mozillians,chirilo/mozillians,hoosteeno/mozillians,safwanrahman/mozillians,fxa90id/mozillians,fxa90id/mozillians,fxa90id/mozillians,fxa90id/mozillians,johngian/mozillians,akatsoulas/mozillians,anistark/mozillians,hoosteeno/mozillians,mozilla/mozillians,chirilo/mozillians,justinpotts/mozillians,akatsoulas/mozillians,brian-yang/mozillians,ChristineLaMuse/mozillians,ChristineLaMuse/mozillians,akarki15/mozillians,akarki15/mozillians,akatsoulas/mozillians,brian-yang/mozillians,anistark/mozillians,anistark/mozillians,akarki15/mozillians,chirilo/mozillians,justinpotts/mozillians,justinpotts/mozillians,justinpotts/mozillians,johngian/mozillians,brian-yang/mozillians,mozilla/mozillians,safwanrahman/mozillians,chirilo/mozillians,ChristineLaMuse/mozillians,anistark/mozillians,hoosteeno/mozillians,safwanrahman/mozillians,brian-yang/mozillians,mozilla/mozillians,safwanrahman/mozillians
--- +++ @@ -3,6 +3,7 @@ import cronjobs from celery.task.sets import TaskSet +from celeryutils import chunked from elasticutils.contrib.django import get_es from mozillians.users.tasks import index_objects @@ -26,15 +27,11 @@ # mozillians index ids = UserProfile.objects.complete().values_list('id', flat=True) - ts = [index_objects.subtask(kwargs={'mapping_type': UserProfileMappingType, - 'ids': ids, - 'chunk_size': 150, - 'public_index': False})] + ts = [index_objects.subtask(args=[UserProfileMappingType, chunk, 150, False]) + for chunk in chunked(sorted(list(ids)), 150)] # public index - ts += [index_objects.subtask(kwargs={'mapping_type': UserProfileMappingType, - 'ids': ids, - 'chunk_size': 150, - 'public_index': True})] + ts += [index_objects.subtask(args=[UserProfileMappingType, chunk, 150, True]) + for chunk in chunked(sorted(list(ids)), 150)] TaskSet(ts).apply_async()
657f72c2aae5bd83efff3520fa642d66ad172822
tests/test_commands.py
tests/test_commands.py
import django from django.core.management import call_command from django.test import TestCase from bananas.management.commands import show_urls class CommandTests(TestCase): def test_show_urls(self): urls = show_urls.collect_urls() if django.VERSION < (1, 9): n_urls = 23 + 8 elif django.VERSION < (2, 0): n_urls = 25 + 8 else: n_urls = 27 + 8 self.assertEqual(len(urls), n_urls) class FakeSys: class stdout: lines = [] @classmethod def write(cls, line): cls.lines.append(line) show_urls.sys = FakeSys show_urls.show_urls() self.assertEqual(len(FakeSys.stdout.lines), n_urls) call_command('show_urls')
import django from django.core.management import call_command from django.test import TestCase from bananas.management.commands import show_urls class CommandTests(TestCase): def test_show_urls(self): urls = show_urls.collect_urls() admin_api_url_count = 0 if django.VERSION >= (1, 10): admin_api_url_count = 8 if django.VERSION < (1, 9): n_urls = 23 + admin_api_url_count elif django.VERSION < (2, 0): n_urls = 25 + admin_api_url_count else: n_urls = 27 + admin_api_url_count self.assertEqual(len(urls), n_urls) class FakeSys: class stdout: lines = [] @classmethod def write(cls, line): cls.lines.append(line) show_urls.sys = FakeSys show_urls.show_urls() self.assertEqual(len(FakeSys.stdout.lines), n_urls) call_command('show_urls')
Fix test_show_urls without admin api urls
Fix test_show_urls without admin api urls
Python
mit
5monkeys/django-bananas,5monkeys/django-bananas,5monkeys/django-bananas
--- +++ @@ -9,12 +9,16 @@ def test_show_urls(self): urls = show_urls.collect_urls() + admin_api_url_count = 0 + if django.VERSION >= (1, 10): + admin_api_url_count = 8 + if django.VERSION < (1, 9): - n_urls = 23 + 8 + n_urls = 23 + admin_api_url_count elif django.VERSION < (2, 0): - n_urls = 25 + 8 + n_urls = 25 + admin_api_url_count else: - n_urls = 27 + 8 + n_urls = 27 + admin_api_url_count self.assertEqual(len(urls), n_urls)
9b18e4833a3550d424aa18fddbf5373d142ce3f1
dddp/apps.py
dddp/apps.py
"""Django DDP app config.""" from __future__ import print_function from django.apps import AppConfig from django.conf import settings, ImproperlyConfigured from django.db import DatabaseError from django.db.models import signals from dddp import autodiscover from dddp.models import Connection class DjangoDDPConfig(AppConfig): """Django app config for django-ddp.""" api = None name = 'dddp' verbose_name = 'Django DDP' _in_migration = False def ready(self): """Initialisation for django-ddp (setup lookups and signal handlers).""" if not settings.DATABASES: raise ImproperlyConfigured('No databases configured.') for (alias, conf) in settings.DATABASES.items(): if conf['ENGINE'] != 'django.db.backends.postgresql_psycopg2': raise ImproperlyConfigured( '%r uses %r: django-ddp only works with PostgreSQL.' % ( alias, conf['backend'], ) ) self.api = autodiscover() self.api.ready()
"""Django DDP app config.""" from __future__ import print_function from django.apps import AppConfig from django.conf import settings, ImproperlyConfigured from dddp import autodiscover class DjangoDDPConfig(AppConfig): """Django app config for django-ddp.""" api = None name = 'dddp' verbose_name = 'Django DDP' _in_migration = False def ready(self): """Initialisation for django-ddp (setup lookups and signal handlers).""" if not settings.DATABASES: raise ImproperlyConfigured('No databases configured.') for (alias, conf) in settings.DATABASES.items(): if conf['ENGINE'] != 'django.db.backends.postgresql_psycopg2': raise ImproperlyConfigured( '%r uses %r: django-ddp only works with PostgreSQL.' % ( alias, conf['backend'], ) ) self.api = autodiscover() self.api.ready()
Remove unused imports from AppConfig module.
Remove unused imports from AppConfig module.
Python
mit
commoncode/django-ddp,commoncode/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,django-ddp/django-ddp,django-ddp/django-ddp
--- +++ @@ -4,11 +4,8 @@ from django.apps import AppConfig from django.conf import settings, ImproperlyConfigured -from django.db import DatabaseError -from django.db.models import signals from dddp import autodiscover -from dddp.models import Connection class DjangoDDPConfig(AppConfig):
b54dc115710416b92161fa0f69b4928cdef07997
oauth2_provider/forms.py
oauth2_provider/forms.py
from django import forms from .models import get_application_model class AllowForm(forms.Form): allow = forms.BooleanField(required=False) redirect_uri = forms.CharField(widget=forms.HiddenInput()) scope = forms.CharField(required=False, widget=forms.HiddenInput()) client_id = forms.CharField(widget=forms.HiddenInput()) state = forms.CharField(required=False, widget=forms.HiddenInput()) response_type = forms.CharField(widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): data = kwargs.get('data') # backwards compatible support for plural `scopes` query parameter if data and 'scopes' in data: data['scope'] = data['scopes'] return super(AllowForm, self).__init__(*args, **kwargs) class RegistrationForm(forms.ModelForm): """ TODO: add docstring """ class Meta: model = get_application_model() fields = ('name', 'client_id', 'client_secret', 'client_type', 'authorization_grant_type', 'redirect_uris')
from django import forms from .models import get_application_model class AllowForm(forms.Form): allow = forms.BooleanField(required=False) redirect_uri = forms.CharField(widget=forms.HiddenInput()) scope = forms.CharField(required=False, widget=forms.HiddenInput()) client_id = forms.CharField(widget=forms.HiddenInput()) state = forms.CharField(required=False, widget=forms.HiddenInput()) response_type = forms.CharField(widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): data = kwargs.get('data') # backwards compatible support for plural `scopes` query parameter if data and 'scopes' in data: data['scope'] = data['scopes'] return super(AllowForm, self).__init__(*args, **kwargs) class RegistrationForm(forms.ModelForm): """ TODO: add docstring """ class Meta: model = get_application_model() fields = ('client_id', 'client_secret', 'client_type', 'authorization_grant_type', 'redirect_uris')
Remove name field from form
Remove name field from form
Python
bsd-2-clause
vmalavolta/django-oauth-toolkit,vmalavolta/django-oauth-toolkit
--- +++ @@ -25,4 +25,4 @@ """ class Meta: model = get_application_model() - fields = ('name', 'client_id', 'client_secret', 'client_type', 'authorization_grant_type', 'redirect_uris') + fields = ('client_id', 'client_secret', 'client_type', 'authorization_grant_type', 'redirect_uris')
8ae9da1cf93d45cadcfd3c3857542ce9cabdff64
filer/__init__.py
filer/__init__.py
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.4' # pragma: nocover
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.5' # pragma: nocover
Bump version as instructed by bamboo
Bump version as instructed by bamboo
Python
bsd-3-clause
pbs/django-filer,pbs/django-filer,pbs/django-filer,pbs/django-filer,pbs/django-filer
--- +++ @@ -1,3 +1,3 @@ #-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 -__version__ = '0.9pbs.4' # pragma: nocover +__version__ = '0.9pbs.5' # pragma: nocover
ac5a339f73cb80b54b0298a02bce41c27c25b9ae
authentication/forms.py
authentication/forms.py
from django import forms as newform from django.forms import ModelForm from people.models import Beneficiary, Donor from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ # from django.core.urlresolvers import reverse # from crispy_forms.helper import FormHelper # from crispy_forms.layout import Submit, Layout, Fieldset class LoginForm(newform.Form): username = newform.CharField() password = newform.CharField(widget=newform.PasswordInput) # def __init__(self, *args, **kwargs): # super(LoginForm, self).__init__(*args, **kwargs) # self.helper = FormHelper() # self.helper.form_id = 'login-form' # self.helper.form_class = 'form-horizontal' # self.helper.form_method = 'post' # self.helper.form_action = reverse('accounts:login') # self.helper.add_input(Submit('submit', 'Login', css_class='btn btn- # primary'))
from django import forms as newform class LoginForm(newform.Form): username = newform.CharField() password = newform.CharField(widget=newform.PasswordInput)
Remove unused and commented parts
Remove unused and commented parts
Python
bsd-3-clause
agiliq/fundraiser,agiliq/fundraiser,febinstephen/django-fundrasiser-app,agiliq/fundraiser,febinstephen/django-fundrasiser-app,febinstephen/django-fundrasiser-app
--- +++ @@ -1,24 +1,5 @@ from django import forms as newform -from django.forms import ModelForm -from people.models import Beneficiary, Donor -from django.contrib.auth.models import User -from django.utils.translation import ugettext_lazy as _ - -# from django.core.urlresolvers import reverse -# from crispy_forms.helper import FormHelper -# from crispy_forms.layout import Submit, Layout, Fieldset - class LoginForm(newform.Form): username = newform.CharField() password = newform.CharField(widget=newform.PasswordInput) - - # def __init__(self, *args, **kwargs): - # super(LoginForm, self).__init__(*args, **kwargs) - # self.helper = FormHelper() - # self.helper.form_id = 'login-form' - # self.helper.form_class = 'form-horizontal' - # self.helper.form_method = 'post' - # self.helper.form_action = reverse('accounts:login') - # self.helper.add_input(Submit('submit', 'Login', css_class='btn btn- - # primary'))
25273e699b2b901eec53656dbcdc437e4a4cdc11
backend/breach/tests.py
backend/breach/tests.py
from django.test import TestCase from breach.models import SampleSet, Victim, Target, Round from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='http://di.uoa.gr/', prefix='test', alphabet='0123456789' ) victim = Victim.objects.create( target=target, sourceip='192.168.10.140', snifferendpoint='http://localhost/' ) round = Round.objects.create( victim=victim, amount=1, knownsecret='testsecret', knownalphabet='01' ) self.samplesets = [ SampleSet.objects.create( round=round, candidatealphabet='0', data='bigbigbigbigbigbig' ), SampleSet.objects.create( round=round, candidatealphabet='1', data='small' ) ] def test_decide(self): state, confidence = decide_next_world_state(self.samplesets) self.assertEqual(state["knownsecret"], "testsecret1")
from django.test import TestCase from breach.models import SampleSet, Victim, Target, Round from breach.analyzer import decide_next_world_state class RuptureTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='http://di.uoa.gr/', prefix='test', alphabet='0123456789' ) victim = Victim.objects.create( target=target, sourceip='192.168.10.140', snifferendpoint='http://localhost/' ) round = Round.objects.create( victim=victim, amount=1, knownsecret='testsecret', knownalphabet='01' ) self.samplesets = [ SampleSet.objects.create( round=round, candidatealphabet='0', data='bigbigbigbigbigbig' ), SampleSet.objects.create( round=round, candidatealphabet='1', data='small' ) ] class AnalyzerTestCase(RuptureTestCase): def test_decide(self): state, confidence = decide_next_world_state(self.samplesets) self.assertEqual(state["knownsecret"], "testsecret1")
Create base test case class for rupture
Create base test case class for rupture
Python
mit
dimkarakostas/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,esarafianou/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,dionyziz/rupture,dimkarakostas/rupture
--- +++ @@ -3,7 +3,7 @@ from breach.analyzer import decide_next_world_state -class AnalyzerTestCase(TestCase): +class RuptureTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='http://di.uoa.gr/', @@ -34,6 +34,7 @@ ) ] +class AnalyzerTestCase(RuptureTestCase): def test_decide(self): state, confidence = decide_next_world_state(self.samplesets)
a28a29af31b1ea604ed97544b2d84a39c9ba3e7b
automation/src/rabird/automation/selenium/webelement.py
automation/src/rabird/automation/selenium/webelement.py
#--IMPORT_ALL_FROM_FUTURE--# ''' @date 2014-11-16 @author Hong-she Liang <starofrainnight@gmail.com> ''' # Import the global selenium unit, not our selenium . global_selenium = __import__('selenium') import types import time def set_attribute(self, name, value): value = value.replace(r"'", r"\'") # Replace all r"'" with r"\'" value = value.replace("\n", r"\n") value = value.replace("\r", r"\r") value = value.replace("\t", r"\t") script = "arguments[0].setAttribute('%s', '%s')" % (name, value) self._parent.execute_script(script, self) def force_focus(self): global_selenium.webdriver.ActionChains(self._parent).move_to_element(self).perform() def force_click(self): self._parent.execute_script("arguments[0].click();", self);
#--IMPORT_ALL_FROM_FUTURE--# ''' @date 2014-11-16 @author Hong-she Liang <starofrainnight@gmail.com> ''' # Import the global selenium unit, not our selenium . global_selenium = __import__('selenium') import types import time def set_attribute(self, name, value): value = value.replace(r"'", r"\'") # Replace all r"'" with r"\'" value = value.replace("\n", r"\n") value = value.replace("\r", r"\r") value = value.replace("\t", r"\t") script = "arguments[0].setAttribute('%s', '%s');" % (name, value) self._parent.execute_script(script, self) def force_focus(self): self._parent.execute_script("arguments[0].focus();", self); def force_click(self): self._parent.execute_script("arguments[0].click();", self);
Use javascript to force focus on an element, because the action chains seems take no effect!
Use javascript to force focus on an element, because the action chains seems take no effect!
Python
apache-2.0
starofrainnight/rabird.core,starofrainnight/rabird.auto
--- +++ @@ -16,11 +16,11 @@ value = value.replace("\n", r"\n") value = value.replace("\r", r"\r") value = value.replace("\t", r"\t") - script = "arguments[0].setAttribute('%s', '%s')" % (name, value) + script = "arguments[0].setAttribute('%s', '%s');" % (name, value) self._parent.execute_script(script, self) def force_focus(self): - global_selenium.webdriver.ActionChains(self._parent).move_to_element(self).perform() + self._parent.execute_script("arguments[0].focus();", self); def force_click(self): self._parent.execute_script("arguments[0].click();", self);
730b5acb9c715a0b7e2f70d4ee3d26cd2a8a03ca
wordcloud/views.py
wordcloud/views.py
import json import os from django.conf import settings from django.http import HttpResponse from django.views.decorators.cache import cache_page from .wordcloud import popular_words @cache_page(60*60*4) def wordcloud(request, max_entries=30): """ Return tag cloud JSON results""" cache_path = settings.WORDCLOUD_CACHE_PATH if os.path.exists(cache_path): response = HttpResponse() response['Content-Type'] = 'application/json' response['X-Sendfile'] = cache_path.encode('utf-8') return response content = json.dumps(popular_words(max_entries=max_entries)) return HttpResponse( content, mimetype='application/json', )
import json import os from django.conf import settings from django.http import HttpResponse from django.views.decorators.cache import cache_page from .wordcloud import popular_words @cache_page(60*60*4) def wordcloud(request, max_entries=30): """ Return tag cloud JSON results""" cache_path = settings.WORDCLOUD_CACHE_PATH if os.path.exists(cache_path): response = HttpResponse() response['Content-Type'] = 'application/json' response['X-Sendfile'] = cache_path.encode('utf-8') return response content = json.dumps(popular_words(max_entries=max_entries)) return HttpResponse( content, content_type='application/json', )
Fix a deprecation warning; content_type replaces mimetype
Fix a deprecation warning; content_type replaces mimetype
Python
agpl-3.0
geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola
--- +++ @@ -22,5 +22,5 @@ return HttpResponse( content, - mimetype='application/json', - ) + content_type='application/json', + )
7e6af723e15a785b403010de4b44b49fce924e91
social_auth/backends/pipeline/misc.py
social_auth/backends/pipeline/misc.py
from social_auth.backends import PIPELINE from social_auth.utils import setting PIPELINE_ENTRY = 'social_auth.backends.pipeline.misc.save_status_to_session' def save_status_to_session(request, auth, *args, **kwargs): """Saves current social-auth status to session.""" next_entry = setting('SOCIAL_AUTH_PIPELINE_RESUME_ENTRY') try: if next_entry: idx = PIPELINE.index(next_entry) else: idx = PIPELINE.index(PIPELINE_ENTRY) + 1 except ValueError: idx = None data = auth.to_session_dict(idx, *args, **kwargs) name = setting('SOCIAL_AUTH_PARTIAL_PIPELINE_KEY', 'partial_pipeline') request.session[name] = data request.session.modified = True
from social_auth.backends import PIPELINE from social_auth.utils import setting PIPELINE_ENTRY = 'social_auth.backends.pipeline.misc.save_status_to_session' def tuple_index(t, e): for (i, te) in enumerate(t): if te == e: return i return None def save_status_to_session(request, auth, *args, **kwargs): """Saves current social-auth status to session.""" next_entry = setting('SOCIAL_AUTH_PIPELINE_RESUME_ENTRY') if next_entry: idx = tuple_index(PIPELINE, next_entry) else: idx = tuple_index(PIPELINE, PIPELINE_ENTRY) if idx: idx += 1 data = auth.to_session_dict(idx, *args, **kwargs) name = setting('SOCIAL_AUTH_PARTIAL_PIPELINE_KEY', 'partial_pipeline') request.session[name] = data request.session.modified = True
Add own tuple_index function to stay compatible with python 2.5
Add own tuple_index function to stay compatible with python 2.5
Python
bsd-3-clause
WW-Digital/django-social-auth,duoduo369/django-social-auth,limdauto/django-social-auth,vuchau/django-social-auth,gustavoam/django-social-auth,1st/django-social-auth,vxvinh1511/django-social-auth,VishvajitP/django-social-auth,MjAbuz/django-social-auth,sk7/django-social-auth,getsentry/django-social-auth,omab/django-social-auth,omab/django-social-auth,michael-borisov/django-social-auth,mayankcu/Django-social,vxvinh1511/django-social-auth,caktus/django-social-auth,beswarm/django-social-auth,krvss/django-social-auth,MjAbuz/django-social-auth,antoviaque/django-social-auth-norel,qas612820704/django-social-auth,lovehhf/django-social-auth,adw0rd/django-social-auth,michael-borisov/django-social-auth,gustavoam/django-social-auth,qas612820704/django-social-auth,VishvajitP/django-social-auth,vuchau/django-social-auth,dongguangming/django-social-auth,limdauto/django-social-auth,caktus/django-social-auth,dongguangming/django-social-auth,czpython/django-social-auth,lovehhf/django-social-auth,beswarm/django-social-auth
--- +++ @@ -4,18 +4,22 @@ PIPELINE_ENTRY = 'social_auth.backends.pipeline.misc.save_status_to_session' +def tuple_index(t, e): + for (i, te) in enumerate(t): + if te == e: + return i + return None def save_status_to_session(request, auth, *args, **kwargs): """Saves current social-auth status to session.""" next_entry = setting('SOCIAL_AUTH_PIPELINE_RESUME_ENTRY') - try: - if next_entry: - idx = PIPELINE.index(next_entry) - else: - idx = PIPELINE.index(PIPELINE_ENTRY) + 1 - except ValueError: - idx = None + if next_entry: + idx = tuple_index(PIPELINE, next_entry) + else: + idx = tuple_index(PIPELINE, PIPELINE_ENTRY) + if idx: + idx += 1 data = auth.to_session_dict(idx, *args, **kwargs)
1f83364822a1c80dc26f58d3908006a7f643e7c9
json_protocol.py
json_protocol.py
# -*- coding: iso-8859-1 -*- from twisted.protocols.basic import Int32StringReceiver import json import apps class JSONProtocol(Int32StringReceiver): app = apps.LoginApp def connectionMade(self): self.app = self.__class__.app(self) def connectionLost(self, reason): self.app.disconnect(reason) def stringReceived(self, string): try: expr = json.loads(string) except: print 'Bad message received: %s' % string error = {'type': 'parse error'} error['message'] = string self.send_json(error) return self.app.run(expr) def send_json(self, object): message = json.dumps(object) self.sendString(message)
# -*- coding: iso-8859-1 -*- from twisted.protocols.basic import Int32StringReceiver import json import apps class JSONProtocol(Int32StringReceiver): app = apps.LoginApp def connectionMade(self): self.app = self.__class__.app(self) def connectionLost(self, reason): self.app.disconnect(reason) def stringReceived(self, string): try: expr = json.loads(string) except: print 'Bad message received: %s' % string error = {'type': 'parse error'} error['args'] = {'message': string} self.send_json(error) return self.app.run(expr) def send_json(self, object): message = json.dumps(object) self.sendString(message)
Change parse errors to standard format.
Change parse errors to standard format.
Python
bsd-3-clause
siggame/server
--- +++ @@ -20,7 +20,7 @@ except: print 'Bad message received: %s' % string error = {'type': 'parse error'} - error['message'] = string + error['args'] = {'message': string} self.send_json(error) return self.app.run(expr)
877f7fe856c640ee7cafa41226622d18eee39257
update-database/update-latest-from-so.py
update-database/update-latest-from-so.py
import pymongo import stackexchange import time so = stackexchange.Site(stackexchange.StackOverflow, "WNe2LOp*hdsbD5U7kp0bhg((") so.be_inclusive() connection = pymongo.Connection() db = connection.stack_doc posts = db.posts up_to_date = False while not up_to_date: last_in_database = posts.find_one(sort=[("last_activity", pymongo.DESCENDING)])["last_activity"] last_in_database_as_unix = int(time.mktime(last_in_database.timetuple())) print "Fetching questions active after %s" % last_in_database_as_unix rq = so.recent_questions(from_date=last_in_database_as_unix) print rq[0]
import pymongo import stackexchange import time so = stackexchange.Site(stackexchange.StackOverflow) so.be_inclusive() connection = pymongo.Connection() db = connection.stack_doc posts = db.posts up_to_date = False while not up_to_date: last_in_database = posts.find_one(sort=[("last_activity", pymongo.DESCENDING)])["last_activity"] last_in_database_as_unix = int(time.mktime(last_in_database.timetuple())) print "Fetching questions active after %s" % last_in_database_as_unix rq = so.recent_questions(from_date=last_in_database_as_unix) for q in rq: print q time.sleep(0.01) # Do our own throttling as the built in throttling seems broken
Remove API key (it's for the wrong API version)
Remove API key (it's for the wrong API version)
Python
bsd-3-clause
alnorth/stackdoc,alnorth/stackdoc,alnorth/stackdoc
--- +++ @@ -2,7 +2,7 @@ import stackexchange import time -so = stackexchange.Site(stackexchange.StackOverflow, "WNe2LOp*hdsbD5U7kp0bhg((") +so = stackexchange.Site(stackexchange.StackOverflow) so.be_inclusive() @@ -17,4 +17,6 @@ last_in_database_as_unix = int(time.mktime(last_in_database.timetuple())) print "Fetching questions active after %s" % last_in_database_as_unix rq = so.recent_questions(from_date=last_in_database_as_unix) - print rq[0] + for q in rq: + print q + time.sleep(0.01) # Do our own throttling as the built in throttling seems broken
346d6e38e84a5addc5173a331dbc0cc6fa39e754
corehq/apps/domain/management/commands/fill_last_modified_date.py
corehq/apps/domain/management/commands/fill_last_modified_date.py
from django.core.management.base import BaseCommand from corehq.apps.domain.models import Domain from dimagi.utils.couch.database import iter_docs class Command(BaseCommand): def _get_domains_without_last_modified_date(self): docs = iter_docs(Domain.get_db(), [ domain['id'] for domain in Domain.view( "domain/domains", reduce=False, include_docs=False ) ]) return filter(lambda x: 'last_modified' not in x, docs) def handle(self, *args, **options): for domain_doc in self._get_domains_without_last_modified_date(): print "Updating domain {}".format(domain_doc['name']) domain = Domain.wrap(domain_doc) domain.save()
from django.core.management.base import BaseCommand from corehq.apps.domain.models import Domain from dimagi.utils.couch.database import iter_docs class Command(BaseCommand): def _get_domains_without_last_modified_date(self): docs = iter_docs(Domain.get_db(), [ domain['id'] for domain in Domain.view( "domain/domains", reduce=False, include_docs=False ) ]) return filter(lambda x: 'last_modified' not in x or not x['last_modified'], docs) def handle(self, *args, **options): for domain_doc in self._get_domains_without_last_modified_date(): print "Updating domain {}".format(domain_doc['name']) domain = Domain.wrap(domain_doc) domain.save()
Include domains which have last_modified equal to None
Include domains which have last_modified equal to None
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
--- +++ @@ -15,7 +15,7 @@ include_docs=False ) ]) - return filter(lambda x: 'last_modified' not in x, docs) + return filter(lambda x: 'last_modified' not in x or not x['last_modified'], docs) def handle(self, *args, **options): for domain_doc in self._get_domains_without_last_modified_date():
6f18d3a00e776cf972f814fbf6ce50ec4b7cf85e
eblog/managers.py
eblog/managers.py
""" Managers of ``blog`` application. """ from django.db import models class CategoryOnlineManager(models.Manager): """ Manager that manages online ``Category`` objects. """ def get_query_set(self): from blog.models import Entry entry_status = Entry.STATUS_ONLINE return super(CategoryOnlineManager, self).get_query_set().filter( entry__status=entry_status).distinct() class EntryOnlineManager(models.Manager): """ Manager that manages online ``Entry`` objects. """ def get_query_set(self): return super(EntryOnlineManager, self).get_query_set().filter( status=self.model.STATUS_ONLINE)
""" Managers of ``blog`` application. """ from django.db import models class CategoryOnlineManager(models.Manager): """ Manager that manages online ``Category`` objects. """ def get_queryset(self): from blog.models import Entry entry_status = Entry.STATUS_ONLINE return super(CategoryOnlineManager, self).get_queryset().filter( entry__status=entry_status).distinct() class EntryOnlineManager(models.Manager): """ Manager that manages online ``Entry`` objects. """ def get_queryset(self): return super(EntryOnlineManager, self).get_queryset().filter( status=self.model.STATUS_ONLINE)
Change the method get_query_set() to get_queryset() as required by django 1.7
Change the method get_query_set() to get_queryset() as required by django 1.7
Python
bsd-3-clause
pandamasta/django-eblog
--- +++ @@ -9,10 +9,10 @@ Manager that manages online ``Category`` objects. """ - def get_query_set(self): + def get_queryset(self): from blog.models import Entry entry_status = Entry.STATUS_ONLINE - return super(CategoryOnlineManager, self).get_query_set().filter( + return super(CategoryOnlineManager, self).get_queryset().filter( entry__status=entry_status).distinct() @@ -21,7 +21,7 @@ Manager that manages online ``Entry`` objects. """ - def get_query_set(self): - return super(EntryOnlineManager, self).get_query_set().filter( + def get_queryset(self): + return super(EntryOnlineManager, self).get_queryset().filter( status=self.model.STATUS_ONLINE)
0293170e0e8d309e4b2c37e3a07f64d4447b244f
pylearn2/costs/tests/test_lp_norm_cost.py
pylearn2/costs/tests/test_lp_norm_cost.py
""" Test LpNorm cost """ import numpy import theano from theano import tensor as T from nose.tools import raises def test_shared_variables(): ''' LpNorm should handle shared variables. ''' assert False def test_symbolic_expressions_of_shared_variables(): ''' LpNorm should handle symbolic expressions of shared variables. ''' assert False @raises(Exception) def test_symbolic_variables(): ''' LpNorm should not handle symbolic variables ''' assert True if __name__ == '__main__': test_shared_variables() test_symbolic_expressions_of_shared_variables() test_symbolic_variables()
""" Test LpNorm cost """ import os from nose.tools import raises from pylearn2.models.mlp import Linear from pylearn2.models.mlp import Softmax from pylearn2.models.mlp import MLP from pylearn2.costs.cost import LpNorm from pylearn2.datasets.cifar10 import CIFAR10 from pylearn2.training_algorithms.sgd import SGD from pylearn2.termination_criteria import EpochCounter from pylearn2.train import Train def test_shared_variables(): ''' LpNorm should handle shared variables. ''' model = MLP( layers=[Linear(dim=100, layer_name='linear', irange=1.0), Softmax(n_classes=10, layer_name='softmax', irange=1.0)], batch_size=100, nvis=3072 ) dataset = CIFAR10(which_set='train') cost = LpNorm(variables=model.get_params(), p=2) algorithm = SGD( learning_rate=0.01, cost=cost, batch_size=100, monitoring_dataset=dataset, termination_criterion=EpochCounter(1) ) trainer = Train( dataset=dataset, model=model, algorithm=algorithm ) trainer.main_loop() assert False def test_symbolic_expressions_of_shared_variables(): ''' LpNorm should handle symbolic expressions of shared variables. ''' assert False @raises(Exception) def test_symbolic_variables(): ''' LpNorm should not handle symbolic variables ''' assert True if __name__ == '__main__': test_shared_variables() test_symbolic_expressions_of_shared_variables() test_symbolic_variables()
Add more code to LpNorm unit tests
Add more code to LpNorm unit tests
Python
bsd-3-clause
caidongyun/pylearn2,mclaughlin6464/pylearn2,kose-y/pylearn2,chrish42/pylearn,sandeepkbhat/pylearn2,junbochen/pylearn2,fishcorn/pylearn2,w1kke/pylearn2,Refefer/pylearn2,hyqneuron/pylearn2-maxsom,chrish42/pylearn,daemonmaker/pylearn2,fulmicoton/pylearn2,hyqneuron/pylearn2-maxsom,fyffyt/pylearn2,TNick/pylearn2,hantek/pylearn2,mclaughlin6464/pylearn2,junbochen/pylearn2,jamessergeant/pylearn2,fyffyt/pylearn2,CIFASIS/pylearn2,fishcorn/pylearn2,skearnes/pylearn2,jeremyfix/pylearn2,daemonmaker/pylearn2,chrish42/pylearn,hantek/pylearn2,kose-y/pylearn2,fulmicoton/pylearn2,kastnerkyle/pylearn2,KennethPierce/pylearnk,lisa-lab/pylearn2,daemonmaker/pylearn2,fishcorn/pylearn2,KennethPierce/pylearnk,chrish42/pylearn,fyffyt/pylearn2,theoryno3/pylearn2,lunyang/pylearn2,bartvm/pylearn2,se4u/pylearn2,msingh172/pylearn2,pombredanne/pylearn2,cosmoharrigan/pylearn2,se4u/pylearn2,se4u/pylearn2,lancezlin/pylearn2,jeremyfix/pylearn2,ddboline/pylearn2,theoryno3/pylearn2,shiquanwang/pylearn2,junbochen/pylearn2,msingh172/pylearn2,JesseLivezey/plankton,TNick/pylearn2,skearnes/pylearn2,jeremyfix/pylearn2,JesseLivezey/plankton,fulmicoton/pylearn2,alexjc/pylearn2,shiquanwang/pylearn2,cosmoharrigan/pylearn2,jamessergeant/pylearn2,alexjc/pylearn2,nouiz/pylearn2,shiquanwang/pylearn2,TNick/pylearn2,matrogers/pylearn2,lisa-lab/pylearn2,lamblin/pylearn2,skearnes/pylearn2,jeremyfix/pylearn2,mclaughlin6464/pylearn2,fishcorn/pylearn2,pkainz/pylearn2,lisa-lab/pylearn2,abergeron/pylearn2,jamessergeant/pylearn2,aalmah/pylearn2,lancezlin/pylearn2,msingh172/pylearn2,JesseLivezey/pylearn2,cosmoharrigan/pylearn2,w1kke/pylearn2,sandeepkbhat/pylearn2,lamblin/pylearn2,goodfeli/pylearn2,Refefer/pylearn2,ashhher3/pylearn2,woozzu/pylearn2,woozzu/pylearn2,matrogers/pylearn2,CIFASIS/pylearn2,woozzu/pylearn2,lunyang/pylearn2,pombredanne/pylearn2,bartvm/pylearn2,JesseLivezey/plankton,pkainz/pylearn2,ddboline/pylearn2,aalmah/pylearn2,lunyang/pylearn2,aalmah/pylearn2,ddboline/pylearn2,hantek/pylearn2,KennethPierce/pylearnk,sandeepkbhat/pylearn2,skearnes/pylearn2,pombredanne/pylearn2,sandeepkbhat/pylearn2,matrogers/pylearn2,fulmicoton/pylearn2,JesseLivezey/pylearn2,msingh172/pylearn2,aalmah/pylearn2,JesseLivezey/pylearn2,CIFASIS/pylearn2,goodfeli/pylearn2,matrogers/pylearn2,kastnerkyle/pylearn2,nouiz/pylearn2,TNick/pylearn2,bartvm/pylearn2,shiquanwang/pylearn2,bartvm/pylearn2,pombredanne/pylearn2,woozzu/pylearn2,ashhher3/pylearn2,kastnerkyle/pylearn2,se4u/pylearn2,lamblin/pylearn2,alexjc/pylearn2,abergeron/pylearn2,KennethPierce/pylearnk,mkraemer67/pylearn2,ashhher3/pylearn2,caidongyun/pylearn2,JesseLivezey/plankton,mkraemer67/pylearn2,ddboline/pylearn2,nouiz/pylearn2,cosmoharrigan/pylearn2,fyffyt/pylearn2,lisa-lab/pylearn2,nouiz/pylearn2,w1kke/pylearn2,hyqneuron/pylearn2-maxsom,hyqneuron/pylearn2-maxsom,lamblin/pylearn2,caidongyun/pylearn2,hantek/pylearn2,caidongyun/pylearn2,Refefer/pylearn2,goodfeli/pylearn2,CIFASIS/pylearn2,mkraemer67/pylearn2,mkraemer67/pylearn2,kose-y/pylearn2,pkainz/pylearn2,w1kke/pylearn2,theoryno3/pylearn2,lancezlin/pylearn2,alexjc/pylearn2,junbochen/pylearn2,abergeron/pylearn2,jamessergeant/pylearn2,ashhher3/pylearn2,theoryno3/pylearn2,lancezlin/pylearn2,Refefer/pylearn2,kastnerkyle/pylearn2,JesseLivezey/pylearn2,pkainz/pylearn2,mclaughlin6464/pylearn2,goodfeli/pylearn2,abergeron/pylearn2,lunyang/pylearn2,kose-y/pylearn2,daemonmaker/pylearn2
--- +++ @@ -1,16 +1,48 @@ """ Test LpNorm cost """ -import numpy -import theano -from theano import tensor as T +import os from nose.tools import raises +from pylearn2.models.mlp import Linear +from pylearn2.models.mlp import Softmax +from pylearn2.models.mlp import MLP +from pylearn2.costs.cost import LpNorm +from pylearn2.datasets.cifar10 import CIFAR10 +from pylearn2.training_algorithms.sgd import SGD +from pylearn2.termination_criteria import EpochCounter +from pylearn2.train import Train def test_shared_variables(): ''' LpNorm should handle shared variables. ''' + model = MLP( + layers=[Linear(dim=100, layer_name='linear', irange=1.0), + Softmax(n_classes=10, layer_name='softmax', irange=1.0)], + batch_size=100, + nvis=3072 + ) + + dataset = CIFAR10(which_set='train') + + cost = LpNorm(variables=model.get_params(), p=2) + + algorithm = SGD( + learning_rate=0.01, + cost=cost, batch_size=100, + monitoring_dataset=dataset, + termination_criterion=EpochCounter(1) + ) + + trainer = Train( + dataset=dataset, + model=model, + algorithm=algorithm + ) + + trainer.main_loop() + assert False
4cc45954ba71af6b81c930a99f05e8a6cf8b48f6
update-database/stackdoc/questionimport.py
update-database/stackdoc/questionimport.py
def import_question(posts, namespaces, id, title, body, tags, last_activity_date, last_updated_date, score, answer_count, has_accepted_answer): namespaces_for_post = {} for name, n in namespaces.items(): namespace_tags = n.get_tags() if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)): ids = n.get_ids(title, body, tags) if len(ids) > 0: ids = map(lambda x: x.lower(), ids) namespaces_for_post[name] = ids if len(namespaces_for_post): post = posts.find_one({"question_id": int(id)}) previously_existed = False update = True if post: previously_existed = True # Only update title, score etc. if this is the latest data update = post["last_activity"] < last_activity_date else: post = { "question_id": int(id), "url": "http://stackoverflow.com/questions/%s" % id } post["namespaces"] = namespaces_for_post if update: post["title"] = title post["score"] = int(score) post["answers"] = int(answer_count) post["accepted_answer"] = has_accepted_answer post["last_activity"] = last_activity_date post["last_updated"] = last_updated_date if previously_existed: posts.update({"question_id": int(id)}, post) else: posts.insert(post) update_text = "Fully updated" if update else "Partially updated" print "%s %s question from %s (%s)" % (update_text if previously_existed else "Inserted", ", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
def import_question(posts, namespaces, id, title, body, tags, last_activity_date, last_updated_date, score, answer_count, has_accepted_answer): namespaces_for_post = {} for name, n in namespaces.items(): namespace_tags = n.get_tags() if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)): ids = n.get_ids(title, body, tags) if len(ids) > 0: ids = map(lambda x: x.lower(), ids) namespaces_for_post[name] = ids if len(namespaces_for_post): post = { "question_id": id, "url": "http://stackoverflow.com/questions/%s" % id, "namespaces": namespaces_for_post, "title": title, "score": int(score), "accepted_answer": has_accepted_answer, "last_activity": last_activity_date, "last_updated": last_updated_date } posts.update({"question_id": id}, post, True); print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
Rewrite inserting function. It can be a lot simpler now we know we're always dealing with up-to-date data.
Rewrite inserting function. It can be a lot simpler now we know we're always dealing with up-to-date data.
Python
bsd-3-clause
alnorth/stackdoc,alnorth/stackdoc,alnorth/stackdoc
--- +++ @@ -10,32 +10,17 @@ namespaces_for_post[name] = ids if len(namespaces_for_post): - post = posts.find_one({"question_id": int(id)}) - previously_existed = False - update = True - if post: - previously_existed = True - # Only update title, score etc. if this is the latest data - update = post["last_activity"] < last_activity_date - else: - post = { - "question_id": int(id), - "url": "http://stackoverflow.com/questions/%s" % id - } + post = { + "question_id": id, + "url": "http://stackoverflow.com/questions/%s" % id, + "namespaces": namespaces_for_post, + "title": title, + "score": int(score), + "accepted_answer": has_accepted_answer, + "last_activity": last_activity_date, + "last_updated": last_updated_date + } - post["namespaces"] = namespaces_for_post - if update: - post["title"] = title - post["score"] = int(score) - post["answers"] = int(answer_count) - post["accepted_answer"] = has_accepted_answer - post["last_activity"] = last_activity_date - post["last_updated"] = last_updated_date + posts.update({"question_id": id}, post, True); - if previously_existed: - posts.update({"question_id": int(id)}, post) - else: - posts.insert(post) - - update_text = "Fully updated" if update else "Partially updated" - print "%s %s question from %s (%s)" % (update_text if previously_existed else "Inserted", ", ".join(namespaces_for_post.keys()), str(last_activity_date), id) + print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
a13e13d0fef4a342c5a419365b9ac7053eddafb3
loader/helpers/lib/forgeFixes.py
loader/helpers/lib/forgeFixes.py
import os import fileinput def modify(path, build): config = os.path.join(path, 'config/forge.cfg') replacements = { 'removeErroringEntities=false': 'removeErroringEntities=true', 'removeErroringTileEntities=false': 'removeErroringTileEntities=true' } if not os.path.isfile(config): return True for line in fileinput.FileInput(config, inplace=True): for find, replace in replacements.iteritems(): line = line.replace(find, replace) print line,
import os import fileinput import requests import zipfile import distutils.dir_util import tempfile patchfiles = 'gdn/static/cache/forgepatch01' def patchForge(path): if not os.path.exists(patchfiles): print 'Downloading forgepatch' r = requests.get('http://s3.amazonaws.com/SpaceZips/forgepatch.zip', stream=True) handle, temp_file_path = tempfile.mkstemp() with open(temp_file_path, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() with zipfile.ZipFile(temp_file_path) as z: z.extractall(patchfiles) os.remove(temp_file_path) distutils.dir_util.copy_tree(patchfiles, path) def modify(path, build): patchForge(path) config = os.path.join(path, 'config/forge.cfg') replacements = { 'removeErroringEntities=false': 'removeErroringEntities=true', 'removeErroringTileEntities=false': 'removeErroringTileEntities=true' } if not os.path.isfile(config): return True for line in fileinput.FileInput(config, inplace=True): for find, replace in replacements.iteritems(): line = line.replace(find, replace) print line,
Add forge libraries to patch helper
Add forge libraries to patch helper
Python
mpl-2.0
MCProHosting/SpaceGDN,XereoNet/SpaceGDN,MCProHosting/SpaceGDN,XereoNet/SpaceGDN,MCProHosting/SpaceGDN,XereoNet/SpaceGDN
--- +++ @@ -1,7 +1,36 @@ import os import fileinput +import requests +import zipfile +import distutils.dir_util +import tempfile + +patchfiles = 'gdn/static/cache/forgepatch01' + +def patchForge(path): + + if not os.path.exists(patchfiles): + print 'Downloading forgepatch' + r = requests.get('http://s3.amazonaws.com/SpaceZips/forgepatch.zip', stream=True) + + handle, temp_file_path = tempfile.mkstemp() + + with open(temp_file_path, 'wb') as f: + for chunk in r.iter_content(chunk_size=1024): + if chunk: # filter out keep-alive new chunks + f.write(chunk) + f.flush() + + with zipfile.ZipFile(temp_file_path) as z: + z.extractall(patchfiles) + + os.remove(temp_file_path) + + distutils.dir_util.copy_tree(patchfiles, path) def modify(path, build): + patchForge(path) + config = os.path.join(path, 'config/forge.cfg') replacements = { 'removeErroringEntities=false': 'removeErroringEntities=true',
90bc53c743095fd3a6a848aa2447b6ae6ab1a98f
tg/release.py
tg/release.py
"""TurboGears project related information""" version = "2.0a1" description = "Next generation TurboGears built on Pylons" long_description=""" TurboGears brings together a variety of best of breed python tools to create an easy to install, easy to use web megaframework. It provides and integrated and well tested set of tools for everything you need to build dynamic, database driven applications. TurboGears 2 provides you with everything you need from the javascript programming tools, like ToscaWidgets and automatic JSON generation, to one of the world's most powerful Object Relational Mappers (SQLAlchemy). The latest development version is available in <a href="http://svn.turbogears.org/trunk#egg=turbogears-dev" >the TurboGears subversion repository</a>.""" url="http://www.turbogears.org" author='Alberto Valverde, Mark Ramm' email = "alberto@toscat.net, mark.ramm@gmail.com" copyright = """Copyright 2005-2007 Kevin Dangoor, Alberto Valverde, Mark.Ramm and contributors""" license = "MIT"
"""TurboGears project related information""" version = "2.0a1" description = "Next generation TurboGears built on Pylons" long_description=""" TurboGears brings together a variety of best of breed python tools to create an easy to install, easy to use web megaframework. It provides and integrated and well tested set of tools for everything you need to build dynamic, database driven applications. TurboGears 2 provides you with everything you need from the javascript programming tools, like ToscaWidgets and automatic JSON generation, to one of the world's most powerful Object Relational Mappers (SQLAlchemy). The latest development version is available in the `TurboGears subversion repository`_. .. _TurboGears subversion repository: http://svn.turbogears.org/trunk#egg=turbogears-dev """ url="http://www.turbogears.org" author='Alberto Valverde, Mark Ramm' email = "alberto@toscat.net, mark.ramm@gmail.com" copyright = """Copyright 2005-2007 Kevin Dangoor, Alberto Valverde, Mark Ramm and contributors""" license = "MIT"
Convert description in setup.py to rest format for better display in Cheeseshop
Convert description in setup.py to rest format for better display in Cheeseshop --HG-- extra : convert_revision : svn%3A77541ad4-5f01-0410-9ede-a1b63cd9a898/trunk%403340
Python
mit
lucius-feng/tg2,lucius-feng/tg2
--- +++ @@ -2,23 +2,25 @@ version = "2.0a1" description = "Next generation TurboGears built on Pylons" long_description=""" -TurboGears brings together a variety of best of breed python tools -to create an easy to install, easy to use web megaframework. +TurboGears brings together a variety of best of breed python tools +to create an easy to install, easy to use web megaframework. -It provides and integrated and well tested set of tools for -everything you need to build dynamic, database driven applications. -TurboGears 2 provides you with everything you need from the -javascript programming tools, like ToscaWidgets and automatic -JSON generation, to one of the world's most powerful Object +It provides and integrated and well tested set of tools for +everything you need to build dynamic, database driven applications. +TurboGears 2 provides you with everything you need from the +javascript programming tools, like ToscaWidgets and automatic +JSON generation, to one of the world's most powerful Object Relational Mappers (SQLAlchemy). +The latest development version is available in the +`TurboGears subversion repository`_. -The latest development version is available in -<a href="http://svn.turbogears.org/trunk#egg=turbogears-dev" ->the TurboGears subversion repository</a>.""" +.. _TurboGears subversion repository: + http://svn.turbogears.org/trunk#egg=turbogears-dev +""" url="http://www.turbogears.org" author='Alberto Valverde, Mark Ramm' email = "alberto@toscat.net, mark.ramm@gmail.com" -copyright = """Copyright 2005-2007 Kevin Dangoor, -Alberto Valverde, Mark.Ramm and contributors""" +copyright = """Copyright 2005-2007 Kevin Dangoor, +Alberto Valverde, Mark Ramm and contributors""" license = "MIT"
a8a7f6ecbe1abd4fcb6dad8e6c635c3ef38ab40f
scoring_engine/engine/execute_command.py
scoring_engine/engine/execute_command.py
from scoring_engine.celery_app import celery_app from celery.exceptions import SoftTimeLimitExceeded import subprocess from scoring_engine.logger import logger @celery_app.task(name='execute_command', soft_time_limit=30) def execute_command(job): output = "" # Disable duplicate celery log messages if logger.propagate: logger.propagate = False logger.info("Running cmd for " + str(job)) try: cmd_result = subprocess.run( job['command'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) output = cmd_result.stdout.decode("utf-8") job['errored_out'] = False except SoftTimeLimitExceeded: job['errored_out'] = True job['output'] = output return job
from scoring_engine.celery_app import celery_app from celery.exceptions import SoftTimeLimitExceeded import subprocess from scoring_engine.logger import logger @celery_app.task(name='execute_command', acks_late=True, reject_on_worker_lost=True, soft_time_limit=30) def execute_command(job): output = "" # Disable duplicate celery log messages if logger.propagate: logger.propagate = False logger.info("Running cmd for " + str(job)) try: cmd_result = subprocess.run( job['command'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) output = cmd_result.stdout.decode("utf-8") job['errored_out'] = False except SoftTimeLimitExceeded: job['errored_out'] = True job['output'] = output return job
Modify worker to requeue jobs if worker is killed
Modify worker to requeue jobs if worker is killed
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
--- +++ @@ -5,7 +5,7 @@ from scoring_engine.logger import logger -@celery_app.task(name='execute_command', soft_time_limit=30) +@celery_app.task(name='execute_command', acks_late=True, reject_on_worker_lost=True, soft_time_limit=30) def execute_command(job): output = "" # Disable duplicate celery log messages
08fa37d71cf8f1d5d83227349b49da142f9781da
markdo/markdo.py
markdo/markdo.py
#!/usr/bin/env python from appkit.api.v0_2_8 import App from flask import render_template, request import os import sys import codecs app = App(__name__) try: file_name = sys.argv[1] if not os.path.exists(file_name): open(file_name, 'w').close() except: file_name = None app.file_name = file_name print(app.file_name) @app.route('/') def index(): markdown = None if app.file_name is not None: markdown = codecs.open(file_name, 'r', 'utf-8').read() return render_template( '/ui.html', file_name=app.file_name, text=markdown) @app.route('/save/', methods=['POST',]) def save(): """save markdown content to the file""" file_name = request.form.get('file', None) text = request.form.get('text', None) f = open(file_name, 'w') f.write(text) f.close() return 'Saved' if __name__ == '__main__': app.run()
#!/usr/bin/env python from appkit.api.v0_2_8 import App from flask import render_template, request import os import sys import codecs app = App(__name__) try: file_name = sys.argv[1] if not os.path.exists(file_name): open(file_name, 'w').close() except: file_name = None app.file_name = file_name print(app.file_name) @app.route('/') def index(): markdown = None if app.file_name is not None: markdown = codecs.open(file_name, 'r', 'utf-8').read() return render_template( '/ui.html', file_name=app.file_name, text=markdown) @app.route('/save/', methods=['POST',]) def save(): """save markdown content to the file""" file_name = request.form.get('file', None) text = request.form.get('text', None) f = codecs.open(file_name, 'w', encoding='utf-8') f.write(text) f.close() return 'Saved' app.debug = True app.run()
Fix utf-8 encoding error when saving the file.
Fix utf-8 encoding error when saving the file.
Python
mit
nitipit/markdo,nitipit/markdo,nitipit/markdo
--- +++ @@ -37,10 +37,10 @@ file_name = request.form.get('file', None) text = request.form.get('text', None) - f = open(file_name, 'w') + f = codecs.open(file_name, 'w', encoding='utf-8') f.write(text) f.close() return 'Saved' -if __name__ == '__main__': - app.run() +app.debug = True +app.run()
71b42d288b68b2bac07f8e423429971e68a7ffd5
database_files/migrations/0001_initial.py
database_files/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='File', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(unique=True, max_length=255, db_index=True)), ('size', models.PositiveIntegerField(db_index=True)), ('_content', models.TextField(db_column=b'content')), ('created_datetime', models.DateTimeField(default=django.utils.timezone.now, verbose_name=b'Created datetime', db_index=True)), ('_content_hash', models.CharField(db_index=True, max_length=128, null=True, db_column=b'content_hash', blank=True)), ], options={ 'db_table': 'database_files_file', }, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='File', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(unique=True, max_length=255, db_index=True)), ('size', models.PositiveIntegerField(db_index=True)), ('_content', models.TextField(db_column='content')), ('created_datetime', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Created datetime', db_index=True)), ('_content_hash', models.CharField(db_index=True, max_length=128, null=True, db_column='content_hash', blank=True)), ], options={ 'db_table': 'database_files_file', }, ), ]
Make Django 1.7 migrations compatible with Python3
Make Django 1.7 migrations compatible with Python3
Python
bsd-3-clause
rhunwicks/django-database-files
--- +++ @@ -17,9 +17,9 @@ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(unique=True, max_length=255, db_index=True)), ('size', models.PositiveIntegerField(db_index=True)), - ('_content', models.TextField(db_column=b'content')), - ('created_datetime', models.DateTimeField(default=django.utils.timezone.now, verbose_name=b'Created datetime', db_index=True)), - ('_content_hash', models.CharField(db_index=True, max_length=128, null=True, db_column=b'content_hash', blank=True)), + ('_content', models.TextField(db_column='content')), + ('created_datetime', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Created datetime', db_index=True)), + ('_content_hash', models.CharField(db_index=True, max_length=128, null=True, db_column='content_hash', blank=True)), ], options={ 'db_table': 'database_files_file',
1af3111e4f2422c1d6484c237700013386d4638d
minutes/forms.py
minutes/forms.py
from django.forms import ModelForm, Textarea, ChoiceField from django.urls import reverse_lazy from .models import Meeting, Folder MD_INPUT = { 'class': 'markdown-input', 'data-endpoint': reverse_lazy('utilities:preview_safe') } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1]) class MeetingForm(ModelForm): folder = ChoiceField(choices=sorted_folders) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Meeting fields = ['name', 'folder', 'title', 'body', 'date'] widgets = { 'body': Textarea(attrs=MD_INPUT), } def clean_folder(self): return Folder.objects.get(pk=self.cleaned_data['folder'])
from django.forms import ModelForm, Textarea, ChoiceField from django.utils.functional import lazy from .models import Meeting, Folder MD_INPUT = { 'class': 'markdown-input' } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1]) class MeetingForm(ModelForm): folder = ChoiceField(choices=sorted_folders) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Meeting fields = ['name', 'folder', 'title', 'body', 'date'] widgets = { 'body': Textarea(attrs=MD_INPUT), } def clean_folder(self): return Folder.objects.get(pk=self.cleaned_data['folder'])
Revert "Allow admin preview in minutes as well"
Revert "Allow admin preview in minutes as well" This reverts commit f4806655
Python
isc
ashbc/tgrsite,ashbc/tgrsite,ashbc/tgrsite
--- +++ @@ -1,11 +1,10 @@ from django.forms import ModelForm, Textarea, ChoiceField -from django.urls import reverse_lazy +from django.utils.functional import lazy from .models import Meeting, Folder MD_INPUT = { - 'class': 'markdown-input', - 'data-endpoint': reverse_lazy('utilities:preview_safe') + 'class': 'markdown-input' }
dd9030413af99e05fe935a2dafb9a6012b09b248
modules/karma.py
modules/karma.py
import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' module_db = 'karma.json' module_version = '0.1.0' listen_for_reaction = True async def parse_command(self, message, client): pass async def on_reaction(self, reaction, client): target_user = self.module_db.Query() if self.module_db.get(target_user.userid == reaction.message.author.id) == None: self.module_db.insert({'userid': reaction.message.author.id, 'karma': 1}) msg = 'New entry for ' + reaction.message.author.id + ' added.' await client.send_message(reaction.message.channel, msg) else: new_karma = self.module_db.get(target_user.userid == reaction.message.author.id)['karma'] + 1 self.module_db.update({'karma': new_karma}, target_user.userid == reaction.message.author.id) msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma await client.send_message(reaction.message.channel, msg) #msg = "I saw that!" + reaction.message.author.name + reaction.emoji #await client.send_message(reaction.message.channel, msg)
import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' module_db = 'karma.json' module_version = '0.1.0' listen_for_reaction = True async def parse_command(self, message, client): pass async def on_reaction(self, reaction, client): target_user = self.karma.Query() if self.karma.get(target_user.userid == reaction.message.author.id) == None: self.karma.insert({'userid': reaction.message.author.id, 'karma': 1}) msg = 'New entry for ' + reaction.message.author.id + ' added.' await client.send_message(reaction.message.channel, msg) else: new_karma = self.karma.get(target_user.userid == reaction.message.author.id)['karma'] + 1 self.karma.update({'karma': new_karma}, target_user.userid == reaction.message.author.id) msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma await client.send_message(reaction.message.channel, msg) #msg = "I saw that!" + reaction.message.author.name + reaction.emoji #await client.send_message(reaction.message.channel, msg)
Fix where db name should be used in db operations (name conflict!)
Fix where db name should be used in db operations (name conflict!)
Python
mit
suclearnub/scubot
--- +++ @@ -20,15 +20,15 @@ pass async def on_reaction(self, reaction, client): - target_user = self.module_db.Query() - if self.module_db.get(target_user.userid == reaction.message.author.id) == None: - self.module_db.insert({'userid': reaction.message.author.id, 'karma': 1}) + target_user = self.karma.Query() + if self.karma.get(target_user.userid == reaction.message.author.id) == None: + self.karma.insert({'userid': reaction.message.author.id, 'karma': 1}) msg = 'New entry for ' + reaction.message.author.id + ' added.' await client.send_message(reaction.message.channel, msg) else: - new_karma = self.module_db.get(target_user.userid == reaction.message.author.id)['karma'] + 1 - self.module_db.update({'karma': new_karma}, target_user.userid == reaction.message.author.id) + new_karma = self.karma.get(target_user.userid == reaction.message.author.id)['karma'] + 1 + self.karma.update({'karma': new_karma}, target_user.userid == reaction.message.author.id) msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma await client.send_message(reaction.message.channel, msg)
20e293b49438a2428eee21bdc07799328a69ec48
dadd/worker/handlers.py
dadd/worker/handlers.py
import json import socket import requests from flask import request, jsonify from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info()) @app.route('/register/', methods=['POST']) def register_with_master(): register(app) return jsonify({'message': 'ok'}) def register(host, port): sess = requests.Session() if 'USERNAME' in app.config and 'PASSWORD' in app.config: sess.auth = (app.config['USERNAME'], app.config['PASSWORD']) sess.headers = {'content-type': 'application/json'} try: url = app.config['MASTER_URL'] + '/api/hosts/' resp = sess.post(url, data=json.dumps({ 'host': socket.getfqdn(), 'port': port })) if not resp.ok: app.logger.warning('Error registering with master: %s' % app.config['MASTER_URL']) except Exception as e: app.logger.warning('Connection Error: %s' % e)
import os import json import socket import requests from flask import request, jsonify, Response, abort from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info()) @app.route('/register/', methods=['POST']) def register_with_master(): register(app) return jsonify({'message': 'ok'}) def register(host, port): sess = requests.Session() if 'USERNAME' in app.config and 'PASSWORD' in app.config: sess.auth = (app.config['USERNAME'], app.config['PASSWORD']) sess.headers = {'content-type': 'application/json'} try: url = app.config['MASTER_URL'] + '/api/hosts/' resp = sess.post(url, data=json.dumps({ 'host': app.config.get('HOSTNAME', socket.getfqdn()), 'port': port })) if not resp.ok: app.logger.warning('Error registering with master: %s' % app.config['MASTER_URL']) except Exception as e: app.logger.warning('Connection Error: %s' % e) @app.route('/logs/<path>', methods=['GET']) def tail_log(path): if os.path.exists(path) and path.startswith('/tmp/'): return Response(open(path), content_type='text/plain') abort(404)
Allow setting the HOSTNAME reported to the master via an env var; Stub and endpoint for tailing the log of a process assuming you know the path.
Allow setting the HOSTNAME reported to the master via an env var; Stub and endpoint for tailing the log of a process assuming you know the path. I'd like to get this log processing a bit more automatic but I need to spend more time in Dadd's API.
Python
bsd-3-clause
ionrock/dadd,ionrock/dadd,ionrock/dadd,ionrock/dadd
--- +++ @@ -1,9 +1,10 @@ +import os import json import socket import requests -from flask import request, jsonify +from flask import request, jsonify, Response, abort from dadd.worker import app from dadd.worker.proc import ChildProcess @@ -32,10 +33,18 @@ try: url = app.config['MASTER_URL'] + '/api/hosts/' resp = sess.post(url, data=json.dumps({ - 'host': socket.getfqdn(), 'port': port + 'host': app.config.get('HOSTNAME', socket.getfqdn()), + 'port': port })) if not resp.ok: app.logger.warning('Error registering with master: %s' % app.config['MASTER_URL']) except Exception as e: app.logger.warning('Connection Error: %s' % e) + + +@app.route('/logs/<path>', methods=['GET']) +def tail_log(path): + if os.path.exists(path) and path.startswith('/tmp/'): + return Response(open(path), content_type='text/plain') + abort(404)
c74c38bb615d048eb26634c048a833ddc2da7d62
jcppy/__init__.py
jcppy/__init__.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2017 Stanislav Ivochkin <isn@extrn.org> # License: MIT (see LICENSE for details) from jcppy._version import __version__, __revision__ from jcppy.header import header from jcppy.source import source
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2017 Stanislav Ivochkin <isn@extrn.org> # License: MIT (see LICENSE for details) try: from jcppy._version import __version__, __revision__ except ImportError: __version__ = 'latest' __revision__ = 'latest' __hash__ = 'unknown' from jcppy.header import header from jcppy.source import source
Work around missing jcppy._version for local development
Work around missing jcppy._version for local development
Python
mit
isn-/jcppy,isn-/jcppy
--- +++ @@ -3,6 +3,11 @@ # Copyright (c) 2017 Stanislav Ivochkin <isn@extrn.org> # License: MIT (see LICENSE for details) -from jcppy._version import __version__, __revision__ +try: + from jcppy._version import __version__, __revision__ +except ImportError: + __version__ = 'latest' + __revision__ = 'latest' + __hash__ = 'unknown' from jcppy.header import header from jcppy.source import source
1379b3031e63330d03c85b0d1d22ce11c84bf5e9
telemetry/telemetry/core/browser_info.py
telemetry/telemetry/core/browser_info.py
# Copyright 2014 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. _check_webgl_supported_script = """ (function () { var c = document.createElement('canvas'); var gl = c.getContext('webgl'); if (gl == null) { gl = c.getContext("experimental-webgl"); if (gl == null) { return false; } } return true; })(); """ class BrowserInfo(object): """A wrapper around browser object that allows looking up infos of the browser. """ def __init__(self, browser): self._browser = browser def HasWebGLSupport(self): result = False # If no tab is opened, open one and close it after evaluate # _check_webgl_supported_script if len(self._browser.tabs) == 0 and self._browser.supports_tab_control: self._browser.tabs.New() tab = self._browser.tabs[0] result = tab.EvaluateJavaScript(_check_webgl_supported_script) tab.Close() elif len(self._browser.tabs) > 0: tab = self._browser.tabs[0] result = tab.EvaluateJavaScript(_check_webgl_supported_script) return result
# Copyright 2014 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. _check_webgl_supported_script = """ (function () { var c = document.createElement('canvas'); var gl = c.getContext('webgl'); if (gl == null) { gl = c.getContext("experimental-webgl"); if (gl == null) { return false; } } return true; })(); """ class BrowserInfo(object): """A wrapper around browser object that allows looking up infos of the browser. """ def __init__(self, browser): self._browser = browser def HasWebGLSupport(self): result = False # If no tab is opened, open one and close it after evaluate # _check_webgl_supported_script if len(self._browser.tabs) == 0 and self._browser.supports_tab_control: self._browser.tabs.New() tab = self._browser.tabs[0] result = tab.EvaluateJavaScript(_check_webgl_supported_script) tab.Close() elif len(self._browser.tabs) > 0: tab = self._browser.tabs[0] result = tab.EvaluateJavaScript(_check_webgl_supported_script) return result def HasFlingGestureSupport(self): # Synthetic fling gestures weren't properly tracked by telemetry until # Chromium branch number 2339 (see crrev.com/1003023002). # TODO(jdduke): Resolve lack of branch number support for content_shell # targets, see crbug.com/470273. branch_num = ( self._browser._browser_backend.devtools_client.GetChromeBranchNumber()) return branch_num >= 2339
Add a fling-driven variant of SimpleMobileSites
Add a fling-driven variant of SimpleMobileSites Create a basic pageset that uses the newly supported fling interaction, paralleling the existing SimpleMobileSites pageset that uses smooth scrolling. This should allow basic comparisons between touch scrolling and fling performance. More stressful fling-related pages will be added in a separate set. BUG=321141 Review URL: https://codereview.chromium.org/1023763004 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#322172}
Python
bsd-3-clause
benschmaus/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult,catapult-project/catapult-csm,sahiljain/catapult,sahiljain/catapult,catapult-project/catapult-csm,sahiljain/catapult,SummerLW/Perf-Insight-Report,sahiljain/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult,sahiljain/catapult,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,sahiljain/catapult,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,catapult-project/catapult,benschmaus/catapult,catapult-project/catapult-csm
--- +++ @@ -36,3 +36,12 @@ tab = self._browser.tabs[0] result = tab.EvaluateJavaScript(_check_webgl_supported_script) return result + + def HasFlingGestureSupport(self): + # Synthetic fling gestures weren't properly tracked by telemetry until + # Chromium branch number 2339 (see crrev.com/1003023002). + # TODO(jdduke): Resolve lack of branch number support for content_shell + # targets, see crbug.com/470273. + branch_num = ( + self._browser._browser_backend.devtools_client.GetChromeBranchNumber()) + return branch_num >= 2339
2594433a32e03af15ca67002f2eb76227dd1f8c1
binstar_client/utils/notebook/__init__.py
binstar_client/utils/notebook/__init__.py
import os from binstar_client import errors from uploader import * def parse(handle): """ Handle can take the form of: notebook path/to/notebook[.ipynb] project:notebook[.ipynb] :param handle: String :return: (project, notebook) :raises: NotebookNotFound """ if ':' in handle: project, filepath = handle.split(':', 1) else: project = None filepath = handle if not filepath.endswith('.ipynb'): filepath += '.ipynb' if not os.path.isfile(filepath): raise errors.NotebookNotExist(filepath) notebook = os.path.splitext(os.path.basename(filepath))[0] if project is None: project = notebook return project, notebook
import os from binstar_client import errors from .uploader import * def parse(handle): """ Handle can take the form of: notebook path/to/notebook[.ipynb] project:notebook[.ipynb] :param handle: String :return: (project, notebook) :raises: NotebookNotFound """ if ':' in handle: project, filepath = handle.split(':', 1) else: project = None filepath = handle if not filepath.endswith('.ipynb'): filepath += '.ipynb' if not os.path.isfile(filepath): raise errors.NotebookNotExist(filepath) notebook = os.path.splitext(os.path.basename(filepath))[0] if project is None: project = notebook return project, notebook
Fix relative import (compatible with p3
Fix relative import (compatible with p3
Python
bsd-3-clause
Anaconda-Platform/anaconda-client,Anaconda-Platform/anaconda-client,Anaconda-Platform/anaconda-client
--- +++ @@ -1,6 +1,6 @@ import os from binstar_client import errors -from uploader import * +from .uploader import * def parse(handle):
810ae97b3b38a91c8ae3f87aca8479533a1784dd
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/config/urls.py
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/config/urls.py
import django.views.static from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView admin.autodiscover() urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='base.html')), url(r'^admin/', admin.site.urls), {%- if cookiecutter.use_djangocms == 'y' %} url(r'^', include('cms.urls')), {%- endif %} ] if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^media/(?P<path>.*)$', django.views.static.serve, {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), url(r'^__debug__/', include(debug_toolbar.urls)), ] + staticfiles_urlpatterns() + urlpatterns
import django.views.static from django.conf import settings from django.urls import include, path from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView admin.autodiscover() urlpatterns = [ path('', TemplateView.as_view(template_name='base.html')), path('admin/', admin.site.urls), {%- if cookiecutter.use_djangocms == 'y' %} path('', include('cms.urls')), {%- endif %} ] if settings.DEBUG: import debug_toolbar urlpatterns = [ path('media/<path:path>/', django.views.static.serve, {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), path('__debug__/', include(debug_toolbar.urls)), ] + staticfiles_urlpatterns() + urlpatterns
Use `path` helper for URLConf
Use `path` helper for URLConf
Python
mit
r0x73/django-template,r0x73/django-template,r0x73/django-template
--- +++ @@ -1,6 +1,6 @@ import django.views.static from django.conf import settings -from django.conf.urls import include, url +from django.urls import include, path from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView @@ -8,17 +8,17 @@ admin.autodiscover() urlpatterns = [ - url(r'^$', TemplateView.as_view(template_name='base.html')), - url(r'^admin/', admin.site.urls), + path('', TemplateView.as_view(template_name='base.html')), + path('admin/', admin.site.urls), {%- if cookiecutter.use_djangocms == 'y' %} - url(r'^', include('cms.urls')), + path('', include('cms.urls')), {%- endif %} ] if settings.DEBUG: import debug_toolbar urlpatterns = [ - url(r'^media/(?P<path>.*)$', django.views.static.serve, + path('media/<path:path>/', django.views.static.serve, {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), - url(r'^__debug__/', include(debug_toolbar.urls)), + path('__debug__/', include(debug_toolbar.urls)), ] + staticfiles_urlpatterns() + urlpatterns
f54db5d4e132fe1c227fe5bf1f7079772433429d
yunity/models/utils.py
yunity/models/utils.py
from django.db.models import Model, CharField, Field class MaxLengthCharField(CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 super().__init__(*args, **kwargs) class BaseModel(Model): class Meta: abstract = True def _get_explicit_field_names(self): return [field.name for field in self._meta.get_fields() if isinstance(field, Field) and field.name != 'id'] def to_dict(self): fields = self._get_explicit_field_names() return {field: getattr(self, field) for field in fields} def __repr__(self): return 'Model({})'.format(repr(self.to_dict()))
from django.db.models import Model, CharField, Field class MaxLengthCharField(CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 super().__init__(*args, **kwargs) class BaseModel(Model): class Meta: abstract = True def _get_explicit_field_names(self): return [field.name for field in self._meta.get_fields() if isinstance(field, Field) and field.name != 'id'] def to_dict(self): fields = self._get_explicit_field_names() return {field: getattr(self, field) for field in fields} def __repr__(self): model = str(self.__class__.__name__) columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items()) return '{}({})'.format(model, columns)
Add columns and values to repr
Add columns and values to repr
Python
agpl-3.0
yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend
--- +++ @@ -20,4 +20,6 @@ return {field: getattr(self, field) for field in fields} def __repr__(self): - return 'Model({})'.format(repr(self.to_dict())) + model = str(self.__class__.__name__) + columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items()) + return '{}({})'.format(model, columns)
b2bc77023ed3e19f6f7483645e2a11952c061de0
tests/registryd/test_registry_startup.py
tests/registryd/test_registry_startup.py
PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def test_accessible_iface_properties(registry, session_manager): val = registry.Get(ACCESSIBLE_IFACE, 'Name', dbus_interface=PROPERTIES_IFACE) assert str(val) == 'main'
PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry, session_manager): values = [ ('Name', 'main'), ('Description', ''), ] for prop_name, expected in values: assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected
Test the Description property of the registry's root
Test the Description property of the registry's root
Python
lgpl-2.1
GNOME/at-spi2-core,GNOME/at-spi2-core,GNOME/at-spi2-core
--- +++ @@ -1,6 +1,14 @@ PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' +def get_property(proxy, iface_name, prop_name): + return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) + def test_accessible_iface_properties(registry, session_manager): - val = registry.Get(ACCESSIBLE_IFACE, 'Name', dbus_interface=PROPERTIES_IFACE) - assert str(val) == 'main' + values = [ + ('Name', 'main'), + ('Description', ''), + ] + + for prop_name, expected in values: + assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected
9231612c0631c784dc7188822b47a4bde38db488
uni_form/templatetags/uni_form_field.py
uni_form/templatetags/uni_form_field.py
from django import template register = template.Library() class_converter = { "textinput":"textinput textInput", "fileinput":"fileinput fileUpload", "passwordinput":"passwordinput textInput" } @register.filter def is_checkbox(field): return field.field.widget.__class__.__name__.lower() == "checkboxinput" @register.filter def with_class(field): class_name = field.field.widget.__class__.__name__.lower() class_name = class_converter.get(class_name, class_name) if "class" in field.field.widget.attrs: css_class = field.field.widget.attrs['class'] if field.field.widget.attrs['class'].find(class_name) == -1: css_class += " %s" % (class_name,) else: css_class = class_name return field.as_widget(attrs={'class': css_class})
from django import template register = template.Library() class_converter = { "textinput":"textinput textInput", "fileinput":"fileinput fileUpload", "passwordinput":"textinput textInput", >>>>>>> f85af74... Convert css class of PasswordInput widget:uni_form/templatetags/uni_form_field.py } @register.filter def is_checkbox(field): return field.field.widget.__class__.__name__.lower() == "checkboxinput" @register.filter def with_class(field): class_name = field.field.widget.__class__.__name__.lower() class_name = class_converter.get(class_name, class_name) if "class" in field.field.widget.attrs: css_class = field.field.widget.attrs['class'] if field.field.widget.attrs['class'].find(class_name) == -1: css_class += " %s" % (class_name,) else: css_class = class_name return field.as_widget(attrs={'class': css_class})
Convert css class of PasswordInput widget
Convert css class of PasswordInput widget
Python
mit
maraujop/django-crispy-forms,jtyoung/django-crispy-forms,ngenovictor/django-crispy-forms,saydulk/django-crispy-forms,carltongibson/django-crispy-forms,treyhunner/django-crispy-forms,dessibelle/django-crispy-forms,Stranger6667/django-crispy-forms,iris-edu-int/django-crispy-forms,spectras/django-crispy-forms,HungryCloud/django-crispy-forms,saydulk/django-crispy-forms,jtyoung/django-crispy-forms,rfleschenberg/django-crispy-forms,davidszotten/django-crispy-forms,davidszotten/django-crispy-forms,IanLee1521/django-crispy-forms,tarunlnmiit/django-crispy-forms,eykanal/django-crispy-forms,pjdelport/django-crispy-forms,iris-edu/django-crispy-forms,VishvajitP/django-crispy-forms,Stranger6667/django-crispy-forms,iris-edu-int/django-crispy-forms,carltongibson/django-crispy-forms,iedparis8/django-crispy-forms,pydanny/django-uni-form,uranusjr/django-crispy-forms-ng,tarunlnmiit/django-crispy-forms,django-crispy-forms/django-crispy-forms,damienjones/django-crispy-forms,HungryCloud/django-crispy-forms,CashStar/django-uni-form,RamezIssac/django-crispy-forms,impulse-cloud/django-crispy-forms,schrd/django-crispy-forms,avsd/django-crispy-forms,dessibelle/django-crispy-forms,iris-edu/django-crispy-forms,rfleschenberg/django-crispy-forms,damienjones/django-crispy-forms,VishvajitP/django-crispy-forms,alanwj/django-crispy-forms,scuml/django-crispy-forms,smirolo/django-crispy-forms,CashStar/django-uni-form,zixan/django-crispy-forms,iedparis8/django-crispy-forms,HungryCloud/django-crispy-forms,agepoly/django-crispy-forms,PetrDlouhy/django-crispy-forms,scuml/django-crispy-forms,eykanal/django-crispy-forms,avsd/django-crispy-forms,django-crispy-forms/django-crispy-forms,maraujop/django-crispy-forms,dzhuang/django-crispy-forms,pydanny/django-uni-form,uranusjr/django-crispy-forms-ng,PetrDlouhy/django-crispy-forms,jcomeauictx/django-crispy-forms,bouttier/django-crispy-forms,bouttier/django-crispy-forms,spectras/django-crispy-forms,treyhunner/django-crispy-forms,schrd/django-crispy-forms,ngenovictor/django-crispy-forms,dzhuang/django-crispy-forms,alanwj/django-crispy-forms,RamezIssac/django-crispy-forms,IanLee1521/django-crispy-forms,zixan/django-crispy-forms,jcomeauictx/django-crispy-forms,impulse-cloud/django-crispy-forms,agepoly/django-crispy-forms,smirolo/django-crispy-forms
--- +++ @@ -5,7 +5,8 @@ class_converter = { "textinput":"textinput textInput", "fileinput":"fileinput fileUpload", - "passwordinput":"passwordinput textInput" + "passwordinput":"textinput textInput", +>>>>>>> f85af74... Convert css class of PasswordInput widget:uni_form/templatetags/uni_form_field.py } @register.filter
efb1057b122664ee8e1ab0a06259988aa9f50092
experiments/management/commands/update_experiment_reports.py
experiments/management/commands/update_experiment_reports.py
import logging l=logging.getLogger(__name__) from django.conf import settings from django.core.management.base import BaseCommand, CommandError from experiments.reports import (EngagementReportGenerator, ConversionReportGenerator) class Command(BaseCommand): help = ('update_experiment_reports : Generate all the daily reports for' ' for the SplitTesting experiments') def __init__(self): super(self.__class__, self).__init__() def handle(self, *args, **options): if len(args): raise CommandError("This command does not take any arguments") engagement_calculator = _load_function(settings.LEAN_ENGAGEMENT_CALCULATOR) EngagementReportGenerator(engagement_score_calculator=engagement_calculator).generate_all_daily_reports() ConversionReportGenerator().generate_all_daily_reports() def _load_function(fully_qualified_name): i = fully_qualified_name.rfind('.') module, attr = fully_qualified_name[:i], fully_qualified_name[i+1:] try: mod = __import__(module, globals(), locals(), [attr]) except ImportError, e: raise ImproperlyConfigured, 'Error importing template source loader %s: "%s"' % (module, e) try: func = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured, 'Module "%s" does not define a "%s" callable template source loader' % (module, attr) return func
import logging l=logging.getLogger(__name__) from django.conf import settings from django.core.management.base import BaseCommand, CommandError from experiments.reports import (EngagementReportGenerator, ConversionReportGenerator) class Command(BaseCommand): help = ('update_experiment_reports : Generate all the daily reports for' ' for the SplitTesting experiments') def __init__(self): super(self.__class__, self).__init__() def handle(self, *args, **options): if len(args): raise CommandError("This command does not take any arguments") engagement_calculator = _load_function(settings.LEAN_ENGAGEMENT_CALCULATOR) EngagementReportGenerator(engagement_score_calculator=engagement_calculator).generate_all_daily_reports() ConversionReportGenerator().generate_all_daily_reports() def _load_function(fully_qualified_name): i = fully_qualified_name.rfind('.') module, attr = fully_qualified_name[:i], fully_qualified_name[i+1:] try: mod = __import__(module, globals(), locals(), [attr]) except ImportError, e: raise Exception, 'Error importing engagement function %s: "%s"' % (module, e) try: func = getattr(mod, attr) except AttributeError: raise Exception, 'Module "%s does not define a "%s" attribute' % (module, attr) return func
Fix typos in exception messages and use less specific exception in management commands.
Fix typos in exception messages and use less specific exception in management commands.
Python
bsd-3-clause
e-loue/django-lean,MontmereLimited/django-lean,MontmereLimited/django-lean,uhuramedia/django-lean,MontmereLimited/django-lean,uhuramedia/django-lean,e-loue/django-lean,uhuramedia/django-lean
--- +++ @@ -29,9 +29,9 @@ try: mod = __import__(module, globals(), locals(), [attr]) except ImportError, e: - raise ImproperlyConfigured, 'Error importing template source loader %s: "%s"' % (module, e) + raise Exception, 'Error importing engagement function %s: "%s"' % (module, e) try: func = getattr(mod, attr) except AttributeError: - raise ImproperlyConfigured, 'Module "%s" does not define a "%s" callable template source loader' % (module, attr) + raise Exception, 'Module "%s does not define a "%s" attribute' % (module, attr) return func
a1e6da688cc41f0dc4a22e546d076358bd626990
billjobs/tests/tests_export_account_email.py
billjobs/tests/tests_export_account_email.py
from django.test import TestCase from django.contrib.admin.sites import AdminSite from billjobs.admin import UserAdmin class EmailExportTestCase(TestCase): """ Tests for email account export """ def test_method_is_avaible(self): """ Test admin can select the action in dropdown list """ self.assertTrue(hasattr(UserAdmin, 'export_email'))
from django.test import TestCase from django.contrib.admin.sites import AdminSite from billjobs.admin import UserAdmin class EmailExportTestCase(TestCase): """ Tests for email account export """ def test_method_is_avaible(self): """ Test admin can select the action in dropdown list """ self.assertTrue(hasattr(UserAdmin, 'export_email')) def test_method_is_model_admin_action(self): """ Test method is an custom action for user admin """ self.assertTrue('export_email' in UserAdmin.actions)
Test modelAdmin actions is present
Test modelAdmin actions is present
Python
mit
ioO/billjobs
--- +++ @@ -9,3 +9,6 @@ """ Test admin can select the action in dropdown list """ self.assertTrue(hasattr(UserAdmin, 'export_email')) + def test_method_is_model_admin_action(self): + """ Test method is an custom action for user admin """ + self.assertTrue('export_email' in UserAdmin.actions)
055fa862e09c1a7c215e26034ad9da5998d90d0f
wafer/sponsors/templatetags/sponsors.py
wafer/sponsors/templatetags/sponsors.py
from django import template from wafer.sponsors.models import Sponsor, SponsorshipPackage register = template.Library() @register.inclusion_tag('wafer.sponsors/sponsors_block.html') def sponsors(): return { 'sponsors': Sponsor.objects.all().order_by('packages'), 'packages': SponsorshipPackage.objects.all().prefetch_related('files'), }
from django import template from wafer.sponsors.models import Sponsor, SponsorshipPackage register = template.Library() @register.inclusion_tag('wafer.sponsors/sponsors_block.html') def sponsors(): return { 'sponsors': Sponsor.objects.all().order_by('packages'), 'packages': SponsorshipPackage.objects.all().prefetch_related('files'), } # We use assignment_tag for compatibility with Django 1.8 # Once we drop 1.8 support, we should change this to # simple_tag @register.assignment_tag(takes_context=True) def sponsor_image_url(context, name): """Returns the corresponding url from the sponsors images""" sponsor = context['sponsor'] if sponsor.files.filter(name=name).exists(): # We avoid worrying about multiple matches by always # returning the first one. return sponsor.files.filter(name=name).first().item.url return ''
Add template tag to look up sponsor images
Add template tag to look up sponsor images
Python
isc
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
--- +++ @@ -11,3 +11,17 @@ 'sponsors': Sponsor.objects.all().order_by('packages'), 'packages': SponsorshipPackage.objects.all().prefetch_related('files'), } + + +# We use assignment_tag for compatibility with Django 1.8 +# Once we drop 1.8 support, we should change this to +# simple_tag +@register.assignment_tag(takes_context=True) +def sponsor_image_url(context, name): + """Returns the corresponding url from the sponsors images""" + sponsor = context['sponsor'] + if sponsor.files.filter(name=name).exists(): + # We avoid worrying about multiple matches by always + # returning the first one. + return sponsor.files.filter(name=name).first().item.url + return ''
a703c68738385319b714b94ada39f847568b9d36
django_evolution/utils.py
django_evolution/utils.py
from django_evolution.db import evolver def write_sql(sql): "Output a list of SQL statements, unrolling parameters as required" for statement in sql: if isinstance(statement, tuple): print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1])) else: print unicode(statement) def execute_sql(cursor, sql): """ Execute a list of SQL statements on the provided cursor, unrolling parameters as required """ for statement in sql: if isinstance(statement, tuple): if not statement[0].startswith('--'): cursor.execute(*statement) else: if not statement.startswith('--'): try: cursor.execute(statement) except: print statement print sql raise Exception(statement)
from django_evolution.db import evolver def write_sql(sql): "Output a list of SQL statements, unrolling parameters as required" for statement in sql: if isinstance(statement, tuple): print unicode(statement[0] % tuple(evolver.quote_sql_param(s) for s in statement[1])) else: print unicode(statement) def execute_sql(cursor, sql): """ Execute a list of SQL statements on the provided cursor, unrolling parameters as required """ for statement in sql: if isinstance(statement, tuple): if not statement[0].startswith('--'): cursor.execute(*statement) else: if not statement.startswith('--'): cursor.execute(statement)
Revert a debugging change that slipped in.
Revert a debugging change that slipped in.
Python
bsd-3-clause
beanbaginc/django-evolution
--- +++ @@ -19,9 +19,4 @@ cursor.execute(*statement) else: if not statement.startswith('--'): - try: - cursor.execute(statement) - except: - print statement - print sql - raise Exception(statement) + cursor.execute(statement)
384e2fd9ae794e182dfdf4072d2689cff5f5d91d
log4django/routers.py
log4django/routers.py
from .settings import CONNECTION_NAME class Log4DjangoRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'log4django': return CONNECTION_NAME return None def db_for_write(self, model, **hints): if model._meta.app_label == 'log4django': return CONNECTION_NAME return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'log4django' or obj2._meta.app_label == 'log4django': return True return None def allow_syncdb(self, db, model): if db == CONNECTION_NAME: return model._meta.app_label == 'log4django' elif model._meta.app_label == 'log4django': return False return None
from .settings import CONNECTION_NAME class Log4DjangoRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'log4django': return CONNECTION_NAME return None def db_for_write(self, model, **hints): if model._meta.app_label == 'log4django': return CONNECTION_NAME return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'log4django' or obj2._meta.app_label == 'log4django': return True return None def allow_syncdb(self, db, model): if db == CONNECTION_NAME and model._meta.app_label == 'log4django': return True return None
Fix syncdb in database router
Fix syncdb in database router
Python
bsd-3-clause
CodeScaleInc/log4django,CodeScaleInc/log4django,CodeScaleInc/log4django
--- +++ @@ -18,8 +18,6 @@ return None def allow_syncdb(self, db, model): - if db == CONNECTION_NAME: - return model._meta.app_label == 'log4django' - elif model._meta.app_label == 'log4django': - return False + if db == CONNECTION_NAME and model._meta.app_label == 'log4django': + return True return None
97c6ea1cbbbe142b1005fb741ba1a0205a45189a
basket/news/tests/test_middleware.py
basket/news/tests/test_middleware.py
from basket.news.middleware import is_ip_address def test_is_ip_address(): assert is_ip_address('1.2.3.4') assert is_ip_address('192.168.1.1') assert not is_ip_address('basket.mozilla.org') assert not is_ip_address('42.basket.mozilla.org')
from django.test import RequestFactory, override_settings from mock import Mock from basket.news.middleware import EnforceHostnameMiddleware, is_ip_address def test_is_ip_address(): assert is_ip_address('1.2.3.4') assert is_ip_address('192.168.1.1') assert not is_ip_address('basket.mozilla.org') assert not is_ip_address('42.basket.mozilla.org') @override_settings(DEBUG=False, ENFORCE_HOSTNAME=['basket.mozilla.org']) def test_enforce_hostname_middleware(): get_resp_mock = Mock() mw = EnforceHostnameMiddleware(get_resp_mock) req = RequestFactory().get('/', HTTP_HOST='basket.mozilla.org') resp = mw(req) get_resp_mock.assert_called_once_with(req) get_resp_mock.reset_mock() req = RequestFactory().get('/', HTTP_HOST='basket.allizom.org') resp = mw(req) get_resp_mock.assert_not_called() assert resp.status_code == 301 assert resp['location'] == 'http://basket.mozilla.org/' # IP address should not redirect get_resp_mock.reset_mock() req = RequestFactory().get('/', HTTP_HOST='123.123.123.123') resp = mw(req) get_resp_mock.assert_called_once_with(req) # IP with port should also work get_resp_mock.reset_mock() req = RequestFactory().get('/', HTTP_HOST='1.2.3.4:12345') resp = mw(req) get_resp_mock.assert_called_once_with(req)
Add tests for enforce hostname middleware
Add tests for enforce hostname middleware
Python
mpl-2.0
glogiotatidis/basket,glogiotatidis/basket,glogiotatidis/basket
--- +++ @@ -1,4 +1,8 @@ -from basket.news.middleware import is_ip_address +from django.test import RequestFactory, override_settings + +from mock import Mock + +from basket.news.middleware import EnforceHostnameMiddleware, is_ip_address def test_is_ip_address(): @@ -6,3 +10,31 @@ assert is_ip_address('192.168.1.1') assert not is_ip_address('basket.mozilla.org') assert not is_ip_address('42.basket.mozilla.org') + + +@override_settings(DEBUG=False, ENFORCE_HOSTNAME=['basket.mozilla.org']) +def test_enforce_hostname_middleware(): + get_resp_mock = Mock() + mw = EnforceHostnameMiddleware(get_resp_mock) + req = RequestFactory().get('/', HTTP_HOST='basket.mozilla.org') + resp = mw(req) + get_resp_mock.assert_called_once_with(req) + + get_resp_mock.reset_mock() + req = RequestFactory().get('/', HTTP_HOST='basket.allizom.org') + resp = mw(req) + get_resp_mock.assert_not_called() + assert resp.status_code == 301 + assert resp['location'] == 'http://basket.mozilla.org/' + + # IP address should not redirect + get_resp_mock.reset_mock() + req = RequestFactory().get('/', HTTP_HOST='123.123.123.123') + resp = mw(req) + get_resp_mock.assert_called_once_with(req) + + # IP with port should also work + get_resp_mock.reset_mock() + req = RequestFactory().get('/', HTTP_HOST='1.2.3.4:12345') + resp = mw(req) + get_resp_mock.assert_called_once_with(req)
df01d83a35c59ee2295b358d8eceeb842adb568d
listings/admin.py
listings/admin.py
from django.contrib import admin from .models import Region, City, GatheringCenter, Resource admin.site.register(Region) admin.site.register(City) class PublishMixin(object): actions = ('publish', 'unpublish') def publish(self, request, queryset): queryset.update(published=True) def unpublish(self, request, queryset): queryset.update(published=False) class GatheringCenterAdmin(PublishMixin, admin.ModelAdmin): list_filter = ('published', 'city', 'created') list_editable = ('published', ) list_display = ('location_name', 'created', 'published', 'author', 'city') raw_id_fields = ('author', ) admin.site.register(GatheringCenter, GatheringCenterAdmin) class ResourceAdmin(PublishMixin, admin.ModelAdmin): list_filter = ('published', 'created') list_editable = ('published', ) list_display = ('name', 'created', 'published', 'author', 'url', 'country') raw_id_fields = ('author', ) admin.site.register(Resource, ResourceAdmin)
from django.contrib import admin from .models import Region, City, GatheringCenter, Resource admin.site.register(Region) admin.site.register(City) class PublishMixin(object): actions = ('publish', 'unpublish') def publish(self, request, queryset): queryset.update(published=True) def unpublish(self, request, queryset): queryset.update(published=False) class GatheringCenterAdmin(PublishMixin, admin.ModelAdmin): date_hierarchy = 'created' list_filter = ('published', 'city', ) list_editable = ('published', ) list_display = ('location_name', 'created', 'published', 'author', 'city') raw_id_fields = ('author', ) admin.site.register(GatheringCenter, GatheringCenterAdmin) class ResourceAdmin(PublishMixin, admin.ModelAdmin): date_hierarchy = 'created' list_filter = ('published', ) list_editable = ('published', ) list_display = ('name', 'created', 'published', 'author', 'url', 'country') raw_id_fields = ('author', ) admin.site.register(Resource, ResourceAdmin)
Order by create, don't filter
Order by create, don't filter
Python
apache-2.0
pony-revolution/helpothers,pony-revolution/helpothers,pony-revolution/helpothers
--- +++ @@ -17,7 +17,8 @@ class GatheringCenterAdmin(PublishMixin, admin.ModelAdmin): - list_filter = ('published', 'city', 'created') + date_hierarchy = 'created' + list_filter = ('published', 'city', ) list_editable = ('published', ) list_display = ('location_name', 'created', 'published', 'author', 'city') raw_id_fields = ('author', ) @@ -26,7 +27,8 @@ class ResourceAdmin(PublishMixin, admin.ModelAdmin): - list_filter = ('published', 'created') + date_hierarchy = 'created' + list_filter = ('published', ) list_editable = ('published', ) list_display = ('name', 'created', 'published', 'author', 'url', 'country') raw_id_fields = ('author', )
6758a6f3f62441d21747d1faedb45fc059dc37dc
models/product.py
models/product.py
from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from models.base import Base from models.user import User from models.store import Store class Product(Base): __tablename__ = "product" __table_args__ = {'sqlite_autoincrement': True} id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) category = Column(String(80), nullable=False) description = Column(String(250)) price = Column(String(10)) store_id = Column(Integer, ForeignKey('store.id')) store = relationship(Store) user_id = Column(Integer, ForeignKey('user.id')) user = relationship(User) @property def serialize(self): """Return product type object data in easily serializeable format""" return { 'id': self.id, 'name': self.name, 'category': self.category, 'description': self.description, 'price': self.price, 'store': self.store_id, 'user': self.user_id, }
from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from models.base import Base from models.user import User from models.store import Store class Product(Base): __tablename__ = "product" __table_args__ = {'sqlite_autoincrement': True} id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) category = Column(String(80), nullable=False) description = Column(String(2000)) price = Column(String(10)) store_id = Column(Integer, ForeignKey('store.id')) store = relationship(Store) user_id = Column(Integer, ForeignKey('user.id')) user = relationship(User) @property def serialize(self): """Return product type object data in easily serializeable format""" return { 'id': self.id, 'name': self.name, 'category': self.category, 'description': self.description, 'price': self.price, 'store': self.store_id, 'user': self.user_id, }
Correct the character limit for descriptions
bug: Correct the character limit for descriptions
Python
mit
caasted/aws-flask-catalog-app,caasted/aws-flask-catalog-app
--- +++ @@ -12,7 +12,7 @@ id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) category = Column(String(80), nullable=False) - description = Column(String(250)) + description = Column(String(2000)) price = Column(String(10)) store_id = Column(Integer, ForeignKey('store.id')) store = relationship(Store)
19ce87dd98c65338a35a4f81c3210745d330fc4c
data/tests/test_data.py
data/tests/test_data.py
from __future__ import absolute_import, division, print_function import os, sys, tempfile sys.path.append("data/") import data try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen def test_check_hashes(): with tempfile.NamedTemporaryFile() as temp: temp.write(b'Some data') temp.flush() fname = temp.name d = {fname: "5b82f8bf4df2bfb0e66ccaa7306fd024"} assert data.check_hashes(d) d = {fname: "4b82f8bf4df2bfb0e66ccaa7306fd024"} assert not data.check_hashes(d) def test_make_hash_dict(): l = "http://www.jarrodmillman.com/rcsds/_downloads/ds107_sub001_highres.nii" with open("ds107_sub001_highres.nii", 'wb') as outfile: outfile.write(urlopen(l).read()) hash_O = data.make_hash_dict(".")["./ds107_sub001_highres.nii"] hash_E = "fd733636ae8abe8f0ffbfadedd23896c" assert hash_O == hash_E os.remove("ds107_sub001_highres.nii")
from __future__ import absolute_import, division, print_function import os, sys, tempfile from data import data try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen def test_check_hashes(): with tempfile.NamedTemporaryFile() as temp: temp.write(b'Some data') temp.flush() fname = temp.name d = {fname: "5b82f8bf4df2bfb0e66ccaa7306fd024"} assert data.check_hashes(d) d = {fname: "4b82f8bf4df2bfb0e66ccaa7306fd024"} assert not data.check_hashes(d) def test_make_hash_dict(): l = "http://www.jarrodmillman.com/rcsds/_downloads/ds107_sub001_highres.nii" with open("ds107_sub001_highres.nii", 'wb') as outfile: outfile.write(urlopen(l).read()) hash_O = data.make_hash_dict(".")["./ds107_sub001_highres.nii"] hash_E = "fd733636ae8abe8f0ffbfadedd23896c" assert hash_O == hash_E os.remove("ds107_sub001_highres.nii")
Fix build exitting from make coverage
Fix build exitting from make coverage
Python
bsd-3-clause
berkeley-stat159/project-delta
--- +++ @@ -1,8 +1,7 @@ from __future__ import absolute_import, division, print_function import os, sys, tempfile -sys.path.append("data/") -import data +from data import data try: from urllib.request import urlopen
d13896e05922d6d57e552719963e6918cef981d0
democracylab/logging.py
democracylab/logging.py
import copy import logging import traceback def dump(obj): for attr in dir(obj): print("obj.%s = %r" % (attr, getattr(obj, attr))) def dump_request_summary(request): user = request.user.username if request.user.is_authenticated() else '' url = request.path method = request.method body = censor_sensitive_fields(dict(getattr(request, method))) return '({user}) {method} {url} {body}'.format(user=user, url=url, method=method, body=body) sensitive_fields = ['password', 'password1', 'password2'] def censor_sensitive_fields(fields_dict): fields_copy = copy.deepcopy(fields_dict) for field in sensitive_fields: if field in fields_copy: censored_length = len(fields_copy[field][0]) fields_copy[field][0] = '*' * censored_length return fields_copy class CustomErrorHandler(logging.Handler): def emit(self, record): exception_info = traceback.format_exc() request_info = dump_request_summary(record.request) print('ERROR: {exception_info} REQUEST: {request_info}'.format(exception_info=exception_info, request_info=request_info))
import copy import logging import traceback def dump(obj): for attr in dir(obj): print("obj.%s = %r" % (attr, getattr(obj, attr))) def dump_request_summary(request): user = request.user.username if request.user.is_authenticated() else '' url = request.path method = request.method body = censor_sensitive_fields(dict(getattr(request, method))) return '({user}) {method} {url} {body}'.format(user=user, url=url, method=method, body=body) sensitive_fields = ['password', 'password1', 'password2'] def censor_sensitive_fields(fields_dict): fields_copy = copy.deepcopy(fields_dict) for field in sensitive_fields: if field in fields_copy: censored_length = len(fields_copy[field][0]) fields_copy[field][0] = '*' * censored_length return fields_copy class CustomErrorHandler(logging.Handler): def emit(self, record): error_msg = 'ERROR: {}'.format(traceback.format_exc()) if hasattr(record, 'request'): error_msg += ' REQUEST: {}'.format(dump_request_summary(record.request)) print(error_msg)
Fix django logger issue when error has no attached request object
Fix django logger issue when error has no attached request object
Python
mit
DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange
--- +++ @@ -13,7 +13,9 @@ url = request.path method = request.method body = censor_sensitive_fields(dict(getattr(request, method))) + return '({user}) {method} {url} {body}'.format(user=user, url=url, method=method, body=body) + sensitive_fields = ['password', 'password1', 'password2'] @@ -30,6 +32,7 @@ class CustomErrorHandler(logging.Handler): def emit(self, record): - exception_info = traceback.format_exc() - request_info = dump_request_summary(record.request) - print('ERROR: {exception_info} REQUEST: {request_info}'.format(exception_info=exception_info, request_info=request_info)) + error_msg = 'ERROR: {}'.format(traceback.format_exc()) + if hasattr(record, 'request'): + error_msg += ' REQUEST: {}'.format(dump_request_summary(record.request)) + print(error_msg)
cdef62151437e9bf1187b955ad212d9d32e007e3
django_olcc/olcc/api.py
django_olcc/olcc/api.py
from tastypie.resources import ModelResource from olcc.models import Product, ProductPrice, Store class ProductResource(ModelResource): class Meta: queryset = Product.objects.all() resource_name = 'product' class ProductPriceResource(ModelResource): class Meta: queryset = ProductPrice.objects.all() resource_name = 'price' class StoreResource(ModelResource): class Meta: queryset = Store.objects.all() resource_name = 'store'
from tastypie import fields from tastypie.resources import ModelResource, ALL from olcc.models import Product, ProductPrice, Store class ProductResource(ModelResource): class Meta: queryset = Product.objects.all() resource_name = 'product' allowed_methods = ['get'] filtering = { 'title': ALL, 'code': ALL, 'proof': ALL, 'size': ALL, 'status': ALL, 'on_sale': ALL, } class ProductPriceResource(ModelResource): product = fields.ToOneField(ProductResource, 'product') class Meta: queryset = ProductPrice.objects.all() resource_name = 'price' allowed_methods = ['get'] filtering = { 'product': ['exact'], } class StoreResource(ModelResource): class Meta: queryset = Store.objects.all() resource_name = 'store' allowed_methods = ['get']
Tweak the tastypie resource configuration.
Tweak the tastypie resource configuration.
Python
mit
twaddington/django-olcc,twaddington/django-olcc,twaddington/django-olcc
--- +++ @@ -1,17 +1,34 @@ -from tastypie.resources import ModelResource +from tastypie import fields +from tastypie.resources import ModelResource, ALL from olcc.models import Product, ProductPrice, Store class ProductResource(ModelResource): class Meta: queryset = Product.objects.all() resource_name = 'product' + allowed_methods = ['get'] + filtering = { + 'title': ALL, + 'code': ALL, + 'proof': ALL, + 'size': ALL, + 'status': ALL, + 'on_sale': ALL, + } class ProductPriceResource(ModelResource): + product = fields.ToOneField(ProductResource, 'product') + class Meta: queryset = ProductPrice.objects.all() resource_name = 'price' + allowed_methods = ['get'] + filtering = { + 'product': ['exact'], + } class StoreResource(ModelResource): class Meta: queryset = Store.objects.all() resource_name = 'store' + allowed_methods = ['get']
c3a6554ce24781a3eaa9229f9609a09e4e018069
lcd_restful/__main__.py
lcd_restful/__main__.py
#!/usr/bin/env python import sys from getopt import getopt, GetoptError from .api import Server from .fake import FakeLcdApi USAGE = """\ Usage %s [-h|--help] \t-h or --help\tThis help message """ def get_args(args): try: opts, args = getopt(args[1:], 'hf', ['help', 'fake']) except GetoptError as e: print('GetoptError %s' % e) sys.exit(2) ret_args = {} ret_args['fake'] = False for opt, arg in opts: if opt in ['-h', '--help']: print(USAGE % args[0]) sys.exit(0) elif opt in ['-f', '--fake']: ret_args['fake'] = True else: print(USAGE % args[0]) sys.exit(1) return ret_args def main_serv(clargs=sys.argv): opts = get_args(clargs) lcd = None if opts['fake']: lcd = FakeLcdApi() s = Server(lcd=lcd) s.run() return 0 if __name__ == "__main__": sys.exit(main_serv())
#!/usr/bin/env python import sys from getopt import getopt, GetoptError from .api import Server from .lcd import Lcd USAGE = """\ Usage %s [-h|--help] [-f|--fake] \t-h or --help\tThis help message \t-f or --fake\tIf on RPi, use FakeHw """ def get_args(args): arg0 = args[0] try: opts, args = getopt(args[1:], 'hf', ['help', 'fake']) except GetoptError as e: print('GetoptError %s' % e) sys.exit(2) ret_args = {} ret_args['fake'] = False for opt, arg in opts: if opt in ['-h', '--help']: print(USAGE % arg0) sys.exit(0) elif opt in ['-f', '--fake']: ret_args['fake'] = True else: print(USAGE % arg0) sys.exit(1) return ret_args def main_serv(clargs=sys.argv): opts = get_args(clargs) s = Server(lcd=Lcd(opts['fake'])) s.run() return 0 if __name__ == "__main__": sys.exit(main_serv())
Update main Lcd import and init, and fix help msg
Update main Lcd import and init, and fix help msg
Python
mit
rfarley3/lcd-restful,rfarley3/lcd-restful
--- +++ @@ -2,17 +2,19 @@ import sys from getopt import getopt, GetoptError from .api import Server -from .fake import FakeLcdApi +from .lcd import Lcd USAGE = """\ -Usage %s [-h|--help] +Usage %s [-h|--help] [-f|--fake] \t-h or --help\tThis help message +\t-f or --fake\tIf on RPi, use FakeHw """ def get_args(args): + arg0 = args[0] try: opts, args = getopt(args[1:], 'hf', ['help', 'fake']) except GetoptError as e: @@ -22,25 +24,23 @@ ret_args['fake'] = False for opt, arg in opts: if opt in ['-h', '--help']: - print(USAGE % args[0]) + print(USAGE % arg0) sys.exit(0) elif opt in ['-f', '--fake']: ret_args['fake'] = True else: - print(USAGE % args[0]) + print(USAGE % arg0) sys.exit(1) return ret_args def main_serv(clargs=sys.argv): opts = get_args(clargs) - lcd = None - if opts['fake']: - lcd = FakeLcdApi() - s = Server(lcd=lcd) + s = Server(lcd=Lcd(opts['fake'])) s.run() return 0 if __name__ == "__main__": sys.exit(main_serv()) +
172175811e6532d23586e54c5b48032e52745f35
fjord/api_auth/migrations/0001_initial.py
fjord/api_auth/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Token', fields=[ ('token', models.CharField(help_text='API token to use for authentication. When creating a new token, leave this blank. Click on SAVE AND CONTINUE EDITING. The token will be generated and you can copy and paste it.', max_length=32, serialize=False, primary_key=True)), ('summary', models.CharField(help_text='Brief explanation of what will use this token', max_length=200)), ('enabled', models.BooleanField(default=False)), ('disabled_reason', models.TextField(default='', help_text='If disabled, explanation of why.', blank=True)), ('contact', models.CharField(default='', help_text='Contact information for what uses this token. Email address, etc', max_length=200, blank=True)), ('created', models.DateTimeField(auto_now_add=True)), ], options={ }, bases=(models.Model,), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Token', fields=[ ('token', models.CharField(help_text='API token to use for authentication. Click on SAVE AND CONTINUE EDITING. The token will be generated and you can copy and paste it.', max_length=32, serialize=False, primary_key=True)), ('summary', models.CharField(help_text='Brief explanation of what will use this token', max_length=200)), ('enabled', models.BooleanField(default=False)), ('disabled_reason', models.TextField(default='', help_text='If disabled, explanation of why.', blank=True)), ('contact', models.CharField(default='', help_text='Contact information for what uses this token. Email address, etc', max_length=200, blank=True)), ('created', models.DateTimeField(auto_now_add=True)), ], options={ }, bases=(models.Model,), ), ]
Update help_text in api_auth initial migration
Update help_text in api_auth initial migration I'm updating the help_text in the original migration rather than creating a new migration that doesn't affect the db, but does do a bunch of SQL stuff in the migration.
Python
bsd-3-clause
hoosteeno/fjord,staranjeet/fjord,rlr/fjord,mozilla/fjord,lgp171188/fjord,rlr/fjord,rlr/fjord,Ritsyy/fjord,mozilla/fjord,Ritsyy/fjord,staranjeet/fjord,staranjeet/fjord,staranjeet/fjord,lgp171188/fjord,lgp171188/fjord,mozilla/fjord,hoosteeno/fjord,hoosteeno/fjord,Ritsyy/fjord,lgp171188/fjord,mozilla/fjord,rlr/fjord,hoosteeno/fjord,Ritsyy/fjord
--- +++ @@ -13,7 +13,7 @@ migrations.CreateModel( name='Token', fields=[ - ('token', models.CharField(help_text='API token to use for authentication. When creating a new token, leave this blank. Click on SAVE AND CONTINUE EDITING. The token will be generated and you can copy and paste it.', max_length=32, serialize=False, primary_key=True)), + ('token', models.CharField(help_text='API token to use for authentication. Click on SAVE AND CONTINUE EDITING. The token will be generated and you can copy and paste it.', max_length=32, serialize=False, primary_key=True)), ('summary', models.CharField(help_text='Brief explanation of what will use this token', max_length=200)), ('enabled', models.BooleanField(default=False)), ('disabled_reason', models.TextField(default='', help_text='If disabled, explanation of why.', blank=True)),
596a29505351ec0e497cbe114a6e4d57d7cbada6
backoff/__init__.py
backoff/__init__.py
# coding:utf-8 """ Function decoration for backoff and retry This module provides function decorators which can be used to wrap a function such that it will be retried until some condition is met. It is meant to be of use when accessing unreliable resources with the potential for intermittent failures i.e. network resources and external APIs. Somewhat more generally, it may also be of use for dynamically polling resources for externally generated content. For examples and full documentation see the README at https://github.com/litl/backoff """ from backoff._decorator import on_predicate, on_exception from backoff._jitter import full_jitter, random_jitter from backoff._wait_gen import constant, expo, fibo, runtime __all__ = [ 'on_predicate', 'on_exception', 'constant', 'expo', 'fibo', 'runtime', 'full_jitter', 'random_jitter', ] __version__ = '2.1.0'
# coding:utf-8 """ Function decoration for backoff and retry This module provides function decorators which can be used to wrap a function such that it will be retried until some condition is met. It is meant to be of use when accessing unreliable resources with the potential for intermittent failures i.e. network resources and external APIs. Somewhat more generally, it may also be of use for dynamically polling resources for externally generated content. For examples and full documentation see the README at https://github.com/litl/backoff """ import importlib.metadata from backoff._decorator import on_exception, on_predicate from backoff._jitter import full_jitter, random_jitter from backoff._wait_gen import constant, expo, fibo, runtime __all__ = [ 'on_predicate', 'on_exception', 'constant', 'expo', 'fibo', 'runtime', 'full_jitter', 'random_jitter', ] __version__ = importlib.metadata.version("backoff")
Use importlib.metadata to set __version__
Use importlib.metadata to set __version__ This way we don't have to remember to update the version in two places every release. The version will only need to be set in pyproject.toml
Python
mit
litl/backoff
--- +++ @@ -12,7 +12,9 @@ For examples and full documentation see the README at https://github.com/litl/backoff """ -from backoff._decorator import on_predicate, on_exception +import importlib.metadata + +from backoff._decorator import on_exception, on_predicate from backoff._jitter import full_jitter, random_jitter from backoff._wait_gen import constant, expo, fibo, runtime @@ -27,4 +29,4 @@ 'random_jitter', ] -__version__ = '2.1.0' +__version__ = importlib.metadata.version("backoff")
2c8dafec701d80ddd9a3d1855a14a8eef0c44790
tests/modules/contrib/test_network_traffic.py
tests/modules/contrib/test_network_traffic.py
import pytest pytest.importorskip("psutil") pytest.importorskip("netifaces") def test_load_module(): __import__("modules.contrib.network_traffic")
import pytest from unittest import TestCase, mock import core.config import core.widget import modules.contrib.network_traffic from types import SimpleNamespace pytest.importorskip("psutil") pytest.importorskip("netifaces") def io_counters_mock(recv, sent): return { 'lo': SimpleNamespace( bytes_sent = sent, bytes_recv = recv ) } def gateways_response(): return { 'default': { 1: ('10.0.0.10', 'lo') } } def build_module(): return modules.contrib.network_traffic.Module(config=core.config.Config([]), theme=None) class TestNetworkTrafficUnit(TestCase): def test_load_module(self): __import__("modules.contrib.network_traffic") @mock.patch('psutil.net_io_counters') @mock.patch('netifaces.gateways') @mock.patch('netifaces.AF_INET', 1) def test_update_rates(self, gateways_mock, net_io_counters_mock): net_io_counters_mock.return_value = io_counters_mock(0, 0) gateways_mock.return_value = gateways_response() module = build_module() net_io_counters_mock.return_value = io_counters_mock(2842135, 1932215) module.update() assert module.widgets()[1].full_text() == '1.84MiB/s' assert module.widgets()[0].full_text() == '2.71MiB/s' def test_initial_download_rate(self): module = build_module() assert module.widgets()[0].full_text() == '0.00B/s' def test_initial_upload_rate(self): module = build_module() assert module.widgets()[1].full_text() == '0.00B/s'
Add Network Traffic module tests
Add Network Traffic module tests
Python
mit
tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status
--- +++ @@ -1,9 +1,57 @@ import pytest +from unittest import TestCase, mock + +import core.config +import core.widget +import modules.contrib.network_traffic + +from types import SimpleNamespace pytest.importorskip("psutil") - pytest.importorskip("netifaces") -def test_load_module(): - __import__("modules.contrib.network_traffic") +def io_counters_mock(recv, sent): + return { + 'lo': SimpleNamespace( + bytes_sent = sent, + bytes_recv = recv + ) + } +def gateways_response(): + return { + 'default': { + 1: ('10.0.0.10', 'lo') + } + } + +def build_module(): + return modules.contrib.network_traffic.Module(config=core.config.Config([]), theme=None) + +class TestNetworkTrafficUnit(TestCase): + def test_load_module(self): + __import__("modules.contrib.network_traffic") + + @mock.patch('psutil.net_io_counters') + @mock.patch('netifaces.gateways') + @mock.patch('netifaces.AF_INET', 1) + def test_update_rates(self, gateways_mock, net_io_counters_mock): + net_io_counters_mock.return_value = io_counters_mock(0, 0) + gateways_mock.return_value = gateways_response() + + module = build_module() + + net_io_counters_mock.return_value = io_counters_mock(2842135, 1932215) + module.update() + + assert module.widgets()[1].full_text() == '1.84MiB/s' + assert module.widgets()[0].full_text() == '2.71MiB/s' + + def test_initial_download_rate(self): + module = build_module() + assert module.widgets()[0].full_text() == '0.00B/s' + + def test_initial_upload_rate(self): + module = build_module() + assert module.widgets()[1].full_text() == '0.00B/s' +
7c494c9216247d4480f2b293947b75947b1fcb01
readme_renderer/__main__.py
readme_renderer/__main__.py
from __future__ import absolute_import, print_function from readme_renderer.rst import render import sys if len(sys.argv) == 2: with open(sys.argv[1]) as fp: out = render(fp.read(), stream=sys.stderr) if out is not None: print(out) else: sys.exit(1) else: print("Syntax: python -m readme_renderer <file.rst>", file=sys.stderr)
from __future__ import absolute_import, print_function import argparse from readme_renderer.rst import render import sys if __name__ == '__main__': parser = argparse.ArgumentParser( description="Renders a .rst README to HTML", ) parser.add_argument('input', help="Input README file") parser.add_argument('-o', '--output', help="Output file (default: stdout)") args = parser.parse_args() if args.output: output_file = open(args.output, 'w') else: output_file = sys.stdout input_file = open(args.input) rendered = render(input_file.read(), stream=sys.stderr) if rendered is None: sys.exit(1) print(rendered, file=output_file)
Use `if __name__` and argparse
Use `if __name__` and argparse
Python
apache-2.0
pypa/readme_renderer,pypa/readme
--- +++ @@ -1,14 +1,23 @@ from __future__ import absolute_import, print_function +import argparse from readme_renderer.rst import render import sys -if len(sys.argv) == 2: - with open(sys.argv[1]) as fp: - out = render(fp.read(), stream=sys.stderr) - if out is not None: - print(out) - else: - sys.exit(1) -else: - print("Syntax: python -m readme_renderer <file.rst>", file=sys.stderr) +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="Renders a .rst README to HTML", + ) + parser.add_argument('input', help="Input README file") + parser.add_argument('-o', '--output', help="Output file (default: stdout)") + args = parser.parse_args() + if args.output: + output_file = open(args.output, 'w') + else: + output_file = sys.stdout + input_file = open(args.input) + + rendered = render(input_file.read(), stream=sys.stderr) + if rendered is None: + sys.exit(1) + print(rendered, file=output_file)
4a8292f2c01323743cc41cbff4c9dfe0e4203f25
comics/accounts/models.py
comics/accounts/models.py
import uuid from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): UserProfile.objects.get_or_create(user=instance) class UserProfile(models.Model): user = models.OneToOneField(User) secret_key = models.CharField(max_length=32, blank=False, help_text='Secret key for feed and API access') class Meta: db_table = 'comics_user_profile' def __init__(self, *args, **kwargs): super(UserProfile, self).__init__(*args, **kwargs) self.generate_new_secret_key() def __unicode__(self): return u'User profile for %s' % self.user def generate_new_secret_key(self): self.secret_key = uuid.uuid4().hex
import uuid from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) class UserProfile(models.Model): user = models.OneToOneField(User) secret_key = models.CharField(max_length=32, blank=False, help_text='Secret key for feed and API access') class Meta: db_table = 'comics_user_profile' def __init__(self, *args, **kwargs): super(UserProfile, self).__init__(*args, **kwargs) self.generate_new_secret_key() def __unicode__(self): return u'User profile for %s' % self.user def generate_new_secret_key(self): self.secret_key = uuid.uuid4().hex
Remove conditional sql-select on new user creation
Remove conditional sql-select on new user creation Only create a user profile if a new user is actually created.
Python
agpl-3.0
datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics
--- +++ @@ -7,8 +7,8 @@ @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): - UserProfile.objects.get_or_create(user=instance) - + if created: + UserProfile.objects.create(user=instance) class UserProfile(models.Model): user = models.OneToOneField(User)
7443217044931466618e4ed8065b03dd7c08b05d
integration-test/990-add-art-galleries.py
integration-test/990-add-art-galleries.py
# http://www.openstreetmap.org/node/2026996113 assert_has_feature( 16, 10485, 25328, 'pois', { 'id': 2026996113, 'kind': 'gallery', 'min_zoom': 17 }) # http://www.openstreetmap.org/way/31510288 assert_has_feature( 15, 16371, 10895, 'pois', { 'id': 31510288, 'kind': 'gallery' })
# http://www.openstreetmap.org/node/2026996113 assert_has_feature( 16, 10485, 25328, 'pois', { 'id': 2026996113, 'kind': 'gallery', 'min_zoom': 17 }) # https://www.openstreetmap.org/way/83488820 assert_has_feature( 15, 16370, 10894, 'pois', { 'id': 83488820, 'kind': 'gallery' })
Update tests to deal with changeset 41943013, in which the Royal Academy of Arts was changed to a museum.
Update tests to deal with changeset 41943013, in which the Royal Academy of Arts was changed to a museum.
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
--- +++ @@ -3,7 +3,7 @@ 16, 10485, 25328, 'pois', { 'id': 2026996113, 'kind': 'gallery', 'min_zoom': 17 }) -# http://www.openstreetmap.org/way/31510288 +# https://www.openstreetmap.org/way/83488820 assert_has_feature( - 15, 16371, 10895, 'pois', - { 'id': 31510288, 'kind': 'gallery' }) + 15, 16370, 10894, 'pois', + { 'id': 83488820, 'kind': 'gallery' })
46f2b508eb5f4350a06bdf832c7481ad8d8aab33
node/multi_var.py
node/multi_var.py
from nodes import Node class MultiVar(Node): char = "'" args = 0 results = None contents = -1 def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle): self.node_1 = node_1 self.node_2 = node_2 self.args = max([node_1.args, node_2.args]) def prepare(self, stack): if len(stack) == 0: self.add_arg(stack) @Node.is_func def apply(self, *stack): self.node_2.prepare(stack) rtn = self.node_2(stack[:self.node_2.args]) self.node_1.prepare(stack) rtn.extend(self.node_1(stack[:self.node_1.args])) return rtn
from nodes import Node class MultiVar(Node): char = "'" args = 0 results = None contents = -1 def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle): self.node_1 = node_1 self.node_2 = node_2 def prepare(self, stack): self.node_1.prepare(stack) self.node_2.prepare(stack) self.args = max([self.node_1.args,self.node_2.args]) @Node.is_func def apply(self, *stack): rtn = self.node_2(stack[:self.node_2.args]) rtn.extend(self.node_1(stack[:self.node_1.args])) return rtn
Fix multivar for nodes with variable length stacks
Fix multivar for nodes with variable length stacks
Python
mit
muddyfish/PYKE,muddyfish/PYKE
--- +++ @@ -10,16 +10,14 @@ def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle): self.node_1 = node_1 self.node_2 = node_2 - self.args = max([node_1.args, node_2.args]) def prepare(self, stack): - if len(stack) == 0: - self.add_arg(stack) + self.node_1.prepare(stack) + self.node_2.prepare(stack) + self.args = max([self.node_1.args,self.node_2.args]) @Node.is_func def apply(self, *stack): - self.node_2.prepare(stack) rtn = self.node_2(stack[:self.node_2.args]) - self.node_1.prepare(stack) rtn.extend(self.node_1(stack[:self.node_1.args])) return rtn
b5bf3a92309dac40deefbaea555e4d96aa6bca62
jesusmtnez/python/kata/tests/test_game.py
jesusmtnez/python/kata/tests/test_game.py
import unittest from game import Game class BowlingGameTest(unittest.TestCase): def setUp(self): self.g = Game() def tearDown(self): self.g = None def test_gutter_game(self): for i in range(20): self.g.roll(0); self.assertEqual(0, self.g.score()) def test_all_ones(self): for i in range(20): self.g.roll(1) self.assertEqual(20, self.g.score()) if __name__ == '__main__': unittest.main()
import unittest from game import Game class BowlingGameTest(unittest.TestCase): def setUp(self): self.g = Game() def tearDown(self): self.g = None def _roll_many(self, n, pins): "Roll 'n' times a roll of 'pins' pins" for i in range(n): self.g.roll(pins) def test_gutter_game(self): self._roll_many(20, 0) self.assertEqual(0, self.g.score()) def test_all_ones(self): self._roll_many(20, 1) self.assertEqual(20, self.g.score()) if __name__ == '__main__': unittest.main()
Refactor for code to roll many times
[Python] Refactor for code to roll many times
Python
mit
JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge
--- +++ @@ -9,16 +9,17 @@ def tearDown(self): self.g = None + def _roll_many(self, n, pins): + "Roll 'n' times a roll of 'pins' pins" + for i in range(n): + self.g.roll(pins) + def test_gutter_game(self): - for i in range(20): - self.g.roll(0); - + self._roll_many(20, 0) self.assertEqual(0, self.g.score()) def test_all_ones(self): - for i in range(20): - self.g.roll(1) - + self._roll_many(20, 1) self.assertEqual(20, self.g.score()) if __name__ == '__main__':
17bfdbfdf56e01a1bda24dab4b2ac35f871cb4c1
bmibuilder/build.py
bmibuilder/build.py
#! /usr/bin/env python from .writers.c import CWriter def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('file', type=argparse.FileType('r'), help='YAML file') parser.add_argument('--language', choices=('c', ), default='c', help='BMI language') parser.add_argument('--clobber', action='store_true', help='overwrite any existing files') args = parser.parse_args() w = CWriter.from_file_like(args.file) w.write(clobber=args.clobber)
#! /usr/bin/env python import os from distutils.dir_util import mkpath from jinja2 import Environment, FileSystemLoader import yaml from .writers.c import CWriter YAML_TEMPLATE = """ name: <str> language: c grids: - id: <int> type: <str> rank: <int> time: units: <str> start: <float> end: <float> exchange_items: - name: <str> grid: <id> type: <str> units: <str> intent: {in, out, inout} """ TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'templates') def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('file', type=argparse.FileType('r'), help='YAML file') parser.add_argument('--language', choices=('c', 'cxx', 'python'), default='c', help='BMI language') parser.add_argument('--clobber', action='store_true', help='Overwrite any existing files.') args = parser.parse_args() path_to_templates = os.path.join(TEMPLATE_PATH, args.language) env = Environment(loader=FileSystemLoader(path_to_templates), trim_blocks=True, lstrip_blocks=True) meta = yaml.load(args.file) meta['input_vars'] = [ var for var in meta['exchange_items'] if var['intent'].startswith('in')] meta['output_vars'] = [ var for var in meta['exchange_items'] if var['intent'].endswith('out')] meta['vars'] = meta['exchange_items'] for name in env.list_templates(): base, ext = os.path.splitext(name) template = env.get_template(name) if os.path.isfile(name) and not args.clobber: print '{name}: file exists. skipping.'.format(name=name) else: mkpath(os.path.dirname(name)) with open(name, 'w') as fp: fp.write(template.render(meta))
Use new jinja templating system.
Use new jinja templating system.
Python
mit
bmi-forum/bmi-builder,bmi-forum/bmi-builder,bmi-forum/bmi-builder
--- +++ @@ -1,5 +1,34 @@ #! /usr/bin/env python +import os + +from distutils.dir_util import mkpath +from jinja2 import Environment, FileSystemLoader +import yaml + + from .writers.c import CWriter + + +YAML_TEMPLATE = """ +name: <str> +language: c +grids: + - id: <int> + type: <str> + rank: <int> +time: + units: <str> + start: <float> + end: <float> +exchange_items: + - name: <str> + grid: <id> + type: <str> + units: <str> + intent: {in, out, inout} +""" + +TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'templates') def main(): @@ -7,12 +36,30 @@ parser = argparse.ArgumentParser() parser.add_argument('file', type=argparse.FileType('r'), help='YAML file') - parser.add_argument('--language', choices=('c', ), default='c', - help='BMI language') + parser.add_argument('--language', choices=('c', 'cxx', 'python'), + default='c', help='BMI language') parser.add_argument('--clobber', action='store_true', - help='overwrite any existing files') + help='Overwrite any existing files.') args = parser.parse_args() - w = CWriter.from_file_like(args.file) - w.write(clobber=args.clobber) + path_to_templates = os.path.join(TEMPLATE_PATH, args.language) + env = Environment(loader=FileSystemLoader(path_to_templates), + trim_blocks=True, lstrip_blocks=True) + + meta = yaml.load(args.file) + meta['input_vars'] = [ + var for var in meta['exchange_items'] if var['intent'].startswith('in')] + meta['output_vars'] = [ + var for var in meta['exchange_items'] if var['intent'].endswith('out')] + meta['vars'] = meta['exchange_items'] + + for name in env.list_templates(): + base, ext = os.path.splitext(name) + template = env.get_template(name) + if os.path.isfile(name) and not args.clobber: + print '{name}: file exists. skipping.'.format(name=name) + else: + mkpath(os.path.dirname(name)) + with open(name, 'w') as fp: + fp.write(template.render(meta))
d2643bb7c4eba543da0067eb4bf82539d222845c
Lesson01_Variables/MilestonesSOLUTION.py
Lesson01_Variables/MilestonesSOLUTION.py
birth_year = raw_input("What is the birth year for the milestones?") # raw_input always gives strings, so convert to int birth_year = int(birth_year) # Calculate milestone years driving_year = birth_year + 16 drinking_year = birth_year + 21 president_year = birth_year + 35 print "You are able to drive in " + driving_year print "You are able to drink in " + drinking_year print "You are able to run for president in " + president_year
birth_year = raw_input("What is the birth year for the milestones?") # raw_input always gives strings, so convert to int birth_year = int(birth_year) # Calculate milestone years driving_year = birth_year + 16 drinking_year = birth_year + 21 president_year = birth_year + 35 print "You are able to drive in " + str(driving_year) print "You are able to drink in " + str(drinking_year) print "You are able to run for president in " + str(president_year)
Convert int to string for printing
Convert int to string for printing
Python
mit
WomensCodingCircle/CodingCirclePython
--- +++ @@ -7,6 +7,6 @@ drinking_year = birth_year + 21 president_year = birth_year + 35 -print "You are able to drive in " + driving_year -print "You are able to drink in " + drinking_year -print "You are able to run for president in " + president_year +print "You are able to drive in " + str(driving_year) +print "You are able to drink in " + str(drinking_year) +print "You are able to run for president in " + str(president_year)
a4598c9454a2011b6aeff4a3759d8d2fb5a8ece3
xclib/tests/51_online_postfix_failure_test.py
xclib/tests/51_online_postfix_failure_test.py
# Second half of the postfix_io tests. # If the authentication host is unreachable, postfix # should have a 400 error returned. This tests for it. # This test also works if the local machine is offline, # nevertheless, it sends packets to the network, therefore # is considered an online test import sys import unittest import logging import shutil import tempfile import json from xclib.sigcloud import sigcloud from xclib import xcauth from xclib.tests.iostub import iostub from xclib.configuration import get_args from xclib.authops import perform from xclib.check import assertEqual def setup_module(): global dirname dirname = tempfile.mkdtemp() def teardown_module(): shutil.rmtree(dirname) class TestOnlinePostfix(unittest.TestCase, iostub): # Run this (connection-error) online test even when /etc/xcauth.accounts does not exist def test_postfix_connection_error(self): self.stub_stdin('get user@example.org\n') self.stub_stdout() args = get_args(None, None, None, 'xcauth', args=['-t', 'postfix', '-u', 'https://no-connection.jsxc.org/', '-s', '0', '-l', dirname], config_file_contents='#') perform(args) output = sys.stdout.getvalue().rstrip('\n') logging.debug(output) assertEqual(output[0:4], '400 ')
# Second half of the postfix_io tests. # If the authentication host is unreachable, postfix # should have a 400 error returned. This tests for it. # This test also works if the local machine is offline, # nevertheless, it sends packets to the network, therefore # is considered an online test import sys import unittest import logging import shutil import tempfile import json from xclib.sigcloud import sigcloud from xclib import xcauth from xclib.tests.iostub import iostub from xclib.configuration import get_args from xclib.authops import perform from xclib.check import assertEqual def setup_module(): global dirname dirname = tempfile.mkdtemp() def teardown_module(): shutil.rmtree(dirname) class TestOnlinePostfix(unittest.TestCase, iostub): # Run this (connection-error) online test even when /etc/xcauth.accounts does not exist def test_postfix_connection_error(self): self.stub_stdin('get user@example.org\n') self.stub_stdout() args = get_args(None, None, None, 'xcauth', args=['-t', 'postfix', '-u', 'https://no-connection.jsxc.org/', '-s', '0', '-l', dirname, '--db', ':memory:' ], config_file_contents='#') perform(args) output = sys.stdout.getvalue().rstrip('\n') logging.debug(output) assertEqual(output[0:4], '400 ')
Use in-memory db for all tests
Use in-memory db for all tests
Python
mit
jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth
--- +++ @@ -30,7 +30,12 @@ self.stub_stdin('get user@example.org\n') self.stub_stdout() args = get_args(None, None, None, 'xcauth', - args=['-t', 'postfix', '-u', 'https://no-connection.jsxc.org/', '-s', '0', '-l', dirname], + args=['-t', 'postfix', + '-u', 'https://no-connection.jsxc.org/', + '-s', '0', + '-l', dirname, + '--db', ':memory:' + ], config_file_contents='#') perform(args) output = sys.stdout.getvalue().rstrip('\n')
5c000543ce943619ea89b2443395a2ee10c49ee0
solutions/beecrowd/1010/1010.py
solutions/beecrowd/1010/1010.py
import sys s = 0.0 for line in sys.stdin: a, b, c = line.split() a, b, c = int(a), int(b), float(c) s += c * b print(f'VALOR A PAGAR: R$ {s:.2f}')
import sys s = 0.0 for line in sys.stdin: _, b, c = line.split() b, c = int(b), float(c) s += c * b print(f'VALOR A PAGAR: R$ {s:.2f}')
Refactor python version of Simple Calculate
Refactor python version of Simple Calculate
Python
mit
deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground
--- +++ @@ -3,8 +3,8 @@ s = 0.0 for line in sys.stdin: - a, b, c = line.split() - a, b, c = int(a), int(b), float(c) + _, b, c = line.split() + b, c = int(b), float(c) s += c * b print(f'VALOR A PAGAR: R$ {s:.2f}')
fc5614c040cccff6411c87ad6cc191f7ec0b6971
SoftLayer/CLI/account/bandwidth_pools.py
SoftLayer/CLI/account/bandwidth_pools.py
"""Displays information about the accounts bandwidth pools""" # :license: MIT, see LICENSE for more details. import click from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.managers.account import AccountManager as AccountManager from SoftLayer import utils @click.command() @environment.pass_env def cli(env): """Displays bandwidth pool information Similiar to https://cloud.ibm.com/classic/network/bandwidth/vdr """ manager = AccountManager(env.client) items = manager.get_bandwidth_pools() table = formatting.Table([ "Pool Name", "Region", "Servers", "Allocation", "Current Usage", "Projected Usage" ], title="Bandwidth Pools") table.align = 'l' for item in items: name = item.get('name') region = utils.lookup(item, 'locationGroup', 'name') servers = manager.get_bandwidth_pool_counts(identifier=item.get('id')) allocation = "{} GB".format(item.get('totalBandwidthAllocated', 0)) current = "{} GB".format(utils.lookup(item, 'billingCyclePublicBandwidthUsage', 'amountOut')) projected = "{} GB".format(item.get('projectedPublicBandwidthUsage', 0)) table.add_row([name, region, servers, allocation, current, projected]) env.fout(table)
"""Displays information about the accounts bandwidth pools""" # :license: MIT, see LICENSE for more details. import click from SoftLayer.CLI import environment from SoftLayer.CLI import formatting from SoftLayer.managers.account import AccountManager as AccountManager from SoftLayer import utils @click.command() @environment.pass_env def cli(env): """Displays bandwidth pool information Similiar to https://cloud.ibm.com/classic/network/bandwidth/vdr """ manager = AccountManager(env.client) items = manager.get_bandwidth_pools() table = formatting.Table([ "Id", "Pool Name", "Region", "Servers", "Allocation", "Current Usage", "Projected Usage" ], title="Bandwidth Pools") table.align = 'l' for item in items: id = item.get('id') name = item.get('name') region = utils.lookup(item, 'locationGroup', 'name') servers = manager.get_bandwidth_pool_counts(identifier=item.get('id')) allocation = "{} GB".format(item.get('totalBandwidthAllocated', 0)) current = "{} GB".format(utils.lookup(item, 'billingCyclePublicBandwidthUsage', 'amountOut')) projected = "{} GB".format(item.get('projectedPublicBandwidthUsage', 0)) table.add_row([id, name, region, servers, allocation, current, projected]) env.fout(table)
Add id in the result in the command bandwidth-pools
Add id in the result in the command bandwidth-pools
Python
mit
softlayer/softlayer-python,allmightyspiff/softlayer-python
--- +++ @@ -20,6 +20,7 @@ items = manager.get_bandwidth_pools() table = formatting.Table([ + "Id", "Pool Name", "Region", "Servers", @@ -28,8 +29,8 @@ "Projected Usage" ], title="Bandwidth Pools") table.align = 'l' - for item in items: + id = item.get('id') name = item.get('name') region = utils.lookup(item, 'locationGroup', 'name') servers = manager.get_bandwidth_pool_counts(identifier=item.get('id')) @@ -37,5 +38,5 @@ current = "{} GB".format(utils.lookup(item, 'billingCyclePublicBandwidthUsage', 'amountOut')) projected = "{} GB".format(item.get('projectedPublicBandwidthUsage', 0)) - table.add_row([name, region, servers, allocation, current, projected]) + table.add_row([id, name, region, servers, allocation, current, projected]) env.fout(table)
3f27e1997c94bcdac23e5cb478e7d2b9c6dc1f37
astropy/io/misc/asdf/__init__.py
astropy/io/misc/asdf/__init__.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- """ The **asdf** subpackage contains code that is used to serialize astropy types so that they can be represented and stored using the Advanced Scientific Data Format (ASDF). This subpackage defines classes, referred to as **tags**, that implement the logic for serialization and deserialization. ASDF makes use of abstract data type definitions called **schemas**. The tag classes provided here are specific implementations of particular schemas. Some of the tags in Astropy (e.g., those related to transforms) implement schemas that are defined by the ASDF Standard. In other cases, both the tags and schemas are defined within Astropy (e.g., those related to many of the coordinate frames). Astropy currently has no ability to read or write ASDF files itself. In order to process ASDF files it is necessary to make use of the standalone **asdf** package. Users should never need to refer to tag implementations directly. Their presence should be entirely transparent when processing ASDF files. If both **asdf** and **astropy** are installed, no further configuration is required in order to process ASDF files. The **asdf** package has been designed to automatically detect the presence of the tags defined by **astropy**. Documentation on the ASDF Standard can be found `here <https://asdf-standard.readthedocs.io>`__. Documentation on the ASDF Python module can be found `here <https://asdf.readthedocs.io>`__. """ from . import connect
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- """ The **asdf** subpackage contains code that is used to serialize astropy types so that they can be represented and stored using the Advanced Scientific Data Format (ASDF). This subpackage defines classes, referred to as **tags**, that implement the logic for serialization and deserialization. ASDF makes use of abstract data type definitions called **schemas**. The tag classes provided here are specific implementations of particular schemas. Some of the tags in Astropy (e.g., those related to transforms) implement schemas that are defined by the ASDF Standard. In other cases, both the tags and schemas are defined within Astropy (e.g., those related to many of the coordinate frames). Astropy currently has no ability to read or write ASDF files itself. In order to process ASDF files it is necessary to make use of the standalone **asdf** package. Users should never need to refer to tag implementations directly. Their presence should be entirely transparent when processing ASDF files. If both **asdf** and **astropy** are installed, no further configuration is required in order to process ASDF files. The **asdf** package has been designed to automatically detect the presence of the tags defined by **astropy**. Documentation on the ASDF Standard can be found `here <https://asdf-standard.readthedocs.io>`__. Documentation on the ASDF Python module can be found `here <https://asdf.readthedocs.io>`__. """ try: import asdf from . import connect except ImportError: pass
Put try/except around ASDF import in init file
Put try/except around ASDF import in init file
Python
bsd-3-clause
astropy/astropy,lpsinger/astropy,mhvk/astropy,MSeifert04/astropy,stargaser/astropy,saimn/astropy,stargaser/astropy,larrybradley/astropy,pllim/astropy,aleksandr-bakanov/astropy,dhomeier/astropy,astropy/astropy,stargaser/astropy,pllim/astropy,aleksandr-bakanov/astropy,astropy/astropy,saimn/astropy,larrybradley/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,saimn/astropy,mhvk/astropy,larrybradley/astropy,pllim/astropy,bsipocz/astropy,saimn/astropy,dhomeier/astropy,bsipocz/astropy,StuartLittlefair/astropy,StuartLittlefair/astropy,pllim/astropy,mhvk/astropy,bsipocz/astropy,MSeifert04/astropy,lpsinger/astropy,dhomeier/astropy,mhvk/astropy,MSeifert04/astropy,StuartLittlefair/astropy,lpsinger/astropy,stargaser/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,larrybradley/astropy,astropy/astropy,mhvk/astropy,larrybradley/astropy,MSeifert04/astropy,StuartLittlefair/astropy,saimn/astropy,lpsinger/astropy,lpsinger/astropy,astropy/astropy,bsipocz/astropy,pllim/astropy
--- +++ @@ -27,4 +27,8 @@ module can be found `here <https://asdf.readthedocs.io>`__. """ -from . import connect +try: + import asdf + from . import connect +except ImportError: + pass
ed1172cc12654cdf0d221281cd56c51992b4c4af
knotdirectory/knotdirectory/knots/forms.py
knotdirectory/knotdirectory/knots/forms.py
from django import forms from django.forms.models import inlineformset_factory from .models import Knot, Link class KnotForm(forms.ModelForm): class Meta: model = Knot fields = ['name', 'photo', 'other_names', 'creator_name', 'notes', 'tags'] class InlineLinkForm(forms.ModelForm): class Meta: model = Link fields = ['name', 'link'] LinkFormset = inlineformset_factory(Knot, Link)
from django import forms from django.forms.models import inlineformset_factory from django.utils import six from .models import Knot, Link def edit_string_for_tags(tags): """ Convert list of Tags into comma-separated list. We can't use the one built into django-taggit, because select2 freaks out about the space after the comma. """ names = [] for tag in tags: name = tag.name if ',' in name or ' ' in name: names.append('"%s"' % name) else: names.append(name) return ','.join(sorted(names)) class HiddenTagWidget(forms.HiddenInput): """ For use with select2 and ajax tagging """ def render(self, name, value, attrs=None): if value is not None and not isinstance(value, six.string_types): value = edit_string_for_tags([o.tag for o in value.select_related("tag")]) return super(HiddenTagWidget, self).render(name, value, attrs) class KnotForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(KnotForm, self).__init__(*args, **kwargs) print self.fields.keys() self.fields['tags'].widget = HiddenTagWidget() class Meta: model = Knot fields = ['name', 'photo', 'other_names', 'creator_name', 'notes', 'tags'] class InlineLinkForm(forms.ModelForm): class Meta: model = Link fields = ['name', 'link'] LinkFormset = inlineformset_factory(Knot, Link)
Set up form to use special widget for tags
Set up form to use special widget for tags
Python
mit
althalus/knotcrafters,althalus/knotcrafters,althalus/knotcrafters
--- +++ @@ -1,10 +1,41 @@ from django import forms from django.forms.models import inlineformset_factory +from django.utils import six from .models import Knot, Link +def edit_string_for_tags(tags): + """ + Convert list of Tags into comma-separated list. + + We can't use the one built into django-taggit, because select2 freaks out + about the space after the comma. + """ + names = [] + for tag in tags: + name = tag.name + if ',' in name or ' ' in name: + names.append('"%s"' % name) + else: + names.append(name) + return ','.join(sorted(names)) + + +class HiddenTagWidget(forms.HiddenInput): + """ For use with select2 and ajax tagging """ + def render(self, name, value, attrs=None): + if value is not None and not isinstance(value, six.string_types): + value = edit_string_for_tags([o.tag for o in value.select_related("tag")]) + return super(HiddenTagWidget, self).render(name, value, attrs) + + class KnotForm(forms.ModelForm): + def __init__(self, *args, **kwargs): + super(KnotForm, self).__init__(*args, **kwargs) + print self.fields.keys() + self.fields['tags'].widget = HiddenTagWidget() + class Meta: model = Knot fields = ['name', 'photo', 'other_names', 'creator_name', 'notes', 'tags']
8a10c1f0036f681a1b6f499ac03e86b96bb88700
fancypages/__init__.py
fancypages/__init__.py
import os __version__ = (0, 1, 1, 'alpha', 1) def get_fancypages_paths(path): """ Get absolute paths for *path* relative to the project root """ return [os.path.join(os.path.dirname(os.path.abspath(__file__)), path)] def get_required_apps(): return [ 'django_extensions', # used for image thumbnailing 'sorl.thumbnail', # framework used for the internal API 'rest_framework', # provides a convenience layer around model inheritance # that makes lookup of nested models easier. This is used # for the content block hierarchy. 'model_utils', # static file compression and collection 'compressor', # migration handling 'south', # package used for twitter block 'twitter_tag', ] def get_fancypages_apps(): return [ 'fancypages.assets', 'fancypages', ]
import os __version__ = (0, 3, 0, 'alpha', 1) def get_fancypages_paths(path): """ Get absolute paths for *path* relative to the project root """ return [os.path.join(os.path.dirname(os.path.abspath(__file__)), path)] def get_required_apps(): return [ 'django_extensions', # used for image thumbnailing 'sorl.thumbnail', # framework used for the internal API 'rest_framework', # provides a convenience layer around model inheritance # that makes lookup of nested models easier. This is used # for the content block hierarchy. 'model_utils', # static file compression and collection 'compressor', # migration handling 'south', # package used for twitter block 'twitter_tag', ] def get_fancypages_apps(): return [ 'fancypages.assets', 'fancypages', ]
Bump new dev version to 0.3.0
Bump new dev version to 0.3.0
Python
bsd-3-clause
socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages
--- +++ @@ -1,6 +1,6 @@ import os -__version__ = (0, 1, 1, 'alpha', 1) +__version__ = (0, 3, 0, 'alpha', 1) def get_fancypages_paths(path):
d19fd61e746ab4afcb534df6be933716e154b715
memopol/search/templatetags/search_tags.py
memopol/search/templatetags/search_tags.py
from django.core.urlresolvers import reverse from django.template.defaultfilters import urlencode from django import template from dynamiq.utils import get_advanced_search_formset_class from ..forms import MEPSearchForm, MEPSearchAdvancedFormset register = template.Library() @register.simple_tag def simple_search_shortcut(search_string): """ Return a simple search URL from a search string, like "daniel OR country:CZ". """ base_url = reverse("search") return "%s?q=%s" % (base_url, urlencode(search_string)) @register.inclusion_tag('blocks/search_form.html', takes_context=True) def render_search_form(context): """ Display the search form, if a `dynamiq` key is on the context, it will used, otherwise, it create an empty form """ if 'dynamiq' in context: dynamiq = context['dynamiq'] else: request = context['request'] formset_class = get_advanced_search_formset_class(request.user, MEPSearchAdvancedFormset, MEPSearchForm) formset = formset_class(None) dynamiq = { "q": "", "label": "", "formset": formset, } return { 'dynamiq': dynamiq }
from django.core.urlresolvers import reverse from django.template.defaultfilters import urlencode from django import template from dynamiq.utils import get_advanced_search_formset_class from ..forms import MEPSearchForm, MEPSearchAdvancedFormset register = template.Library() @register.simple_tag def simple_search_shortcut(search_string, sort=None): """ Return a simple search URL from a search string, like "daniel OR country:CZ". """ base_url = reverse("search") query_string = "q=%s" % urlencode(search_string) if sort: query_string = "%s&sort=%s" % (query_string, sort) return "%s?%s" % (base_url, query_string) @register.inclusion_tag('blocks/search_form.html', takes_context=True) def render_search_form(context): """ Display the search form, if a `dynamiq` key is on the context, it will used, otherwise, it create an empty form """ if 'dynamiq' in context: dynamiq = context['dynamiq'] else: request = context['request'] formset_class = get_advanced_search_formset_class(request.user, MEPSearchAdvancedFormset, MEPSearchForm) formset = formset_class(None) dynamiq = { "q": "", "label": "", "formset": formset, } return { 'dynamiq': dynamiq }
Make possible to define a sort in simple_search_shortcut tt
[enh] Make possible to define a sort in simple_search_shortcut tt
Python
agpl-3.0
yohanboniface/memopol-core,yohanboniface/memopol-core,yohanboniface/memopol-core
--- +++ @@ -10,12 +10,15 @@ @register.simple_tag -def simple_search_shortcut(search_string): +def simple_search_shortcut(search_string, sort=None): """ Return a simple search URL from a search string, like "daniel OR country:CZ". """ base_url = reverse("search") - return "%s?q=%s" % (base_url, urlencode(search_string)) + query_string = "q=%s" % urlencode(search_string) + if sort: + query_string = "%s&sort=%s" % (query_string, sort) + return "%s?%s" % (base_url, query_string) @register.inclusion_tag('blocks/search_form.html', takes_context=True)
7c3c9e2ab7be0d91b4edc3d15d50cc1245941e47
logicaldelete/models.py
logicaldelete/models.py
from django.db import models try: from django.utils import timezone except ImportError: from datetime import datetime as timezonefrom logicaldelete import managers class Model(models.Model): """ This base model provides date fields and functionality to enable logical delete functionality in derived models. """ date_created = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(default=timezone.now) date_removed = models.DateTimeField(null=True, blank=True) objects = managers.LogicalDeletedManager() def active(self): return self.date_removed is None active.boolean = True def delete(self): ''' Soft delete all fk related objects that inherit from logicaldelete class ''' # Fetch related models related_objs = [relation.get_accessor_name() for relation in self._meta.get_all_related_objects()] for objs_model in related_objs: # Retrieve all related objects objs = getattr(self, objs_model).all() for obj in objs: # Checking if inherits from logicaldelete if not issubclass(obj.__class__, Model): break obj.delete() # Soft delete the object self.date_removed = timezone.now() self.save() class Meta: abstract = True
from django.db import models from logicaldelete import managers try: from django.utils import timezone except ImportError: from datetime import datetime as timezone class Model(models.Model): """ This base model provides date fields and functionality to enable logical delete functionality in derived models. """ date_created = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(default=timezone.now) date_removed = models.DateTimeField(null=True, blank=True) objects = managers.LogicalDeletedManager() def active(self): return self.date_removed is None active.boolean = True def delete(self): ''' Soft delete all fk related objects that inherit from logicaldelete class ''' # Fetch related models related_objs = [relation.get_accessor_name() for relation in self._meta.get_all_related_objects()] for objs_model in related_objs: # Retrieve all related objects objs = getattr(self, objs_model).all() for obj in objs: # Checking if inherits from logicaldelete if not issubclass(obj.__class__, Model): break obj.delete() # Soft delete the object self.date_removed = timezone.now() self.save() class Meta: abstract = True
Fix issue with manager (error w cut and paste)
Fix issue with manager (error w cut and paste)
Python
bsd-3-clause
angvp/django-logical-delete,angvp/django-logical-delete
--- +++ @@ -1,9 +1,11 @@ from django.db import models +from logicaldelete import managers try: from django.utils import timezone except ImportError: - from datetime import datetime as timezonefrom logicaldelete import managers + from datetime import datetime as timezone + class Model(models.Model):
30a982448b4f0baa2abe02ea0d9ef0d4d21c8414
Main.py
Main.py
from App import App #try: app = App() app.run() #except: # print('')
from App import App try: app = App() app.run() except KeyboardInterrupt: print('')
Add try except for keyboard interrupts
Add try except for keyboard interrupts
Python
mit
Rookfighter/TextAdventure
--- +++ @@ -1,7 +1,7 @@ from App import App -#try: -app = App() -app.run() -#except: -# print('') +try: + app = App() + app.run() +except KeyboardInterrupt: + print('')
7f9f98cedb4693e0b5a4c7297d16757224a4e71e
axes/checks.py
axes/checks.py
from django.core.checks import Error, Tags, register from axes.conf import settings class Messages: CACHE_INVALID = 'invalid cache configuration for settings.AXES_CACHE' class Hints: CACHE_INVALID = ( 'django-axes does not work properly with LocMemCache as the cache backend' ' please add e.g. a DummyCache backend and configure it with settings.AXES_CACHE' ) class Codes: CACHE_INVALID = 'axeslE001' @register(Tags.caches) def axes_cache_backend_check(app_configs, **kwargs): # pylint: disable=unused-argument axes_handler = getattr(settings, 'AXES_HANDLER', '') axes_cache_key = getattr(settings, 'AXES_CACHE', 'default') axes_cache_config = settings.CACHES.get(axes_cache_key, {}) axes_cache_backend = axes_cache_config.get('BACKEND', '') axes_cache_backend_incompatible = [ 'django.core.cache.backends.dummy.DummyCache', 'django.core.cache.backends.locmem.LocMemCache', 'django.core.cache.backends.filebased.FileBasedCache', ] errors = [] if axes_handler == 'axes.handlers.cache.AxesCacheHandler': if axes_cache_backend in axes_cache_backend_incompatible: errors.append(Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, )) return errors
from django.core.checks import Error, Tags, register from axes.conf import settings class Messages: CACHE_INVALID = 'invalid cache configuration for settings.AXES_CACHE' class Hints: CACHE_INVALID = ( 'django-axes does not work properly with LocMemCache as the cache backend' ' please add e.g. a DummyCache backend and configure it with settings.AXES_CACHE' ) class Codes: CACHE_INVALID = 'axes.E001' @register(Tags.caches) def axes_cache_backend_check(app_configs, **kwargs): # pylint: disable=unused-argument axes_handler = getattr(settings, 'AXES_HANDLER', '') axes_cache_key = getattr(settings, 'AXES_CACHE', 'default') axes_cache_config = settings.CACHES.get(axes_cache_key, {}) axes_cache_backend = axes_cache_config.get('BACKEND', '') axes_cache_backend_incompatible = [ 'django.core.cache.backends.dummy.DummyCache', 'django.core.cache.backends.locmem.LocMemCache', 'django.core.cache.backends.filebased.FileBasedCache', ] errors = [] if axes_handler == 'axes.handlers.cache.AxesCacheHandler': if axes_cache_backend in axes_cache_backend_incompatible: errors.append(Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, )) return errors
Fix invalid error code format for Axes
Fix invalid error code format for Axes Signed-off-by: Aleksi Häkli <44cb6a94c0d20644d531e2be44779b52833cdcd2@iki.fi>
Python
mit
django-pci/django-axes,jazzband/django-axes
--- +++ @@ -15,7 +15,7 @@ class Codes: - CACHE_INVALID = 'axeslE001' + CACHE_INVALID = 'axes.E001' @register(Tags.caches)
d8369ebff8f4622fe83308e7e65c7120a00e5768
github/events/watch.py
github/events/watch.py
from data_types.hook import Hook from data_types.repository import Repository from data_types.user import User from .base import EventBase class EventWatch(EventBase): def __init__(self, sdk): super(EventWatch, self).__init__(sdk) self.hook = None self.repository = None self.sender = None """ WatchEvent Triggered when someone stars your repository. https://developer.github.com/v3/activity/events/types/#watchevent """ async def process(self, payload, chat): """ Processes Watch event :param payload: JSON object with payload :param chat: current chat object :return: """ self.sdk.log("Watch event payload taken {}".format(payload)) try: self.repository = Repository(payload['repository']) self.sender = User(payload['sender']) except Exception as e: self.sdk.log('Cannot process WatchEvent payload because of {}'.format(e)) await self.send( chat['chat'], '⭐️ <a href=\"{}\">{}</a> starred <a href=\"{}\">{}</a> ★ {}'.format( self.sender.html_url, self.sender.login, self.repository.html_url, self.repository.full_name, self.sender.repository.stargazers_count ), 'HTML' )
from data_types.hook import Hook from data_types.repository import Repository from data_types.user import User from .base import EventBase class EventWatch(EventBase): def __init__(self, sdk): super(EventWatch, self).__init__(sdk) self.hook = None self.repository = None self.sender = None """ WatchEvent Triggered when someone stars your repository. https://developer.github.com/v3/activity/events/types/#watchevent """ async def process(self, payload, chat): """ Processes Watch event :param payload: JSON object with payload :param chat: current chat object :return: """ self.sdk.log("Watch event payload taken {}".format(payload)) try: self.repository = Repository(payload['repository']) self.sender = User(payload['sender']) except Exception as e: self.sdk.log('Cannot process WatchEvent payload because of {}'.format(e)) await self.send( chat['chat'], '⭐️ <a href=\"{}\">{}</a> starred <a href=\"{}\">{}</a> ★ {}'.format( self.sender.html_url, self.sender.login, self.repository.html_url, self.repository.full_name, self.repository.stargazers_count ), 'HTML' )
Add non-breaking space and fix error
Add non-breaking space and fix error
Python
mit
codex-bot/github
--- +++ @@ -40,12 +40,12 @@ await self.send( chat['chat'], - '⭐️ <a href=\"{}\">{}</a> starred <a href=\"{}\">{}</a> ★ {}'.format( + '⭐️ <a href=\"{}\">{}</a> starred <a href=\"{}\">{}</a> ★ {}'.format( self.sender.html_url, self.sender.login, self.repository.html_url, self.repository.full_name, - self.sender.repository.stargazers_count + self.repository.stargazers_count ), 'HTML' )
9f44c09dcb3ce3bd0bec591597e892d4037936f9
main.py
main.py
import os import json import sys from pprint import pprint def loadJSON(fInput): with open(fInput) as f: return json.load(f) return None if __name__ == '__main__': filePath = 'data/example.json' data = loadJSON(filePath) # check if the data is loaded correctly if data is None: sys.exit('wrong json file'); name = data.get('name') lstTypes = data.get('types') lstFuncs = data.get('functions') ''' from dsFileBuilder import DSFileBuilder dsb = DSFileBuilder(name, lstTypes) dsb.buildDS() dicNumpyDS = dsb.getGeneratedNumpyDS() from kernelFuncBuilder import KernelFuncBuilder kfb = KernelFuncBuilder(name, lstFuncs) kfb.buildKF() dicKFuncDS = kfb.getGeneratedKFuncDS() from oclPyObjGenerator import OCLPyObjGenerator opg = OCLPyObjGenerator(name, dicNumpyDS, dicKFuncDS) opg.generateOCLPyObj() pass '''
import os import json import sys from pprint import pprint def loadJSON(fInput): with open(fInput) as f: return json.load(f) return None if __name__ == '__main__': filePath = 'data/example.json' data = loadJSON(filePath) # check if the data is loaded correctly if data is None: sys.exit('wrong json file'); name = data.get('name') lstTypes = data.get('types') lstFuncs = data.get('functions') from dsFileBuilder import DSFileBuilder dsb = DSFileBuilder(name, lstTypes) dsb.buildDS() dicNumpyDS = dsb.getGeneratedNumpyDS() from kernelFuncBuilder import KernelFuncBuilder kfb = KernelFuncBuilder(name, lstFuncs) kfb.buildKF() dicKFuncDS = kfb.getGeneratedKFuncDS() from oclPyObjGenerator import OCLPyObjGenerator opg = OCLPyObjGenerator(name, dicNumpyDS, dicKFuncDS) opg.generateOCLPyObj() pass
Add functions to generate python numpy datastructure and write it into generated python file.
Add functions to generate python numpy datastructure and write it into generated python file.
Python
apache-2.0
kilikkuo/kernel-mapper,PyOCL/kernel-mapper
--- +++ @@ -19,7 +19,6 @@ lstTypes = data.get('types') lstFuncs = data.get('functions') - ''' from dsFileBuilder import DSFileBuilder dsb = DSFileBuilder(name, lstTypes) dsb.buildDS() @@ -34,4 +33,3 @@ opg = OCLPyObjGenerator(name, dicNumpyDS, dicKFuncDS) opg.generateOCLPyObj() pass - '''
3f178359b8649b6b92900ae790e894971405b720
main.py
main.py
from src import create from src import count from src import thefile from src import execute def main(x, y, file): #Create it seats = create.new_2d(x, y) #Count it counted_start = count.count_array(x, y, seats) print(counted_start) #Get the commands commands = thefile.get_cmmds(file) #The execution for line in commands: seats = execute.execute_cmmds(seats, line) counted_after = count.count_array(x, y, seats) counter_occupied = 1000000 - counted_after return counter_occupied results = main(1000, 1000, 'inputfile.txt') print("Cool")
from src import create from src import count from src import thefile from src import execute def main(x, y, file): #Create it seats = create.new_2d(x, y) #Count it counted_start = count.count_array(x, y, seats) print(counted_start) #Get the commands commands = thefile.get_cmmds(file) #The execution for line in commands: seats = execute.execute_cmmds(seats, line) counted_after = count.count_array(x, y, seats) counter_occupied = 1000000 - counted_after return counter_occupied results = main(1000, 1000, 'inputfile.txt') print("Cool") print("Other")
CLEAN TEMPLATE Clean up the project template further still
CLEAN TEMPLATE Clean up the project template further still
Python
bsd-2-clause
kevindiltinero/seass3
--- +++ @@ -26,3 +26,4 @@ results = main(1000, 1000, 'inputfile.txt') print("Cool") +print("Other")
c83dcddd7451d53214cf02f9ad72e280970a2dc8
hydromet/catchments.py
hydromet/catchments.py
import os import numpy as np from catchment_cutter import get_grid_cells def create_grids(catchments, in_directory, out_directory, grid_file): """ Create grid files for the supplied catchments. :param catchments: List of catchment IDs. :type catchments: Array(string) :param in_directory: Path to catchment boundary (geojson) directory. :type in_directory: string :param out_directory: Output directory for catchment grid csv files. :type out_directory: string :param grid_file: Path to input grid file for coordinates to match boundaries against. :type grid_file: string """ for catchment in catchments: boundary = os.path.join(in_directory, catchment + '.json') cells = np.asarray(get_grid_cells(boundary, grid_file)) np.savetxt(os.path.join(out_directory, catchment + '.csv'), cells, fmt="%.2f", delimiter=',')
import os import numpy as np from catchment_tools import get_grid_cells def create_grids(catchments, in_directory, out_directory, grid_file): """ Create grid files for the supplied catchments. :param catchments: List of catchment IDs. :type catchments: Array(string) :param in_directory: Path to catchment boundary (geojson) directory. :type in_directory: string :param out_directory: Output directory for catchment grid csv files. :type out_directory: string :param grid_file: Path to input grid file for coordinates to match boundaries against. :type grid_file: string """ for catchment in catchments: boundary = os.path.join(in_directory, catchment + '.json') cells = np.asarray(get_grid_cells(boundary, grid_file, 0.3)) np.savetxt(os.path.join(out_directory, catchment + '.csv'), cells, fmt="%.2f", delimiter=',')
Use updated catchment tools import
Use updated catchment tools import
Python
bsd-3-clause
amacd31/hydromet-toolkit,amacd31/hydromet-toolkit
--- +++ @@ -1,7 +1,7 @@ import os import numpy as np -from catchment_cutter import get_grid_cells +from catchment_tools import get_grid_cells def create_grids(catchments, in_directory, out_directory, grid_file): """ @@ -18,7 +18,7 @@ """ for catchment in catchments: boundary = os.path.join(in_directory, catchment + '.json') - cells = np.asarray(get_grid_cells(boundary, grid_file)) + cells = np.asarray(get_grid_cells(boundary, grid_file, 0.3)) np.savetxt(os.path.join(out_directory, catchment + '.csv'), cells, fmt="%.2f", delimiter=',')
a7386ca8a26a7a1cb14c6a802d284c2b87114f3d
condor-copasi-daemon/condor-copasi-daemon.py
condor-copasi-daemon/condor-copasi-daemon.py
#!/usr/bin/env python #Script adapted from example by Sander Marechal, released into public domain #Taken from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ import sys, time from daemon import Daemon from web_frontend import settings class MyDaemon(Daemon): def run(self): while True: min_repeat_time = settings.MIN_CONDOR_Q_POLL_TIME * 60 start_time = time.time() import background_run finish_time = time.time() difference = finish_time - start_time print 'Took ' + str(difference) + ' seconds' if difference < min_repeat_time: print 'Sleeping for ' + str(min_repeat_time - difference) + ' seconds' time.sleep(min_repeat_time - difference) if __name__ == "__main__": daemon = MyDaemon('/tmp/helper_daemon.pid') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.start() elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() else: print "Unknown command" sys.exit(2) sys.exit(0) else: print "usage: %s start|stop|restart" % sys.argv[0] sys.exit(2)
#!/usr/bin/env python #Script adapted from example by Sander Marechal, released into public domain #Taken from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ import sys, time from daemon import Daemon from web_frontend import settings class MyDaemon(Daemon): def run(self): while True: min_repeat_time = settings.MIN_CONDOR_Q_POLL_TIME * 60 start_time = time.time() import background_run finish_time = time.time() difference = finish_time - start_time if difference < min_repeat_time: time.sleep(min_repeat_time - difference) if __name__ == "__main__": daemon = MyDaemon('/tmp/helper_daemon.pid') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.start() elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() else: print "Unknown command" sys.exit(2) sys.exit(0) else: print "usage: %s start|stop|restart" % sys.argv[0] sys.exit(2)
Remove print statements from daemon
Remove print statements from daemon
Python
artistic-2.0
Nucleoos/condor-copasi,copasi/condor-copasi,copasi/condor-copasi,Nucleoos/condor-copasi
--- +++ @@ -15,9 +15,7 @@ finish_time = time.time() difference = finish_time - start_time - print 'Took ' + str(difference) + ' seconds' if difference < min_repeat_time: - print 'Sleeping for ' + str(min_repeat_time - difference) + ' seconds' time.sleep(min_repeat_time - difference) if __name__ == "__main__":
5586ea0d038365b38b2e2d1fa68ae2c77569146c
conjureup/controllers/vspheresetup/common.py
conjureup/controllers/vspheresetup/common.py
from conjureup import controllers from conjureup.app_config import app class BaseVSphereSetupController: def __init__(self): # Assign current datacenter app.provider.login() for dc in app.provider.client.get_datacenters(): if dc.name == app.provider.region: self.datacenter = dc def finish(self, data): app.provider.model_defaults = { 'primary-network': data['primary-network'], 'external-network': data['external-network'], 'datastore': data['datastore'] } return controllers.use('controllerpicker').render()
from conjureup import controllers from conjureup.app_config import app class BaseVSphereSetupController: def __init__(self): # Assign current datacenter app.provider.login() for dc in app.provider.get_datacenters(): if dc.name == app.provider.region: self.datacenter = dc def finish(self, data): app.provider.model_defaults = { 'primary-network': data['primary-network'], 'external-network': data['external-network'], 'datastore': data['datastore'] } return controllers.use('controllerpicker').render()
Fix attribute error in vsphere controller
Fix attribute error in vsphere controller Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com>
Python
mit
Ubuntu-Solutions-Engineering/conjure,conjure-up/conjure-up,ubuntu/conjure-up,Ubuntu-Solutions-Engineering/conjure,ubuntu/conjure-up,conjure-up/conjure-up
--- +++ @@ -6,7 +6,7 @@ def __init__(self): # Assign current datacenter app.provider.login() - for dc in app.provider.client.get_datacenters(): + for dc in app.provider.get_datacenters(): if dc.name == app.provider.region: self.datacenter = dc
8a947bda06142ba60cac08aee380e723398e5150
music_essentials/chord.py
music_essentials/chord.py
class Chord(object): # TODO: doctring def __init__(self, root_note): # TODO: doctring # TODO: validation self.notes = [root_note] def root(self): # TODO: doctring return self.notes[0]
class Chord(object): # TODO: doctring def __init__(self, root_note): # TODO: doctring # TODO: validation self.notes = [root_note] def root(self): # TODO: doctring # TODO: tests return self.notes[0] def add_note(self, new_note): # TODO: docstring # TODO: tests if new_note < self.root(): self.notes.insert(0, new_note) return for i in range(len(self.notes) - 1): if (new_note >= self.notes[i]) and (new_note < self.notes[i + 1]): self.notes.insert(i + 1, new_note) return self.notes.append(new_note)
Add ability to add notes to a Chord.
Add ability to add notes to a Chord. Signed-off-by: Charlotte Pierce <351429ca27f6e4bff2dbb77adb5046c88cd12fae@malformed-bits.com>
Python
mit
charlottepierce/music_essentials
--- +++ @@ -7,4 +7,19 @@ def root(self): # TODO: doctring + # TODO: tests return self.notes[0] + + def add_note(self, new_note): + # TODO: docstring + # TODO: tests + if new_note < self.root(): + self.notes.insert(0, new_note) + return + + for i in range(len(self.notes) - 1): + if (new_note >= self.notes[i]) and (new_note < self.notes[i + 1]): + self.notes.insert(i + 1, new_note) + return + + self.notes.append(new_note)
56ee5ac8225ffb7320c2b640160d0860dba3dee6
prompt_toolkit/contrib/validators/base.py
prompt_toolkit/contrib/validators/base.py
from __future__ import unicode_literals from prompt_toolkit.validation import Validator, ValidationError from six import string_types class SentenceValidator(Validator): """ Validate input only when it appears in this list of sentences. :param sentences: List of sentences. :param ignore_case: If True, case-insensitive comparisons. """ def __init__(self, sentences, ignore_case=False, error_message='Invalid input', move_cursor_to_end=False): assert all(isinstance(s, string_types) for s in sentences) assert isinstance(ignore_case, bool) assert isinstance(error_message, string_types) self.sentences = list(sentences) self.ignore_case = ignore_case self.error_message = error_message self.move_cursor_to_end = move_cursor_to_end if ignore_case: self.sentences = {s.lower() for s in self.sentences} def validate(self, document): if document.text not in self.sentences: if self.move_cursor_to_end: index = len(document.text) else: index = 0 raise ValidationError(cursor_position=index, message=self.error_message)
from __future__ import unicode_literals from prompt_toolkit.validation import Validator, ValidationError from six import string_types class SentenceValidator(Validator): """ Validate input only when it appears in this list of sentences. :param sentences: List of sentences. :param ignore_case: If True, case-insensitive comparisons. """ def __init__(self, sentences, ignore_case=False, error_message='Invalid input', move_cursor_to_end=False): assert all(isinstance(s, string_types) for s in sentences) assert isinstance(ignore_case, bool) assert isinstance(error_message, string_types) self.sentences = list(sentences) self.ignore_case = ignore_case self.error_message = error_message self.move_cursor_to_end = move_cursor_to_end if ignore_case: self.sentences = set([s.lower() for s in self.sentences]) def validate(self, document): if document.text not in self.sentences: if self.move_cursor_to_end: index = len(document.text) else: index = 0 raise ValidationError(cursor_position=index, message=self.error_message)
Remove set comprehension to support python 2.6
Remove set comprehension to support python 2.6
Python
bsd-3-clause
melund/python-prompt-toolkit,jonathanslenders/python-prompt-toolkit
--- +++ @@ -21,7 +21,7 @@ self.move_cursor_to_end = move_cursor_to_end if ignore_case: - self.sentences = {s.lower() for s in self.sentences} + self.sentences = set([s.lower() for s in self.sentences]) def validate(self, document): if document.text not in self.sentences:
758ca0f2308f2545a76f90a0f30c180c87ce3674
transport_tester.py
transport_tester.py
from gevent import monkey monkey.patch_all() # noqa import sys import time from ethereum import slogging from raiden.network.transport import UDPTransport from raiden.network.sockfactory import socket_factory class DummyProtocol(object): def __init__(self): self.raiden = None def receive(self, data): print data if __name__ == "__main__": slogging.configure(':DEBUG') with socket_factory('0.0.0.0', 8885) as mapped_socket: print mapped_socket t = UDPTransport(mapped_socket.socket, protocol=DummyProtocol()) while True: time.sleep(1) if len(sys.argv) > 1: t.send(None, (sys.argv[1], 8885), b'hello')
""" Usage: transport_tester.py [--port=<port>] [<target_ip_optional_port>] Options: -p --port=<port> Number to use [default: 8885]. """ from gevent import monkey monkey.patch_all() # noqa import time from docopt import docopt from ethereum import slogging from raiden.network.transport import UDPTransport from raiden.network.sockfactory import socket_factory class DummyProtocol(object): def __init__(self): self.raiden = None def receive(self, data): print data if __name__ == "__main__": slogging.configure(':DEBUG') options = docopt(__doc__) port = int(options['--port']) target = options['<target_ip_optional_port>'] if target and ':' in target: target, target_port = target.split(':') target_port = int(target_port) else: target_port = port with socket_factory('0.0.0.0', port) as mapped_socket: print mapped_socket t = UDPTransport(mapped_socket.socket, protocol=DummyProtocol()) while True: time.sleep(1) if target: t.send(None, (target, target_port), b'hello')
Allow more complex targetting in script test
Allow more complex targetting in script test
Python
mit
charles-cooper/raiden,charles-cooper/raiden,tomashaber/raiden,tomashaber/raiden,hackaugusto/raiden,tomashaber/raiden,tomashaber/raiden,tomashaber/raiden,hackaugusto/raiden
--- +++ @@ -1,8 +1,15 @@ +""" +Usage: + transport_tester.py [--port=<port>] [<target_ip_optional_port>] + +Options: + -p --port=<port> Number to use [default: 8885]. +""" from gevent import monkey monkey.patch_all() # noqa -import sys import time +from docopt import docopt from ethereum import slogging from raiden.network.transport import UDPTransport @@ -20,10 +27,18 @@ if __name__ == "__main__": slogging.configure(':DEBUG') - with socket_factory('0.0.0.0', 8885) as mapped_socket: + options = docopt(__doc__) + port = int(options['--port']) + target = options['<target_ip_optional_port>'] + if target and ':' in target: + target, target_port = target.split(':') + target_port = int(target_port) + else: + target_port = port + with socket_factory('0.0.0.0', port) as mapped_socket: print mapped_socket t = UDPTransport(mapped_socket.socket, protocol=DummyProtocol()) while True: time.sleep(1) - if len(sys.argv) > 1: - t.send(None, (sys.argv[1], 8885), b'hello') + if target: + t.send(None, (target, target_port), b'hello')
c073bc3290bbe33ede95a23354062b48b68ca23f
kbcstorage/__init__.py
kbcstorage/__init__.py
from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution('kbcstorage').version except DistributionNotFound: # package is not installed pass
from pkg_resources import get_distribution, DistributionNotFound try: release = get_distribution('kbcstorage').version __version__ = '.'.join(release.split('.')[:2]) except DistributionNotFound: # package is not installed pass
Make package version string major.minor only
Make package version string major.minor only
Python
mit
Ogaday/sapi-python-client,Ogaday/sapi-python-client
--- +++ @@ -1,6 +1,7 @@ from pkg_resources import get_distribution, DistributionNotFound try: - __version__ = get_distribution('kbcstorage').version + release = get_distribution('kbcstorage').version + __version__ = '.'.join(release.split('.')[:2]) except DistributionNotFound: # package is not installed pass
eb2f720d53ea4ff3450e78a30e1cdb53cd3357bb
tests/render/texture/runtest.py
tests/render/texture/runtest.py
#!/usr/bin/env python3 # # Copyright 2011-2015 Jeff Bush # # 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. # import sys sys.path.insert(0, '../..') import test_harness test_harness.register_render_test('render_texture', ['main.cpp'], '2ec4cc681873bc5978617e347d46f3b38230a3a0', targets=['emulator']) test_harness.execute_tests()
#!/usr/bin/env python3 # # Copyright 2011-2015 Jeff Bush # # 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. # import sys sys.path.insert(0, '../..') import test_harness test_harness.register_render_test('render_texture', ['main.cpp'], 'feb853e1a54d4ba2ce394142ea6119d5e401a60b', targets=['emulator']) test_harness.execute_tests()
Fix failing test caused by new toolchain
Fix failing test caused by new toolchain The challenge with floating point values in tests is that the value can change slightly based on the order of operations, which can legally be affected by optimizations. The results aren't visible (often just 1 ULP), but the tests validate exact bit patterns. This test would be more robust if it did a comparison with the target image and allowed some small amount of variability. Currently it computes a SHA checksum of the framebuffer. Updated the checksum for the new toolchain.
Python
apache-2.0
jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor
--- +++ @@ -21,6 +21,6 @@ import test_harness test_harness.register_render_test('render_texture', ['main.cpp'], - '2ec4cc681873bc5978617e347d46f3b38230a3a0', + 'feb853e1a54d4ba2ce394142ea6119d5e401a60b', targets=['emulator']) test_harness.execute_tests()
a04f3d167011e6d0e50d6a088f5877769fbedaa2
testfixtures/shop_order.py
testfixtures/shop_order.py
""" testfixtures.shop_order ~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.order.models.order import Order from byceps.services.shop.order.models.orderer import Orderer from byceps.services.shop.order import service from byceps.services.shop.order.transfer.models import PaymentMethod ANY_ORDER_NUMBER = 'AEC-03-B00074' def create_orderer(user): return Orderer( user.id, user.detail.first_names, user.detail.last_name, user.detail.country, user.detail.zip_code, user.detail.city, user.detail.street) def create_order(shop_id, placed_by, *, order_number=ANY_ORDER_NUMBER, payment_method=PaymentMethod.bank_transfer, shipping_required=False): order = Order( shop_id, order_number, placed_by.id, placed_by.detail.first_names, placed_by.detail.last_name, placed_by.detail.country, placed_by.detail.zip_code, placed_by.detail.city, placed_by.detail.street, payment_method, ) order.shipping_required = shipping_required return order def create_order_item(order, article, quantity): return service._add_article_to_order(order, article, quantity)
""" testfixtures.shop_order ~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.order.models.order import Order from byceps.services.shop.order.models.orderer import Orderer from byceps.services.shop.order.transfer.models import PaymentMethod ANY_ORDER_NUMBER = 'AEC-03-B00074' def create_orderer(user): return Orderer( user.id, user.detail.first_names, user.detail.last_name, user.detail.country, user.detail.zip_code, user.detail.city, user.detail.street) def create_order(shop_id, placed_by, *, order_number=ANY_ORDER_NUMBER, payment_method=PaymentMethod.bank_transfer, shipping_required=False): order = Order( shop_id, order_number, placed_by.id, placed_by.detail.first_names, placed_by.detail.last_name, placed_by.detail.country, placed_by.detail.zip_code, placed_by.detail.city, placed_by.detail.street, payment_method, ) order.shipping_required = shipping_required return order
Remove unused test fixture `create_order_item`
Remove unused test fixture `create_order_item`
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps
--- +++ @@ -8,7 +8,6 @@ from byceps.services.shop.order.models.order import Order from byceps.services.shop.order.models.orderer import Orderer -from byceps.services.shop.order import service from byceps.services.shop.order.transfer.models import PaymentMethod @@ -45,7 +44,3 @@ order.shipping_required = shipping_required return order - - -def create_order_item(order, article, quantity): - return service._add_article_to_order(order, article, quantity)
0cad0060afcc5936541b3739ff03c06b8a773ec8
tests/templatetags/test_tags.py
tests/templatetags/test_tags.py
from django import template from lazy_tags.decorators import lazy_tag register = template.Library() @register.simple_tag def test(): return '<p>hello world</p>' @register.simple_tag @lazy_tag def test_decorator(): return 'Success!' @register.simple_tag @lazy_tag def test_simple_dec_args(arg, kwarg=None): return '{0} {1}'.format(arg, kwarg) @register.inclusion_tag('tests/decorator_tag_with_args.html') @lazy_tag def test_decorator_with_args(arg, kwarg=None): return { 'arg': arg, 'kwarg': kwarg } @register.simple_tag def test_with_sleep(): import time time.sleep(2) return '<ul style="text-align: left;"><li>Steve Jobs</li><li>Bill Gates</li><li>Elon Musk</li></ul>' @register.inclusion_tag('tests/inclusion_tag_with_args.html') def test_with_args(arg, kwarg=None): return { 'arg': arg, 'kwarg': kwarg } @register.simple_tag def test_orm(user): return '<p>{} | {}</p>'.format(user.username, user.email) @register.inclusion_tag('tests/inclusion_tag.html') def inclusion(): return {'test': 'hello world'}
from django import template from django.utils.safestring import mark_safe from lazy_tags.decorators import lazy_tag register = template.Library() @register.simple_tag def test(): return mark_safe('<p>hello world</p>') @register.simple_tag @lazy_tag def test_decorator(): return 'Success!' @register.simple_tag @lazy_tag def test_simple_dec_args(arg, kwarg=None): return '{0} {1}'.format(arg, kwarg) @register.inclusion_tag('tests/decorator_tag_with_args.html') @lazy_tag def test_decorator_with_args(arg, kwarg=None): return { 'arg': arg, 'kwarg': kwarg } @register.simple_tag def test_with_sleep(): import time time.sleep(2) return '<ul style="text-align: left;"><li>Steve Jobs</li><li>Bill Gates</li><li>Elon Musk</li></ul>' @register.inclusion_tag('tests/inclusion_tag_with_args.html') def test_with_args(arg, kwarg=None): return { 'arg': arg, 'kwarg': kwarg } @register.simple_tag def test_orm(user): return '<p>{} | {}</p>'.format(user.username, user.email) @register.inclusion_tag('tests/inclusion_tag.html') def inclusion(): return {'test': 'hello world'}
Fix test on Django 1.9
Fix test on Django 1.9
Python
mit
grantmcconnaughey/django-lazy-tags,grantmcconnaughey/django-lazy-tags
--- +++ @@ -1,4 +1,5 @@ from django import template +from django.utils.safestring import mark_safe from lazy_tags.decorators import lazy_tag @@ -8,7 +9,7 @@ @register.simple_tag def test(): - return '<p>hello world</p>' + return mark_safe('<p>hello world</p>') @register.simple_tag
3b71f6600d437a4e5f167315683e7f0137cd3788
tilenol/xcb/keysymparse.py
tilenol/xcb/keysymparse.py
import os import re keysym_re = re.compile(r"^#define\s+(XF86)?XK_(\w+)\s+(\S+)") class Keysyms(object): __slots__ = ('name_to_code', 'code_to_name', '__dict__') def __init__(self): self.name_to_code = {} self.code_to_name = {} def add_from_file(self, filename): with open(filename, 'rt') as f: for line in f: m = keysym_re.match(line) if not m: continue name = (m.group(1) or '') + m.group(2) code = int(m.group(3), 0) self.__dict__[name] = code self.name_to_code[name] = code self.code_to_name[code] = name def load_default(self): xproto_dir = os.environ.get("XPROTO_DIR", "/usr/include/X11") self.add_from_file(xproto_dir + '/keysymdef.h') self.add_from_file(xproto_dir + '/XF86keysym.h')
import os import re import logging log = logging.getLogger(__name__) keysym_re = re.compile( r"^#define\s+(XF86)?XK_(\w+)\s+" r"(?:(0x[a-fA-F0-9]+)|_EVDEV\((0x[0-9a-fA-F]+)\))" ) class Keysyms(object): __slots__ = ('name_to_code', 'code_to_name', '__dict__') def __init__(self): self.name_to_code = {} self.code_to_name = {} def add_from_file(self, filename): with open(filename, 'rt') as f: for line in f: m = keysym_re.match(line) if not m: continue name = (m.group(1) or '') + m.group(2) if m.group(3): try: code = int(m.group(3), 0) except ValueError: log.warn("Bad code %r for key %r", code, name) continue elif m.group(4): try: code = int(m.group(4), 0) except ValueError: log.warn("Bad code %r for evdev key %r", code, name) continue else: continue self.__dict__[name] = code self.name_to_code[name] = code self.code_to_name[code] = name def load_default(self): xproto_dir = os.environ.get("XPROTO_DIR", "/usr/include/X11") self.add_from_file(xproto_dir + '/keysymdef.h') self.add_from_file(xproto_dir + '/XF86keysym.h')
Fix support of fresh keysym file
Fix support of fresh keysym file
Python
mit
tailhook/tilenol,tailhook/tilenol
--- +++ @@ -1,7 +1,12 @@ import os import re +import logging -keysym_re = re.compile(r"^#define\s+(XF86)?XK_(\w+)\s+(\S+)") +log = logging.getLogger(__name__) +keysym_re = re.compile( + r"^#define\s+(XF86)?XK_(\w+)\s+" + r"(?:(0x[a-fA-F0-9]+)|_EVDEV\((0x[0-9a-fA-F]+)\))" +) class Keysyms(object): @@ -18,7 +23,22 @@ if not m: continue name = (m.group(1) or '') + m.group(2) - code = int(m.group(3), 0) + + if m.group(3): + try: + code = int(m.group(3), 0) + except ValueError: + log.warn("Bad code %r for key %r", code, name) + continue + elif m.group(4): + try: + code = int(m.group(4), 0) + except ValueError: + log.warn("Bad code %r for evdev key %r", code, name) + continue + else: + continue + self.__dict__[name] = code self.name_to_code[name] = code self.code_to_name[code] = name
0a718ccee8301f28e86791e06159e6ed8a2674b4
twobuntu/articles/forms.py
twobuntu/articles/forms.py
from django import forms from twobuntu.articles.models import Article, ScheduledArticle class EditorForm(forms.ModelForm): """ Form for entering or editing articles. """ class Meta: model = Article fields = ('category', 'title', 'body') class ScheduledArticleForm(forms.ModelForm): """ Form for scheduling articles. """ class Meta: model = ScheduledArticle fields = ('date',) class DeleteArticleForm(forms.Form): """ Form for deleting articles. """ # Intentionally blank - submitting the form # is considered consent to delete the article.
from django import forms from twobuntu.articles.models import Article, ScheduledArticle class EditorForm(forms.ModelForm): """ Form for entering or editing articles. """ # The <textarea> needs this set so that the form can validate on the client # side without any content (due to ACE editor) use_required_attribute = False class Meta: model = Article fields = ('category', 'title', 'body') class ScheduledArticleForm(forms.ModelForm): """ Form for scheduling articles. """ class Meta: model = ScheduledArticle fields = ('date',) class DeleteArticleForm(forms.Form): """ Form for deleting articles. """ # Intentionally blank - submitting the form # is considered consent to delete the article.
Fix error submitting article caused by extra HTML attribute.
Fix error submitting article caused by extra HTML attribute.
Python
apache-2.0
2buntu/2buntu-blog,2buntu/2buntu-blog,2buntu/2buntu-blog
--- +++ @@ -7,6 +7,10 @@ """ Form for entering or editing articles. """ + + # The <textarea> needs this set so that the form can validate on the client + # side without any content (due to ACE editor) + use_required_attribute = False class Meta: model = Article
56448179cb1e93670c478f45258a261ec972385d
weathergenerator.py
weathergenerator.py
class WeatherType: def __init__(self, weathers, temperature_range, temperature_night_offset, wind_range, humidity_range): self.__weathers = weathers self.__min_temp_day, self.__max_temp_day = \ tuple(temperature_range) self.__min_temp_night, self.__max_temp_night = \ tuple(map(lambda x: x- temperature_night_offset, temperature_range)) self.__min_wind_speed, self.__max_wind_speed = \ tuple(wind_range) self.__min_humidity, self.__max_humidity = \ tuple(humidity_range)
class WeatherType: def __init__(self, weathers, temperature_range, temperature_night_offset, wind_range, humidity_range): self.__weathers = weathers self.__min_temp_day, self.__max_temp_day = \ tuple(temperature_range) self.__min_temp_night, self.__max_temp_night = \ tuple(map(lambda x: x- temperature_night_offset, temperature_range)) self.__min_wind_speed, self.__max_wind_speed = \ tuple(wind_range) self.__min_humidity, self.__max_humidity = \ tuple(humidity_range) # FIXME: temperature_night_offset is always the same weather_types = \ [WeatherType(["sunny, cloudy", "rain"], (3, 40), 7, (2, 20), (10, 90)), WeatherType(["sunny", "cloudy", "snow"], (-25, 0), 7, (2, 20), (10, 90))]
Add some draft weather types
Add some draft weather types temperature_night_offset should possibly be the range so difference between night and day is not always the same.
Python
mit
foxpy/random-weather-bot,foxpy/random-weather-bot
--- +++ @@ -11,3 +11,10 @@ tuple(wind_range) self.__min_humidity, self.__max_humidity = \ tuple(humidity_range) + +# FIXME: temperature_night_offset is always the same +weather_types = \ + [WeatherType(["sunny, cloudy", "rain"], + (3, 40), 7, (2, 20), (10, 90)), + WeatherType(["sunny", "cloudy", "snow"], + (-25, 0), 7, (2, 20), (10, 90))]
e12a4504da0b40ad66e116aa9a0373d1abc6d160
mongo_test/handlers.py
mongo_test/handlers.py
import subprocess import commands import re import signal import os import logging _logger = logging.getLogger(__name__) TARGET_DIR='test/target' PORT='27018' def startup(): _logger.info("about to start mongod") p = subprocess.Popen([commands.getoutput('which mongod'), '--port', PORT, '--fork', '--dbpath', '{0}/db'.format(TARGET_DIR), '--logpath', '{0}/mongo.log'.format(TARGET_DIR), '--smallfiles', '--noprealloc']) p.wait() _logger.info("mongod started successfully") def teardown(): _logger.info("about to stop mongod") with open('{0}/db/mongod.lock'.format(TARGET_DIR), 'r') as log_file: first_line = log_file.readline() pid = int(first_line) os.kill(pid, signal.SIGTERM) _logger.info("mongodb stopped")
import subprocess import commands import signal import os import logging _logger = logging.getLogger(__name__) TARGET_DIR='test/target' PORT='27018' def startup(mongo_path): _logger.info("about to start mongod") path = mongo_path or commands.getoutput('which mongod') p = subprocess.Popen([path, '--port', PORT, '--fork', '--dbpath', '{0}/db'.format(TARGET_DIR), '--logpath', '{0}/mongo.log'.format(TARGET_DIR), '--smallfiles', '--noprealloc']) p.wait() _logger.info("mongod started successfully") def teardown(): _logger.info("about to stop mongod") with open('{0}/db/mongod.lock'.format(TARGET_DIR), 'r') as log_file: first_line = log_file.readline() pid = int(first_line) os.kill(pid, signal.SIGTERM) _logger.info("mongodb stopped")
Allow the option of specifying a path in startup
Allow the option of specifying a path in startup
Python
mit
idbentley/MongoTest
--- +++ @@ -1,6 +1,5 @@ import subprocess import commands -import re import signal import os import logging @@ -10,9 +9,10 @@ TARGET_DIR='test/target' PORT='27018' -def startup(): +def startup(mongo_path): _logger.info("about to start mongod") - p = subprocess.Popen([commands.getoutput('which mongod'), + path = mongo_path or commands.getoutput('which mongod') + p = subprocess.Popen([path, '--port', PORT, '--fork', '--dbpath', '{0}/db'.format(TARGET_DIR),
cf8b49edfc38a98b4f6beba66bedcc13298eb114
yunity/utils/tests/mock.py
yunity/utils/tests/mock.py
from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, post_generation, SubFactory from yunity.models import Category from yunity.utils.tests.fake import faker class Mock(DjangoModelFactory): class Meta: strategy = CREATE_STRATEGY model = None abstract = True class MockCategory(Mock): class Meta: model = "yunity.Category" strategy = CREATE_STRATEGY class MockUser(Mock): class Meta: model = "yunity.User" strategy = CREATE_STRATEGY is_active = True is_staff = False type = Category.objects.get(name='user.default') display_name = LazyAttribute(lambda _: faker.name()) email = LazyAttribute(lambda _: faker.email()) password = LazyAttribute(lambda _: faker.password()) locations = LazyAttribute(lambda _: [faker.location() for _ in range(2)]) class MockChat(Mock): class Meta: model = "yunity.Chat" strategy = CREATE_STRATEGY administrated_by = SubFactory(MockUser) @post_generation def participants(self, create, extracted, **kwargs): if not create: return if extracted: for participant in extracted: self.participants.add(participant)
from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, post_generation, SubFactory from yunity.models import Category from yunity.utils.tests.fake import faker class Mock(DjangoModelFactory): class Meta: strategy = CREATE_STRATEGY model = None abstract = True class MockCategory(Mock): class Meta: model = "yunity.Category" strategy = CREATE_STRATEGY class MockUser(Mock): class Meta: model = "yunity.User" strategy = CREATE_STRATEGY is_active = True is_staff = False type = Category.objects.get(name='user.default') display_name = LazyAttribute(lambda _: faker.name()) email = LazyAttribute(lambda _: faker.email()) password = LazyAttribute(lambda _: faker.password()) locations = LazyAttribute(lambda _: [faker.location() for _ in range(2)]) class MockChat(Mock): class Meta: model = "yunity.Chat" strategy = CREATE_STRATEGY administrated_by = SubFactory(MockUser) @post_generation def participants(self, created, participants, **kwargs): if not created: return if participants: for participant in participants: self.participants.add(participant)
Rename some variables to try to explain magic
Rename some variables to try to explain magic
Python
agpl-3.0
yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core
--- +++ @@ -39,9 +39,9 @@ administrated_by = SubFactory(MockUser) @post_generation - def participants(self, create, extracted, **kwargs): - if not create: + def participants(self, created, participants, **kwargs): + if not created: return - if extracted: - for participant in extracted: + if participants: + for participant in participants: self.participants.add(participant)
bc9f4d4e5022f4219727e9085164982f9efb005e
editor/views/generic.py
editor/views/generic.py
import git import os from django.conf import settings from django.http import HttpResponseRedirect from django.shortcuts import render class SaveContentMixin(): """Save exam or question content to a git repository and to a database.""" # object = None # request = None # template_name = None def write_content(self, directory, form, inlines=None): try: repo = git.Repo(settings.GLOBAL_SETTINGS['REPO_PATH']) path_to_file = os.path.join(settings.GLOBAL_SETTINGS['REPO_PATH'], directory, self.object.filename) fh = open(path_to_file, 'w') fh.write(self.object.content) fh.close() repo.index.add([os.path.join(directory, self.object.filename)]) repo.index.commit('Made some changes to %s' % self.object.name) except IOError: error = "Could not save file." return render(self.request, self.template_name, {'form': form, 'inlines': inlines, 'error': error, 'object': self.object}) self.object = form.save() if inlines is not None: for formset in inlines: formset.save() return HttpResponseRedirect(self.get_success_url())
import git import os from django.conf import settings from django.http import HttpResponseRedirect from django.shortcuts import render class SaveContentMixin(): """Save exam or question content to a git repository and to a database.""" # object = None # request = None # template_name = None def write_content(self, directory, form, inlines=None): try: repo = git.Repo(settings.GLOBAL_SETTINGS['REPO_PATH']) os.environ['GIT_AUTHOR_NAME'] = 'Numbas' os.environ['GIT_AUTHOR_EMAIL'] = 'numbas@ncl.ac.uk' path_to_file = os.path.join(settings.GLOBAL_SETTINGS['REPO_PATH'], directory, self.object.filename) fh = open(path_to_file, 'w') fh.write(self.object.content) fh.close() repo.index.add([os.path.join(directory, self.object.filename)]) repo.index.commit('Made some changes to %s' % self.object.name) except IOError: error = "Could not save file." return render(self.request, self.template_name, {'form': form, 'inlines': inlines, 'error': error, 'object': self.object}) self.object = form.save() if inlines is not None: for formset in inlines: formset.save() return HttpResponseRedirect(self.get_success_url())
Set the git author name and e-mail
Set the git author name and e-mail
Python
apache-2.0
numbas/editor,numbas/editor,numbas/editor
--- +++ @@ -16,6 +16,8 @@ def write_content(self, directory, form, inlines=None): try: repo = git.Repo(settings.GLOBAL_SETTINGS['REPO_PATH']) + os.environ['GIT_AUTHOR_NAME'] = 'Numbas' + os.environ['GIT_AUTHOR_EMAIL'] = 'numbas@ncl.ac.uk' path_to_file = os.path.join(settings.GLOBAL_SETTINGS['REPO_PATH'], directory, self.object.filename) fh = open(path_to_file, 'w')
7b8ba30efc8853ab19dfd95a97f56c8329ddfb4b
newsParser/__init__.py
newsParser/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: balicanta # @Date: 2014-11-01 21:02:00 # @Last Modified by: balicanta # @Last Modified time: 2014-11-01 21:02:00
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: balicanta # @Date: 2014-11-01 21:02:00 # @Last Modified by: balicanta # @Last Modified time: 2014-11-05 22:19:01 from NewsParser import NewsParser
Add initi for beautiful API
Add initi for beautiful API
Python
mit
Lab-317/NewsParser
--- +++ @@ -3,4 +3,6 @@ # @Author: balicanta # @Date: 2014-11-01 21:02:00 # @Last Modified by: balicanta -# @Last Modified time: 2014-11-01 21:02:00 +# @Last Modified time: 2014-11-05 22:19:01 + +from NewsParser import NewsParser
e15484bc57b47513545b2be423f24d4dd0312590
comics/management/commands/generatesecretkey.py
comics/management/commands/generatesecretkey.py
from __future__ import unicode_literals import os, re import tenma from django.conf import settings from django.core import management from django.utils.crypto import get_random_string from shutil import copyfile, move BASE_DIR = os.path.dirname(tenma.__file__) class Command(management.BaseCommand): help = 'Generates a random secret key.' @staticmethod def _generate_secret_key(): chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+[\{]\{;:,<.>/?' return get_random_string(50, chars) def handle(self, *args, **options): orig = os.path.join(BASE_DIR, 'settings.py') temp = os.path.join(BASE_DIR, 'temp.py') copyfile(orig, temp) with open(temp, 'w') as new_file: with open(orig) as old_file: for line in old_file: secret_key = re.match(r'^SECRET_KEY ?=', line) if secret_key: line = "SECRET_KEY = '{0}'".format(Command._generate_secret_key()) + '\n' new_file.write(line) new_file.close() os.remove(orig) os.rename(temp, orig)
from __future__ import unicode_literals import os, re import tenma from django.conf import settings from django.core import management from django.utils.crypto import get_random_string from shutil import copyfile, move BASE_DIR = os.path.dirname(tenma.__file__) class Command(management.BaseCommand): help = 'Generates a random secret key.' @staticmethod def _generate_secret_key(): chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+' return get_random_string(50, chars) def handle(self, *args, **options): orig = os.path.join(BASE_DIR, 'settings.py') temp = os.path.join(BASE_DIR, 'temp.py') copyfile(orig, temp) with open(temp, 'w') as new_file: with open(orig) as old_file: for line in old_file: secret_key = re.match(r'^SECRET_KEY ?=', line) if secret_key: line = "SECRET_KEY = '{0}'".format(Command._generate_secret_key()) + '\n' new_file.write(line) new_file.close() os.remove(orig) os.rename(temp, orig)
Fix some characters messing up the SECRET_KEY
Fix some characters messing up the SECRET_KEY
Python
mit
Tenma-Server/Tenma,hmhrex/Tenma,Tenma-Server/Tenma,hmhrex/Tenma,Tenma-Server/Tenma,hmhrex/Tenma
--- +++ @@ -15,7 +15,7 @@ @staticmethod def _generate_secret_key(): - chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+[\{]\{;:,<.>/?' + chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+' return get_random_string(50, chars) def handle(self, *args, **options):
e3c7322b0efe10041ba9c38963b9e9f188d9a54a
pkit/slot/decorators.py
pkit/slot/decorators.py
import functools from pkit.slot import get_slot_pool def acquire(pool_name): """Actor's method decorator to auto-acquire a slot before execution""" def decorator(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): slots_pool = get_slot_pool(pool_name) try: # Unix semaphores are acquired through sem_post and sem_wait # syscalls, which can potentially fail. slots_pool.acquire() except OSError: pass res = method(self, *args, **kwargs) return res return wrapper return decorator def release(pool_name): """Actors method decorator to auto-release a used slot after execution""" def decorator(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): slots_pool = get_slot_pool(pool_name) res = method(self, *args, **kwargs) try: slots_pool.release() except OSError: pass return res return wrapper return decorator
import functools from pkit.slot import get_slot_pool def acquire(pool_name): """Actor's method decorator to auto-acquire a slot before execution""" def decorator(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): slots_pool = get_slot_pool(pool_name) try: # Unix semaphores are acquired through sem_post and sem_wait # syscalls, which can potentially fail. slots_pool.acquire() except OSError: pass res = method(self, *args, **kwargs) return res return wrapper return decorator def release(pool_name): """Actors method decorator to auto-release a used slot after execution""" def decorator(method): @functools.wraps(method) def wrapper(self, *args, **kwargs): slots_pool = get_slot_pool(pool_name) try: res = method(self, *args, **kwargs) except Exception: raise finally: try: slots_pool.release() except OSError: pass return res return wrapper return decorator
Fix slot release on method exception
Fix slot release on method exception
Python
mit
botify-labs/process-kit
--- +++ @@ -29,12 +29,16 @@ @functools.wraps(method) def wrapper(self, *args, **kwargs): slots_pool = get_slot_pool(pool_name) - res = method(self, *args, **kwargs) try: - slots_pool.release() - except OSError: - pass + res = method(self, *args, **kwargs) + except Exception: + raise + finally: + try: + slots_pool.release() + except OSError: + pass return res
e567b70608d25a4f3e0e189ea51edb2c4f0aa2be
cronos/libraries/log.py
cronos/libraries/log.py
# -*- coding: utf-8 -*- from django.conf import settings from django.core.mail import send_mail import logging #import traceback def cronos_debug(msg, logfile): ''' To be deprecated, along with the import logging and settings ''' logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s: %(message)s', filename = settings.LOGDIR + logfile, filemode = 'a+') logging.debug(msg) def mail_cronos_admin(title, message): ''' Wrapper function of send_mail ''' try: send_mail(title, message, 'notification@cronos.teilar.gr', ['cronos@teilar.gr']) except: pass class CronosError(Exception): ''' Custom Exception class ''' def __init__(self, value): self.value = value def __unicode__(self): return repr(self.value) def log_extra_data(request = None, form = None): ''' Extra data needed by the custom formatter All values default to None ''' log_extra_data = { 'client_ip': request.META.get('REMOTE_ADDR','None') if request else '', 'username': '', } if form: log_extra_data['username'] = form.data.get('username', 'None') else: try: if request.user.is_authenticated(): ''' Handle logged in users ''' log_extra_data['username'] = request.user.name else: ''' Handle anonymous users ''' log_extra_data['username'] = 'Anonymous' except AttributeError: pass return log_extra_data
# -*- coding: utf-8 -*- from django.conf import settings from django.core.mail import send_mail def mail_cronos_admin(title, message): ''' Wrapper function of send_mail ''' try: send_mail(title, message, 'notification@cronos.teilar.gr', [settings.ADMIN[0][1]]) except: pass class CronosError(Exception): ''' Custom Exception class ''' def __init__(self, value): self.value = value def __unicode__(self): return repr(self.value) def log_extra_data(request = None, form = None): ''' Extra data needed by the custom formatter All values default to None ''' log_extra_data = { 'client_ip': request.META.get('REMOTE_ADDR','None') if request else '', 'username': '', } if form: log_extra_data['username'] = form.data.get('username', 'None') else: try: if request.user.is_authenticated(): ''' Handle logged in users ''' log_extra_data['username'] = request.user.name else: ''' Handle anonymous users ''' log_extra_data['username'] = 'Anonymous' except AttributeError: pass return log_extra_data
Remove cronos_debug, un-hardcode the mail address in mail_cronos_admin
Remove cronos_debug, un-hardcode the mail address in mail_cronos_admin
Python
agpl-3.0
LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr
--- +++ @@ -2,22 +2,13 @@ from django.conf import settings from django.core.mail import send_mail -import logging -#import traceback - -def cronos_debug(msg, logfile): - ''' - To be deprecated, along with the import logging and settings - ''' - logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s: %(message)s', filename = settings.LOGDIR + logfile, filemode = 'a+') - logging.debug(msg) def mail_cronos_admin(title, message): ''' Wrapper function of send_mail ''' try: - send_mail(title, message, 'notification@cronos.teilar.gr', ['cronos@teilar.gr']) + send_mail(title, message, 'notification@cronos.teilar.gr', [settings.ADMIN[0][1]]) except: pass
06d0f52608f79f675847e903577e20be03189041
django_any/forms.py
django_any/forms.py
# -*- coding: utf-8 -*- """ Django forms data generators """ from django import forms from django_any import xunit class FormFieldDataFactory(object): def __init__(self): self.registry = {} def register(self, field_type, impl=None): def _wrapper(func): self.registry[field_type] = func return func if impl: return _wrapper(func) return _wrapper def decorator(self, impl=None): self.__call__ = impl(self.__call__) def __call__(self, *args, **kwargs): if not len(args): raise TypeError('Field instance are not provided') function = self.registry.get(args[0].__class__) if function is None: raise TypeError("no match %s" % types) return function(*args, **kwargs) any_form_field = FormFieldDataFactory() @any_form_field.register(forms.BooleanField) def field(field, **kwargs): """ Return random value for BooleanField >>> result = any_form_field(forms.BooleanField()) >>> type(result) <type 'bool'> """ return xunit.any_boolean()
# -*- coding: utf-8 -*- """ Django forms data generators """ from django import forms from django_any import xunit class FormFieldDataFactory(object): """ Registry storage for form field data functions Works like one parameter multimethod """ def __init__(self): self.registry = {} def register(self, field_type, impl=None): """ Register form field data function. Could be used as decorator """ def _wrapper(func): self.registry[field_type] = func return func if impl: return _wrapper(func) return _wrapper def decorator(self, impl=None): """ Decorator for register decorators """ self.__call__ = impl(self.__call__) def __call__(self, *args, **kwargs): if not len(args): raise TypeError('Field instance are not provided') field_type = args[0].__class__ function = self.registry.get(field_type) if function is None: raise TypeError("no match %s" % field_type) return function(*args, **kwargs) any_form_field = FormFieldDataFactory() @any_form_field.register(forms.BooleanField) def boolean_field_data(field, **kwargs): """ Return random value for BooleanField >>> result = any_form_field(forms.BooleanField()) >>> type(result) <type 'bool'> """ return xunit.any_boolean()
Fix some pylint found errors and warnings
Fix some pylint found errors and warnings
Python
mit
kmmbvnr/django-any,abakar/django-whatever,abakar/django-whatever
--- +++ @@ -7,10 +7,20 @@ from django_any import xunit class FormFieldDataFactory(object): + """ + Registry storage for form field data functions + + Works like one parameter multimethod + """ def __init__(self): self.registry = {} def register(self, field_type, impl=None): + """ + Register form field data function. + + Could be used as decorator + """ def _wrapper(func): self.registry[field_type] = func return func @@ -20,16 +30,21 @@ return _wrapper def decorator(self, impl=None): + """ + Decorator for register decorators + """ self.__call__ = impl(self.__call__) def __call__(self, *args, **kwargs): if not len(args): raise TypeError('Field instance are not provided') - function = self.registry.get(args[0].__class__) + field_type = args[0].__class__ + + function = self.registry.get(field_type) if function is None: - raise TypeError("no match %s" % types) + raise TypeError("no match %s" % field_type) return function(*args, **kwargs) @@ -37,7 +52,7 @@ @any_form_field.register(forms.BooleanField) -def field(field, **kwargs): +def boolean_field_data(field, **kwargs): """ Return random value for BooleanField
6dcbc85b59bd9cc7eed381c7ef0efeb2f78620cf
comics/comics/whomp.py
comics/comics/whomp.py
import re from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Whomp!" language = "en" url = "http://www.whompcomic.com/" start_date = "2010-06-14" rights = "Ronnie Filyaw" class Crawler(CrawlerBase): history_capable_days = 30 schedule = "Mo,We,Fr" time_zone = "US/Eastern" def crawl(self, pub_date): feed = self.parse_feed("http://www.whompcomic.com/feed/rss/") for entry in feed.all(): url = entry.summary.src('img[src*="/comics-rss/"]') if not url: continue title = entry.title url = url.replace("comics-rss", "comics") text = entry.summary.alt('img[src*="/comics-rss/"]') # Extract date from URL, since we don't have this in the XML match = re.search(r"comics/(\d{4}-\d{2}-\d{2})", url) if match: comic_date = self.string_to_date(match.group(1), "%Y-%m-%d") if pub_date == comic_date: return CrawlerImage(url, title, text)
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Whomp!" language = "en" url = "http://www.whompcomic.com/" start_date = "2010-06-14" rights = "Ronnie Filyaw" class Crawler(CrawlerBase): history_capable_days = 70 schedule = "We,Fr" time_zone = "US/Eastern" def crawl(self, pub_date): feed = self.parse_feed("http://www.whompcomic.com/comic/rss") for entry in feed.for_date(pub_date): page = self.parse_page(entry.link) url = page.src("img#cc-comic") text = page.title("img#cc-comic") title = entry.title.replace("Whomp! - ", "") return CrawlerImage(url, title, text)
Rewrite crawler for "Whomp!" after feed change
Rewrite crawler for "Whomp!" after feed change
Python
agpl-3.0
datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics
--- +++ @@ -1,5 +1,3 @@ -import re - from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase @@ -13,26 +11,16 @@ class Crawler(CrawlerBase): - history_capable_days = 30 - schedule = "Mo,We,Fr" + history_capable_days = 70 + schedule = "We,Fr" time_zone = "US/Eastern" def crawl(self, pub_date): - feed = self.parse_feed("http://www.whompcomic.com/feed/rss/") + feed = self.parse_feed("http://www.whompcomic.com/comic/rss") + for entry in feed.for_date(pub_date): + page = self.parse_page(entry.link) + url = page.src("img#cc-comic") + text = page.title("img#cc-comic") + title = entry.title.replace("Whomp! - ", "") - for entry in feed.all(): - url = entry.summary.src('img[src*="/comics-rss/"]') - if not url: - continue - - title = entry.title - url = url.replace("comics-rss", "comics") - text = entry.summary.alt('img[src*="/comics-rss/"]') - - # Extract date from URL, since we don't have this in the XML - match = re.search(r"comics/(\d{4}-\d{2}-\d{2})", url) - if match: - comic_date = self.string_to_date(match.group(1), "%Y-%m-%d") - - if pub_date == comic_date: - return CrawlerImage(url, title, text) + return CrawlerImage(url, title, text)
1224e7e2f12b455ffa1f8c102b30012d63716cae
flask_bracket/errors.py
flask_bracket/errors.py
"""API errors.""" from werkzeug.exceptions import HTTPException class Error(Exception): status = 500 error = "internal server error" def __init__(self, error=None, status=None): """Create an API error with the given error and status code.""" self.status = status or self.__class__.status self.error = error or self.__class__.error @property def response(self): """Return the error as a repsonse tuple.""" return {'status': self.status, 'error': self.error}, self.status def get_error_response(error): """Return an error as a response tuple.""" if isinstance(error, HTTPException): error = Error(error.name, error.code) if not isinstance(error, Error): error = Error() return error.response
"""API errors.""" from werkzeug.exceptions import HTTPException class Error(Exception): status = 500 error = "internal server error" def __init__(self, error=None, status=None): """Create an API error with the given error and status code.""" self.status = status or self.__class__.status self.error = error or self.__class__.error @property def response(self): """Return the error as a repsonse tuple.""" return {'error': self.error}, self.status def get_error_response(error): """Return an error as a response tuple.""" if isinstance(error, HTTPException): error = Error(error.name, error.code) if not isinstance(error, Error): error = Error() return error.response
Remove redundant status code from error response body.
Remove redundant status code from error response body.
Python
bsd-3-clause
JsonChiu/flask-bracket
--- +++ @@ -14,7 +14,7 @@ @property def response(self): """Return the error as a repsonse tuple.""" - return {'status': self.status, 'error': self.error}, self.status + return {'error': self.error}, self.status def get_error_response(error):
4029da285fff38524cd30212475868ccda457df6
pylibscrypt/__init__.py
pylibscrypt/__init__.py
'Scrypt for Python' __version__ = '1.1.0' # First, try loading libscrypt _done = False try: from pylibscrypt import * except ImportError: pass else: _done = True # If that didn't work, try the scrypt module if not _done: try: from pyscrypt import * except ImportError: pass else: _done = True # Unless we are on pypy, we want to try libsodium as well if not _done: import platform if platform.python_implementation() != 'PyPy': try: from pylibsodium import * except ImportError: pass else: _done = True # If that didn't work either, the inlined Python version if not _done: try: from pypyscrypt_inline import * except ImportError: pass else: _done = True # Finally the non-inlined if not _done: from pypyscrypt import * __all__ = ['scrypt', 'scrypt_mcf', 'scrypt_mcf_check'] # Clean up pydoc output del __path__ del consts
"""Scrypt for Python""" __version__ = '1.2.0-git' # First, try loading libscrypt _done = False try: from pylibscrypt import * except ImportError: pass else: _done = True # If that didn't work, try the scrypt module if not _done: try: from pyscrypt import * except ImportError: pass else: _done = True # Unless we are on pypy, we want to try libsodium as well if not _done: import platform if platform.python_implementation() != 'PyPy': try: from pylibsodium import * except ImportError: pass else: _done = True # If that didn't work either, the inlined Python version if not _done: try: from pypyscrypt_inline import * except ImportError: pass else: _done = True # Finally the non-inlined if not _done: from pypyscrypt import * __all__ = ['scrypt', 'scrypt_mcf', 'scrypt_mcf_check'] # Clean up pydoc output del __path__ del consts
Increment version number for git master
Increment version number for git master
Python
isc
jvarho/pylibscrypt,jvarho/pylibscrypt
--- +++ @@ -1,6 +1,6 @@ -'Scrypt for Python' +"""Scrypt for Python""" -__version__ = '1.1.0' +__version__ = '1.2.0-git' # First, try loading libscrypt _done = False
111dc7a749e783af2bd9bb391520cf5b8f846027
test/python_api/disassemble-raw-data/TestDisassembleRawData.py
test/python_api/disassemble-raw-data/TestDisassembleRawData.py
""" Use lldb Python API to disassemble raw machine code bytes """ import os, time import re import unittest2 import lldb, lldbutil from lldbtest import * class DisassembleRawDataTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @python_api_test def test_disassemble_raw_data(self): """Test disassembling raw bytes with the API.""" self.disassemble_raw_data() def disassemble_raw_data(self): """Test disassembling raw bytes with the API.""" # Create a target from the debugger. target = self.dbg.CreateTargetWithFileAndTargetTriple ("", "x86_64") self.assertTrue(target, VALID_TARGET) raw_bytes = bytearray([0x48, 0x89, 0xe5]) insts = target.GetInstructions(lldb.SBAddress(), raw_bytes) inst = insts.GetInstructionAtIndex(0) if self.TraceOn(): print print "Raw bytes: ", [hex(x) for x in raw_bytes] print "Disassembled%s" % str(inst) self.assertTrue (inst.GetMnemonic(target) == "movq") self.assertTrue (inst.GetOperands(target) == '%' + "rsp, " + '%' + "rbp") if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
""" Use lldb Python API to disassemble raw machine code bytes """ import os, time import re import unittest2 import lldb, lldbutil from lldbtest import * class DisassembleRawDataTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @python_api_test def test_disassemble_raw_data(self): """Test disassembling raw bytes with the API.""" self.disassemble_raw_data() def disassemble_raw_data(self): """Test disassembling raw bytes with the API.""" # Create a target from the debugger. target = self.dbg.CreateTargetWithFileAndTargetTriple ("", "x86_64") self.assertTrue(target, VALID_TARGET) raw_bytes = bytearray([0x48, 0x89, 0xe5]) insts = target.GetInstructions(lldb.SBAddress(0, target), raw_bytes) inst = insts.GetInstructionAtIndex(0) if self.TraceOn(): print print "Raw bytes: ", [hex(x) for x in raw_bytes] print "Disassembled%s" % str(inst) self.assertTrue (inst.GetMnemonic(target) == "movq") self.assertTrue (inst.GetOperands(target) == '%' + "rsp, " + '%' + "rbp") if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
Fix the test to disassemble as if at address zero, not at an invalid address. The default SBAddress constructor sets the offset to 0xffffffffffffffff and the section to NULL.
Fix the test to disassemble as if at address zero, not at an invalid address. The default SBAddress constructor sets the offset to 0xffffffffffffffff and the section to NULL. This was causing problems on clang 602 branches that use MemoryObjects to as the container for opcode bytes instead of a plain array of bytes. So we were asking for 3 bytes to be disassembled at address 0xffffffffffffffff which would cause an unsigned overflow and cause the MemoryObject to refuse to read anymore bytes. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@227153 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb
--- +++ @@ -26,7 +26,7 @@ raw_bytes = bytearray([0x48, 0x89, 0xe5]) - insts = target.GetInstructions(lldb.SBAddress(), raw_bytes) + insts = target.GetInstructions(lldb.SBAddress(0, target), raw_bytes) inst = insts.GetInstructionAtIndex(0)
ef0a411af84a70f1176fde320a974d213ca96f4d
field_required_res_partner/__openerp__.py
field_required_res_partner/__openerp__.py
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Field(s) Required Res Partner", "summary": "Customers and Suppliers Field Required", "version": "9.0.1.0.0", "category": "", "website": "https://odoo-community.org/", "author": "<Deysy Mascorro Preciado>, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends": [ "base", ], "data": [ "views/base_partner_view.xml", ], "demo": [ ], "qweb": [ ] }
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Field Required in Partners", "summary": "Customers and Suppliers Field Required", "version": "9.0.1.0.0", "category": "", "website": "https://odoo-community.org/", "author": "<Deysy Mascorro Preciado>, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends": [ "base", ], "data": [ "views/base_partner_view.xml", ], "demo": [ ], "qweb": [ ] }
Change the name of module in the manifest
[FIX] Change the name of module in the manifest
Python
agpl-3.0
Gebesa-Dev/Addons-gebesa
--- +++ @@ -2,7 +2,7 @@ # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { - "name": "Field(s) Required Res Partner", + "name": "Field Required in Partners", "summary": "Customers and Suppliers Field Required", "version": "9.0.1.0.0", "category": "", @@ -19,7 +19,7 @@ "base", ], "data": [ - "views/base_partner_view.xml", + "views/base_partner_view.xml", ], "demo": [
efc9013bff8251fc910ecb70d546a8508ed0f7ec
tests/race_deleting_keys_test.py
tests/race_deleting_keys_test.py
import time as _time import subprocess import sys import redisdl import unittest import json import os.path from . import util from . import big_data class RaceDeletingKeysTest(unittest.TestCase): def setUp(self): import redis self.r = redis.Redis() for key in self.r.keys('*'): self.r.delete(key) # slow def test_delete_race(self): bd = big_data.BigData(self.r) count = bd.determine_key_count() # data is already inserted big_data_path = os.path.join(os.path.dirname(__file__), 'big_data.py') p = subprocess.Popen( [sys.executable, big_data_path, 'delete', str(count)], stdout=subprocess.PIPE, ) _time.sleep(1) start = _time.time() dump = redisdl.dumps() finish = _time.time() out, err = p.communicate() delete_start, delete_finish = [int(time) for time in out.split(' ')] assert delete_start < start assert delete_finish > finish
import nose.plugins.attrib import time as _time import subprocess import sys import redisdl import unittest import json import os.path from . import util from . import big_data @nose.plugins.attrib.attr('slow') class RaceDeletingKeysTest(unittest.TestCase): def setUp(self): import redis self.r = redis.Redis() for key in self.r.keys('*'): self.r.delete(key) def test_delete_race(self): bd = big_data.BigData(self.r) count = bd.determine_key_count() # data is already inserted big_data_path = os.path.join(os.path.dirname(__file__), 'big_data.py') p = subprocess.Popen( [sys.executable, big_data_path, 'delete', str(count)], stdout=subprocess.PIPE, ) _time.sleep(1) start = _time.time() dump = redisdl.dumps() finish = _time.time() out, err = p.communicate() delete_start, delete_finish = [int(time) for time in out.split(' ')] assert delete_start < start assert delete_finish > finish
Mark test slow via nose attrib plugin
Mark test slow via nose attrib plugin
Python
bsd-2-clause
p/redis-dump-load,hyunchel/redis-dump-load,hyunchel/redis-dump-load,p/redis-dump-load
--- +++ @@ -1,3 +1,4 @@ +import nose.plugins.attrib import time as _time import subprocess import sys @@ -8,6 +9,7 @@ from . import util from . import big_data +@nose.plugins.attrib.attr('slow') class RaceDeletingKeysTest(unittest.TestCase): def setUp(self): import redis @@ -15,7 +17,6 @@ for key in self.r.keys('*'): self.r.delete(key) - # slow def test_delete_race(self): bd = big_data.BigData(self.r) count = bd.determine_key_count()
ac7e966e22c9919ef3b3235ee2c69ee30d83c41f
test.py
test.py
import subprocess import unittest class CompareErrorMessages(unittest.TestCase): def test_missing_file_return_code_the_same_as_ls(self): args = ['./lss.sh', 'foo'] ret = subprocess.call(args) args2 = ['ls', 'foo'] ret2 = subprocess.call(args2) self.assertEqual(ret == 0, ret2 == 0) def test_missing_file_message_code_the_same_as_ls(self): args = ['./lss.sh', 'foo'] try: subprocess.check_output(args, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: msg = e.output args2 = ['ls', 'foo'] try: subprocess.check_output(args2, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: msg2 = e.output self.assertEqual(msg, msg2)
import subprocess import unittest class CompareErrorMessages(unittest.TestCase): def test_missing_file_return_code_the_same_as_ls(self): args = ['./lss.sh', 'foo'] ret = subprocess.call(args) args2 = ['ls', 'foo'] ret2 = subprocess.call(args2) self.assertEqual(ret == 0, ret2 == 0) def get_output(self, args): try: msg = subprocess.check_output(args, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: msg = e.output return msg def test_missing_file_message_code_the_same_as_ls(self): args = ['./lss.sh', 'foo'] msg = self.get_output(args) args2 = ['ls', 'foo'] msg2 = self.get_output(args2) self.assertEqual(msg, msg2)
Move retrieving output into method.
Move retrieving output into method.
Python
bsd-3-clause
jwg4/les,jwg4/les
--- +++ @@ -9,15 +9,16 @@ ret2 = subprocess.call(args2) self.assertEqual(ret == 0, ret2 == 0) + def get_output(self, args): + try: + msg = subprocess.check_output(args, stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as e: + msg = e.output + return msg + def test_missing_file_message_code_the_same_as_ls(self): args = ['./lss.sh', 'foo'] - try: - subprocess.check_output(args, stderr=subprocess.STDOUT) - except subprocess.CalledProcessError as e: - msg = e.output + msg = self.get_output(args) args2 = ['ls', 'foo'] - try: - subprocess.check_output(args2, stderr=subprocess.STDOUT) - except subprocess.CalledProcessError as e: - msg2 = e.output + msg2 = self.get_output(args2) self.assertEqual(msg, msg2)
d73492a62e5ddc1eb85f4b17a6a0e6ce88410070
infosystem/scheduler.py
infosystem/scheduler.py
from apscheduler.schedulers.background import BackgroundScheduler class Scheduler(BackgroundScheduler): def __init__(self): super().__init__() self.start() def schedule(self, callback, **kwargs): self.add_job(callback, 'cron', **kwargs)
from apscheduler.schedulers.background import BackgroundScheduler class Scheduler(BackgroundScheduler): def __init__(self): super().__init__() self.start() def schedule(self, callback, **kwargs): self.add_job(callback, 'cron', **kwargs) def hourly(self, callback, minute=0): self.add_job(callback, 'cron', minute=minute) def daily(self, callback, hour=0, minute=0): self.add_job(callback, 'cron', hour=hour, minute=minute) def weekly(self, callback, day='mon',hour=0, minute=0): if not day in ('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'): raise ValueError self.add_job(callback, 'cron', day_of_week=day, hour=hour, minute=minute) def monthly(self, callback, day=1, hour=0, minute=0): self.add_job(callback, 'cron', day=day, hour=hour, minute=minute)
Add hourly, daily, weelky and monthly sched helpers
Add hourly, daily, weelky and monthly sched helpers
Python
apache-2.0
samueldmq/infosystem
--- +++ @@ -9,3 +9,17 @@ def schedule(self, callback, **kwargs): self.add_job(callback, 'cron', **kwargs) + + def hourly(self, callback, minute=0): + self.add_job(callback, 'cron', minute=minute) + + def daily(self, callback, hour=0, minute=0): + self.add_job(callback, 'cron', hour=hour, minute=minute) + + def weekly(self, callback, day='mon',hour=0, minute=0): + if not day in ('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'): + raise ValueError + self.add_job(callback, 'cron', day_of_week=day, hour=hour, minute=minute) + + def monthly(self, callback, day=1, hour=0, minute=0): + self.add_job(callback, 'cron', day=day, hour=hour, minute=minute)
3edff34538855e6916c8185fe271c6574a76fb08
tx_salaries/utils/transformer.py
tx_salaries/utils/transformer.py
import hashlib from StringIO import StringIO from csvkit import convert from csvkit.unicsv import UnicodeCSVReader from django.core import exceptions from .transformers import TRANSFORMERS def convert_to_csv_reader(filename, sheet=None): format = convert.guess_format(filename) f = open(filename, "rb") if sheet is None: converted = StringIO(convert.convert(f, format)) else: converted = StringIO(convert.convert(f, format, sheet=sheet)) reader = UnicodeCSVReader(converted) return reader def transform(filename, sheet=None): reader = convert_to_csv_reader(filename, sheet=sheet) labels = reader.next() transformers = get_transformers(labels) if len(transformers) > 1: raise Exception("TODO") transformer = transformers[0] # TODO: Figure out a better way to pass a dict reader in data = transformer(labels, reader) return data def generate_key(labels): return hashlib.sha1("::".join(labels)).hexdigest() def get_transformers(labels): """ Return one (or more) transfer for a given set of headers This takes a list of headers for a given spreadsheet and returns the known transformers that match against it. """ try: return TRANSFORMERS[generate_key(labels)] except KeyError: raise exceptions.ImproperlyConfigured()
import hashlib from StringIO import StringIO from csvkit import convert from csvkit.unicsv import UnicodeCSVReader from django.core import exceptions from .transformers import TRANSFORMERS def convert_to_csv_reader(filename, sheet=None): format = convert.guess_format(filename) f = open(filename, "rb") convert_kwargs = {} if sheet is not None: # Only pass `sheet` to the `convert` function when its set to # a non-None value. This is done to satisfy csvkit which checks # for the presence of `sheet`, not whether it's valid. convert_kwargs['sheet'] = sheet converted = StringIO(convert.convert(f, format, **convert_kwargs)) reader = UnicodeCSVReader(converted) return reader def transform(filename, sheet=None): reader = convert_to_csv_reader(filename, sheet=sheet) labels = reader.next() transformers = get_transformers(labels) if len(transformers) > 1: raise Exception("TODO") transformer = transformers[0] # TODO: Figure out a better way to pass a dict reader in data = transformer(labels, reader) return data def generate_key(labels): return hashlib.sha1("::".join(labels)).hexdigest() def get_transformers(labels): """ Return one (or more) transfer for a given set of headers This takes a list of headers for a given spreadsheet and returns the known transformers that match against it. """ try: return TRANSFORMERS[generate_key(labels)] except KeyError: raise exceptions.ImproperlyConfigured()
Refactor to change the workflow
Refactor to change the workflow This is functionally the same code, but this reads a little better (to me). I've also added a code comment to explain what's going on here since it does seem so weird.
Python
apache-2.0
texastribune/tx_salaries,texastribune/tx_salaries
--- +++ @@ -11,10 +11,13 @@ def convert_to_csv_reader(filename, sheet=None): format = convert.guess_format(filename) f = open(filename, "rb") - if sheet is None: - converted = StringIO(convert.convert(f, format)) - else: - converted = StringIO(convert.convert(f, format, sheet=sheet)) + convert_kwargs = {} + if sheet is not None: + # Only pass `sheet` to the `convert` function when its set to + # a non-None value. This is done to satisfy csvkit which checks + # for the presence of `sheet`, not whether it's valid. + convert_kwargs['sheet'] = sheet + converted = StringIO(convert.convert(f, format, **convert_kwargs)) reader = UnicodeCSVReader(converted) return reader
86a357e9a954348aa59626a37d61fdb43c143142
src/constants.py
src/constants.py
#!/usr/bin/env python TRAJECTORY = 'squared' CONTROLLER = 'pid' # control constants K_X = 0.90 K_Y = 0.90 K_THETA = 0.90 # PID control constants K_P_V = 0.2 K_I_V = 1.905 K_D_V = 0.00 K_P_W = 0.45 K_I_W = 1.25 K_D_W = 0.000 if TRAJECTORY == 'linear': SIMULATION_TIME_IN_SECONDS = 60.0 MAX_V = 0.075 MAX_W = 1.25 elif TRAJECTORY == 'circular': SIMULATION_TIME_IN_SECONDS = 120.0 MAX_V = 0.11 MAX_W = 1.25 elif TRAJECTORY == 'squared': SIMULATION_TIME_IN_SECONDS = 160.0 MAX_V = 0.055 MAX_W = 1.20 DELTA_T = 0.1 # this is the sampling time STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)
#!/usr/bin/env python TRAJECTORY = 'linear' CONTROLLER = 'pid' # control constants K_X = 0.90 K_Y = 0.90 K_THETA = 0.90 # PID control constants K_P_V = 0.2 K_I_V = 1.905 K_D_V = 0.00 K_P_W = 0.45 K_I_W = 1.25 K_D_W = 0.000 if TRAJECTORY == 'linear': SIMULATION_TIME_IN_SECONDS = 60.0 MAX_V = 0.075 MAX_W = 1.25 elif TRAJECTORY == 'circular': SIMULATION_TIME_IN_SECONDS = 120.0 MAX_V = 0.11 MAX_W = 1.25 elif TRAJECTORY == 'squared': SIMULATION_TIME_IN_SECONDS = 160.0 MAX_V = 0.055 MAX_W = 1.20 DELTA_T = 0.1 # this is the sampling time STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T) RESULTS_DIRECTORY = '../last_results/'
Create constant to store path for results
Create constant to store path for results
Python
mit
bit0001/trajectory_tracking,bit0001/trajectory_tracking
--- +++ @@ -1,5 +1,5 @@ #!/usr/bin/env python -TRAJECTORY = 'squared' +TRAJECTORY = 'linear' CONTROLLER = 'pid' # control constants @@ -32,3 +32,4 @@ DELTA_T = 0.1 # this is the sampling time STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T) +RESULTS_DIRECTORY = '../last_results/'
6477768e3040ed43fb10072730b84c29bef1e949
continuate/__init__.py
continuate/__init__.py
# -*- coding: utf-8 -*- import importlib __all__ = ["linalg", "single_parameter"] for m in __all__: importlib.import_module("continuate." + m)
# -*- coding: utf-8 -*- import importlib import os.path as op from glob import glob __all__ = [op.basename(f)[:-3] for f in glob(op.join(op.dirname(__file__), "*.py")) if op.basename(f) != "__init__.py"] for m in __all__: importlib.import_module("continuate." + m)
Change manual listing of submodules to automatic
Change manual listing of submodules to automatic
Python
mit
termoshtt/continuate
--- +++ @@ -1,8 +1,12 @@ # -*- coding: utf-8 -*- import importlib +import os.path as op +from glob import glob -__all__ = ["linalg", "single_parameter"] +__all__ = [op.basename(f)[:-3] + for f in glob(op.join(op.dirname(__file__), "*.py")) + if op.basename(f) != "__init__.py"] for m in __all__: importlib.import_module("continuate." + m)