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 |
|---|---|---|---|---|---|---|---|---|---|---|
021c21207cab0cf3f7cca3cb31ffa4c62d49e58c | python/chigger/base/KeyPressInteractorStyle.py | python/chigger/base/KeyPressInteractorStyle.py | #pylint: disable=missing-docstring
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html
import vtk
from .. import utils
class KeyPressInteractorStyle(vtk.vtkInteractorStyleMultiTouchCamera):
"""
An interactor style for capturing key press events in VTK window.
"""
def __init__(self, parent=None, **kwargs):
self.AddObserver("KeyPressEvent", self.keyPress)
super(KeyPressInteractorStyle, self).__init__(parent, **kwargs)
def keyPress(self, obj, event): #pylint: disable=unused-argument
"""
Executes when a key is pressed.
Inputs:
obj, event: Required by VTK.
"""
key = obj.GetInteractor().GetKeySym()
if key == 'c':
print '\n'.join(utils.print_camera(self.GetCurrentRenderer().GetActiveCamera()))
| #pylint: disable=missing-docstring
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html
import vtk
from .. import utils
class KeyPressInteractorStyle(vtk.vtkInteractorStyleMultiTouchCamera):
"""
An interactor style for capturing key press events in VTK window.
"""
def __init__(self, parent=None, **kwargs):
self.AddObserver("KeyPressEvent", self.keyPress)
super(KeyPressInteractorStyle, self).__init__(parent, **kwargs)
self.SetMotionFactor(0.1*self.GetMotionFactor())
def keyPress(self, obj, event): #pylint: disable=unused-argument
"""
Executes when a key is pressed.
Inputs:
obj, event: Required by VTK.
"""
key = obj.GetInteractor().GetKeySym()
if key == 'c':
print '\n'.join(utils.print_camera(self.GetCurrentRenderer().GetActiveCamera()))
| Make camera interaction more sensitive | Make camera interaction more sensitive
(refs #12095)
| Python | lgpl-2.1 | lindsayad/moose,dschwen/moose,andrsd/moose,milljm/moose,milljm/moose,sapitts/moose,SudiptaBiswas/moose,bwspenc/moose,sapitts/moose,jessecarterMOOSE/moose,dschwen/moose,harterj/moose,sapitts/moose,permcody/moose,andrsd/moose,idaholab/moose,YaqiWang/moose,jessecarterMOOSE/moose,laagesen/moose,SudiptaBiswas/moose,permcody/moose,idaholab/moose,harterj/moose,sapitts/moose,lindsayad/moose,harterj/moose,jessecarterMOOSE/moose,bwspenc/moose,YaqiWang/moose,lindsayad/moose,nuclear-wizard/moose,andrsd/moose,andrsd/moose,idaholab/moose,SudiptaBiswas/moose,jessecarterMOOSE/moose,idaholab/moose,lindsayad/moose,andrsd/moose,permcody/moose,jessecarterMOOSE/moose,harterj/moose,sapitts/moose,bwspenc/moose,laagesen/moose,milljm/moose,lindsayad/moose,laagesen/moose,milljm/moose,SudiptaBiswas/moose,nuclear-wizard/moose,laagesen/moose,nuclear-wizard/moose,permcody/moose,harterj/moose,nuclear-wizard/moose,YaqiWang/moose,YaqiWang/moose,dschwen/moose,bwspenc/moose,milljm/moose,bwspenc/moose,laagesen/moose,idaholab/moose,dschwen/moose,dschwen/moose,SudiptaBiswas/moose | ---
+++
@@ -19,6 +19,8 @@
self.AddObserver("KeyPressEvent", self.keyPress)
super(KeyPressInteractorStyle, self).__init__(parent, **kwargs)
+ self.SetMotionFactor(0.1*self.GetMotionFactor())
+
def keyPress(self, obj, event): #pylint: disable=unused-argument
"""
Executes when a key is pressed. |
2fba1c04c8083211df8664d87080480a1f63ed2a | csunplugged/utils/group_lessons_by_age.py | csunplugged/utils/group_lessons_by_age.py | """Return ordered groups of lessons."""
from collections import OrderedDict
from topics.models import (
AgeGroup,
LessonNumber,
)
def group_lessons_by_age(lessons):
"""Return ordered groups of lessons.
Lessons are grouped by the lesson minimum age and maximum ages,
and then order by number.
Args:
lessons: QuerySet of Lesson objects (QuerySet).
Returns:
A ordered dictionary of grouped lessons.
The key is a tuple of the minimum age and maximum ages for
the lessons.
The value for a key is a sorted list of lessons (ordered by number).
"""
grouped_lessons = OrderedDict()
for age_group in AgeGroup.objects.distinct():
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
grouped_lessons[age_group].append(lesson)
else:
grouped_lessons[age_group] = [lesson]
return grouped_lessons
| """Return ordered groups of lessons."""
from collections import OrderedDict
from topics.models import (
AgeGroup,
LessonNumber,
)
def group_lessons_by_age(lessons):
"""Return ordered groups of lessons.
Lessons are grouped by the lesson minimum age and maximum ages,
and then order by number.
Args:
lessons: QuerySet of Lesson objects (QuerySet).
Returns:
A ordered dictionary of grouped lessons.
The key is a tuple of the minimum age and maximum ages for
the lessons.
The value for a key is a sorted list of lessons (ordered by number).
"""
grouped_lessons = OrderedDict()
for age_group in AgeGroup.objects.distinct():
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
grouped_lessons[ages].add(lesson)
else:
grouped_lessons[ages] = set([lesson])
return grouped_lessons
| Fix bug where lessons are duplicated across age groups. | Fix bug where lessons are duplicated across age groups.
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | ---
+++
@@ -27,7 +27,7 @@
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
- grouped_lessons[age_group].append(lesson)
+ grouped_lessons[ages].add(lesson)
else:
- grouped_lessons[age_group] = [lesson]
+ grouped_lessons[ages] = set([lesson])
return grouped_lessons |
7882f838241ce92c15d49bf17ed7b307342386b6 | pyrax/identity/keystone_identity.py | pyrax/identity/keystone_identity.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pyrax
from pyrax.base_identity import BaseAuth
import pyrax.exceptions as exc
class KeystoneIdentity(BaseAuth):
"""
Implements the Keystone-specific behaviors for Identity. In most
cases you will want to create specific subclasses to implement the
_get_auth_endpoint() method if you want to use something other
than the config file to control your auth endpoint.
"""
_default_region = "RegionOne"
def _get_auth_endpoint(self):
ep = pyrax.get_setting("auth_endpoint")
if ep is None:
raise exc.EndpointNotDefined("No auth enpoint has been specified.")
return ep
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pyrax
from pyrax.base_identity import BaseAuth
import pyrax.exceptions as exc
class KeystoneIdentity(BaseAuth):
"""
Implements the Keystone-specific behaviors for Identity. In most
cases you will want to create specific subclasses to implement the
_get_auth_endpoint() method if you want to use something other
than the config file to control your auth endpoint.
"""
_default_region = "RegionOne"
def _get_auth_endpoint(self):
ep = pyrax.get_setting("auth_endpoint")
if ep is None:
raise exc.EndpointNotDefined("No auth endpoint has been specified.")
return ep
| Fix a minor typo in the EndpointNotDefined exception | Fix a minor typo in the EndpointNotDefined exception
| Python | apache-2.0 | roelvv/pyrax,0dataloss/pyrax,briancurtin/pyrax,naemono/pyrax,rackerlabs/heat-pyrax,vikomall/pyrax,sivel/pyrax,ddaeschler/pyrax,pratikmallya/pyrax,rackspace/pyrax,opsdisk/pyrax,EdLeafe/pyrax,mandx/pyrax | ---
+++
@@ -19,5 +19,5 @@
def _get_auth_endpoint(self):
ep = pyrax.get_setting("auth_endpoint")
if ep is None:
- raise exc.EndpointNotDefined("No auth enpoint has been specified.")
+ raise exc.EndpointNotDefined("No auth endpoint has been specified.")
return ep |
5d663ae690f0c488f7a38f4556c30b169389c441 | flaskiwsapp/projects/models/target.py | flaskiwsapp/projects/models/target.py | '''
Created on Sep 24, 2016
@author: rtorres
'''
from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column
from sqlalchemy.dialects.postgresql.base import ENUM
from sqlalchemy_utils.types.url import URLType
from flask_validator.constraints.internet import ValidateURL
AREAS = ('Policies', 'Billing', 'Claims', 'Reports')
class Target(SurrogatePK, Model):
"""A user of the app."""
__tablename__ = 'targets'
title = Column(db.String(80), nullable=False)
description = Column(db.Text(), nullable=False)
client_id = reference_col('clients', nullable=False)
client = relationship('Client', backref='targets')
client_priority = Column(db.SmallInteger(), nullable=False)
product_area = Column(ENUM(*AREAS, name='areas', create_type=False), nullable=False)
target_date = Column(db.DateTime(), nullable=False)
ticket_url = Column(db.String(256), nullable=False)
def __init__(self, title="", password=None, **kwargs):
"""Create instance."""
db.Model.__init__(self, title=title.strip(), **kwargs)
def __str__(self):
"""String representation of the user. Shows the target title."""
return self.title
def get_id(self):
return self.id
| '''
Created on Sep 24, 2016
@author: rtorres
'''
from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column
from sqlalchemy.dialects.postgresql.base import ENUM
AREAS = ('Policies', 'Billing', 'Claims', 'Reports')
class Target(SurrogatePK, Model):
"""A user of the app."""
__tablename__ = 'targets'
title = Column(db.String(80), nullable=False)
description = Column(db.Text(), nullable=False)
client_id = reference_col('clients', nullable=False)
client = relationship('Client', backref='targets')
client_priority = Column(db.SmallInteger(), nullable=False)
product_area = Column(ENUM(*AREAS, name='areas', create_type=False), nullable=False)
target_date = Column(db.DateTime(), nullable=False)
ticket_url = Column(db.String(256), nullable=False)
def __init__(self, title="", password=None, **kwargs):
"""Create instance."""
db.Model.__init__(self, title=title.strip(), **kwargs)
def __str__(self):
"""String representation of the user. Shows the target title."""
return self.title
def get_id(self):
return self.id
| Remove import from testing packages | Remove import from testing packages | Python | mit | rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel | ---
+++
@@ -5,8 +5,6 @@
'''
from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column
from sqlalchemy.dialects.postgresql.base import ENUM
-from sqlalchemy_utils.types.url import URLType
-from flask_validator.constraints.internet import ValidateURL
AREAS = ('Policies', 'Billing', 'Claims', 'Reports') |
7171b8bba0cd7b595abcdea7b819fc26e27252bc | docker-images/training-webapp/app.py | docker-images/training-webapp/app.py | import os
import pgdb
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
conn = pgdb.connect( host='pg', user='postgres', password='testnet', database='testnet' )
cur = conn.cursor()
cur.execute( "SELECT value FROM kv WHERE key='provider'" )
provider = cur.fetchone()[0]
conn.close()
return 'Hello '+provider+'!'
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port) | import os
import pgdb
import logging
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
conn = pgdb.connect( host='pg', user='postgres', password='testnet', database='testnet' )
cur = conn.cursor()
cur.execute( "SELECT value FROM kv WHERE key='provider'" )
provider = cur.fetchone()[0]
conn.close()
return 'Hello '+provider+'!'
if __name__ == '__main__':
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| Add logging to python webserver | Add logging to python webserver | Python | apache-2.0 | bolcom/docker-for-testers,bolcom/docker-for-testers,bolcom/docker-for-testers | ---
+++
@@ -1,5 +1,6 @@
import os
import pgdb
+import logging
from flask import Flask
@@ -15,6 +16,7 @@
return 'Hello '+provider+'!'
if __name__ == '__main__':
+ logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port) |
730a32f90d618e99a55084cf1442a86eaf4ebdf9 | core/configs/base_config.py | core/configs/base_config.py | """Kraken - base config module.
Classes:
BaseConfig -- Base config object used to configure builders.
"""
class BaseConfig(object):
"""Base Configuration for Kraken builders."""
def __init__(self):
super(BaseConfig, self).__init__()
self.nameTemplate = {
"locations": ['L', 'R', 'M'],
"separator": "_",
"types": {
"default": "null",
"Component": "cmp",
"ComponentInput": "cmpIn",
"ComponentOutput": "cmpOut",
"Container": "",
"Control": "ctrl",
"Curve": "crv",
"HierarchyGroup": "hrc",
"Joint": "def",
"Layer": "",
"Locator": "null",
"SrtBuffer": "srtBuffer"
},
"formats":
{
"default": ['component', 'sep', 'location', 'sep', 'name', 'sep', 'type'],
"Container": ['name'],
"Layer": ['name'],
"Component": ['name', 'sep', 'location', 'sep', 'type']
}
}
def getNameTemplate(self):
"""Returns the naming template for this configuration.
Return:
Dict, naming template.
"""
return self.nameTemplate | """Kraken - base config module.
Classes:
BaseConfig -- Base config object used to configure builders.
"""
class BaseConfig(object):
"""Base Configuration for Kraken builders."""
def __init__(self):
super(BaseConfig, self).__init__()
self.nameTemplate = {
"locations": ['L', 'R', 'M'],
"separator": "_",
"types": {
"default": "null",
"Component": "cmp",
"ComponentInput": "cmpIn",
"ComponentOutput": "cmpOut",
"Container": "",
"Control": "ctrl",
"Curve": "crv",
"HierarchyGroup": "hrc",
"Joint": "def",
"Layer": "",
"Locator": "loc",
"SrtBuffer": "srtBuffer"
},
"formats":
{
"default": ['component', 'sep', 'location', 'sep', 'name', 'sep', 'type'],
"Container": ['name'],
"Layer": ['name'],
"Component": ['name', 'sep', 'location', 'sep', 'type']
}
}
def getNameTemplate(self):
"""Returns the naming template for this configuration.
Return:
Dict, naming template.
"""
return self.nameTemplate | Change suffix for locator to 'loc' | Change suffix for locator to 'loc'
| Python | bsd-3-clause | goshow-jp/Kraken,goshow-jp/Kraken,oculusstorystudio/kraken,oculusstorystudio/kraken,goshow-jp/Kraken | ---
+++
@@ -26,7 +26,7 @@
"HierarchyGroup": "hrc",
"Joint": "def",
"Layer": "",
- "Locator": "null",
+ "Locator": "loc",
"SrtBuffer": "srtBuffer"
},
"formats": |
3c0db422301955430ecd572103097fc68fec254d | tests/testapp/admin.py | tests/testapp/admin.py | from django import forms
from django.contrib import admin
from django.db import models
from content_editor.admin import ContentEditor, ContentEditorInline
from .models import Article, Download, RichText, Thing
class RichTextarea(forms.Textarea):
def __init__(self, attrs=None):
default_attrs = {"class": "richtext"}
if attrs: # pragma: no cover
default_attrs.update(attrs)
super(RichTextarea, self).__init__(default_attrs)
class RichTextInline(ContentEditorInline):
model = RichText
formfield_overrides = {models.TextField: {"widget": RichTextarea}}
fieldsets = [(None, {"fields": ("text", "region", "ordering")})]
regions = ("main",)
class Media:
js = ("//cdn.ckeditor.com/4.5.6/standard/ckeditor.js", "app/plugin_ckeditor.js")
class ThingInline(admin.TabularInline):
model = Thing
admin.site.register(
Article,
ContentEditor,
inlines=[
RichTextInline,
ContentEditorInline.create(
model=Download, regions=lambda inline, regions: regions - {"sidebar"}
),
ThingInline,
],
)
| from django import forms
from django.contrib import admin
from django.db import models
from content_editor.admin import ContentEditor, ContentEditorInline
from .models import Article, Download, RichText, Thing
class RichTextarea(forms.Textarea):
def __init__(self, attrs=None):
default_attrs = {"class": "richtext"}
if attrs: # pragma: no cover
default_attrs.update(attrs)
super(RichTextarea, self).__init__(default_attrs)
class RichTextInline(ContentEditorInline):
model = RichText
formfield_overrides = {models.TextField: {"widget": RichTextarea}}
fieldsets = [(None, {"fields": ("text", "region", "ordering")})]
regions = {"main"}
class Media:
js = ("//cdn.ckeditor.com/4.5.6/standard/ckeditor.js", "app/plugin_ckeditor.js")
class ThingInline(admin.TabularInline):
model = Thing
admin.site.register(
Article,
ContentEditor,
inlines=[
RichTextInline,
ContentEditorInline.create(
model=Download, regions=lambda self, regions: regions - {"sidebar"}
),
ThingInline,
],
)
| Use sets to define allowed regions for plugins | Use sets to define allowed regions for plugins
| Python | bsd-3-clause | matthiask/django-content-editor,matthiask/django-content-editor,matthiask/feincms2-content,matthiask/feincms2-content,matthiask/django-content-editor,matthiask/django-content-editor,matthiask/feincms2-content | ---
+++
@@ -19,7 +19,7 @@
model = RichText
formfield_overrides = {models.TextField: {"widget": RichTextarea}}
fieldsets = [(None, {"fields": ("text", "region", "ordering")})]
- regions = ("main",)
+ regions = {"main"}
class Media:
js = ("//cdn.ckeditor.com/4.5.6/standard/ckeditor.js", "app/plugin_ckeditor.js")
@@ -35,7 +35,7 @@
inlines=[
RichTextInline,
ContentEditorInline.create(
- model=Download, regions=lambda inline, regions: regions - {"sidebar"}
+ model=Download, regions=lambda self, regions: regions - {"sidebar"}
),
ThingInline,
], |
6e0654386c7a5d7e0a399ac363af4f2d59770d16 | coffeestats/caffeine_oauth2/tests/test_models.py | coffeestats/caffeine_oauth2/tests/test_models.py | from __future__ import unicode_literals
from django.test import TestCase
from caffeine_oauth2.models import CoffeestatsApplication
class CoffeestatsApplicationTest(TestCase):
def test___str__(self):
application = CoffeestatsApplication(name='test', client_id='client')
self.assertEquals(str(application), 'test client')
| from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.test import TestCase
from caffeine_oauth2.models import CoffeestatsApplication
User = get_user_model()
class CoffeestatsApplicationTest(TestCase):
def test___str__(self):
application = CoffeestatsApplication(name='test', client_id='client')
self.assertEquals(str(application), 'test client')
def test_get_absolute_url_unapproved(self):
application = CoffeestatsApplication(name='test', client_id='client',
pk=1)
self.assertEqual(
application.get_absolute_url(),
reverse('oauth2_provider:pending_approval', kwargs={'pk': 1}))
def test_get_absolute_url_approved(self):
application = CoffeestatsApplication(name='test', client_id='client',
pk=1, approved=True)
self.assertEqual(
application.get_absolute_url(),
reverse('oauth2_provider:detail', kwargs={'pk': 1}))
def test_approve(self):
application = CoffeestatsApplication(name='test', client_id='client')
self.assertFalse(application.approved)
self.assertIsNone(application.approved_by_id)
self.assertIsNone(application.approved_on)
user = User(username='tester')
application.approve(user)
self.assertTrue(application.approved)
self.assertEqual(application.approved_by, user)
self.assertIsNotNone(application.approved_on)
def test_reject(self):
user = User.objects.create(username='tester')
application = CoffeestatsApplication.objects.create(
name='test', agree=False, user=user)
client_id = application.client_id
self.assertIsNotNone(client_id)
found = CoffeestatsApplication.objects.get(client_id=client_id)
self.assertEqual(found, application)
found.reject()
with self.assertRaises(CoffeestatsApplication.DoesNotExist):
CoffeestatsApplication.objects.get(client_id=client_id)
| Add tests for new caffeine_oauth2.models code | Add tests for new caffeine_oauth2.models code
| Python | mit | coffeestats/coffeestats-django,coffeestats/coffeestats-django,coffeestats/coffeestats-django,coffeestats/coffeestats-django | ---
+++
@@ -1,11 +1,52 @@
from __future__ import unicode_literals
+from django.contrib.auth import get_user_model
+from django.core.urlresolvers import reverse
from django.test import TestCase
from caffeine_oauth2.models import CoffeestatsApplication
+
+User = get_user_model()
class CoffeestatsApplicationTest(TestCase):
def test___str__(self):
application = CoffeestatsApplication(name='test', client_id='client')
self.assertEquals(str(application), 'test client')
+
+ def test_get_absolute_url_unapproved(self):
+ application = CoffeestatsApplication(name='test', client_id='client',
+ pk=1)
+ self.assertEqual(
+ application.get_absolute_url(),
+ reverse('oauth2_provider:pending_approval', kwargs={'pk': 1}))
+
+ def test_get_absolute_url_approved(self):
+ application = CoffeestatsApplication(name='test', client_id='client',
+ pk=1, approved=True)
+ self.assertEqual(
+ application.get_absolute_url(),
+ reverse('oauth2_provider:detail', kwargs={'pk': 1}))
+
+ def test_approve(self):
+ application = CoffeestatsApplication(name='test', client_id='client')
+ self.assertFalse(application.approved)
+ self.assertIsNone(application.approved_by_id)
+ self.assertIsNone(application.approved_on)
+ user = User(username='tester')
+ application.approve(user)
+ self.assertTrue(application.approved)
+ self.assertEqual(application.approved_by, user)
+ self.assertIsNotNone(application.approved_on)
+
+ def test_reject(self):
+ user = User.objects.create(username='tester')
+ application = CoffeestatsApplication.objects.create(
+ name='test', agree=False, user=user)
+ client_id = application.client_id
+ self.assertIsNotNone(client_id)
+ found = CoffeestatsApplication.objects.get(client_id=client_id)
+ self.assertEqual(found, application)
+ found.reject()
+ with self.assertRaises(CoffeestatsApplication.DoesNotExist):
+ CoffeestatsApplication.objects.get(client_id=client_id) |
249293336d2bfcc018c44d9279b89b31522c37da | u2fserver/jsobjects.py | u2fserver/jsobjects.py | from u2flib_server.jsapi import (JSONDict, RegisterRequest, RegisterResponse,
SignRequest, SignResponse)
__all__ = [
'RegisterRequestData',
'RegisterResponseData',
'AuthenticateRequestData',
'AuthenticateResponseData'
]
class RegisterRequestData(JSONDict):
@property
def authenticateRequests(self):
return map(SignRequest, self['authenticateRequests'])
@property
def registerRequests(self):
return map(RegisterRequest, self['registerRequests'])
class RegisterResponseData(JSONDict):
@property
def registerResponse(self):
return RegisterResponse(self['registerResponse'])
@property
def getProps(self):
return self.get('getProps', [])
@property
def setProps(self):
return self.get('setProps', {})
class AuthenticateRequestData(JSONDict):
@property
def authenticateRequests(self):
return map(SignRequest, self['authenticateRequests'])
class AuthenticateResponseData(JSONDict):
@property
def authenticateResponse(self):
return SignResponse(self['authenticateResponse'])
@property
def getProps(self):
return self.get('getProps', [])
@property
def setProps(self):
return self.get('setProps', {})
| # Copyright (C) 2014 Yubico AB
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from u2flib_server.jsapi import (JSONDict, RegisterRequest, RegisterResponse,
SignRequest, SignResponse)
__all__ = [
'RegisterRequestData',
'RegisterResponseData',
'AuthenticateRequestData',
'AuthenticateResponseData'
]
class WithProps(object):
@property
def getProps(self):
return self.get('getProps', [])
@property
def setProps(self):
return self.get('setProps', {})
class RegisterRequestData(JSONDict):
@property
def authenticateRequests(self):
return map(SignRequest, self['authenticateRequests'])
@property
def registerRequests(self):
return map(RegisterRequest, self['registerRequests'])
class RegisterResponseData(JSONDict, WithProps):
@property
def registerResponse(self):
return RegisterResponse(self['registerResponse'])
class AuthenticateRequestData(JSONDict):
@property
def authenticateRequests(self):
return map(SignRequest, self['authenticateRequests'])
class AuthenticateResponseData(JSONDict, WithProps):
@property
def authenticateResponse(self):
return SignResponse(self['authenticateResponse'])
| Use a mixin for get-/setProps | Use a mixin for get-/setProps
| Python | bsd-2-clause | moreati/u2fval,Yubico/u2fval | ---
+++
@@ -1,3 +1,18 @@
+# Copyright (C) 2014 Yubico AB
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
from u2flib_server.jsapi import (JSONDict, RegisterRequest, RegisterResponse,
SignRequest, SignResponse)
@@ -7,6 +22,17 @@
'AuthenticateRequestData',
'AuthenticateResponseData'
]
+
+
+class WithProps(object):
+
+ @property
+ def getProps(self):
+ return self.get('getProps', [])
+
+ @property
+ def setProps(self):
+ return self.get('setProps', {})
class RegisterRequestData(JSONDict):
@@ -20,19 +46,11 @@
return map(RegisterRequest, self['registerRequests'])
-class RegisterResponseData(JSONDict):
+class RegisterResponseData(JSONDict, WithProps):
@property
def registerResponse(self):
return RegisterResponse(self['registerResponse'])
-
- @property
- def getProps(self):
- return self.get('getProps', [])
-
- @property
- def setProps(self):
- return self.get('setProps', {})
class AuthenticateRequestData(JSONDict):
@@ -42,16 +60,8 @@
return map(SignRequest, self['authenticateRequests'])
-class AuthenticateResponseData(JSONDict):
+class AuthenticateResponseData(JSONDict, WithProps):
@property
def authenticateResponse(self):
return SignResponse(self['authenticateResponse'])
-
- @property
- def getProps(self):
- return self.get('getProps', [])
-
- @property
- def setProps(self):
- return self.get('setProps', {}) |
b48bc4c1fff91173327f10a29e140fc781619edb | src/adhocracy/lib/helpers/staticpage_helper.py | src/adhocracy/lib/helpers/staticpage_helper.py | import babel.core
from adhocracy.lib import cache
from adhocracy.lib.helpers import url as _url
@cache.memoize('staticpage_url')
def url(staticpage, **kwargs):
pid = staticpage.key + '_' + staticpage.lang
return _url.build(None, 'static', pid, **kwargs)
def get_lang_info(lang):
locale = babel.core.Locale(lang)
return {'id': lang, 'name': locale.display_name}
| import babel.core
from adhocracy.lib import cache, staticpage
from adhocracy.lib.helpers import url as _url
@cache.memoize('staticpage_url')
def url(staticpage, **kwargs):
pid = staticpage.key + '_' + staticpage.lang
return _url.build(None, 'static', pid, **kwargs)
def get_lang_info(lang):
locale = babel.core.Locale(lang)
return {'id': lang, 'name': locale.display_name}
def can_edit():
return staticpage.can_edit()
| Make can_edit available in the helper | Make can_edit available in the helper
| Python | agpl-3.0 | alkadis/vcv,liqd/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,SysTheron/adhocracy,phihag/adhocracy,alkadis/vcv,SysTheron/adhocracy,alkadis/vcv,liqd/adhocracy,phihag/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,liqd/adhocracy,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,phihag/adhocracy,SysTheron/adhocracy,DanielNeugebauer/adhocracy | ---
+++
@@ -1,6 +1,6 @@
import babel.core
-from adhocracy.lib import cache
+from adhocracy.lib import cache, staticpage
from adhocracy.lib.helpers import url as _url
@@ -12,3 +12,7 @@
def get_lang_info(lang):
locale = babel.core.Locale(lang)
return {'id': lang, 'name': locale.display_name}
+
+def can_edit():
+ return staticpage.can_edit()
+ |
bbfc0357c9a37599776584c40f6a3b4f462ad110 | run_notebooks.py | run_notebooks.py | #!/usr/bin/env python
import subprocess
NOTEBOOKS_DIR = 'notebooks'
SKIP_NOTEBOOKS = ['Bonus/What to do when things go wrong.ipynb']
def run_notebook(notebook):
args = ['jupyter', 'nbconvert', '--execute',
'--ExecutePreprocessor.timeout=900',
'--ExecutePreprocessor.kernel_name=workshop',
'--to=notebook', '--stdout']
args.append(notebook)
with subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=None) as proc:
proc.wait()
return proc.returncode
if __name__ == '__main__':
import glob
import os.path
import sys
ret = 0
notebooks = set(glob.glob(os.path.join(NOTEBOOKS_DIR, '**/*.ipynb'), recursive=True))
notebooks -= set(os.path.join(NOTEBOOKS_DIR, s)
for s in SKIP_NOTEBOOKS)
for path in sorted(notebooks):
ret = max(run_notebook(path), ret)
sys.exit(ret)
| #!/usr/bin/env python
import subprocess
import os.path
NOTEBOOKS_DIR = 'notebooks'
SKIP_NOTEBOOKS = [os.path.join('Bonus','What to do when things go wrong.ipynb')]
def run_notebook(notebook):
args = ['jupyter', 'nbconvert', '--execute',
'--ExecutePreprocessor.timeout=900',
'--ExecutePreprocessor.kernel_name=workshop',
'--to=notebook', '--stdout']
args.append(notebook)
with subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=None) as proc:
proc.wait()
return proc.returncode
if __name__ == '__main__':
import glob
import sys
ret = 0
notebooks = set(glob.glob(os.path.join(NOTEBOOKS_DIR, '**', '*.ipynb'), recursive=True))
notebooks -= set(os.path.join(NOTEBOOKS_DIR, s)
for s in SKIP_NOTEBOOKS)
for path in sorted(notebooks):
ret = max(run_notebook(path), ret)
sys.exit(ret)
| Use os.join for testing on multiple platforms. | Use os.join for testing on multiple platforms.
| Python | mit | Unidata/unidata-python-workshop,julienchastang/unidata-python-workshop,julienchastang/unidata-python-workshop | ---
+++
@@ -1,9 +1,10 @@
#!/usr/bin/env python
import subprocess
+import os.path
NOTEBOOKS_DIR = 'notebooks'
-SKIP_NOTEBOOKS = ['Bonus/What to do when things go wrong.ipynb']
+SKIP_NOTEBOOKS = [os.path.join('Bonus','What to do when things go wrong.ipynb')]
def run_notebook(notebook):
@@ -20,11 +21,10 @@
if __name__ == '__main__':
import glob
- import os.path
import sys
ret = 0
- notebooks = set(glob.glob(os.path.join(NOTEBOOKS_DIR, '**/*.ipynb'), recursive=True))
+ notebooks = set(glob.glob(os.path.join(NOTEBOOKS_DIR, '**', '*.ipynb'), recursive=True))
notebooks -= set(os.path.join(NOTEBOOKS_DIR, s)
for s in SKIP_NOTEBOOKS)
for path in sorted(notebooks): |
af52a3967568a3d5af838e695d5fcdd825f585cf | numba2/runtime/tests/test_ffi.py | numba2/runtime/tests/test_ffi.py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import math
import unittest
from numba2 import jit, types, int32, float64, Type
from numba2.runtime import ffi
# ______________________________________________________________________
class TestFFI(unittest.TestCase):
def test_malloc(self):
raise unittest.SkipTest
@jit
def f():
p = ffi.malloc(2, types.int32)
p[0] = 4
p[1] = 5
return p
p = f()
self.assertEqual(p[0], 4)
self.assertEqual(p[1], 5)
def test_sizeof(self):
def func(x):
return ffi.sizeof(x)
def apply(signature, arg):
return jit(signature)(func)(arg)
self.assertEqual(apply('int32 -> int64', 10), 4)
self.assertEqual(apply('Type[int32] -> int64', int32), 4)
self.assertEqual(apply('float64 -> int64', 10.0), 8)
self.assertEqual(apply('Type[float64] -> int64', float64), 8)
# ______________________________________________________________________
if __name__ == "__main__":
unittest.main() | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import math
import unittest
from numba2 import jit, types, int32, float64, Type, cast
from numba2.runtime import ffi
# ______________________________________________________________________
class TestFFI(unittest.TestCase):
def test_malloc(self):
@jit
def f():
p = ffi.malloc(cast(2, types.int64), types.int32)
p[0] = 4
p[1] = 5
return p
p = f()
self.assertEqual(p[0], 4)
self.assertEqual(p[1], 5)
def test_sizeof(self):
def func(x):
return ffi.sizeof(x)
def apply(signature, arg):
return jit(signature)(func)(arg)
self.assertEqual(apply('int32 -> int64', 10), 4)
self.assertEqual(apply('Type[int32] -> int64', int32), 4)
self.assertEqual(apply('float64 -> int64', 10.0), 8)
self.assertEqual(apply('Type[float64] -> int64', float64), 8)
# ______________________________________________________________________
if __name__ == "__main__":
unittest.main() | Insert explicit cast to malloc implementation | Insert explicit cast to malloc implementation
| Python | bsd-2-clause | flypy/flypy,flypy/flypy | ---
+++
@@ -4,7 +4,7 @@
import math
import unittest
-from numba2 import jit, types, int32, float64, Type
+from numba2 import jit, types, int32, float64, Type, cast
from numba2.runtime import ffi
# ______________________________________________________________________
@@ -12,11 +12,9 @@
class TestFFI(unittest.TestCase):
def test_malloc(self):
- raise unittest.SkipTest
-
@jit
def f():
- p = ffi.malloc(2, types.int32)
+ p = ffi.malloc(cast(2, types.int64), types.int32)
p[0] = 4
p[1] = 5
return p |
c0374d50f1265bdbce566cb712ab848375f6794e | schwag/schwag/urls.py | schwag/schwag/urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'schwag.views.home', name='home'),
url(r'^account/login/$', 'schwag.views.login', name='login'),
url(r'^account/logout/$', 'schwag.views.logout', name='logout'),
url(r'^account/register/$', 'schwag.views.register', name='register'),
url(r'^account/', include('django.contrib.auth.urls')),
url(r'^checkout/', include('senex_shop.checkout.urls')),
url(r'^cart/', include('senex_shop.cart.urls')),
url(r'^shop/', include('senex_shop.urls')),
url(r'^news/', include('senex_shop.news.urls')),
url(r'^admin/', include(admin.site.urls)),
)
# Uncomment the next line to serve media files in dev.
# urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}),
) | from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'schwag.views.home', name='home'),
url(r'^account/login/$', 'schwag.views.login', name='login'),
url(r'^account/logout/$', 'schwag.views.logout', name='logout'),
url(r'^account/register/$', 'schwag.views.register', name='register'),
url(r'^account/', include('django.contrib.auth.urls')),
url(r'^checkout/', include('senex_shop.checkout.urls')),
url(r'^cart/', include('senex_shop.cart.urls')),
url(r'^shop/', include('senex_shop.urls')),
url(r'^news/', include('senex_shop.news.urls')),
url(r'^admin/', include(admin.site.urls)),
)
# Uncomment the next line to serve media files in dev.
# urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
try:
import debug_toolbar
urlpatterns += patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
except ImportError:
pass
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}),
) | Configure debug_toolbar to not fail. | Configure debug_toolbar to not fail.
| Python | mit | endthestart/schwag,endthestart/schwag,endthestart/schwag | ---
+++
@@ -23,11 +23,14 @@
# urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
- import debug_toolbar
+ try:
+ import debug_toolbar
- urlpatterns += patterns('',
- url(r'^__debug__/', include(debug_toolbar.urls)),
- )
+ urlpatterns += patterns('',
+ url(r'^__debug__/', include(debug_toolbar.urls)),
+ )
+ except ImportError:
+ pass
if settings.DEBUG:
urlpatterns += patterns('django.views.static', |
c7461cfe456b0aaf2f6ab4c9625cf7afc8a02eff | scripts/lib/logger.py | scripts/lib/logger.py | # logger module
from datetime import datetime
import os
logfile = None
logbuf = []
def init(analysis_path):
global logfile
if not os.path.isdir(analysis_path):
log("logger: analysis_path missing:", analysis_path)
use_log_dir = False
if use_log_dir:
logdir = os.path.join(analysis_path, "log")
if not os.path.isdir(logdir):
log("logger: creating log directory:", logdir)
os.makedirs(logdir)
logfile = os.path.join(logdir, "messages")
else:
logfile = os.path.join(analysis_path, "messages")
# log a message to messages files (and to stdout by default)
def log(*args, quiet=False, fancy=False):
global logbuf
# timestamp
now = datetime.now()
timestamp = str(now) + ": "
# assemble message line
msg = []
for a in args:
msg.append(str(a))
if not fancy:
logbuf.append(timestamp + " ".join(msg))
else:
logbuf.append("")
logbuf.append("############################################################################")
logbuf.append("### " + timestamp + " ".join(msg))
logbuf.append("############################################################################")
logbuf.append("")
if logfile:
# flush log buffer
f = open(logfile, "a")
for line in logbuf:
f.write(line)
f.write("\n")
f.close()
logbuf = []
if not quiet:
print(*msg)
# log quietly (log to file, but not to stdout)
def qlog(*args):
log(*args, quiet=True)
| # logger module
from datetime import datetime
import os
import socket # gethostname()
logfile = None
logbuf = []
def init(analysis_path):
global logfile
if not os.path.isdir(analysis_path):
log("logger: analysis_path missing:", analysis_path)
logfile = os.path.join(analysis_path, "messages-" + socket.gethostname())
# log a message to messages files (and to stdout by default)
def log(*args, quiet=False, fancy=False):
global logbuf
# timestamp
now = datetime.now()
timestamp = str(now) + ": "
# assemble message line
msg = []
for a in args:
msg.append(str(a))
if not fancy:
logbuf.append(timestamp + " ".join(msg))
else:
logbuf.append("")
logbuf.append("############################################################################")
logbuf.append("### " + timestamp + " ".join(msg))
logbuf.append("############################################################################")
logbuf.append("")
if logfile:
# flush log buffer
f = open(logfile, "a")
for line in logbuf:
f.write(line)
f.write("\n")
f.close()
logbuf = []
if not quiet:
print(*msg)
# log quietly (log to file, but not to stdout)
def qlog(*args):
log(*args, quiet=True)
| Append hostname to messages file. This supports a use-case where portions of the processing could happen on various hosts. | Append hostname to messages file. This supports a use-case where portions of
the processing could happen on various hosts.
| Python | mit | UASLab/ImageAnalysis | ---
+++
@@ -2,6 +2,7 @@
from datetime import datetime
import os
+import socket # gethostname()
logfile = None
logbuf = []
@@ -10,15 +11,7 @@
global logfile
if not os.path.isdir(analysis_path):
log("logger: analysis_path missing:", analysis_path)
- use_log_dir = False
- if use_log_dir:
- logdir = os.path.join(analysis_path, "log")
- if not os.path.isdir(logdir):
- log("logger: creating log directory:", logdir)
- os.makedirs(logdir)
- logfile = os.path.join(logdir, "messages")
- else:
- logfile = os.path.join(analysis_path, "messages")
+ logfile = os.path.join(analysis_path, "messages-" + socket.gethostname())
# log a message to messages files (and to stdout by default)
def log(*args, quiet=False, fancy=False): |
484233e1c3140e7cca9cd1874c1cf984280e2c92 | zeus/tasks/send_build_notifications.py | zeus/tasks/send_build_notifications.py | from uuid import UUID
from zeus import auth
from zeus.config import celery
from zeus.constants import Result, Status
from zeus.models import Build
from zeus.notifications import email
@celery.task(name='zeus.tasks.send_build_notifications', max_retries=None)
def send_build_notifications(build_id: UUID):
build = Build.query.get(build_id)
if not build:
raise ValueError('Unable to find build with id = {}'.format(build_id))
auth.set_current_tenant(auth.Tenant(
repository_ids=[build.repository_id]))
# double check that the build is still finished and only send when
# its failing
if build.result != Result.failed or build.status != Status.finished:
return
email.send_email_notification(build=build)
| from uuid import UUID
from zeus import auth
from zeus.config import celery
from zeus.constants import Result, Status
from zeus.models import Build
from zeus.notifications import email
@celery.task(name='zeus.tasks.send_build_notifications', max_retries=None)
def send_build_notifications(build_id: UUID):
build = Build.query.unrestricted_unsafe().get(build_id)
if not build:
raise ValueError('Unable to find build with id = {}'.format(build_id))
auth.set_current_tenant(auth.Tenant(
repository_ids=[build.repository_id]))
# double check that the build is still finished and only send when
# its failing
if build.result != Result.failed or build.status != Status.finished:
return
email.send_email_notification(build=build)
| Remove tenant req from task query | Remove tenant req from task query
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus | ---
+++
@@ -9,7 +9,7 @@
@celery.task(name='zeus.tasks.send_build_notifications', max_retries=None)
def send_build_notifications(build_id: UUID):
- build = Build.query.get(build_id)
+ build = Build.query.unrestricted_unsafe().get(build_id)
if not build:
raise ValueError('Unable to find build with id = {}'.format(build_id))
|
97bcf652a18808d89c8de2235e2b32ae933036b6 | tests/options_tests.py | tests/options_tests.py | from nose.tools import istest, assert_equal
from mammoth import style_reader
from mammoth.options import read_options, _default_style_map
@istest
def default_style_map_is_used_if_style_map_is_not_set():
assert_equal(_default_style_map, read_options({})["style_map"])
@istest
def custom_style_mappings_are_prepended_to_default_style_mappings():
style_map = read_options({
"style_map": "p.SectionTitle => h2"
})["style_map"]
assert_equal(style_reader.read_style("p.SectionTitle => h2"), style_map[0])
assert_equal(_default_style_map, style_map[1:])
@istest
def default_style_mappings_are_ignored_if_include_default_style_map_is_false():
style_map = read_options({
"style_map": "p.SectionTitle => h2",
"include_default_style_map": False
})["style_map"]
assert_equal([style_reader.read_style("p.SectionTitle => h2")], style_map)
| from nose.tools import istest, assert_equal
from mammoth import style_reader
from mammoth.options import read_options, _default_style_map
@istest
def default_style_map_is_used_if_style_map_is_not_set():
assert_equal(_default_style_map, read_options({})["style_map"])
@istest
def custom_style_mappings_are_prepended_to_default_style_mappings():
style_map = read_options({
"style_map": "p.SectionTitle => h2"
})["style_map"]
assert_equal(style_reader.read_style("p.SectionTitle => h2"), style_map[0])
assert_equal(_default_style_map, style_map[1:])
@istest
def default_style_mappings_are_ignored_if_include_default_style_map_is_false():
style_map = read_options({
"style_map": "p.SectionTitle => h2",
"include_default_style_map": False
})["style_map"]
assert_equal([style_reader.read_style("p.SectionTitle => h2")], style_map)
@istest
def lines_starting_with_hash_in_custom_style_map_are_ignored():
style_map = read_options({
"style_map": "#p.SectionTitle => h3\np.SectionTitle => h2",
"include_default_style_map": False
})["style_map"]
assert_equal([style_reader.read_style("p.SectionTitle => h2")], style_map)
| Add test to ensure that style map lines beginning with hash are ignored | Add test to ensure that style map lines beginning with hash are ignored
| Python | bsd-2-clause | mwilliamson/python-mammoth | ---
+++
@@ -25,3 +25,12 @@
"include_default_style_map": False
})["style_map"]
assert_equal([style_reader.read_style("p.SectionTitle => h2")], style_map)
+
+
+@istest
+def lines_starting_with_hash_in_custom_style_map_are_ignored():
+ style_map = read_options({
+ "style_map": "#p.SectionTitle => h3\np.SectionTitle => h2",
+ "include_default_style_map": False
+ })["style_map"]
+ assert_equal([style_reader.read_style("p.SectionTitle => h2")], style_map) |
398a3f8856b1390c2ad8a0fda2dd14eda4efbd2d | test_input/test70.py | test_input/test70.py | 'test checking constant conditions'
# __pychecker__ = ''
def func1(x):
'should not produce a warning'
if 1:
pass
while 1:
print x
break
assert x, 'test'
return 0
def func2(x):
'should produce a warning'
__pychecker__ = 'constant1'
if 1:
pass
while 1:
print x
break
return 0
def func3(x):
'should produce a warning'
if 21:
return 1
if 31:
return 2
assert(x, 'test')
assert(5, 'test')
assert 5, 'test'
if 'str':
return 3
return 4
def func4(x):
'should not produce a warning'
if x == 204 or x == 201 or 200 <= x < 300:
x = 0
if x == 1:
pass
while x == 'str':
print x
break
return 0
| 'test checking constant conditions'
# __pychecker__ = ''
def func1(x):
'should not produce a warning'
if 1:
pass
while 1:
print x
break
assert x, 'test'
return 0
def func2(x):
'should produce a warning'
__pychecker__ = 'constant1'
if 1:
pass
while 1:
print x
break
return 0
def func3(x):
'should produce a warning'
if 21:
return 1
if 31:
return 2
assert(x, 'test')
assert(5, 'test')
assert 5, 'test'
if 'str':
return 3
return 4
def func4(x):
'should not produce a warning'
if x == 204 or x == 201 or 200 <= x < 300:
x = 0
if x == 1:
pass
while x == 'str':
print x
break
return 0
def func5(need_quotes, text):
'should not produce a warning'
return (need_quotes) and ('"%s"' % text) or (text)
| Fix a problem reported by Greg Ward and pointed out by John Machin when doing: | Fix a problem reported by Greg Ward and pointed out by John Machin when doing:
return (need_quotes) and ('"%s"' % text) or (text)
The following warning was generated:
Using a conditional statement with a constant value ("%s")
This was because even the stack wasn't modified after a BINARY_MODULO
to say the value on the stack was no longer const.
| Python | bsd-3-clause | thomasvs/pychecker,thomasvs/pychecker,akaihola/PyChecker,akaihola/PyChecker | ---
+++
@@ -47,3 +47,8 @@
print x
break
return 0
+
+def func5(need_quotes, text):
+ 'should not produce a warning'
+ return (need_quotes) and ('"%s"' % text) or (text)
+ |
e229c797a507932d7992f44d3ab93517096c2e94 | tests/test_autotime.py | tests/test_autotime.py | from IPython import get_ipython
from IPython.testing import tools as tt
from IPython.terminal.interactiveshell import TerminalInteractiveShell
def test_full_cycle():
shell = TerminalInteractiveShell.instance()
ip = get_ipython()
with tt.AssertPrints('time: '):
ip.run_cell("%load_ext autotime")
with tt.AssertPrints('time: '):
ip.run_cell("x = 1")
with tt.AssertPrints(''):
ip.run_cell("%unload_ext autotime")
| from IPython import get_ipython
from IPython.testing import tools as tt
from IPython.terminal.interactiveshell import TerminalInteractiveShell
def test_full_cycle():
shell = TerminalInteractiveShell.instance()
ip = get_ipython()
with tt.AssertPrints('time: '):
ip.run_cell('%load_ext autotime')
with tt.AssertPrints('time: '):
ip.run_cell('x = 1')
with tt.AssertNotPrints('time: '):
ip.run_cell('%unload_ext autotime')
| Make unload test assertion explicit | Make unload test assertion explicit | Python | apache-2.0 | cpcloud/ipython-autotime | ---
+++
@@ -8,10 +8,10 @@
ip = get_ipython()
with tt.AssertPrints('time: '):
- ip.run_cell("%load_ext autotime")
+ ip.run_cell('%load_ext autotime')
with tt.AssertPrints('time: '):
- ip.run_cell("x = 1")
+ ip.run_cell('x = 1')
- with tt.AssertPrints(''):
- ip.run_cell("%unload_ext autotime")
+ with tt.AssertNotPrints('time: '):
+ ip.run_cell('%unload_ext autotime') |
daed28559cc16374f85830ef9d939ccddece64a1 | tests/test_parser.py | tests/test_parser.py | # -*- coding: utf-8 -*-
import codecs
import pytest
from poyo import parse_string
@pytest.fixture
def string_data():
with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile:
return ymlfile.read()
def test_parse_string(string_data):
expected = {
u'default_context': {
u'greeting': u'こんにちは',
u'email': u'raphael@hackebrot.de',
u'docs': True,
u'gui': False,
123: 456.789,
u'someint': 1000000,
u'foo': u'hallo #welt',
u'trueish': u'Falseeeeeee',
},
u'zZz': True,
u'NullValue': None,
u'Hello World': {
None: u'This is madness',
u'gh': u'https://github.com/{0}.git',
},
u'Yay #python': u'Cool!'
}
assert parse_string(string_data) == expected
| # -*- coding: utf-8 -*-
import codecs
import pytest
from poyo import parse_string
@pytest.fixture
def string_data():
with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile:
return ymlfile.read()
def test_parse_string(string_data):
expected = {
u'default_context': {
u'greeting': u'こんにちは',
u'email': u'raphael@hackebrot.de',
u'docs': True,
u'gui': False,
123: 456.789,
u'someint': 1000000,
u'foo': u'hallo #welt',
u'trueish': u'Falseeeeeee',
u'doc_tools': [u'mkdocs', u'sphinx', None],
},
u'zZz': True,
u'NullValue': None,
u'Hello World': {
None: u'This is madness',
u'gh': u'https://github.com/{0}.git',
},
u'Yay #python': u'Cool!'
}
assert parse_string(string_data) == expected
| Add list to expectation in test | Add list to expectation in test
| Python | mit | hackebrot/poyo | ---
+++
@@ -23,6 +23,7 @@
u'someint': 1000000,
u'foo': u'hallo #welt',
u'trueish': u'Falseeeeeee',
+ u'doc_tools': [u'mkdocs', u'sphinx', None],
},
u'zZz': True,
u'NullValue': None, |
3a5cbdbe4a79efd59114ca11f86e282aee0eac5c | tests/trunk_aware.py | tests/trunk_aware.py | import functools
import sys
import nose
from preparation.resources.Resource import trunks_registered, applied_modifiers, resource_by_trunk
__author__ = 'moskupols'
_multiprocess_shared_ = True
_all_trunks = set(trunks_registered())
_trunk_filter = _all_trunks
def trunk_parametrized(trunks=set(trunks_registered())):
def decorate(tester):
@functools.wraps(tester)
def generate_tests(*args):
for t in _trunk_filter & trunks:
yield (tester, t) + args
return generate_tests
return decorate
@functools.lru_cache()
def asset_cache(trunk):
return tuple(applied_modifiers(resource_by_trunk(trunk)()))
def main(args=None):
global _trunk_filter
if args is None:
args = sys.argv
_trunk_filter = _all_trunks & set(args)
if len(_trunk_filter) == 0:
_trunk_filter = _all_trunks
args = [arg for arg in args if arg not in _trunk_filter]
nose.main(argv=args)
| import functools
import sys
import nose
from preparation.resources.Resource import trunks_registered, applied_modifiers, resource_by_trunk
__author__ = 'moskupols'
_multiprocess_shared_ = True
_all_trunks = set(trunks_registered())
_trunk_filter = _all_trunks
def trunk_parametrized(trunks=set(trunks_registered())):
def decorate(tester):
@functools.wraps(tester)
def generate_tests(*args):
for t in _trunk_filter & trunks:
yield (tester, t) + args
return generate_tests
return decorate
@functools.lru_cache()
def asset_cache(trunk):
return tuple(applied_modifiers(resource_by_trunk(trunk)()))
def main(args=None):
global _trunk_filter
if args is None:
args = sys.argv
include = _all_trunks & set(args)
exclude_percented = set('%' + t for t in _all_trunks) & set(args)
exclude = set(e[1:] for e in exclude_percented)
if len(include) == 0:
include = _all_trunks
_trunk_filter = include - exclude
args = [arg for arg in args if arg not in include | exclude_percented]
nose.main(argv=args)
| Add ability to exclude trunks by passing % before it | Add ability to exclude trunks by passing % before it
For example, ./run_nose -v %FilmTitles %BookTitles
| Python | mit | hatbot-team/hatbot_resources | ---
+++
@@ -33,9 +33,13 @@
if args is None:
args = sys.argv
- _trunk_filter = _all_trunks & set(args)
- if len(_trunk_filter) == 0:
- _trunk_filter = _all_trunks
+ include = _all_trunks & set(args)
+ exclude_percented = set('%' + t for t in _all_trunks) & set(args)
+ exclude = set(e[1:] for e in exclude_percented)
- args = [arg for arg in args if arg not in _trunk_filter]
+ if len(include) == 0:
+ include = _all_trunks
+ _trunk_filter = include - exclude
+
+ args = [arg for arg in args if arg not in include | exclude_percented]
nose.main(argv=args) |
acba9a027eafb1877f0b6208613206674ba5d55d | tmc/models/employee.py | tmc/models/employee.py | # -*- coding: utf-8 -*-
from odoo import fields, models
class Employee(models.Model):
_name = 'tmc.hr.employee'
_order = 'name'
name = fields.Char()
internal_number = fields.Char(
size=3,
required=True
)
docket_number = fields.Integer(
required=True
)
bank_account_number = fields.Char()
bank_branch = fields.Integer(
size=2
)
admission_date = fields.Date()
email = fields.Char()
active = fields.Boolean(
default=True
)
employee_title_ids = fields.Many2many(
comodel_name='tmc.hr.employee_title'
)
employee_job_id = fields.Many2one(
comodel_name='tmc.hr.employee_job'
)
office_id = fields.Many2one(
comodel_name='tmc.hr.office'
)
_sql_constraints = [
('number_uniq',
'unique(docket_number, bank_account_number)',
'Number must be unique!'),
]
| # -*- coding: utf-8 -*-
from odoo import fields, models
class Employee(models.Model):
_name = 'tmc.hr.employee'
_order = 'name'
name = fields.Char()
internal_number = fields.Char(
size=3
)
docket_number = fields.Integer()
bank_account_number = fields.Char()
bank_branch = fields.Integer(
size=2
)
admission_date = fields.Date()
email = fields.Char()
active = fields.Boolean(
default=True
)
employee_title_ids = fields.Many2many(
comodel_name='tmc.hr.employee_title'
)
employee_job_id = fields.Many2one(
comodel_name='tmc.hr.employee_job'
)
office_id = fields.Many2one(
comodel_name='tmc.hr.office'
)
_sql_constraints = [
('number_uniq',
'unique(docket_number, bank_account_number)',
'Number must be unique!'),
]
| Remove required property on some fields | [DEL] Remove required property on some fields
| Python | agpl-3.0 | tmcrosario/odoo-tmc | ---
+++
@@ -11,13 +11,10 @@
name = fields.Char()
internal_number = fields.Char(
- size=3,
- required=True
+ size=3
)
- docket_number = fields.Integer(
- required=True
- )
+ docket_number = fields.Integer()
bank_account_number = fields.Char()
|
5f7137b8167704e3a9893ce0b9e72c0f6a64ac4e | warehouse/__init__.py | warehouse/__init__.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import importlib
import logging
import os
from flask import Flask
from flask.ext.script import Manager
from flask.ext.sqlalchemy import SQLAlchemy
__all__ = ["create_app", "db", "script"]
MODULES = [
{"name": "packages"},
]
logger = logging.getLogger("warehouse")
db = SQLAlchemy()
def create_app(config=None):
# Create the Flask Application
app = Flask("warehouse")
# Load Configuration
logger.debug("Loading configuration")
app.config.from_object("warehouse.defaults")
if "WAREHOUSE_CONF" in os.environ:
app.config.from_envvar("WAREHOUSE_CONF")
if config:
app.config.from_pyfile(config)
# Initialize Extensions
logger.debug("Initializing extensions")
db.init_app(app)
# Load Modules
logger.debug("Loading modules")
for module in MODULES:
# Load Models
if module.get("models", True):
logger.debug("Loading models for %s", module["name"])
importlib.import_module("warehouse.%(name)s.models" % module)
return app
script = Manager(create_app)
script.add_option("-c", "--config", dest="config", required=False)
| from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import importlib
import logging
import os
from flask import Flask
from flask.ext.script import Manager
from flask.ext.sqlalchemy import SQLAlchemy
__all__ = ["create_app", "db", "script"]
MODULES = [
{"name": "packages"},
]
logger = logging.getLogger("warehouse")
db = SQLAlchemy()
def create_app(config=None):
# Create the Flask Application
app = Flask("warehouse")
# Load Configuration
logger.debug("Loading configuration")
app.config.from_object("warehouse.defaults")
if "WAREHOUSE_CONF" in os.environ:
app.config.from_envvar("WAREHOUSE_CONF")
if config:
app.config.from_pyfile(config)
# Initialize Extensions
logger.debug("Initializing extensions")
db.init_app(app)
# Load Modules
logger.debug("Loading modules")
for module in MODULES:
# Load Models
if module.get("models", True):
logger.debug("Loading models for %s", module["name"])
importlib.import_module("warehouse.%(name)s.models" % module)
return app
script = Manager(create_app)
script.add_option("-c", "--config", dest="config", required=False)
for module in MODULES:
# Load commands
if module.get("commands"):
logger.debug("Loading commands for %s", module["name"])
importlib.import_module("warehouse.%(name)s.commands" % module)
| Enable registering commands in a module | Enable registering commands in a module
* Looks for a key "commands" with a value of True to import the
module named warehouse.MODULE.commands to trigger command
registration
| Python | bsd-2-clause | davidfischer/warehouse | ---
+++
@@ -56,3 +56,9 @@
script = Manager(create_app)
script.add_option("-c", "--config", dest="config", required=False)
+
+for module in MODULES:
+ # Load commands
+ if module.get("commands"):
+ logger.debug("Loading commands for %s", module["name"])
+ importlib.import_module("warehouse.%(name)s.commands" % module) |
3c9b49ef968c7e59028eb0bda78b1474a49339f3 | numscons/tools/intel_common/common.py | numscons/tools/intel_common/common.py | # INPUTS:
# ICC_ABI: x86, amd64
_ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'}
def get_abi(env):
try:
abi = env['ICC_ABI']
except KeyError:
abi = 'default'
try:
return _ARG2ABI[abi]
except KeyError:
ValueError("Unknown abi %s" % abi)
| # INPUTS:
# ICC_ABI: x86, amd64
_ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'}
def get_abi(env, lang='C'):
if lang == 'C' or lang == 'CXX':
try:
abi = env['ICC_ABI']
except KeyError:
abi = 'default'
elif lang == 'FORTRAN':
try:
abi = env['IFORT_ABI']
except KeyError:
abi = 'default'
try:
return _ARG2ABI[abi]
except KeyError:
ValueError("Unknown abi %s" % abi)
| Add a language argument to get abi for intel tools. | Add a language argument to get abi for intel tools.
| Python | bsd-3-clause | cournape/numscons,cournape/numscons,cournape/numscons | ---
+++
@@ -3,11 +3,17 @@
_ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'}
-def get_abi(env):
- try:
- abi = env['ICC_ABI']
- except KeyError:
- abi = 'default'
+def get_abi(env, lang='C'):
+ if lang == 'C' or lang == 'CXX':
+ try:
+ abi = env['ICC_ABI']
+ except KeyError:
+ abi = 'default'
+ elif lang == 'FORTRAN':
+ try:
+ abi = env['IFORT_ABI']
+ except KeyError:
+ abi = 'default'
try:
return _ARG2ABI[abi] |
ecbb3ffdf063bc53eae0f8bd180e62ae61f99fee | opencontrail_netns/vrouter_control.py | opencontrail_netns/vrouter_control.py |
from contrail_vrouter_api.vrouter_api import ContrailVRouterApi
def interface_register(vm, vmi, iface_name):
api = ContrailVRouterApi()
mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0]
api.add_port(vm.uuid, vmi.uuid, iface_name, mac)
def interface_unregister(vmi_uuid):
api = ContrailVRouterApi()
api.delete_port(vmi_uuid)
|
from contrail_vrouter_api.vrouter_api import ContrailVRouterApi
def interface_register(vm, vmi, iface_name):
api = ContrailVRouterApi()
mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0]
api.add_port(vm.uuid, vmi.uuid, iface_name, mac, port_type='NovaVMPort')
def interface_unregister(vmi_uuid):
api = ContrailVRouterApi()
api.delete_port(vmi_uuid)
| Use NovaVMPort type; otherwise the agent will believe it is a Use NovaVMPort as type; otherwise the agent will believe it is dealing with a service-instance and will not send a VM registration. | Use NovaVMPort type; otherwise the agent will believe it is a
Use NovaVMPort as type; otherwise the agent will believe it is dealing with
a service-instance and will not send a VM registration.
| Python | apache-2.0 | pedro-r-marques/opencontrail-netns,DreamLab/opencontrail-netns | ---
+++
@@ -4,7 +4,7 @@
def interface_register(vm, vmi, iface_name):
api = ContrailVRouterApi()
mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0]
- api.add_port(vm.uuid, vmi.uuid, iface_name, mac)
+ api.add_port(vm.uuid, vmi.uuid, iface_name, mac, port_type='NovaVMPort')
def interface_unregister(vmi_uuid): |
ac4eb3cbbd8e08092ddfb8f55e0ce838a803aa43 | __init__.py | __init__.py | # Apparently South has some problems with upgrading permissions. The
# following piece of code hooks into the migrations and recreates the
# permissions. See also
# http://stackoverflow.com/questions/1742021/adding-new-custom-permissions-in-django/11914435#11914435
from south.signals import post_migrate
def update_permissions_after_migration(app,**kwargs):
"""
Update app permission just after every migration.
This is based on app django_extensions update_permissions management command.
"""
from django.conf import settings
from django.db.models import get_app, get_models
from django.contrib.auth.management import create_permissions
create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0)
post_migrate.connect(update_permissions_after_migration)
| Add a hack to work around a problem with South and permissions | Add a hack to work around a problem with South and permissions
| Python | agpl-3.0 | sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer | ---
+++
@@ -0,0 +1,20 @@
+# Apparently South has some problems with upgrading permissions. The
+# following piece of code hooks into the migrations and recreates the
+# permissions. See also
+# http://stackoverflow.com/questions/1742021/adding-new-custom-permissions-in-django/11914435#11914435
+
+from south.signals import post_migrate
+
+def update_permissions_after_migration(app,**kwargs):
+ """
+ Update app permission just after every migration.
+ This is based on app django_extensions update_permissions management command.
+ """
+ from django.conf import settings
+ from django.db.models import get_app, get_models
+ from django.contrib.auth.management import create_permissions
+
+ create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0)
+
+post_migrate.connect(update_permissions_after_migration)
+ | |
8a080a94300403487dce023eec8467832af8ae79 | tests/core/migrations/0004_bookwithchapters.py | tests/core/migrations/0004_bookwithchapters.py | from __future__ import unicode_literals
from django import VERSION
from django.db import migrations, models
if VERSION >= (1, 8):
from django.contrib.postgres.fields import ArrayField
chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None)
else:
chapters_field = models.Field() # Dummy field
class PostgresOnlyCreateModel(migrations.CreateModel):
def database_forwards(self, app_label, schema_editor, from_state, to_state):
if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"):
super(PostgresOnlyCreateModel, self).database_forwards(app_label, schema_editor, from_state, to_state)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"):
super(PostgresOnlyCreateModel, self).database_backwards(app_label, schema_editor, from_state, to_state)
class Migration(migrations.Migration):
dependencies = [
('core', '0003_withfloatfield'),
]
operations = [
PostgresOnlyCreateModel(
name='BookWithChapters',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Book name')),
('chapters', chapters_field)
],
),
]
| from __future__ import unicode_literals
from django import VERSION
from django.db import migrations, models
can_use_arrayfield = False
chapters_field = models.Field() # Dummy field
if VERSION >= (1, 8):
try:
from django.contrib.postgres.fields import ArrayField
chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None)
can_use_arrayfield = True
except ImportError:
# We can't use ArrayField if psycopg2 is not installed
pass
class Migration(migrations.Migration):
dependencies = [
('core', '0003_withfloatfield'),
]
operations = []
pg_only_operations = [
migrations.CreateModel(
name='BookWithChapters',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Book name')),
('chapters', chapters_field)
],
),
]
def apply(self, project_state, schema_editor, collect_sql=False):
if can_use_arrayfield and schema_editor.connection.vendor.startswith("postgres"):
self.operations = self.operations + self.pg_only_operations
return super(Migration, self).apply(project_state, schema_editor, collect_sql)
| Refactor migration script to handle case where Postgres is being used but psycopg2 isn't installed | Refactor migration script to handle case where Postgres is being used but psycopg2 isn't installed
| Python | bsd-2-clause | brillgen/django-import-export,copperleaftech/django-import-export,bmihelac/django-import-export,jnns/django-import-export,copperleaftech/django-import-export,jnns/django-import-export,brillgen/django-import-export,PetrDlouhy/django-import-export,jnns/django-import-export,PetrDlouhy/django-import-export,brillgen/django-import-export,django-import-export/django-import-export,bmihelac/django-import-export,django-import-export/django-import-export,PetrDlouhy/django-import-export,copperleaftech/django-import-export,daniell/django-import-export,bmihelac/django-import-export,PetrDlouhy/django-import-export,daniell/django-import-export,copperleaftech/django-import-export,bmihelac/django-import-export,jnns/django-import-export,brillgen/django-import-export,django-import-export/django-import-export,daniell/django-import-export,django-import-export/django-import-export,daniell/django-import-export | ---
+++
@@ -2,21 +2,17 @@
from django import VERSION
from django.db import migrations, models
+
+can_use_arrayfield = False
+chapters_field = models.Field() # Dummy field
if VERSION >= (1, 8):
- from django.contrib.postgres.fields import ArrayField
- chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None)
-else:
- chapters_field = models.Field() # Dummy field
-
-
-class PostgresOnlyCreateModel(migrations.CreateModel):
- def database_forwards(self, app_label, schema_editor, from_state, to_state):
- if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"):
- super(PostgresOnlyCreateModel, self).database_forwards(app_label, schema_editor, from_state, to_state)
-
- def database_backwards(self, app_label, schema_editor, from_state, to_state):
- if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"):
- super(PostgresOnlyCreateModel, self).database_backwards(app_label, schema_editor, from_state, to_state)
+ try:
+ from django.contrib.postgres.fields import ArrayField
+ chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None)
+ can_use_arrayfield = True
+ except ImportError:
+ # We can't use ArrayField if psycopg2 is not installed
+ pass
class Migration(migrations.Migration):
@@ -25,8 +21,10 @@
('core', '0003_withfloatfield'),
]
- operations = [
- PostgresOnlyCreateModel(
+ operations = []
+
+ pg_only_operations = [
+ migrations.CreateModel(
name='BookWithChapters',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
@@ -35,3 +33,8 @@
],
),
]
+
+ def apply(self, project_state, schema_editor, collect_sql=False):
+ if can_use_arrayfield and schema_editor.connection.vendor.startswith("postgres"):
+ self.operations = self.operations + self.pg_only_operations
+ return super(Migration, self).apply(project_state, schema_editor, collect_sql) |
c53725ef0c30875e8727001b05f50c6eb02abe00 | nn/models/font2char2word2sent2doc.py | nn/models/font2char2word2sent2doc.py | import tensorflow as tf
from ..font import font2char
from ..util import static_rank, funcname_scope
from .ar2word2sent2doc import ar2word2sent2doc
@funcname_scope
def font2char2word2sent2doc(document,
*,
words,
fonts,
char_embedding_size,
dropout_prob,
**ar2word2sent2doc_hyper_params):
assert static_rank(document) == 3
assert static_rank(words) == 2
assert static_rank(fonts) == 3
return ar2word2sent2doc(
document,
words=words,
char_embeddings=font2char(fonts,
dropout_prob=dropout_prob,
char_embedding_size=char_embedding_size),
dropout_prob=dropout_prob,
**ar2word2sent2doc_hyper_params)
| import tensorflow as tf
from ..font import font2char
from ..util import static_rank, funcname_scope
from .ar2word2sent2doc import ar2word2sent2doc
@funcname_scope
def font2char2word2sent2doc(document,
*,
words,
fonts,
char_embedding_size,
dropout_prob,
**ar2word2sent2doc_hyper_params):
assert static_rank(document) == 3
assert static_rank(words) == 2
assert static_rank(fonts) == 3
return ar2word2sent2doc(
document,
words=words,
char_embeddings=font2char(fonts,
dropout_prob=dropout_prob,
char_embedding_size=char_embedding_size),
dropout_prob=dropout_prob,
**ar2word2sent2doc_hyper_params)
| Delete an extra blank line | Delete an extra blank line
| Python | unlicense | raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten | ---
+++
@@ -18,7 +18,6 @@
assert static_rank(words) == 2
assert static_rank(fonts) == 3
-
return ar2word2sent2doc(
document,
words=words, |
7a77b42691e051269a146fd218dd619ccefecc54 | src/ansible/models.py | src/ansible/models.py | from django.db import models
class Project(models.Model):
project_name = models.CharField(max_length=200)
playbook_path = models.CharField(max_length=200, default="~/")
ansible_config_path = models.CharField(max_length=200, default="~/")
default_inventory = models.CharField(max_length=200, default="hosts")
default_user = models.CharField(max_length=200, default="ubuntu")
class Registry(models.Model):
project = models.OneToOneField(
Project,
on_delete=models.CASCADE,
primary_key=True,
)
name = models.CharField(max_length=200)
def __str__(self):
return "project name: %s" % self.project.project_name
| from django.db import models
class Project(models.Model):
project_name = models.CharField(max_length=200)
playbook_path = models.CharField(max_length=200, default="~/")
ansible_config_path = models.CharField(max_length=200, default="~/")
default_inventory = models.CharField(max_length=200, default="hosts")
default_user = models.CharField(max_length=200, default="ubuntu")
class Registry(models.Model):
class Meta:
verbose_name_plural = "registries"
project = models.OneToOneField(
Project,
on_delete=models.CASCADE,
primary_key=True,
)
name = models.CharField(max_length=200)
def __str__(self):
return "project name: %s" % self.project.project_name
| Fix plural form of Registry | Fix plural form of Registry
TIL how to use meta class
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin | ---
+++
@@ -9,6 +9,10 @@
class Registry(models.Model):
+ class Meta:
+ verbose_name_plural = "registries"
+
+
project = models.OneToOneField(
Project,
on_delete=models.CASCADE, |
4a4abb215684a169be4ba7e0a670000f25870cd7 | nodeconductor/logging/serializers.py | nodeconductor/logging/serializers.py | from rest_framework import serializers
from nodeconductor.core.serializers import GenericRelatedField
from nodeconductor.core.fields import MappedChoiceField, JsonField
from nodeconductor.logging import models, utils, log
class AlertSerializer(serializers.HyperlinkedModelSerializer):
scope = GenericRelatedField(related_models=utils.get_loggable_models())
severity = MappedChoiceField(
choices=[(v, k) for k, v in models.Alert.SeverityChoices.CHOICES],
choice_mappings={v: k for k, v in models.Alert.SeverityChoices.CHOICES},
)
context = JsonField(read_only=True)
status = serializers.ChoiceField(
choices=(('PROBLEM', 'Problem'), ('OK', 'OK')), default='PROBLEM', write_only=True)
class Meta(object):
model = models.Alert
fields = (
'url', 'uuid', 'alert_type', 'message', 'severity', 'scope', 'created', 'closed', 'context', 'status')
read_only_fields = ('uuid', 'created', 'closed')
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
}
def create(self, validated_data):
alert, _ = log.AlertLogger().process(
severity=validated_data['severity'],
message_template=validated_data['message'],
scope=validated_data['scope'],
alert_type=validated_data['alert_type'],
)
return alert
| from rest_framework import serializers
from nodeconductor.core.serializers import GenericRelatedField
from nodeconductor.core.fields import MappedChoiceField, JsonField
from nodeconductor.logging import models, utils, log
class AlertSerializer(serializers.HyperlinkedModelSerializer):
scope = GenericRelatedField(related_models=utils.get_loggable_models())
severity = MappedChoiceField(
choices=[(v, k) for k, v in models.Alert.SeverityChoices.CHOICES],
choice_mappings={v: k for k, v in models.Alert.SeverityChoices.CHOICES},
)
context = JsonField(read_only=True)
class Meta(object):
model = models.Alert
fields = (
'url', 'uuid', 'alert_type', 'message', 'severity', 'scope', 'created', 'closed', 'context')
read_only_fields = ('uuid', 'created', 'closed')
extra_kwargs = {
'url': {'lookup_field': 'uuid'},
}
def create(self, validated_data):
alert, _ = log.AlertLogger().process(
severity=validated_data['severity'],
message_template=validated_data['message'],
scope=validated_data['scope'],
alert_type=validated_data['alert_type'],
)
return alert
| Remove wrong serializer field (nc-553) | Remove wrong serializer field (nc-553)
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | ---
+++
@@ -12,13 +12,11 @@
choice_mappings={v: k for k, v in models.Alert.SeverityChoices.CHOICES},
)
context = JsonField(read_only=True)
- status = serializers.ChoiceField(
- choices=(('PROBLEM', 'Problem'), ('OK', 'OK')), default='PROBLEM', write_only=True)
class Meta(object):
model = models.Alert
fields = (
- 'url', 'uuid', 'alert_type', 'message', 'severity', 'scope', 'created', 'closed', 'context', 'status')
+ 'url', 'uuid', 'alert_type', 'message', 'severity', 'scope', 'created', 'closed', 'context')
read_only_fields = ('uuid', 'created', 'closed')
extra_kwargs = {
'url': {'lookup_field': 'uuid'}, |
6528a426ffb7a9a55c9f84f3c134a195a5e17046 | problems/examples/cryptography/ecb-1/challenge.py | problems/examples/cryptography/ecb-1/challenge.py | import string
from hacksport.problem import ProtectedFile, Remote
class Problem(Remote):
program_name = "ecb.py"
files = [ProtectedFile("flag"), ProtectedFile("key")]
def initialize(self):
# generate random 32 hexadecimal characters
self.enc_key = "".join(
self.random.choice(string.digits + "abcdef") for _ in range(32)
)
self.welcome_message = "Welcome to Secure Encryption Service version 1.{}".format(
self.random.randint(0, 10)
)
| import secrets
import string
from hacksport.problem import ProtectedFile, Remote
from hacksport.deploy import flag_fmt
class Problem(Remote):
program_name = "ecb.py"
files = [ProtectedFile("flag"), ProtectedFile("key")]
def initialize(self):
# generate random 32 hexadecimal characters
self.enc_key = "".join(
self.random.choice(string.digits + "abcdef") for _ in range(32)
)
self.welcome_message = "Welcome to Secure Encryption Service version 1.{}".format(
self.random.randint(0, 10)
)
# flag length must be a multiple of 16
def generate_flag(self, random):
flag = (flag_fmt() % secrets.token_hex(32))[:32]
if "{" in flag:
flag = flag[:31] + "}"
assert len(flag) % 16 == 0
return flag
| Fix ecb-1 to assert flag length | Fix ecb-1 to assert flag length
| Python | mit | picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF | ---
+++
@@ -1,6 +1,8 @@
+import secrets
import string
from hacksport.problem import ProtectedFile, Remote
+from hacksport.deploy import flag_fmt
class Problem(Remote):
@@ -16,3 +18,11 @@
self.welcome_message = "Welcome to Secure Encryption Service version 1.{}".format(
self.random.randint(0, 10)
)
+
+ # flag length must be a multiple of 16
+ def generate_flag(self, random):
+ flag = (flag_fmt() % secrets.token_hex(32))[:32]
+ if "{" in flag:
+ flag = flag[:31] + "}"
+ assert len(flag) % 16 == 0
+ return flag |
35303ce7654e14a88fcb9db0690f72c07410dade | python/pythagorean-triplet/pythagorean_triplet.py | python/pythagorean-triplet/pythagorean_triplet.py | def triplets_with_sum(n):
pass
| from math import ceil, gcd, sqrt
def triplets_in_range(range_start, range_end):
for limit in range(range_start, range_end, 4):
for x, y, z in primitive_triplets(limit):
a, b, c = (x, y, z)
# yield multiples of primitive triplet
while a < range_start:
a, b, c = (a + x, b + y, c + z)
while c < range_end:
yield (a, b, c)
a, b, c = (a + x, b + y, c + z)
def euclidian_coprimes(limit):
"""See Euclidean algorithm
https://en.wikipedia.org/wiki/Euclidean_algorithm#Description
"""
mn = limit // 2
for n in range(1, int(ceil(sqrt(mn)))):
if mn % n == 0:
m = mn // n
if (m - n) % 2 == 1 and gcd(m, n) == 1:
yield m, n
def primitive_triplets(limit):
"""See Euclid's formula
https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple
"""
for m, n in euclidian_coprimes(limit):
a = m ** 2 - n ** 2
b = 2 * m * n
c = m ** 2 + n ** 2
yield sorted([a, b, c])
def triplets_with_sum(triplet_sum):
return {
triplet
for triplet in triplets_in_range(1, triplet_sum // 2)
if sum(triplet) == triplet_sum
}
| Solve pythagorean_triple - reference solution | Solve pythagorean_triple - reference solution
| Python | mit | rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism | ---
+++
@@ -1,2 +1,44 @@
-def triplets_with_sum(n):
- pass
+from math import ceil, gcd, sqrt
+
+
+def triplets_in_range(range_start, range_end):
+ for limit in range(range_start, range_end, 4):
+ for x, y, z in primitive_triplets(limit):
+ a, b, c = (x, y, z)
+
+ # yield multiples of primitive triplet
+ while a < range_start:
+ a, b, c = (a + x, b + y, c + z)
+ while c < range_end:
+ yield (a, b, c)
+ a, b, c = (a + x, b + y, c + z)
+
+
+def euclidian_coprimes(limit):
+ """See Euclidean algorithm
+ https://en.wikipedia.org/wiki/Euclidean_algorithm#Description
+ """
+ mn = limit // 2
+ for n in range(1, int(ceil(sqrt(mn)))):
+ if mn % n == 0:
+ m = mn // n
+ if (m - n) % 2 == 1 and gcd(m, n) == 1:
+ yield m, n
+
+def primitive_triplets(limit):
+ """See Euclid's formula
+ https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple
+ """
+ for m, n in euclidian_coprimes(limit):
+ a = m ** 2 - n ** 2
+ b = 2 * m * n
+ c = m ** 2 + n ** 2
+ yield sorted([a, b, c])
+
+
+def triplets_with_sum(triplet_sum):
+ return {
+ triplet
+ for triplet in triplets_in_range(1, triplet_sum // 2)
+ if sum(triplet) == triplet_sum
+ } |
af184be16c4bd0ea45f7e8c6dc59388c4d8893c5 | main.py | main.py | import tweepy
import app_config
# Twitter API configuration
consumer_key = app_config.twitter["consumer_key"]
consumer_secret = app_config.twitter["consumer_secret"]
access_token = app_config.twitter["access_token"]
access_token_secret = app_config.twitter["access_token_secret"]
# Start
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
followers = api.followers(count=200)
for follower in followers:
print follower.screen_name | import tweepy
import json
import unicodedata
import sqlite3
import app_config
import definitions
API_launch()
followers_list(followers_name[1])
create_db()
create_table()
tweet_info(followers_name[1],tweets_number=100)
| Update Main.py to work with definitions.py | Update Main.py to work with definitions.py
functions are loaded from definitions.py and the database can be created without modifying functions | Python | mit | franckbrignoli/twitter-bot-detection | ---
+++
@@ -1,19 +1,17 @@
import tweepy
+import json
+import unicodedata
+import sqlite3
+
import app_config
+import definitions
-# Twitter API configuration
-consumer_key = app_config.twitter["consumer_key"]
-consumer_secret = app_config.twitter["consumer_secret"]
+API_launch()
-access_token = app_config.twitter["access_token"]
-access_token_secret = app_config.twitter["access_token_secret"]
+followers_list(followers_name[1])
-# Start
-auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
-auth.set_access_token(access_token, access_token_secret)
+create_db()
-api = tweepy.API(auth)
+create_table()
-followers = api.followers(count=200)
-for follower in followers:
- print follower.screen_name
+tweet_info(followers_name[1],tweets_number=100) |
47593fae71deb378bd60a14d1b6f4a3a2bb98bf6 | pitz.py | pitz.py | #!/usr/bin/python
import sys
import subprocess
cmd = sys.argv[1]
new_args = sys.argv[2:] or []
subprocess.call(["pitz-%s" % cmd] + new_args)
| #!/usr/bin/python
import sys
import subprocess
def _help():
subprocess.call(['pitz-help'])
sys.exit(1)
if len(sys.argv) < 2:
_help()
cmd = sys.argv[1]
new_args = sys.argv[2:] or []
try:
subprocess.call(["pitz-%s" % cmd] + new_args)
except OSError as exc:
_help()
| Add at least a minimal exception handling (missing subcommand). | Add at least a minimal exception handling (missing subcommand).
| Python | bsd-3-clause | mw44118/pitz,mw44118/pitz,mw44118/pitz | ---
+++
@@ -3,6 +3,16 @@
import sys
import subprocess
+def _help():
+ subprocess.call(['pitz-help'])
+ sys.exit(1)
+
+if len(sys.argv) < 2:
+ _help()
+
cmd = sys.argv[1]
new_args = sys.argv[2:] or []
-subprocess.call(["pitz-%s" % cmd] + new_args)
+try:
+ subprocess.call(["pitz-%s" % cmd] + new_args)
+except OSError as exc:
+ _help() |
1c2ea508bd0c4e687d6a46c438a476609b43d264 | databroker/tests/test_document.py | databroker/tests/test_document.py | import copy
import pytest
from ..core import Document, NotMutable
def test_immutable():
d = Document({'a': 1})
with pytest.raises(NotMutable):
# Update existing key
d['a'] = 2
with pytest.raises(NotMutable):
# Add new key
d['b'] = 2
with pytest.raises(NotMutable):
d.setdefault('a', 2)
with pytest.raises(NotMutable):
d.setdefault('b', 2)
with pytest.raises(NotMutable):
del d['a']
with pytest.raises(NotMutable):
d.pop('a')
with pytest.raises(NotMutable):
d.popitem()
with pytest.raises(NotMutable):
d.clear()
with pytest.raises(NotMutable):
# Update existing key
d.update({'a': 2})
with pytest.raises(NotMutable):
# Add new key
d.update({'b': 2})
def test_deep_copy():
a = Document({'x': {'y': {'z': 1}}})
b = copy.deepcopy(a)
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
def test_to_dict():
a = Document({'x': {'y': {'z': 1}}})
b = a.to_dict()
assert not isinstance(b, Document)
assert isinstance(b, dict)
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
| import copy
import pytest
from ..core import Document, NotMutable
def test_immutable():
d = Document({'a': 1})
with pytest.raises(NotMutable):
# Update existing key
d['a'] = 2
with pytest.raises(NotMutable):
# Add new key
d['b'] = 2
with pytest.raises(NotMutable):
d.setdefault('a', 2)
with pytest.raises(NotMutable):
d.setdefault('b', 2)
with pytest.raises(NotMutable):
del d['a']
with pytest.raises(NotMutable):
d.pop('a')
with pytest.raises(NotMutable):
d.popitem()
with pytest.raises(NotMutable):
d.clear()
with pytest.raises(NotMutable):
# Update existing key
d.update({'a': 2})
with pytest.raises(NotMutable):
# Add new key
d.update({'b': 2})
def test_deep_copy():
a = Document({'x': {'y': {'z': 1}}})
b = copy.deepcopy(a)
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
def test_to_dict():
a = Document({'x': {'y': {'z': 1}}})
b = a.to_dict()
assert type(b) is dict # i.e. not Document
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1
| Make test stricter to be safe. | Make test stricter to be safe.
| Python | bsd-3-clause | ericdill/databroker,ericdill/databroker | ---
+++
@@ -44,8 +44,7 @@
def test_to_dict():
a = Document({'x': {'y': {'z': 1}}})
b = a.to_dict()
- assert not isinstance(b, Document)
- assert isinstance(b, dict)
+ assert type(b) is dict # i.e. not Document
b['x']['y']['z'] = 2
# Verify original is not modified.
assert a['x']['y']['z'] == 1 |
869db9b392356912beebfc4ed1db97baa82e87e3 | resin/models/config.py | resin/models/config.py | import sys
from ..base_request import BaseRequest
from ..settings import Settings
class Config(object):
"""
This class implements configuration model for Resin Python SDK.
Attributes:
_config (dict): caching configuration.
"""
def __init__(self):
self.base_request = BaseRequest()
self.settings = Settings()
self._config = None
def _get_config(self, key):
if self._config:
return self._config[key]
# Load all config again
self.get_all()
return self._config[key]
def get_all(self):
"""
Get all configuration.
Returns:
dict: configuration information.
Examples:
>>> resin.models.config.get_all()
{ all configuration details }
"""
if self._config is None:
self._config = self.base_request.request(
'config', 'GET', endpoint=self.settings.get('api_endpoint'))
return self._config
def get_device_types(self):
"""
Get device types configuration.
Returns:
list: device types information.
Examples:
>>> resin.models.config.get_device_types()
[ all configuration details ]
"""
return self._get_config('deviceTypes')
| import sys
from ..base_request import BaseRequest
from ..settings import Settings
def _normalize_device_type(dev_type):
if dev_type['state'] == 'PREVIEW':
dev_type['state'] = 'ALPHA'
dev_type['name'] = dev_type['name'].replace('(PREVIEW)', '(ALPHA)')
if dev_type['state'] == 'EXPERIMENTAL':
dev_type['state'] = 'BETA'
dev_type['name'] = dev_type['name'].replace('(EXPERIMENTAL)', ('BETA'))
if dev_type['slug'] == 'raspberry-pi':
dev_type['name'] = 'Raspberry Pi (v1 or Zero)'
return dev_type
class Config(object):
"""
This class implements configuration model for Resin Python SDK.
Attributes:
_config (dict): caching configuration.
"""
def __init__(self):
self.base_request = BaseRequest()
self.settings = Settings()
self._config = None
def _get_config(self, key):
if self._config:
return self._config[key]
# Load all config again
self.get_all()
return self._config[key]
def get_all(self):
"""
Get all configuration.
Returns:
dict: configuration information.
Examples:
>>> resin.models.config.get_all()
{ all configuration details }
"""
if self._config is None:
self._config = self.base_request.request(
'config', 'GET', endpoint=self.settings.get('api_endpoint'))
self._config['deviceTypes'] = map(_normalize_device_type, self._config['deviceTypes'])
return self._config
def get_device_types(self):
"""
Get device types configuration.
Returns:
list: device types information.
Examples:
>>> resin.models.config.get_device_types()
[ all configuration details ]
"""
return self._get_config('deviceTypes')
| Patch device types to be marked as ALPHA and BETA | Patch device types to be marked as ALPHA and BETA
| Python | apache-2.0 | resin-io/resin-sdk-python,resin-io/resin-sdk-python,nghiant2710/resin-sdk-python,nghiant2710/resin-sdk-python | ---
+++
@@ -2,6 +2,18 @@
from ..base_request import BaseRequest
from ..settings import Settings
+
+
+def _normalize_device_type(dev_type):
+ if dev_type['state'] == 'PREVIEW':
+ dev_type['state'] = 'ALPHA'
+ dev_type['name'] = dev_type['name'].replace('(PREVIEW)', '(ALPHA)')
+ if dev_type['state'] == 'EXPERIMENTAL':
+ dev_type['state'] = 'BETA'
+ dev_type['name'] = dev_type['name'].replace('(EXPERIMENTAL)', ('BETA'))
+ if dev_type['slug'] == 'raspberry-pi':
+ dev_type['name'] = 'Raspberry Pi (v1 or Zero)'
+ return dev_type
class Config(object):
@@ -41,6 +53,7 @@
if self._config is None:
self._config = self.base_request.request(
'config', 'GET', endpoint=self.settings.get('api_endpoint'))
+ self._config['deviceTypes'] = map(_normalize_device_type, self._config['deviceTypes'])
return self._config
def get_device_types(self): |
732430fcfa1cfc6e7303ae1fb6d0f2eea43bdd00 | deps/pyextensibletype/extensibletype/test/test_interning.py | deps/pyextensibletype/extensibletype/test/test_interning.py | from .. import intern
def test_global_interning():
try:
intern.global_intern("hello")
except AssertionError as e:
pass
else:
raise Exception("Expects complaint about uninitialized table")
intern.global_intern_initialize()
id1 = intern.global_intern("hello")
id2 = intern.global_intern("hello")
id3 = intern.global_intern("hallo")
assert id1 == id2
assert id1 != id3
def test_interning():
table = intern.InternTable()
id1 = intern.global_intern("hello")
id2 = intern.global_intern("hello")
id3 = intern.global_intern("hallo")
assert id1 == id2
assert id1 != id3
| from .. import intern
def test_global_interning():
try:
intern.global_intern("hello")
except AssertionError as e:
pass
else:
raise Exception("Expects complaint about uninitialized table")
intern.global_intern_initialize()
id1 = intern.global_intern("hello")
id2 = intern.global_intern("hello")
id3 = intern.global_intern("hallo")
assert id1 == id2
assert id1 != id3
def test_interning():
table = intern.InternTable()
id1 = intern.global_intern("hello")
id2 = intern.global_intern("hello")
id3 = intern.global_intern("hallo")
assert id1 == id2
assert id1 != id3
def test_intern_many():
table = intern.InternTable()
for i in range(1000000):
table.global_intern("my randrom string %d" % i)
table.global_intern("my randrom string %d" % (i // 2))
table.global_intern("my randrom string %d" % (i // 4))
| Add more thorough intern test | Add more thorough intern test
| Python | bsd-2-clause | stefanseefeld/numba,GaZ3ll3/numba,sklam/numba,stonebig/numba,stefanseefeld/numba,pitrou/numba,GaZ3ll3/numba,seibert/numba,ssarangi/numba,seibert/numba,pombredanne/numba,GaZ3ll3/numba,shiquanwang/numba,IntelLabs/numba,IntelLabs/numba,GaZ3ll3/numba,stonebig/numba,ssarangi/numba,IntelLabs/numba,gdementen/numba,numba/numba,pombredanne/numba,cpcloud/numba,stuartarchibald/numba,gdementen/numba,pombredanne/numba,gdementen/numba,stuartarchibald/numba,gdementen/numba,gmarkall/numba,cpcloud/numba,ssarangi/numba,sklam/numba,shiquanwang/numba,stonebig/numba,pitrou/numba,numba/numba,seibert/numba,sklam/numba,cpcloud/numba,stefanseefeld/numba,numba/numba,numba/numba,gmarkall/numba,gmarkall/numba,seibert/numba,gmarkall/numba,shiquanwang/numba,gmarkall/numba,stuartarchibald/numba,IntelLabs/numba,stuartarchibald/numba,pombredanne/numba,jriehl/numba,stonebig/numba,jriehl/numba,stefanseefeld/numba,jriehl/numba,stefanseefeld/numba,ssarangi/numba,jriehl/numba,ssarangi/numba,cpcloud/numba,cpcloud/numba,seibert/numba,numba/numba,gdementen/numba,sklam/numba,pitrou/numba,stuartarchibald/numba,stonebig/numba,pombredanne/numba,GaZ3ll3/numba,jriehl/numba,sklam/numba,pitrou/numba,pitrou/numba,IntelLabs/numba | ---
+++
@@ -23,3 +23,11 @@
id3 = intern.global_intern("hallo")
assert id1 == id2
assert id1 != id3
+
+def test_intern_many():
+ table = intern.InternTable()
+
+ for i in range(1000000):
+ table.global_intern("my randrom string %d" % i)
+ table.global_intern("my randrom string %d" % (i // 2))
+ table.global_intern("my randrom string %d" % (i // 4)) |
832f30022e29ac882f6dcaf3af50dfd0a935d73c | picoCTF-web/api/setup.py | picoCTF-web/api/setup.py | """
Setup for the API
"""
import api
log = api.logger.use(__name__)
def index_mongo():
"""
Ensure the mongo collections are indexed.
"""
db = api.common.get_conn()
log.debug("Ensuring mongo is indexed.")
db.users.ensure_index("uid", unique=True, name="unique uid")
db.users.ensure_index("username", unique=True, name="unique username")
db.groups.ensure_index("gid", unique=True, name="unique gid")
db.problems.ensure_index("pid", unique=True, name="unique pid")
db.submissions.ensure_index("tid", name="submission tids")
db.ssh.ensure_index("tid", unique=True, name="unique ssh tid")
db.teams.ensure_index("team_name", unique=True, name="unique team names")
db.shell_servers.ensure_index("name", unique=True, name="unique shell name")
db.shell_servers.ensure_index("sid", unique=True, name="unique shell sid")
db.cache.ensure_index("expireAt", expireAfterSeconds=0)
db.cache.ensure_index("kwargs", name="kwargs")
db.cache.ensure_index("args", name="args")
db.shell_servers.ensure_index(
"sid", unique=True, name="unique shell server id")
| """
Setup for the API
"""
import api
log = api.logger.use(__name__)
def index_mongo():
"""
Ensure the mongo collections are indexed.
"""
db = api.common.get_conn()
log.debug("Ensuring mongo is indexed.")
db.users.ensure_index("uid", unique=True, name="unique uid")
db.users.ensure_index("username", unique=True, name="unique username")
db.groups.ensure_index("gid", unique=True, name="unique gid")
db.problems.ensure_index("pid", unique=True, name="unique pid")
db.submissions.ensure_index("tid", name="submission tids")
db.ssh.ensure_index("tid", unique=True, name="unique ssh tid")
db.teams.ensure_index("team_name", unique=True, name="unique team names")
db.shell_servers.ensure_index("name", unique=True, name="unique shell name")
db.shell_servers.ensure_index("sid", unique=True, name="unique shell sid")
db.cache.ensure_index("expireAt", expireAfterSeconds=0)
db.cache.ensure_index("kwargs", name="kwargs")
db.cache.ensure_index("kwargs.uid", name="kwargs.uid")
db.cache.ensure_index("kwargs.tid", name="kwargs.tid")
db.cache.ensure_index("args", name="args")
db.shell_servers.ensure_index(
"sid", unique=True, name="unique shell server id")
| Add more 2 indexes to cache to improve invalidation speed | Add more 2 indexes to cache to improve invalidation speed
| Python | mit | royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF | ---
+++
@@ -31,6 +31,8 @@
db.cache.ensure_index("expireAt", expireAfterSeconds=0)
db.cache.ensure_index("kwargs", name="kwargs")
+ db.cache.ensure_index("kwargs.uid", name="kwargs.uid")
+ db.cache.ensure_index("kwargs.tid", name="kwargs.tid")
db.cache.ensure_index("args", name="args")
db.shell_servers.ensure_index( |
fd4ddd1a4978191fdb0d19960960c703569c6348 | examples/rmg/minimal/input.py | examples/rmg/minimal/input.py | # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
drawMolecules=False,
generatePlots=False,
saveEdgeSpecies=True,
saveConcentrationProfiles=True,
)
| # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = 'default',
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
drawMolecules=False,
generatePlots=False,
saveEdgeSpecies=True,
saveConcentrationProfiles=True,
)
| Set minimal example to 'default' kineticsFamilies. | Set minimal example to 'default' kineticsFamilies.
| Python | mit | pierrelb/RMG-Py,faribas/RMG-Py,nickvandewiele/RMG-Py,enochd/RMG-Py,nickvandewiele/RMG-Py,KEHANG/RMG-Py,nyee/RMG-Py,comocheng/RMG-Py,enochd/RMG-Py,pierrelb/RMG-Py,KEHANG/RMG-Py,faribas/RMG-Py,comocheng/RMG-Py,chatelak/RMG-Py,chatelak/RMG-Py,nyee/RMG-Py | ---
+++
@@ -4,7 +4,7 @@
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
- kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
+ kineticsFamilies = 'default',
kineticsEstimator = 'rate rules',
)
|
98389db2ae73147aeab9b56a0ea588843649a5ce | plugin/import-js-sublime/import-js.py | plugin/import-js-sublime/import-js.py | import sublime, sublime_plugin, subprocess, os
importjs_path = os.path.expanduser('~/.rbenv/shims/import-js')
class ImportJsCommand(sublime_plugin.TextCommand):
def run(self, edit):
entire_file_region = sublime.Region(0, self.view.size())
current_file_contents = self.view.substr(entire_file_region)
environment = { 'LC_ALL': 'en_US.UTF-8', 'LC_CTYPE': 'UTF-8', 'LANG': 'en_US.UTF-8' }
project_root = self.view.window().extract_variables()['folder']
proc = subprocess.Popen(
importjs_path,
shell=True,
cwd=project_root,
env=environment,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
result = proc.communicate(input=current_file_contents.encode('utf-8'))
stderr = result[1].decode()
if(len(stderr) > 0):
sublime.error_message('Error when executing import-js: ' + stderr)
return
stdout = result[0].decode()
self.view.replace(edit, entire_file_region, stdout)
| import sublime, sublime_plugin, subprocess, os
importjs_path = os.path.expanduser('~/.rbenv/shims/import-js')
class ImportJsCommand(sublime_plugin.TextCommand):
def run(self, edit):
entire_file_region = sublime.Region(0, self.view.size())
current_file_contents = self.view.substr(entire_file_region)
environment = { 'LC_ALL': 'en_US.UTF-8', 'LC_CTYPE': 'UTF-8', 'LANG': 'en_US.UTF-8' }
project_root = self.view.window().extract_variables()['folder']
proc = subprocess.Popen(
importjs_path,
shell=True,
cwd=project_root,
env=environment,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
result = proc.communicate(input=current_file_contents.encode('utf-8'))
stderr = result[1].decode()
if(proc.returncode > 0):
sublime.error_message('Error when executing import-js: ' + stderr)
return
stdout = result[0].decode()
self.view.replace(edit, entire_file_region, stdout)
| Check for exit code > 0 instead of existence of stderr | Check for exit code > 0 instead of existence of stderr
I'm about to make messages appear in the Sublime plugin. In order to do
that, I need a channel to post them that won't mess up the end results
being posted to stdout.
| Python | mit | lencioni/import-js,trotzig/import-js,trotzig/import-js,trotzig/import-js,lencioni/import-js,Galooshi/import-js,lencioni/import-js | ---
+++
@@ -21,7 +21,7 @@
result = proc.communicate(input=current_file_contents.encode('utf-8'))
stderr = result[1].decode()
- if(len(stderr) > 0):
+ if(proc.returncode > 0):
sublime.error_message('Error when executing import-js: ' + stderr)
return
|
ea60a04280533c00bcefdf3e0fa6d0bcd8692be0 | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '9006e277b20109de165d4a17827c9b2029bf3831'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
}[sys.platform]
DIST_ARCH = {
'32bit': 'ia32',
'64bit': 'x64',
}[ARCH]
TARGET_PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
| #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '5d5539f8232bb4d0253438216de11a99159b3c4d'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
}[sys.platform]
DIST_ARCH = {
'32bit': 'ia32',
'64bit': 'x64',
}[ARCH]
TARGET_PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
| Upgrade libchromiumcontent to fix chromiumviews. | Upgrade libchromiumcontent to fix chromiumviews.
| Python | mit | egoist/electron,yalexx/electron,gerhardberger/electron,arturts/electron,tonyganch/electron,tincan24/electron,adamjgray/electron,fomojola/electron,jsutcodes/electron,minggo/electron,matiasinsaurralde/electron,adamjgray/electron,mattotodd/electron,shennushi/electron,seanchas116/electron,deepak1556/atom-shell,thompsonemerson/electron,egoist/electron,sshiting/electron,bpasero/electron,michaelchiche/electron,stevekinney/electron,bobwol/electron,rreimann/electron,Neron-X5/electron,michaelchiche/electron,subblue/electron,stevekinney/electron,shennushi/electron,baiwyc119/electron,joneit/electron,destan/electron,cos2004/electron,simonfork/electron,preco21/electron,fffej/electron,xiruibing/electron,lrlna/electron,farmisen/electron,mirrh/electron,jjz/electron,bwiggs/electron,matiasinsaurralde/electron,MaxGraey/electron,voidbridge/electron,simonfork/electron,dongjoon-hyun/electron,natgolov/electron,Gerhut/electron,synaptek/electron,LadyNaggaga/electron,maxogden/atom-shell,nagyistoce/electron-atom-shell,vHanda/electron,fffej/electron,Floato/electron,sircharleswatson/electron,vaginessa/electron,deepak1556/atom-shell,zhakui/electron,soulteary/electron,medixdev/electron,tylergibson/electron,rsvip/electron,sircharleswatson/electron,Jonekee/electron,mhkeller/electron,evgenyzinoviev/electron,stevemao/electron,nekuz0r/electron,RIAEvangelist/electron,joneit/electron,gabriel/electron,SufianHassan/electron,leethomas/electron,beni55/electron,kostia/electron,shockone/electron,biblerule/UMCTelnetHub,destan/electron,vHanda/electron,dkfiresky/electron,yalexx/electron,thingsinjars/electron,takashi/electron,jsutcodes/electron,digideskio/electron,brenca/electron,shaundunne/electron,xiruibing/electron,bpasero/electron,xfstudio/electron,pirafrank/electron,jonatasfreitasv/electron,rsvip/electron,John-Lin/electron,John-Lin/electron,ianscrivener/electron,gbn972/electron,simonfork/electron,jaanus/electron,wan-qy/electron,thomsonreuters/electron,aliib/electron,kikong/electron,saronwei/electron,leethomas/electron,Zagorakiss/electron,jannishuebl/electron,dahal/electron,Neron-X5/electron,kazupon/electron,vaginessa/electron,darwin/electron,noikiy/electron,trankmichael/electron,gamedevsam/electron,rreimann/electron,joaomoreno/atom-shell,destan/electron,jjz/electron,bitemyapp/electron,lzpfmh/electron,mattdesl/electron,synaptek/electron,dongjoon-hyun/electron,shockone/electron,SufianHassan/electron,simongregory/electron,sshiting/electron,dahal/electron,setzer777/electron,Jacobichou/electron,bright-sparks/electron,RobertJGabriel/electron,voidbridge/electron,matiasinsaurralde/electron,neutrous/electron,pirafrank/electron,JussMee15/electron,timruffles/electron,evgenyzinoviev/electron,jonatasfreitasv/electron,jacksondc/electron,arturts/electron,benweissmann/electron,aaron-goshine/electron,gabrielPeart/electron,evgenyzinoviev/electron,ianscrivener/electron,IonicaBizauKitchen/electron,neutrous/electron,matiasinsaurralde/electron,leolujuyi/electron,yalexx/electron,greyhwndz/electron,jannishuebl/electron,mubassirhayat/electron,carsonmcdonald/electron,preco21/electron,mirrh/electron,kazupon/electron,davazp/electron,rajatsingla28/electron,christian-bromann/electron,Jacobichou/electron,wan-qy/electron,shockone/electron,Andrey-Pavlov/electron,zhakui/electron,jaanus/electron,aliib/electron,egoist/electron,cqqccqc/electron,oiledCode/electron,sircharleswatson/electron,gerhardberger/electron,jtburke/electron,webmechanicx/electron,Rokt33r/electron,roadev/electron,jaanus/electron,saronwei/electron,kikong/electron,oiledCode/electron,joaomoreno/atom-shell,faizalpribadi/electron,medixdev/electron,DivyaKMenon/electron,twolfson/electron,jiaz/electron,natgolov/electron,aichingm/electron,vipulroxx/electron,farmisen/electron,greyhwndz/electron,electron/electron,eric-seekas/electron,takashi/electron,mrwizard82d1/electron,meowlab/electron,natgolov/electron,egoist/electron,chriskdon/electron,leolujuyi/electron,thompsonemerson/electron,carsonmcdonald/electron,aaron-goshine/electron,DivyaKMenon/electron,shiftkey/electron,tinydew4/electron,kikong/electron,Jonekee/electron,saronwei/electron,edulan/electron,stevekinney/electron,micalan/electron,soulteary/electron,ervinb/electron,chriskdon/electron,BionicClick/electron,aichingm/electron,shennushi/electron,IonicaBizauKitchen/electron,brave/electron,jonatasfreitasv/electron,rajatsingla28/electron,dongjoon-hyun/electron,trigrass2/electron,brave/muon,wolfflow/electron,thomsonreuters/electron,shockone/electron,fabien-d/electron,seanchas116/electron,greyhwndz/electron,simongregory/electron,jonatasfreitasv/electron,voidbridge/electron,sky7sea/electron,benweissmann/electron,trigrass2/electron,Zagorakiss/electron,Jacobichou/electron,nicobot/electron,gabrielPeart/electron,micalan/electron,Andrey-Pavlov/electron,pombredanne/electron,preco21/electron,thomsonreuters/electron,yan-foto/electron,zhakui/electron,thomsonreuters/electron,eric-seekas/electron,timruffles/electron,xiruibing/electron,icattlecoder/electron,Gerhut/electron,GoooIce/electron,aecca/electron,sshiting/electron,fffej/electron,kenmozi/electron,leftstick/electron,mattdesl/electron,mattdesl/electron,vaginessa/electron,dongjoon-hyun/electron,bwiggs/electron,nicobot/electron,twolfson/electron,RIAEvangelist/electron,farmisen/electron,arusakov/electron,digideskio/electron,tincan24/electron,bright-sparks/electron,tonyganch/electron,simongregory/electron,eric-seekas/electron,BionicClick/electron,mubassirhayat/electron,davazp/electron,beni55/electron,abhishekgahlot/electron,xfstudio/electron,mattdesl/electron,IonicaBizauKitchen/electron,felixrieseberg/electron,thompsonemerson/electron,xfstudio/electron,nekuz0r/electron,aecca/electron,systembugtj/electron,mubassirhayat/electron,the-ress/electron,christian-bromann/electron,robinvandernoord/electron,howmuchcomputer/electron,benweissmann/electron,jonatasfreitasv/electron,anko/electron,timruffles/electron,jlhbaseball15/electron,RobertJGabriel/electron,fireball-x/atom-shell,jonatasfreitasv/electron,ervinb/electron,minggo/electron,natgolov/electron,christian-bromann/electron,greyhwndz/electron,BionicClick/electron,cos2004/electron,leftstick/electron,Gerhut/electron,fireball-x/atom-shell,wan-qy/electron,rajatsingla28/electron,hokein/atom-shell,fomojola/electron,felixrieseberg/electron,jannishuebl/electron,miniak/electron,lrlna/electron,renaesop/electron,the-ress/electron,adamjgray/electron,smczk/electron,RIAEvangelist/electron,rhencke/electron,joneit/electron,Faiz7412/electron,gamedevsam/electron,neutrous/electron,iftekeriba/electron,minggo/electron,egoist/electron,jsutcodes/electron,fritx/electron,mjaniszew/electron,simonfork/electron,edulan/electron,jcblw/electron,jaanus/electron,Andrey-Pavlov/electron,gstack/infinium-shell,SufianHassan/electron,mhkeller/electron,adcentury/electron,kostia/electron,bobwol/electron,vipulroxx/electron,ianscrivener/electron,gabrielPeart/electron,kokdemo/electron,eric-seekas/electron,trigrass2/electron,etiktin/electron,jiaz/electron,wolfflow/electron,benweissmann/electron,shiftkey/electron,gbn972/electron,RIAEvangelist/electron,stevemao/electron,iftekeriba/electron,rajatsingla28/electron,leolujuyi/electron,wolfflow/electron,kikong/electron,arusakov/electron,jaanus/electron,zhakui/electron,abhishekgahlot/electron,felixrieseberg/electron,edulan/electron,jjz/electron,mattdesl/electron,BionicClick/electron,medixdev/electron,maxogden/atom-shell,gabriel/electron,gabriel/electron,nagyistoce/electron-atom-shell,davazp/electron,bright-sparks/electron,dahal/electron,gabrielPeart/electron,kcrt/electron,wan-qy/electron,yalexx/electron,Ivshti/electron,matiasinsaurralde/electron,Floato/electron,noikiy/electron,felixrieseberg/electron,darwin/electron,tomashanacek/electron,nicobot/electron,bruce/electron,chriskdon/electron,tylergibson/electron,minggo/electron,aaron-goshine/electron,GoooIce/electron,roadev/electron,gabriel/electron,JussMee15/electron,gabriel/electron,icattlecoder/electron,tomashanacek/electron,MaxWhere/electron,thingsinjars/electron,mattotodd/electron,rhencke/electron,gerhardberger/electron,brave/muon,edulan/electron,miniak/electron,trankmichael/electron,leftstick/electron,biblerule/UMCTelnetHub,nicobot/electron,jiaz/electron,ianscrivener/electron,farmisen/electron,anko/electron,Jonekee/electron,kazupon/electron,medixdev/electron,evgenyzinoviev/electron,bitemyapp/electron,MaxWhere/electron,subblue/electron,mubassirhayat/electron,abhishekgahlot/electron,brave/electron,vaginessa/electron,leftstick/electron,pirafrank/electron,Zagorakiss/electron,leethomas/electron,GoooIce/electron,systembugtj/electron,kenmozi/electron,Rokt33r/electron,roadev/electron,the-ress/electron,gstack/infinium-shell,MaxWhere/electron,tonyganch/electron,brave/muon,ervinb/electron,dkfiresky/electron,renaesop/electron,rprichard/electron,jacksondc/electron,simonfork/electron,tincan24/electron,Neron-X5/electron,lzpfmh/electron,bpasero/electron,seanchas116/electron,pandoraui/electron,MaxGraey/electron,ankitaggarwal011/electron,bobwol/electron,astoilkov/electron,leethomas/electron,dongjoon-hyun/electron,thompsonemerson/electron,vipulroxx/electron,jlord/electron,gbn972/electron,RobertJGabriel/electron,Zagorakiss/electron,icattlecoder/electron,astoilkov/electron,SufianHassan/electron,darwin/electron,christian-bromann/electron,digideskio/electron,micalan/electron,noikiy/electron,stevekinney/electron,gerhardberger/electron,Andrey-Pavlov/electron,BionicClick/electron,coderhaoxin/electron,Floato/electron,posix4e/electron,aichingm/electron,kcrt/electron,carsonmcdonald/electron,gbn972/electron,eriser/electron,meowlab/electron,JesselJohn/electron,carsonmcdonald/electron,bpasero/electron,gamedevsam/electron,coderhaoxin/electron,LadyNaggaga/electron,rreimann/electron,mirrh/electron,systembugtj/electron,shennushi/electron,nicholasess/electron,Evercoder/electron,dahal/electron,Jacobichou/electron,jhen0409/electron,kenmozi/electron,roadev/electron,rsvip/electron,sircharleswatson/electron,jcblw/electron,gamedevsam/electron,trankmichael/electron,fritx/electron,setzer777/electron,Faiz7412/electron,xiruibing/electron,lrlna/electron,vHanda/electron,gabrielPeart/electron,d-salas/electron,arturts/electron,adamjgray/electron,brave/electron,Evercoder/electron,vaginessa/electron,nicholasess/electron,ankitaggarwal011/electron,posix4e/electron,jtburke/electron,darwin/electron,meowlab/electron,beni55/electron,arusakov/electron,fireball-x/atom-shell,shaundunne/electron,gstack/infinium-shell,DivyaKMenon/electron,voidbridge/electron,shaundunne/electron,takashi/electron,aichingm/electron,synaptek/electron,evgenyzinoviev/electron,pombredanne/electron,adamjgray/electron,tinydew4/electron,leethomas/electron,eriser/electron,Faiz7412/electron,bitemyapp/electron,adcentury/electron,oiledCode/electron,soulteary/electron,abhishekgahlot/electron,bobwol/electron,pirafrank/electron,aecca/electron,minggo/electron,christian-bromann/electron,etiktin/electron,brenca/electron,deepak1556/atom-shell,lzpfmh/electron,mhkeller/electron,Rokt33r/electron,etiktin/electron,thomsonreuters/electron,jlord/electron,smczk/electron,nekuz0r/electron,jannishuebl/electron,nicholasess/electron,kostia/electron,vipulroxx/electron,iftekeriba/electron,jlhbaseball15/electron,mrwizard82d1/electron,maxogden/atom-shell,carsonmcdonald/electron,xiruibing/electron,takashi/electron,JussMee15/electron,sshiting/electron,Zagorakiss/electron,fffej/electron,kcrt/electron,neutrous/electron,howmuchcomputer/electron,vipulroxx/electron,webmechanicx/electron,astoilkov/electron,trigrass2/electron,thingsinjars/electron,renaesop/electron,bobwol/electron,coderhaoxin/electron,electron/electron,darwin/electron,mattotodd/electron,icattlecoder/electron,simonfork/electron,brenca/electron,JussMee15/electron,jacksondc/electron,arturts/electron,RIAEvangelist/electron,webmechanicx/electron,LadyNaggaga/electron,christian-bromann/electron,LadyNaggaga/electron,maxogden/atom-shell,baiwyc119/electron,Evercoder/electron,kazupon/electron,LadyNaggaga/electron,simongregory/electron,d-salas/electron,nicobot/electron,jiaz/electron,robinvandernoord/electron,synaptek/electron,thingsinjars/electron,rreimann/electron,evgenyzinoviev/electron,arturts/electron,arusakov/electron,pombredanne/electron,fomojola/electron,MaxGraey/electron,webmechanicx/electron,rprichard/electron,Floato/electron,miniak/electron,pombredanne/electron,aliib/electron,yan-foto/electron,Gerhut/electron,bitemyapp/electron,micalan/electron,kokdemo/electron,jacksondc/electron,yan-foto/electron,bbondy/electron,pandoraui/electron,greyhwndz/electron,stevemao/electron,tonyganch/electron,the-ress/electron,fomojola/electron,cos2004/electron,arturts/electron,michaelchiche/electron,voidbridge/electron,mirrh/electron,bobwol/electron,rprichard/electron,tylergibson/electron,bruce/electron,jlhbaseball15/electron,John-Lin/electron,baiwyc119/electron,seanchas116/electron,bbondy/electron,benweissmann/electron,fritx/electron,DivyaKMenon/electron,Jacobichou/electron,eriser/electron,smczk/electron,jlord/electron,JesselJohn/electron,destan/electron,preco21/electron,Evercoder/electron,eric-seekas/electron,anko/electron,tinydew4/electron,tincan24/electron,bright-sparks/electron,cos2004/electron,Ivshti/electron,Neron-X5/electron,sircharleswatson/electron,smczk/electron,brave/muon,faizalpribadi/electron,Rokt33r/electron,trankmichael/electron,jacksondc/electron,simongregory/electron,shiftkey/electron,mubassirhayat/electron,subblue/electron,coderhaoxin/electron,fabien-d/electron,shaundunne/electron,oiledCode/electron,vHanda/electron,setzer777/electron,fritx/electron,egoist/electron,mjaniszew/electron,edulan/electron,yan-foto/electron,jlhbaseball15/electron,medixdev/electron,joaomoreno/atom-shell,fritx/electron,aliib/electron,JussMee15/electron,anko/electron,brave/muon,takashi/electron,kokdemo/electron,vaginessa/electron,fabien-d/electron,fireball-x/atom-shell,jhen0409/electron,meowlab/electron,kenmozi/electron,sshiting/electron,mjaniszew/electron,eriser/electron,the-ress/electron,destan/electron,pandoraui/electron,IonicaBizauKitchen/electron,chrisswk/electron,kokdemo/electron,bitemyapp/electron,seanchas116/electron,neutrous/electron,brenca/electron,bbondy/electron,jlhbaseball15/electron,John-Lin/electron,jsutcodes/electron,d-salas/electron,etiktin/electron,fritx/electron,fabien-d/electron,vHanda/electron,Evercoder/electron,robinvandernoord/electron,brenca/electron,tincan24/electron,Floato/electron,mhkeller/electron,jhen0409/electron,aliib/electron,beni55/electron,nekuz0r/electron,soulteary/electron,jannishuebl/electron,eriser/electron,nicholasess/electron,rreimann/electron,nekuz0r/electron,stevekinney/electron,chrisswk/electron,roadev/electron,cqqccqc/electron,deed02392/electron,jacksondc/electron,leolujuyi/electron,farmisen/electron,joneit/electron,bbondy/electron,benweissmann/electron,bbondy/electron,chrisswk/electron,biblerule/UMCTelnetHub,brave/electron,leftstick/electron,twolfson/electron,baiwyc119/electron,jjz/electron,adamjgray/electron,cqqccqc/electron,aaron-goshine/electron,kenmozi/electron,cos2004/electron,yan-foto/electron,kcrt/electron,xiruibing/electron,SufianHassan/electron,JesselJohn/electron,RobertJGabriel/electron,meowlab/electron,webmechanicx/electron,setzer777/electron,rhencke/electron,JussMee15/electron,MaxGraey/electron,tinydew4/electron,brave/electron,abhishekgahlot/electron,the-ress/electron,fabien-d/electron,nagyistoce/electron-atom-shell,d-salas/electron,deed02392/electron,howmuchcomputer/electron,davazp/electron,bruce/electron,biblerule/UMCTelnetHub,kikong/electron,tinydew4/electron,dkfiresky/electron,renaesop/electron,kcrt/electron,iftekeriba/electron,dahal/electron,trigrass2/electron,saronwei/electron,jtburke/electron,jtburke/electron,nicholasess/electron,astoilkov/electron,dongjoon-hyun/electron,renaesop/electron,aliib/electron,robinvandernoord/electron,digideskio/electron,gbn972/electron,mirrh/electron,JesselJohn/electron,deed02392/electron,jiaz/electron,jlord/electron,RobertJGabriel/electron,rajatsingla28/electron,cqqccqc/electron,Ivshti/electron,kostia/electron,pandoraui/electron,mhkeller/electron,sky7sea/electron,lzpfmh/electron,nicholasess/electron,vipulroxx/electron,RobertJGabriel/electron,sshiting/electron,twolfson/electron,eric-seekas/electron,cqqccqc/electron,tomashanacek/electron,lrlna/electron,mjaniszew/electron,MaxWhere/electron,twolfson/electron,rhencke/electron,eriser/electron,Andrey-Pavlov/electron,noikiy/electron,John-Lin/electron,chrisswk/electron,gerhardberger/electron,fffej/electron,lrlna/electron,mattotodd/electron,posix4e/electron,Jonekee/electron,abhishekgahlot/electron,yalexx/electron,nagyistoce/electron-atom-shell,jlord/electron,mattdesl/electron,shaundunne/electron,Jonekee/electron,electron/electron,brave/muon,kokdemo/electron,brave/electron,michaelchiche/electron,adcentury/electron,kostia/electron,mrwizard82d1/electron,shennushi/electron,d-salas/electron,astoilkov/electron,DivyaKMenon/electron,jhen0409/electron,gerhardberger/electron,miniak/electron,MaxGraey/electron,trankmichael/electron,gamedevsam/electron,setzer777/electron,stevemao/electron,yalexx/electron,coderhaoxin/electron,d-salas/electron,astoilkov/electron,synaptek/electron,stevekinney/electron,bbondy/electron,Gerhut/electron,bruce/electron,sircharleswatson/electron,seanchas116/electron,mirrh/electron,cos2004/electron,cqqccqc/electron,davazp/electron,timruffles/electron,posix4e/electron,natgolov/electron,robinvandernoord/electron,micalan/electron,digideskio/electron,jjz/electron,bright-sparks/electron,yan-foto/electron,wolfflow/electron,beni55/electron,mattotodd/electron,chrisswk/electron,jaanus/electron,rhencke/electron,mattotodd/electron,brenca/electron,icattlecoder/electron,kostia/electron,bruce/electron,dkfiresky/electron,synaptek/electron,ianscrivener/electron,Neron-X5/electron,systembugtj/electron,bpasero/electron,dkfiresky/electron,subblue/electron,fireball-x/atom-shell,shiftkey/electron,dkfiresky/electron,jhen0409/electron,stevemao/electron,tylergibson/electron,adcentury/electron,shockone/electron,jjz/electron,lrlna/electron,deepak1556/atom-shell,Andrey-Pavlov/electron,gbn972/electron,jtburke/electron,shiftkey/electron,nicobot/electron,hokein/atom-shell,thomsonreuters/electron,kokdemo/electron,ankitaggarwal011/electron,ankitaggarwal011/electron,deepak1556/atom-shell,gstack/infinium-shell,Rokt33r/electron,rajatsingla28/electron,zhakui/electron,mhkeller/electron,fffej/electron,michaelchiche/electron,adcentury/electron,xfstudio/electron,pandoraui/electron,miniak/electron,aichingm/electron,tonyganch/electron,arusakov/electron,tincan24/electron,joneit/electron,mrwizard82d1/electron,mrwizard82d1/electron,wolfflow/electron,jcblw/electron,farmisen/electron,saronwei/electron,soulteary/electron,gerhardberger/electron,jcblw/electron,leolujuyi/electron,roadev/electron,hokein/atom-shell,ervinb/electron,bwiggs/electron,greyhwndz/electron,pirafrank/electron,tylergibson/electron,electron/electron,kcrt/electron,etiktin/electron,thompsonemerson/electron,leftstick/electron,systembugtj/electron,howmuchcomputer/electron,lzpfmh/electron,aaron-goshine/electron,simongregory/electron,chriskdon/electron,zhakui/electron,Faiz7412/electron,anko/electron,thompsonemerson/electron,hokein/atom-shell,adcentury/electron,maxogden/atom-shell,pombredanne/electron,felixrieseberg/electron,pombredanne/electron,deed02392/electron,John-Lin/electron,pirafrank/electron,wan-qy/electron,gamedevsam/electron,mjaniszew/electron,gstack/infinium-shell,Neron-X5/electron,shockone/electron,biblerule/UMCTelnetHub,rreimann/electron,jtburke/electron,JesselJohn/electron,destan/electron,howmuchcomputer/electron,jiaz/electron,Evercoder/electron,robinvandernoord/electron,michaelchiche/electron,aecca/electron,LadyNaggaga/electron,fomojola/electron,tomashanacek/electron,pandoraui/electron,edulan/electron,sky7sea/electron,oiledCode/electron,BionicClick/electron,shiftkey/electron,thingsinjars/electron,coderhaoxin/electron,bpasero/electron,IonicaBizauKitchen/electron,tylergibson/electron,posix4e/electron,faizalpribadi/electron,aaron-goshine/electron,bwiggs/electron,chriskdon/electron,beni55/electron,kazupon/electron,miniak/electron,Floato/electron,trigrass2/electron,thingsinjars/electron,joaomoreno/atom-shell,rsvip/electron,GoooIce/electron,micalan/electron,gabrielPeart/electron,tomashanacek/electron,ervinb/electron,voidbridge/electron,Zagorakiss/electron,bwiggs/electron,joaomoreno/atom-shell,saronwei/electron,setzer777/electron,joneit/electron,Jacobichou/electron,bpasero/electron,jcblw/electron,electron/electron,etiktin/electron,shaundunne/electron,shennushi/electron,preco21/electron,tinydew4/electron,xfstudio/electron,Rokt33r/electron,oiledCode/electron,deed02392/electron,nekuz0r/electron,SufianHassan/electron,lzpfmh/electron,aecca/electron,timruffles/electron,jhen0409/electron,tonyganch/electron,leethomas/electron,Jonekee/electron,ervinb/electron,rsvip/electron,medixdev/electron,IonicaBizauKitchen/electron,systembugtj/electron,faizalpribadi/electron,chriskdon/electron,jlhbaseball15/electron,neutrous/electron,DivyaKMenon/electron,fomojola/electron,jsutcodes/electron,kenmozi/electron,baiwyc119/electron,gabriel/electron,biblerule/UMCTelnetHub,aecca/electron,stevemao/electron,GoooIce/electron,noikiy/electron,wan-qy/electron,renaesop/electron,subblue/electron,GoooIce/electron,wolfflow/electron,natgolov/electron,iftekeriba/electron,faizalpribadi/electron,kazupon/electron,smczk/electron,smczk/electron,xfstudio/electron,matiasinsaurralde/electron,Faiz7412/electron,ankitaggarwal011/electron,jannishuebl/electron,sky7sea/electron,hokein/atom-shell,mrwizard82d1/electron,jcblw/electron,ianscrivener/electron,joaomoreno/atom-shell,minggo/electron,electron/electron,posix4e/electron,rhencke/electron,tomashanacek/electron,aichingm/electron,bitemyapp/electron,mjaniszew/electron,Ivshti/electron,dahal/electron,digideskio/electron,howmuchcomputer/electron,RIAEvangelist/electron,ankitaggarwal011/electron,arusakov/electron,MaxWhere/electron,bright-sparks/electron,webmechanicx/electron,sky7sea/electron,nagyistoce/electron-atom-shell,JesselJohn/electron,deed02392/electron,the-ress/electron,baiwyc119/electron,felixrieseberg/electron,MaxWhere/electron,subblue/electron,iftekeriba/electron,Gerhut/electron,anko/electron,davazp/electron,bruce/electron,sky7sea/electron,vHanda/electron,leolujuyi/electron,rprichard/electron,soulteary/electron,icattlecoder/electron,twolfson/electron,electron/electron,preco21/electron,bwiggs/electron,takashi/electron,Ivshti/electron,trankmichael/electron,noikiy/electron,carsonmcdonald/electron,jsutcodes/electron,faizalpribadi/electron,meowlab/electron | ---
+++
@@ -5,7 +5,7 @@
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
-LIBCHROMIUMCONTENT_COMMIT = '9006e277b20109de165d4a17827c9b2029bf3831'
+LIBCHROMIUMCONTENT_COMMIT = '5d5539f8232bb4d0253438216de11a99159b3c4d'
ARCH = {
'cygwin': '32bit', |
e9a849f311f54e92c86f149670a318b1e5f5f5e6 | update_cloudflare.py | update_cloudflare.py | import pathlib
import socket
import pyflare
import yaml
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 53))
myip = s.getsockname()[0]
s.close()
with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r:
update_list = yaml.load(r)
for account in update_list:
records = {}
p = pyflare.PyflareClient(account['email'], account['token'])
for target in account['targets']:
if target['subdomain'].count('.') < 2:
zone = target['subdomain']
else:
zone = target['subdomain'][target['subdomain'].rfind('.', 0, target['subdomain'].rfind('.'))+1:]
if zone not in records:
records[zone] = list(p.rec_load_all(zone))
for record in records[zone]:
if record['rec_id'] == target['id']:
target_record = record
break
p.rec_edit(zone, 'A', target['id'], target_record['name'], myip, 1, 0)
print('Successfully updated {} to {}'.format(target['subdomain'], myip))
| import pathlib
import socket
import pyflare
from yaml import load
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 53))
myip = s.getsockname()[0]
s.close()
with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r:
update_list = load(r)
for account in update_list:
records = {}
p = pyflare.PyflareClient(account['email'], account['token'])
for target in account['targets']:
if target['subdomain'].count('.') < 2:
zone = target['subdomain']
else:
zone = target['subdomain'][target['subdomain'].rfind('.', 0, target['subdomain'].rfind('.'))+1:]
if zone not in records:
records[zone] = list(p.rec_load_all(zone))
for record in records[zone]:
if record['rec_id'] == target['id']:
target_record = record
break
p.rec_edit(zone, 'A', target['id'], target_record['name'], myip, 1, 0)
print('Successfully updated {} to {}'.format(target['subdomain'], myip))
| Change import statement for external library yaml | Change import statement for external library yaml | Python | mit | tkiapril/cloudflare-updater | ---
+++
@@ -2,7 +2,7 @@
import socket
import pyflare
-import yaml
+from yaml import load
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
@@ -11,7 +11,7 @@
s.close()
with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r:
- update_list = yaml.load(r)
+ update_list = load(r)
for account in update_list:
records = {} |
d1324e8d29d01be3d9f7a83bed21737652a7bf71 | feder/letters/utils.py | feder/letters/utils.py | from textwrap import TextWrapper
BODY_FOOTER_SEPERATOR = "\n\n--\n"
def email_wrapper(text):
wrapper = TextWrapper()
wrapper.subsequent_indent = '> '
wrapper.initial_indent = '> '
return "\n".join(wrapper.wrap(text))
def normalize_msg_id(msg_id):
if msg_id[0] == '<':
msg_id = msg_id[1:]
if msg_id[-1] == '>':
msg_id = msg_id[:-1]
return msg_id
def is_spam_check(email_object):
return email_object['X-Spam-Flag'] == 'YES'
def get_body_with_footer(body, footer):
if footer.strip():
return "{}{}{}".format(body, BODY_FOOTER_SEPERATOR, footer)
return body
| from textwrap import TextWrapper
from django.utils import six
BODY_FOOTER_SEPERATOR = "\n\n--\n"
def email_wrapper(text):
wrapper = TextWrapper()
wrapper.subsequent_indent = '> '
wrapper.initial_indent = '> '
return "\n".join(wrapper.wrap(text))
def normalize_msg_id(msg_id):
if msg_id[0] == '<':
msg_id = msg_id[1:]
if msg_id[-1] == '>':
msg_id = msg_id[:-1]
return msg_id
def is_spam_check(email_object):
return email_object['X-Spam-Flag'] == 'YES'
def get_body_with_footer(body, footer):
if footer.strip():
return six.text_type("{}{}{}").format(body, BODY_FOOTER_SEPERATOR, footer)
return body
| Fix encoding in reply footer | Fix encoding in reply footer
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder | ---
+++
@@ -1,6 +1,8 @@
from textwrap import TextWrapper
+from django.utils import six
BODY_FOOTER_SEPERATOR = "\n\n--\n"
+
def email_wrapper(text):
wrapper = TextWrapper()
@@ -16,10 +18,12 @@
msg_id = msg_id[:-1]
return msg_id
+
def is_spam_check(email_object):
return email_object['X-Spam-Flag'] == 'YES'
+
def get_body_with_footer(body, footer):
if footer.strip():
- return "{}{}{}".format(body, BODY_FOOTER_SEPERATOR, footer)
+ return six.text_type("{}{}{}").format(body, BODY_FOOTER_SEPERATOR, footer)
return body |
69ffc92471536d557de4ea4ddb38d7fdfe3ee120 | salt/utils/pycrypto.py | salt/utils/pycrypto.py |
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
import Crypto.Random
import crypt
import re
def secure_password(length=20):
'''
Generate a secure password.
'''
pw = ''
while len(pw) < length:
pw += re.sub('\W', '', Crypto.Random.get_random_bytes(1))
return pw
def gen_hash(salt=None, password=None):
'''
Generate /etc/shadow hash
'''
if password is None:
password = secure_password()
if salt is None:
salt = '$6' + secure_password(8)
return crypt.crypt(password, salt)
|
# -*- coding: utf-8 -*-
'''
Use pycrypto to generate random passwords on the fly.
'''
# Import python libraries
import Crypto.Random
import crypt
import re
def secure_password(length=20):
'''
Generate a secure password.
'''
pw = ''
while len(pw) < length:
pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1))
return pw
def gen_hash(salt=None, password=None):
'''
Generate /etc/shadow hash
'''
if password is None:
password = secure_password()
if salt is None:
salt = '$6' + secure_password(8)
return crypt.crypt(password, salt)
| Use raw string for secure_password | Use raw string for secure_password
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -16,7 +16,7 @@
'''
pw = ''
while len(pw) < length:
- pw += re.sub('\W', '', Crypto.Random.get_random_bytes(1))
+ pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1))
return pw
|
95686933911fb2720b0fad816056c9008ef1097d | kafka_influxdb/reader/kafka_reader.py | kafka_influxdb/reader/kafka_reader.py | # -*- coding: utf-8 -*-
import logging
import time
from kafka.client import KafkaClient
from kafka.consumer import SimpleConsumer
class KafkaReader(object):
def __init__(self, host, port, group, topic, connection_wait_time=2):
""" Initialize Kafka reader """
self.host = host
self.port = port
self.group = group
self.topic = topic
self.connection_wait_time = connection_wait_time
def connect(self):
connection = "{0}:{1}".format(self.host, self.port)
logging.info("Connecting to Kafka at {}...", connection)
kafka_client = KafkaClient(connection)
self.consumer = SimpleConsumer(kafka_client,
self.group,
self.topic)
def read(self):
""" Yield messages from Kafka topic """
while True:
try:
self.connect()
for raw_message in self.consumer:
yield raw_message.message.value
except Exception:
logging.error("Connection to Kafka lost. Trying to reconnect to {}:{}...",
self.host, self.port)
time.sleep(self.connection_wait_time)
| # -*- coding: utf-8 -*-
import logging
import time
from kafka.client import KafkaClient
from kafka.consumer import SimpleConsumer
class KafkaReader(object):
def __init__(self, host, port, group, topic, connection_wait_time=2):
""" Initialize Kafka reader """
self.host = host
self.port = port
self.group = group
self.topic = topic
self.connection_wait_time = connection_wait_time
def connect(self):
connection = "{0}:{1}".format(self.host, self.port)
logging.info("Connecting to Kafka at {}...", connection)
self.kafka_client = KafkaClient(connection)
self.consumer = SimpleConsumer(self.kafka_client,
self.group,
self.topic)
def read(self):
""" Yield messages from Kafka topic """
while True:
try:
self.connect()
for raw_message in self.consumer:
yield raw_message.message.value
except Exception:
logging.error("Connection to Kafka lost. Trying to reconnect to {}:{}...",
self.host, self.port)
time.sleep(self.connection_wait_time)
| Make kafka client a field in Reader | Make kafka client a field in Reader
| Python | apache-2.0 | mre/kafka-influxdb,mre/kafka-influxdb | ---
+++
@@ -18,8 +18,8 @@
def connect(self):
connection = "{0}:{1}".format(self.host, self.port)
logging.info("Connecting to Kafka at {}...", connection)
- kafka_client = KafkaClient(connection)
- self.consumer = SimpleConsumer(kafka_client,
+ self.kafka_client = KafkaClient(connection)
+ self.consumer = SimpleConsumer(self.kafka_client,
self.group,
self.topic)
|
0fec8460ae0d03aed6956137ec06757812f3f689 | lc0199_binary_tree_right_side_view.py | lc0199_binary_tree_right_side_view.py | """Leetcode 199. Binary Tree Right Side View
Medium
URL: https://leetcode.com/problems/binary-tree-right-side-view/
Given a binary tree, imagine yourself standing on the right side of it,
return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
pass
def main():
pass
if __name__ == '__main__':
main()
| """Leetcode 199. Binary Tree Right Side View
Medium
URL: https://leetcode.com/problems/binary-tree-right-side-view/
Given a binary tree, imagine yourself standing on the right side of it,
return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class SolutionLevelTraversalLast(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
Time complexity: O(n).
Space complexity: O(n).
"""
from collections import deque
# Base case.
if not root:
return []
# Apply level traversal to collect visible values from top to bottom.
visible_vals = []
queue = deque([root])
while queue:
size = len(queue)
for i in range(size):
current = queue.pop()
if i == size - 1:
visible_vals.append(current.val)
# Add current's left or right to queue if existed.
if current.left:
queue.appendleft(current.left)
if current.right:
queue.appendleft(current.right)
return visible_vals
def main():
# Input:
# 1
# / \
# 2 3
# \ \
# 5 4
# Output: [1, 3, 4]
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.right = TreeNode(5)
root.right.right = TreeNode(4)
print SolutionLevelTraversalLast().rightSideView(root)
if __name__ == '__main__':
main()
| Complete level traversal last sol | Complete level traversal last sol
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -25,17 +25,56 @@
self.right = None
-class Solution(object):
+class SolutionLevelTraversalLast(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
+
+ Time complexity: O(n).
+ Space complexity: O(n).
"""
- pass
-
+ from collections import deque
+
+ # Base case.
+ if not root:
+ return []
+
+ # Apply level traversal to collect visible values from top to bottom.
+ visible_vals = []
+
+ queue = deque([root])
+ while queue:
+ size = len(queue)
+ for i in range(size):
+ current = queue.pop()
+ if i == size - 1:
+ visible_vals.append(current.val)
+
+ # Add current's left or right to queue if existed.
+ if current.left:
+ queue.appendleft(current.left)
+ if current.right:
+ queue.appendleft(current.right)
+
+ return visible_vals
+
def main():
- pass
+ # Input:
+ # 1
+ # / \
+ # 2 3
+ # \ \
+ # 5 4
+ # Output: [1, 3, 4]
+ root = TreeNode(1)
+ root.left = TreeNode(2)
+ root.right = TreeNode(3)
+ root.left.right = TreeNode(5)
+ root.right.right = TreeNode(4)
+
+ print SolutionLevelTraversalLast().rightSideView(root)
if __name__ == '__main__': |
9b110b93ab8b2c7e58bb5447b3801138fedc4f51 | src/config/vnc_openstack/vnc_openstack/context.py | src/config/vnc_openstack/vnc_openstack/context.py | import gevent
import bottle
import uuid
class NeutronApiContext(object):
def __init__(self, request=None, user_token=None):
self.request = request
self.user_token = user_token
self.request_id = str(uuid.uuid4())
# end __init__
# end class NeutronApiContext
def get_context():
return gevent.getcurrent().neutron_api_context
def set_context(api_ctx):
gevent.getcurrent().neutron_api_context = api_ctx
def clear_context():
gevent.getcurrent().neutron_api_context = None
def have_context():
return (hasattr(gevent.getcurrent(), 'neutron_api_context') and
gevent.getcurrent().neutron_api_context is not None)
def use_context(fn):
def wrapper(*args, **kwargs):
if not have_context():
context_created = True
user_token = bottle.request.headers.get('X_AUTH_TOKEN',
'no user token for %s %s' %(bottle.request.method,
bottle.request.url))
set_context(NeutronApiContext(
request=bottle.request, user_token=user_token))
else:
context_created = False
try:
return fn(*args, **kwargs)
finally:
if context_created:
clear_context()
# end wrapper
return wrapper
| import gevent
import bottle
import uuid
class NeutronApiContext(object):
def __init__(self, request=None, user_token=None):
self.request = request
self.user_token = user_token
self.request_id = request.json['context'].get('request_id', str(uuid.uuid4()))
# end __init__
# end class NeutronApiContext
def get_context():
return gevent.getcurrent().neutron_api_context
def set_context(api_ctx):
gevent.getcurrent().neutron_api_context = api_ctx
def clear_context():
gevent.getcurrent().neutron_api_context = None
def have_context():
return (hasattr(gevent.getcurrent(), 'neutron_api_context') and
gevent.getcurrent().neutron_api_context is not None)
def use_context(fn):
def wrapper(*args, **kwargs):
if not have_context():
context_created = True
user_token = bottle.request.headers.get('X_AUTH_TOKEN',
'no user token for %s %s' %(bottle.request.method,
bottle.request.url))
set_context(NeutronApiContext(
request=bottle.request, user_token=user_token))
else:
context_created = False
try:
return fn(*args, **kwargs)
finally:
if context_created:
clear_context()
# end wrapper
return wrapper
| Use request_id forwarded by neutron plugin | Use request_id forwarded by neutron plugin
Change-Id: Id395e1bd225c99aafad57eaa48ae3ae3897e249d
Closes-Bug: #1723193
| Python | apache-2.0 | eonpatapon/contrail-controller,eonpatapon/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller | ---
+++
@@ -6,7 +6,7 @@
def __init__(self, request=None, user_token=None):
self.request = request
self.user_token = user_token
- self.request_id = str(uuid.uuid4())
+ self.request_id = request.json['context'].get('request_id', str(uuid.uuid4()))
# end __init__
# end class NeutronApiContext
|
39bc635f083f53b7cf34019e4fa642bfc8f1971b | server_app/__main__.py | server_app/__main__.py | import sys
import os
import logging
logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat.log"), level=logging.DEBUG)
from app import app, db, main, socketio
db.create_all()
app.register_blueprint(main)
port = app.config['PORT']
if len(sys.argv) == 2:
port = int(sys.argv[1])
logging.info("Chat server is now running on 0.0.0.0:%r" % port)
socketio.run(app, host="0.0.0.0", port=port)
| import sys
import os
import logging
if not os.path.exists(os.path.expanduser("~/.chatserver")):
os.makedirs(os.path.expanduser("~/.chatserver")
logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat.log"), level=logging.DEBUG)
from app import app, db, main, socketio
db.create_all()
app.register_blueprint(main)
port = app.config['PORT']
if len(sys.argv) == 2:
port = int(sys.argv[1])
logging.info("Chat server is now running on 0.0.0.0:%r" % port)
socketio.run(app, host="0.0.0.0", port=port)
| Fix logging directory njot existing | Fix logging directory njot existing
| Python | bsd-3-clause | jos0003/Chat,jos0003/Chat,jos0003/Chat,jos0003/Chat,jos0003/Chat | ---
+++
@@ -2,6 +2,8 @@
import os
import logging
+if not os.path.exists(os.path.expanduser("~/.chatserver")):
+ os.makedirs(os.path.expanduser("~/.chatserver")
logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat.log"), level=logging.DEBUG)
from app import app, db, main, socketio |
bf8ae76e7c73dc49beff7a23f2bc5f6a0dfc3b36 | registration/__init__.py | registration/__init__.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.core.exceptions.ImproperlyConfigured`` if the specified
backend cannot be located.
"""
i = settings.REGISTRATION_BACKEND.rfind('.')
module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
| from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
# TODO: When Python 2.7 is released this becomes a try/except falling
# back to Django's implementation.
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.core.exceptions.ImproperlyConfigured`` if the specified
backend cannot be located.
"""
i = settings.REGISTRATION_BACKEND.rfind('.')
module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
| Add reminder to myself to to importlib fallback. | Add reminder to myself to to importlib fallback.
| Python | bsd-3-clause | gone/django-registration,awakeup/django-registration,dirtycoder/django-registration,liberation/django-registration,artursmet/django-registration,ubernostrum/django-registration,Troyhy/django-registration,artursmet/django-registration,liberation/django-registration,euanlau/django-registration,spurfly/django-registration,futurecolors/django-registration,sandipagr/django-registration,gone/django-registration,austinhappel/django-registration,spurfly/django-registration,austinhappel/django-registration,myimages/django-registration,futurecolors/django-registration,akvo/django-registration,danielsamuels/django-registration,mypebble/djregs,akvo/django-registration,Troyhy/django-registration,jnns/django-registration,sandipagr/django-registration,tdruez/django-registration,hacklabr/django-registration,euanlau/django-registration,kennydude/djregs,hacklabr/django-registration | ---
+++
@@ -1,5 +1,8 @@
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
+
+# TODO: When Python 2.7 is released this becomes a try/except falling
+# back to Django's implementation.
from django.utils.importlib import import_module
def get_backend(): |
c9cd06f9bb2a3b7598a49e97bde93e6845394ec7 | gvi/accounts/models.py | gvi/accounts/models.py | from django.db import models
class Currency(models.Model):
name = models.CharField(max_length=25)
contraction = models.CarField(max_length=5)
def __str__(self):
return self.name
class Account(models.Model):
DEFAULT_CURRENCY_ID = 1 # pounds ?
BANK = 'b'
CASH = 'c'
TYPE_CHOICES = (
(BANK, 'Bank'),
(CASH, 'Cash'),
)
account_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=CASH)
bank_name = models.CharField(max_length=25, blank=True)
number = models.CharField(max_length=140, blank=True)
balance = models.DecimalField(decimal_places=10, max_digits=19, default=0)
currency = models.ForeignKey(Currency, default=DEFAULT_CURRENCY_ID)
active = models.BooleanField(initial=True)
#add the account owner
def __str__(self):
if(account_type == 'b')
return self.number
else
return self.currency
| from django.db import models
import datetime
class Currency(models.Model):
name = models.CharField(max_length=25)
contraction = models.CarField(max_length=5)
def __str__(self):
return self.name
class Account(models.Model):
DEFAULT_CURRENCY_ID = 1 # pounds ?
BANK = 'b'
CASH = 'c'
TYPE_CHOICES = (
(BANK, 'Bank'),
(CASH, 'Cash'),
)
account_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=CASH)
bank_name = models.CharField(max_length=25, blank=True)
number = models.CharField(max_length=140, blank=True)
balance = models.DecimalField(decimal_places=10, max_digits=19, default=0)
currency = models.ForeignKey(Currency, default=DEFAULT_CURRENCY_ID)
active = models.BooleanField(initial=True)
#add the account owner
def __str__(self):
if account_type == 'b'
return self.number
else
return self.currency
class Transfer(models.Model):
from_account = models.ForeignKey(Account)
to_account = models.ForeignKey(Account)
amount = models.DecimalField(decimal_places=10, max_digits=19)
exchange_rate = models.DecimalField(decimal_places=10, max_digits=19)
date = models.DateTimeField(default=datetime.now())
def __str__(self):
return self.amount
| Create the transfer model of accounts | Create the transfer model of accounts
| Python | mit | m1k3r/gvi-accounts,m1k3r/gvi-accounts,m1k3r/gvi-accounts | ---
+++
@@ -1,4 +1,5 @@
from django.db import models
+import datetime
class Currency(models.Model):
@@ -25,7 +26,18 @@
#add the account owner
def __str__(self):
- if(account_type == 'b')
+ if account_type == 'b'
return self.number
else
- return self.currency
+ return self.currency
+
+
+class Transfer(models.Model):
+ from_account = models.ForeignKey(Account)
+ to_account = models.ForeignKey(Account)
+ amount = models.DecimalField(decimal_places=10, max_digits=19)
+ exchange_rate = models.DecimalField(decimal_places=10, max_digits=19)
+ date = models.DateTimeField(default=datetime.now())
+
+ def __str__(self):
+ return self.amount |
8115116fb81fd5a121f9f94e47abbadd2c892b3d | pytablewriter/writer/binary/_interface.py | pytablewriter/writer/binary/_interface.py | # encoding: utf-8
import abc
import six
from .._table_writer import AbstractTableWriter
@six.add_metaclass(abc.ABCMeta)
class BinaryWriterInterface(object):
@abc.abstractmethod
def is_opened(self): # pragma: no cover
pass
@abc.abstractmethod
def open(self, file_path): # pragma: no cover
pass
class AbstractBinaryTableWriter(AbstractTableWriter, BinaryWriterInterface):
def dumps(self):
raise NotImplementedError("binary format writers did not support dumps method")
| # encoding: utf-8
import abc
import six
from .._table_writer import AbstractTableWriter
@six.add_metaclass(abc.ABCMeta)
class BinaryWriterInterface(object):
@abc.abstractmethod
def is_opened(self): # pragma: no cover
pass
@abc.abstractmethod
def open(self, file_path): # pragma: no cover
pass
class AbstractBinaryTableWriter(AbstractTableWriter, BinaryWriterInterface):
def dumps(self):
raise NotImplementedError("binary format writers did not support dumps method")
def _verify_stream(self):
if self.stream is None:
raise IOError("null output stream. required to open(file_path) first.")
| Add stream verification for binary format writers | Add stream verification for binary format writers
| Python | mit | thombashi/pytablewriter | ---
+++
@@ -21,3 +21,7 @@
class AbstractBinaryTableWriter(AbstractTableWriter, BinaryWriterInterface):
def dumps(self):
raise NotImplementedError("binary format writers did not support dumps method")
+
+ def _verify_stream(self):
+ if self.stream is None:
+ raise IOError("null output stream. required to open(file_path) first.") |
ef2b13ec19d28b56647c0a11044cba6d400f9175 | vimiv/image_enhance.py | vimiv/image_enhance.py | # vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Wrapper functions for the _image_enhance C extension."""
from gi.repository import GdkPixbuf, GLib
from vimiv import _image_enhance
def enhance_bc(pixbuf, brightness, contrast):
"""Enhance brightness and contrast of a GdkPixbuf.Pixbuf.
Args:
pixbuf: Original GdkPixbuf.Pixbuf to work with.
brightness: Float between -1.0 and 1.0 to change brightness.
contrast: Float between -1.0 and 1.0 to change contrast.
Return:
The enhanced GdkPixbuf.Pixbuf
"""
width = pixbuf.get_width()
height = pixbuf.get_height()
data = pixbuf.get_pixels()
has_alpha = pixbuf.get_has_alpha()
c_has_alpha = 1 if has_alpha else 0 # Numbers are easier for C
rowstride = 4 * width if has_alpha else 3 * width
# Update plain bytes using C extension
# Pylint does not read this properly
# pylint: disable=no-member
data = _image_enhance.enhance_bc(data, c_has_alpha, brightness, contrast)
gdata = GLib.Bytes.new(data)
return GdkPixbuf.Pixbuf.new_from_bytes(
gdata, GdkPixbuf.Colorspace.RGB, has_alpha, 8, width, height, rowstride)
| # vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Wrapper functions for the _image_enhance C extension."""
from gi.repository import GdkPixbuf, GLib
from vimiv import _image_enhance
def enhance_bc(pixbuf, brightness, contrast):
"""Enhance brightness and contrast of a GdkPixbuf.Pixbuf.
Args:
pixbuf: Original GdkPixbuf.Pixbuf to work with.
brightness: Float between -1.0 and 1.0 to change brightness.
contrast: Float between -1.0 and 1.0 to change contrast.
Return:
The enhanced GdkPixbuf.Pixbuf
"""
data = pixbuf.get_pixels()
has_alpha = pixbuf.get_has_alpha()
c_has_alpha = 1 if has_alpha else 0 # Numbers are easier for C
# Update plain bytes using C extension
# Pylint does not read this properly
# pylint: disable=no-member
data = _image_enhance.enhance_bc(data, c_has_alpha, brightness, contrast)
gdata = GLib.Bytes.new(data)
return GdkPixbuf.Pixbuf.new_from_bytes(gdata,
pixbuf.get_colorspace(),
has_alpha,
pixbuf.get_bits_per_sample(),
pixbuf.get_width(),
pixbuf.get_height(),
pixbuf.get_rowstride())
| Use rowstride directly from GdkPixbuf in enhance | Use rowstride directly from GdkPixbuf in enhance
The custom calculation of rowstride failed for images with weird
dimensions and completely broke enhance.
fixes #51
| Python | mit | karlch/vimiv,karlch/vimiv,karlch/vimiv | ---
+++
@@ -15,16 +15,18 @@
Return:
The enhanced GdkPixbuf.Pixbuf
"""
- width = pixbuf.get_width()
- height = pixbuf.get_height()
data = pixbuf.get_pixels()
has_alpha = pixbuf.get_has_alpha()
c_has_alpha = 1 if has_alpha else 0 # Numbers are easier for C
- rowstride = 4 * width if has_alpha else 3 * width
# Update plain bytes using C extension
# Pylint does not read this properly
# pylint: disable=no-member
data = _image_enhance.enhance_bc(data, c_has_alpha, brightness, contrast)
gdata = GLib.Bytes.new(data)
- return GdkPixbuf.Pixbuf.new_from_bytes(
- gdata, GdkPixbuf.Colorspace.RGB, has_alpha, 8, width, height, rowstride)
+ return GdkPixbuf.Pixbuf.new_from_bytes(gdata,
+ pixbuf.get_colorspace(),
+ has_alpha,
+ pixbuf.get_bits_per_sample(),
+ pixbuf.get_width(),
+ pixbuf.get_height(),
+ pixbuf.get_rowstride()) |
116c2a875b3d9384ae744c02f3651b481ee23838 | app/gunicorn-ws.conf.py | app/gunicorn-ws.conf.py | # gunicorn config file for dermshare-ws.py
bind = '0.0.0.0:8025'
# Only one worker, since connections need to share state
workers = 1
worker_class = 'geventwebsocket.gunicorn.workers.GeventWebSocketWorker'
pidfile = 'gunicorn-ws.pid'
proc_name = 'dermshare-ws'
| # gunicorn config file for dermshare-ws.py
bind = '0.0.0.0:8026'
# Only one worker, since connections need to share state
workers = 1
worker_class = 'geventwebsocket.gunicorn.workers.GeventWebSocketWorker'
pidfile = 'gunicorn-ws.pid'
proc_name = 'dermshare-ws'
| Change gunicorn websocket listening port | Change gunicorn websocket listening port
| Python | epl-1.0 | cmusatyalab/dermshare,spressomonkey/dermshare,spressomonkey/dermshare,spressomonkey/dermshare,spressomonkey/dermshare,cmusatyalab/dermshare,cmusatyalab/dermshare,cmusatyalab/dermshare,spressomonkey/dermshare,spressomonkey/dermshare | ---
+++
@@ -1,6 +1,6 @@
# gunicorn config file for dermshare-ws.py
-bind = '0.0.0.0:8025'
+bind = '0.0.0.0:8026'
# Only one worker, since connections need to share state
workers = 1
worker_class = 'geventwebsocket.gunicorn.workers.GeventWebSocketWorker' |
1fb6166198d90166881230d9edb1dd4f6fc36963 | aws/customise-stack-template.py | aws/customise-stack-template.py | from amazonia.classes.sns import SNS
from troposphere import Ref, Join, cloudwatch
from troposphere.sns import Topic, Subscription
def user_registration_topic(emails):
return topic("UserRegistrationReceived", emails)
def new_cors_site_request_received_topic(emails):
return topic("NewCorsSiteRequestReceived", emails)
def topic(topic_title, emails):
topic = Topic(topic_title,
DisplayName=Join("", [Ref("AWS::StackName"), "-", topic_title]))
topic.Subscription = []
for index, email in enumerate(emails):
topic.Subscription.append(Subscription(
topic_title + "Subscription" + str(index),
Endpoint=email,
Protocol="email"))
return topic
def customise_stack_template(template):
template.add_resource(user_registration_topic([]))
template.add_resource(new_cors_site_request_received_topic([]))
return template
| from amazonia.classes.sns import SNS
from troposphere import Ref, Join, cloudwatch
from troposphere.sns import Topic, Subscription
def user_registration_topic(emails):
return topic("UserRegistrationReceived", emails)
def new_cors_site_request_received_topic(emails):
return topic("NewCorsSiteRequestReceived", emails)
def site_log_received_topic(emails):
return topic("SiteLogReceived", emails)
def topic(topic_title, emails):
topic = Topic(topic_title,
DisplayName=Join("", [Ref("AWS::StackName"), "-", topic_title]))
topic.Subscription = []
for index, email in enumerate(emails):
topic.Subscription.append(Subscription(
topic_title + "Subscription" + str(index),
Endpoint=email,
Protocol="email"))
return topic
def customise_stack_template(template):
template.add_resource(user_registration_topic([]))
template.add_resource(new_cors_site_request_received_topic([]))
template.add_resource(site_log_received_topic([]))
return template
| Add site log received SNS topic | Add site log received SNS topic
| Python | bsd-3-clause | GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services | ---
+++
@@ -8,6 +8,9 @@
def new_cors_site_request_received_topic(emails):
return topic("NewCorsSiteRequestReceived", emails)
+
+def site_log_received_topic(emails):
+ return topic("SiteLogReceived", emails)
def topic(topic_title, emails):
topic = Topic(topic_title,
@@ -25,4 +28,5 @@
def customise_stack_template(template):
template.add_resource(user_registration_topic([]))
template.add_resource(new_cors_site_request_received_topic([]))
+ template.add_resource(site_log_received_topic([]))
return template |
97a58f80014fbecd483c45438397a70c0789efd3 | app_metrics/__init__.py | app_metrics/__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
__name__ = 'app_metrics'
__author__ = 'Pivotal Energy Solutions'
__version_info__ = (1, 0, 0)
__version__ = '.'.join(map(str, __version_info__))
__date__ = '2014/07/22 4:47:00 PM'
__credits__ = ['Frank Wiles', 'Ross Poulton', 'Flavio Curella',
'Jacob Burch', 'Jannis Leidel', 'Flávio Juvena',
'Daniel Lindsley', 'Hannes Struß', 'Steven Klass',
'Tim Valenta']
__license__ = 'See the file LICENSE.txt for licensing information.'
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
__name__ = 'app_metrics'
__author__ = 'Pivotal Energy Solutions'
__version_info__ = (1, 1, 0)
__version__ = '.'.join(map(str, __version_info__))
__date__ = '2014/07/22 4:47:00 PM'
__credits__ = ['Frank Wiles', 'Ross Poulton', 'Flavio Curella',
'Jacob Burch', 'Jannis Leidel', 'Flávio Juvena',
'Daniel Lindsley', 'Hannes Struß', 'Steven Klass',
'Tim Valenta']
__license__ = 'See the file LICENSE.txt for licensing information.'
| Support and rollup a release | Support and rollup a release
| Python | bsd-3-clause | pivotal-energy-solutions/django-app-metrics,pivotal-energy-solutions/django-app-metrics | ---
+++
@@ -4,7 +4,7 @@
__name__ = 'app_metrics'
__author__ = 'Pivotal Energy Solutions'
-__version_info__ = (1, 0, 0)
+__version_info__ = (1, 1, 0)
__version__ = '.'.join(map(str, __version_info__))
__date__ = '2014/07/22 4:47:00 PM'
__credits__ = ['Frank Wiles', 'Ross Poulton', 'Flavio Curella', |
0cd084550fc5c1315fe33fcb00e57c1c332be6ab | indra/tests/test_mesh.py | indra/tests/test_mesh.py | from indra.databases import mesh_client
def test_mesh_id_lookup():
mesh_id = 'D003094'
mesh_name = mesh_client.get_mesh_name(mesh_id)
assert mesh_name == 'Collagen'
| from indra.databases import mesh_client
def test_mesh_id_lookup():
mesh_id = 'D003094'
mesh_name = mesh_client.get_mesh_name(mesh_id)
assert mesh_name == 'Collagen'
def test_invalid_id():
mesh_name = mesh_client.get_mesh_name('34jkgfh')
assert mesh_name is None
| Add test for invalid MESH ID | Add test for invalid MESH ID
| Python | bsd-2-clause | pvtodorov/indra,johnbachman/indra,pvtodorov/indra,johnbachman/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,sorgerlab/belpy,sorgerlab/indra,bgyori/indra,johnbachman/indra,johnbachman/belpy,johnbachman/belpy | ---
+++
@@ -4,3 +4,8 @@
mesh_id = 'D003094'
mesh_name = mesh_client.get_mesh_name(mesh_id)
assert mesh_name == 'Collagen'
+
+def test_invalid_id():
+ mesh_name = mesh_client.get_mesh_name('34jkgfh')
+ assert mesh_name is None
+ |
7aab3ca6cdf3cf8c4c2a1e01ededede5a4bad0f1 | tests/test_cardinal/test_context.py | tests/test_cardinal/test_context.py | import pytest
from cardinal.context import Context
from cardinal.errors import IllegalSessionUse
@pytest.fixture
def base_ctor(mocker):
return mocker.patch('cardinal.context.commands.Context.__init__')
@pytest.fixture(params=[
{},
{'asdf': 123}
])
def ctx(base_ctor, request):
yield Context(**request.param)
base_ctor.assert_called_once_with(**request.param)
@pytest.fixture
def sessionmaker(ctx, mocker):
ctx.bot = mocker.Mock()
return ctx.bot.sessionmaker
def test_ctor(ctx):
assert not ctx.session_used
def test_session_not_allowed(ctx, sessionmaker):
with pytest.raises(IllegalSessionUse):
_ = ctx.session
sessionmaker.assert_not_called()
def test_session_allowed(ctx, sessionmaker):
ctx.session_allowed = True
sess1 = ctx.session
sessionmaker.assert_called_once_with()
assert ctx.session_used is True
sessionmaker.reset_mock()
sess2 = ctx.session
sessionmaker.assert_not_called()
assert sess1 is sess2
| import pytest
from cardinal.context import Context
from cardinal.errors import IllegalSessionUse
@pytest.fixture
def base_ctor(mocker):
return mocker.patch('cardinal.context.commands.Context.__init__')
@pytest.fixture
def ctx(base_ctor, request):
kwargs = getattr(request, 'param', {})
yield Context(**kwargs)
if hasattr(request, 'param'):
base_ctor.assert_called_once_with(**kwargs) # Skip unnecessary assertions
@pytest.fixture
def sessionmaker(ctx, mocker):
ctx.bot = mocker.Mock()
return ctx.bot.sessionmaker
@pytest.mark.parametrize(
['ctx'],
[
({},),
({'asdf': 123},)
],
indirect=True
)
def test_ctor(ctx):
assert not ctx.session_used
def test_session_not_allowed(ctx, sessionmaker):
with pytest.raises(IllegalSessionUse):
_ = ctx.session
sessionmaker.assert_not_called()
def test_session_allowed(ctx, sessionmaker):
ctx.session_allowed = True
sess1 = ctx.session
sessionmaker.assert_called_once_with()
assert ctx.session_used is True
sessionmaker.reset_mock()
sess2 = ctx.session
sessionmaker.assert_not_called()
assert sess1 is sess2
| Adjust fixture usage in context tests | Adjust fixture usage in context tests
| Python | mit | FallenWarrior2k/cardinal.py,FallenWarrior2k/cardinal.py | ---
+++
@@ -9,13 +9,13 @@
return mocker.patch('cardinal.context.commands.Context.__init__')
-@pytest.fixture(params=[
- {},
- {'asdf': 123}
-])
+@pytest.fixture
def ctx(base_ctor, request):
- yield Context(**request.param)
- base_ctor.assert_called_once_with(**request.param)
+ kwargs = getattr(request, 'param', {})
+
+ yield Context(**kwargs)
+ if hasattr(request, 'param'):
+ base_ctor.assert_called_once_with(**kwargs) # Skip unnecessary assertions
@pytest.fixture
@@ -24,6 +24,14 @@
return ctx.bot.sessionmaker
+@pytest.mark.parametrize(
+ ['ctx'],
+ [
+ ({},),
+ ({'asdf': 123},)
+ ],
+ indirect=True
+)
def test_ctor(ctx):
assert not ctx.session_used
|
920bc2620533cb4c91d7b7dd186ba59fd09edbf9 | datadog/api/screenboards.py | datadog/api/screenboards.py | from datadog.api.base import GetableAPIResource, CreateableAPIResource, \
UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource
class Screenboard(GetableAPIResource, CreateableAPIResource,
UpdatableAPIResource, DeletableAPIResource,
ActionAPIResource, ListableAPIResource):
"""
A wrapper around Screenboard HTTP API.
"""
_class_name = 'screen'
_class_url = '/screen'
_json_name = 'board'
@classmethod
def share(cls, board_id):
"""
Share the screenboard with given id
:param board_id: screenboard to share
:type board_id: id
:returns: JSON response from HTTP request
"""
return super(Screenboard, cls)._trigger_action('GET', 'screen/share', board_id)
| from datadog.api.base import GetableAPIResource, CreateableAPIResource, \
UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource
class Screenboard(GetableAPIResource, CreateableAPIResource,
UpdatableAPIResource, DeletableAPIResource,
ActionAPIResource, ListableAPIResource):
"""
A wrapper around Screenboard HTTP API.
"""
_class_name = 'screen'
_class_url = '/screen'
_json_name = 'board'
@classmethod
def share(cls, board_id):
"""
Share the screenboard with given id
:param board_id: screenboard to share
:type board_id: id
:returns: JSON response from HTTP request
"""
return super(Screenboard, cls)._trigger_action('GET', 'screen/share', board_id)
@classmethod
def revoke(cls, board_id):
"""
Revoke a shared screenboard with given id
:param board_id: screenboard to revoke
:type board_id: id
:returns: JSON response from HTTP request
"""
return super(Screenboard, cls)._trigger_action('DELETE', 'screen/share', board_id)
| Add `revoke` method to Screenboard | Add `revoke` method to Screenboard
- This method allow to revoke the public access of a shared
screenboard
| Python | bsd-3-clause | percipient/datadogpy,clokep/datadogpy,KyleJamesWalker/datadogpy,jofusa/datadogpy,rogst/datadogpy,rogst/datadogpy,percipient/datadogpy,jofusa/datadogpy,clokep/datadogpy,KyleJamesWalker/datadogpy | ---
+++
@@ -23,3 +23,15 @@
:returns: JSON response from HTTP request
"""
return super(Screenboard, cls)._trigger_action('GET', 'screen/share', board_id)
+
+ @classmethod
+ def revoke(cls, board_id):
+ """
+ Revoke a shared screenboard with given id
+
+ :param board_id: screenboard to revoke
+ :type board_id: id
+
+ :returns: JSON response from HTTP request
+ """
+ return super(Screenboard, cls)._trigger_action('DELETE', 'screen/share', board_id) |
70d0e524051442958b5098e7206c5ab745d20eb6 | adminator/kea_agent.py | adminator/kea_agent.py | #!/usr/bin/python3 -tt
# -*- coding: utf-8 -*-
__all__ = ['KeaAgent']
from os import system
from twisted.python import log
from simplejson import dump, load
from adminator.kea import generate_kea_config, DEFAULTS
class KeaAgent(object):
def __init__(self, db, template=None, output=None, signal=None):
self.db = db
if template is not None:
log.msg('Reading Template {}'.format(template))
with open(template) as fp:
self.template = load(fp)
else:
self.template = DEFAULTS
self.output = output or '/etc/kea/kea.conf'
self.signal = signal or 'keactrl reload'
def start(self):
self.update()
def notify(self, event):
log.msg('Database Notification: {}'.format(event.channel))
if event.channel == 'dhcp':
self.update()
def update(self):
log.msg('Generating Configuration')
config = generate_kea_config(self.db, self.template)
log.msg('Writing: {}'.format(self.output))
with open(self.output, 'w') as fp:
dump(config, fp)
log.msg('Executing: {}'.format(self.signal))
system(self.signal)
# vim:set sw=4 ts=4 et:
| #!/usr/bin/python3 -tt
# -*- coding: utf-8 -*-
__all__ = ['KeaAgent']
from os import system
from twisted.python import log
from json import dump, load
from adminator.kea import generate_kea_config, DEFAULTS
class KeaAgent(object):
def __init__(self, db, template=None, output=None, signal=None):
self.db = db
if template is not None:
log.msg('Reading Template {}'.format(template))
with open(template) as fp:
self.template = load(fp)
else:
self.template = DEFAULTS
self.output = output or '/etc/kea/kea.conf'
self.signal = signal or 'keactrl reload'
def start(self):
self.update()
def notify(self, event):
log.msg('Database Notification: {}'.format(event.channel))
if event.channel == 'dhcp':
self.update()
def update(self):
log.msg('Generating Configuration')
config = generate_kea_config(self.db, self.template)
log.msg('Writing: {}'.format(self.output))
with open(self.output, 'w') as fp:
dump(config, fp)
log.msg('Executing: {}'.format(self.signal))
system(self.signal)
# vim:set sw=4 ts=4 et:
| Use json instead of simplejson | Use json instead of simplejson
Signed-off-by: Jan Dvořák <86df5a4870880bf501c926309e3bcfbe57789f3f@mordae.eu>
| Python | mit | techlib/adminator,techlib/adminator,techlib/adminator | ---
+++
@@ -5,7 +5,7 @@
from os import system
from twisted.python import log
-from simplejson import dump, load
+from json import dump, load
from adminator.kea import generate_kea_config, DEFAULTS
|
f5e67a55535b48afd95272083336d61dd1175765 | administrator/admin.py | administrator/admin.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import User
# Register your models here.
admin.site.register(User)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as Admin
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import Group
from .models import User
class RegistrationForm(UserCreationForm):
"""A form for user creation.
Email, username, password and role are given.
"""
email = forms.EmailField(required=True)
class Meta:
"""Give some options (metadata) attached to the form."""
model = User
fields = ('role',)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.role = self.cleaned_data['role']
user.set_is_staff(user.role)
if commit:
user.save()
return user
class UserAdmin(Admin):
"""Represent a model in the admin interface."""
add_form = RegistrationForm
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'fields': ('email', 'username', 'password1', 'password2', 'role')}
),
)
admin.site.register(User, UserAdmin)
admin.site.unregister(Group)
| Add form for user creation | Add form for user creation
| Python | mit | Social-projects-Rivne/Rv-025.Python,Social-projects-Rivne/Rv-025.Python,Social-projects-Rivne/Rv-025.Python | ---
+++
@@ -1,8 +1,57 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
+from django import forms
from django.contrib import admin
+from django.contrib.auth.admin import UserAdmin as Admin
+from django.contrib.auth.forms import UserCreationForm
+from django.contrib.auth.models import Group
+
from .models import User
-# Register your models here.
-admin.site.register(User)
+
+class RegistrationForm(UserCreationForm):
+
+ """A form for user creation.
+
+ Email, username, password and role are given.
+ """
+
+ email = forms.EmailField(required=True)
+
+
+ class Meta:
+
+ """Give some options (metadata) attached to the form."""
+
+ model = User
+ fields = ('role',)
+
+
+ def save(self, commit=True):
+ user = super(RegistrationForm, self).save(commit=False)
+ user.email = self.cleaned_data['email']
+ user.role = self.cleaned_data['role']
+ user.set_is_staff(user.role)
+ if commit:
+ user.save()
+ return user
+
+
+class UserAdmin(Admin):
+
+ """Represent a model in the admin interface."""
+
+ add_form = RegistrationForm
+
+ # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
+ # overrides get_fieldsets to use this attribute when creating a user.
+ add_fieldsets = (
+ (None, {
+ 'fields': ('email', 'username', 'password1', 'password2', 'role')}
+ ),
+ )
+
+
+admin.site.register(User, UserAdmin)
+admin.site.unregister(Group) |
5b7a1a40ea43834feb5563f566d07bd5b31c589d | tests/test-recipes/metadata/always_include_files_glob/run_test.py | tests/test-recipes/metadata/always_include_files_glob/run_test.py | import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}
elif sys.platform.startswith('linux'):
assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}
if __name__ == '__main__':
main()
| import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}, info['files']
elif sys.platform.startswith('linux'):
assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}, info['files']
if __name__ == '__main__':
main()
| Add error messages to the asserts | Add error messages to the asserts
| Python | bsd-3-clause | ilastik/conda-build,shastings517/conda-build,frol/conda-build,dan-blanchard/conda-build,mwcraig/conda-build,mwcraig/conda-build,dan-blanchard/conda-build,ilastik/conda-build,sandhujasmine/conda-build,rmcgibbo/conda-build,sandhujasmine/conda-build,shastings517/conda-build,rmcgibbo/conda-build,shastings517/conda-build,dan-blanchard/conda-build,mwcraig/conda-build,ilastik/conda-build,rmcgibbo/conda-build,sandhujasmine/conda-build,frol/conda-build,frol/conda-build | ---
+++
@@ -11,9 +11,9 @@
info = json.load(fh)
if sys.platform == 'darwin':
- assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}
+ assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}, info['files']
elif sys.platform.startswith('linux'):
- assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}
+ assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}, info['files']
if __name__ == '__main__':
main() |
f59852e0db6941ce0862545f552a2bc17081086a | schedule/tests/test_templatetags.py | schedule/tests/test_templatetags.py | import datetime
from django.test import TestCase
from schedule.templatetags.scheduletags import querystring_for_date
class TestTemplateTags(TestCase):
def test_querystring_for_datetime(self):
date = datetime.datetime(2008,1,1,0,0,0)
query_string=querystring_for_date(date)
self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0",
query_string) | import datetime
from django.test import TestCase
from schedule.templatetags.scheduletags import querystring_for_date
class TestTemplateTags(TestCase):
def test_querystring_for_datetime(self):
date = datetime.datetime(2008,1,1,0,0,0)
query_string=querystring_for_date(date)
self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0",
query_string)
| Update unit test to use escaped ampersands in comparision. | Update unit test to use escaped ampersands in comparision.
| Python | bsd-3-clause | Gustavosdo/django-scheduler,erezlife/django-scheduler,Gustavosdo/django-scheduler,nharsch/django-scheduler,nharsch/django-scheduler,drodger/django-scheduler,GrahamDigital/django-scheduler,sprightco/django-scheduler,llazzaro/django-scheduler,llazzaro/django-scheduler,rowbot-dev/django-scheduler,nwaxiomatic/django-scheduler,nwaxiomatic/django-scheduler,mbrondani/django-scheduler,drodger/django-scheduler,jrutila/django-scheduler,nwaxiomatic/django-scheduler,sprightco/django-scheduler,drodger/django-scheduler,jrutila/django-scheduler,erezlife/django-scheduler,GrahamDigital/django-scheduler,llazzaro/django-scheduler,GrahamDigital/django-scheduler,sprightco/django-scheduler,mbrondani/django-scheduler,rowbot-dev/django-scheduler | ---
+++
@@ -9,5 +9,5 @@
def test_querystring_for_datetime(self):
date = datetime.datetime(2008,1,1,0,0,0)
query_string=querystring_for_date(date)
- self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0",
+ self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0",
query_string) |
ab7c15b791f42f90fa41dfd0557172ce520933f8 | LibCharm/IO/__init__.py | LibCharm/IO/__init__.py | try:
from Bio import SeqIO
from Bio.Alphabet import IUPAC
except ImportError as e:
print('ERROR: {}'.format(e.msg))
exit(1)
def load_file(filename, file_format="fasta"):
"""
Load sequence from file in FASTA file_format
filename - Path and filename of input sequence file
"""
content = None
try:
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_dna)
except ValueError as e:
print('ERROR: {}'.format(e))
try:
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_rna)
except ValueError as e:
print('ERROR: {}'.format(e))
exit(1)
if content:
seq = content.seq
return seq
else:
return None
| try:
from Bio import SeqIO
from Bio.Alphabet import IUPAC
except ImportError as e:
print('ERROR: {}'.format(e.msg))
exit(1)
def load_file(filename, file_format="fasta"):
"""
Load sequence from file and returns sequence as Bio.Seq object
filename - String; Path and filename of input sequence file
file_format - String; Format to be used. Refer to Biopython docs for available formats. Defaults to 'fasta'
"""
content = None
try:
# assume sequence is DNA
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_dna)
except ValueError as e:
# if this fails, try RNA instead
print('ERROR: {}'.format(e))
try:
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_rna)
except ValueError as e:
# if this fails, too, raise exception and exit with error code 1
print('ERROR: {}'.format(e))
exit(1)
# if some kind of data could be read, return the sequence object
if content:
seq = content.seq
return seq
# else return None
else:
return None
| Prepare for tagging release 0.1: Add comments to LibCharm.IO | Prepare for tagging release 0.1: Add comments to LibCharm.IO
| Python | mit | Athemis/charm | ---
+++
@@ -7,22 +7,28 @@
def load_file(filename, file_format="fasta"):
"""
- Load sequence from file in FASTA file_format
- filename - Path and filename of input sequence file
+ Load sequence from file and returns sequence as Bio.Seq object
+ filename - String; Path and filename of input sequence file
+ file_format - String; Format to be used. Refer to Biopython docs for available formats. Defaults to 'fasta'
"""
content = None
try:
+ # assume sequence is DNA
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_dna)
except ValueError as e:
+ # if this fails, try RNA instead
print('ERROR: {}'.format(e))
try:
content = SeqIO.read(filename, file_format, IUPAC.unambiguous_rna)
except ValueError as e:
+ # if this fails, too, raise exception and exit with error code 1
print('ERROR: {}'.format(e))
exit(1)
+ # if some kind of data could be read, return the sequence object
if content:
seq = content.seq
return seq
+ # else return None
else:
return None |
c581d1aab8df44b3c4e8e809e390517432c67d93 | skan/test/test_vendored_correlate.py | skan/test/test_vendored_correlate.py | from contextlib import contextmanager
from time import time
import numpy as np
from skan.vendored import thresholding as th
@contextmanager
def timer():
result = [0.]
t = time()
yield result
result[0] = time() - t
def test_fast_sauvola():
image = np.random.rand(512, 512)
w0 = 25
w1 = 251
_ = th.threshold_sauvola(image, window_size=3)
with timer() as t0:
th.threshold_sauvola(image, window_size=w0)
with timer() as t1:
th.threshold_sauvola(image, window_size=w1)
assert t1[0] < 2 * t0[0]
| from time import time
import numpy as np
from skan.vendored import thresholding as th
class Timer:
def __init__(self):
self.interval = 0
def __enter__(self):
self.t0 = time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.interval = time() - self.t0
def test_fast_sauvola():
image = np.random.rand(512, 512)
w0 = 25
w1 = 251
_ = th.threshold_sauvola(image, window_size=3)
with Timer() as t0:
th.threshold_sauvola(image, window_size=w0)
with Timer() as t1:
th.threshold_sauvola(image, window_size=w1)
assert t1.interval < 2 * t0.interval
| Use timer class instead of weird list | Use timer class instead of weird list
| Python | bsd-3-clause | jni/skan | ---
+++
@@ -1,15 +1,18 @@
-from contextlib import contextmanager
from time import time
import numpy as np
from skan.vendored import thresholding as th
-@contextmanager
-def timer():
- result = [0.]
- t = time()
- yield result
- result[0] = time() - t
+class Timer:
+ def __init__(self):
+ self.interval = 0
+
+ def __enter__(self):
+ self.t0 = time()
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self.interval = time() - self.t0
def test_fast_sauvola():
@@ -17,8 +20,8 @@
w0 = 25
w1 = 251
_ = th.threshold_sauvola(image, window_size=3)
- with timer() as t0:
+ with Timer() as t0:
th.threshold_sauvola(image, window_size=w0)
- with timer() as t1:
+ with Timer() as t1:
th.threshold_sauvola(image, window_size=w1)
- assert t1[0] < 2 * t0[0]
+ assert t1.interval < 2 * t0.interval |
923f6127eec0a6a576493f41d0f3b2fb9b6156d1 | tests/Settings/TestContainerStack.py | tests/Settings/TestContainerStack.py | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
import UM.Settings
def test_container_stack():
stack = UM.Settings.ContainerStack()
| # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
import pytest
import uuid # For creating unique ID's for each container stack.
import UM.Settings
## Creates a brand new container stack to test with.
#
# The container stack will get a new, unique ID.
@pytest.fixture
def container_stack():
return UM.Settings.ContainerStack(uuid.uuid4().int)
def test_container_stack(container_stack):
assert container_stack != None
| Test creating container stack with fixture | Test creating container stack with fixture
The fixture will automatically generate a unique ID.
Contributes to issue CURA-1278.
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -1,7 +1,18 @@
# Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
+import pytest
+import uuid # For creating unique ID's for each container stack.
+
import UM.Settings
-def test_container_stack():
- stack = UM.Settings.ContainerStack()
+## Creates a brand new container stack to test with.
+#
+# The container stack will get a new, unique ID.
+@pytest.fixture
+def container_stack():
+ return UM.Settings.ContainerStack(uuid.uuid4().int)
+
+def test_container_stack(container_stack):
+ assert container_stack != None
+ |
f6d7bbffcbd5f1df0bbf122054e3c0930128d26c | src/py/handlers/www.py | src/py/handlers/www.py | """www URL handlers"""
import os
import template
import webapp2
def redirect(url):
"""Create a request handler to redirect to the given URL.
Args:
url: The URL to redirect to.
Returns:
A class definition of a request handler that will always redirect the
user to the given URL.
"""
class RequestHandler(webapp2.RequestHandler):
"""Redirect request handler."""
def get(self):
"""GET method handler."""
self.response.location = url
self.response.status = 201
return RequestHandler
def static_resource(mime_type):
"""Create a request handler for the given mime type.
Args:
mime_type: The mime-type of the static resource being served.
Returns:
A class definition of a request handler that returns a static resource.
"""
class RequestHandler(webapp2.RequestHandler):
"""Static resource request handler."""
def get(self):
"""GET method handler"""
self.response.charset = 'utf8'
self.response.content_type = mime_type
with open('www/' + self.request.path_info) as handle:
self.response.text = handle.read().decode()
return RequestHandler
class Index(webapp2.RequestHandler):
"""Index request handler"""
def get(self):
"""GET method handler"""
self.response.charset = 'utf8'
self.response.text = template.render(os.getcwd() + '/www/index.html')
| """www URL handlers"""
import os
import template
import webapp2
def redirect(url):
"""Create a request handler to redirect to the given URL.
Args:
url: The URL to redirect to.
Returns:
A class definition of a request handler that will always redirect the
user to the given URL.
"""
class RequestHandler(webapp2.RequestHandler):
"""Redirect request handler."""
def get(self):
"""GET method handler."""
self.response.location = url
self.response.status = 301
return RequestHandler
def static_resource(mime_type):
"""Create a request handler for the given mime type.
Args:
mime_type: The mime-type of the static resource being served.
Returns:
A class definition of a request handler that returns a static resource.
"""
class RequestHandler(webapp2.RequestHandler):
"""Static resource request handler."""
def get(self):
"""GET method handler"""
self.response.charset = 'utf8'
self.response.content_type = mime_type
with open('www/' + self.request.path_info) as handle:
self.response.text = handle.read().decode()
return RequestHandler
class Index(webapp2.RequestHandler):
"""Index request handler"""
def get(self):
"""GET method handler"""
self.response.charset = 'utf8'
self.response.text = template.render(os.getcwd() + '/www/index.html')
| Use the correct status code in the redirect handler | Use the correct status code in the redirect handler
| Python | mpl-2.0 | kjiwa/till,kjiwa/till,kjiwa/till,kjiwa/till | ---
+++
@@ -19,7 +19,7 @@
def get(self):
"""GET method handler."""
self.response.location = url
- self.response.status = 201
+ self.response.status = 301
return RequestHandler
|
09835326d799cd05200856d6114b2df126d21bfb | wagtail/tests/routablepage/models.py | wagtail/tests/routablepage/models.py | from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
@property
def subpage_urls(self):
return (
url(r'^$', self.main, name='main'),
url(r'^archive/year/(\d+)/$', self.archive_by_year, name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', self.archive_by_author, name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
| from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
subpage_urls = (
url(r'^$', 'main', name='main'),
url(r'^archive/year/(\d+)/$', 'archive_by_year', name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', 'archive_by_author', name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
| Revert "Make subpage_urls a property on RoutablePageTest" | Revert "Make subpage_urls a property on RoutablePageTest"
This reverts commit d80a92cfe45907b9f91fd212a3b06fa0b2321364.
| Python | bsd-3-clause | janusnic/wagtail,marctc/wagtail,nrsimha/wagtail,WQuanfeng/wagtail,nrsimha/wagtail,nilnvoid/wagtail,Klaudit/wagtail,WQuanfeng/wagtail,rv816/wagtail,timorieber/wagtail,mikedingjan/wagtail,thenewguy/wagtail,kaedroho/wagtail,bjesus/wagtail,jordij/wagtail,bjesus/wagtail,thenewguy/wagtail,nimasmi/wagtail,darith27/wagtail,stevenewey/wagtail,mikedingjan/wagtail,kurtw/wagtail,iho/wagtail,nimasmi/wagtail,jnns/wagtail,hamsterbacke23/wagtail,FlipperPA/wagtail,janusnic/wagtail,rsalmaso/wagtail,gasman/wagtail,mayapurmedia/wagtail,tangentlabs/wagtail,quru/wagtail,stevenewey/wagtail,gogobook/wagtail,tangentlabs/wagtail,takeshineshiro/wagtail,Tivix/wagtail,chrxr/wagtail,tangentlabs/wagtail,mixxorz/wagtail,wagtail/wagtail,taedori81/wagtail,rjsproxy/wagtail,chrxr/wagtail,mayapurmedia/wagtail,nealtodd/wagtail,Tivix/wagtail,serzans/wagtail,kurtrwall/wagtail,Toshakins/wagtail,takeshineshiro/wagtail,nutztherookie/wagtail,tangentlabs/wagtail,mjec/wagtail,nealtodd/wagtail,JoshBarr/wagtail,hamsterbacke23/wagtail,rv816/wagtail,torchbox/wagtail,takeshineshiro/wagtail,thenewguy/wagtail,takeflight/wagtail,FlipperPA/wagtail,jnns/wagtail,m-sanders/wagtail,torchbox/wagtail,rsalmaso/wagtail,Pennebaker/wagtail,timorieber/wagtail,mayapurmedia/wagtail,rjsproxy/wagtail,iho/wagtail,inonit/wagtail,gogobook/wagtail,nilnvoid/wagtail,mikedingjan/wagtail,torchbox/wagtail,mayapurmedia/wagtail,davecranwell/wagtail,mephizzle/wagtail,jnns/wagtail,nilnvoid/wagtail,hanpama/wagtail,quru/wagtail,iho/wagtail,nutztherookie/wagtail,iho/wagtail,taedori81/wagtail,marctc/wagtail,mixxorz/wagtail,iansprice/wagtail,bjesus/wagtail,chrxr/wagtail,bjesus/wagtail,hamsterbacke23/wagtail,JoshBarr/wagtail,iansprice/wagtail,FlipperPA/wagtail,marctc/wagtail,zerolab/wagtail,serzans/wagtail,stevenewey/wagtail,kurtw/wagtail,takeflight/wagtail,quru/wagtail,rsalmaso/wagtail,Klaudit/wagtail,jordij/wagtail,darith27/wagtail,taedori81/wagtail,davecranwell/wagtail,davecranwell/wagtail,rjsproxy/wagtail,gogobook/wagtail,mephizzle/wagtail,davecranwell/wagtail,inonit/wagtail,timorieber/wagtail,nealtodd/wagtail,KimGlazebrook/wagtail-experiment,gasman/wagtail,kurtrwall/wagtail,rjsproxy/wagtail,gogobook/wagtail,marctc/wagtail,serzans/wagtail,rv816/wagtail,nilnvoid/wagtail,kurtrwall/wagtail,zerolab/wagtail,mixxorz/wagtail,m-sanders/wagtail,Pennebaker/wagtail,FlipperPA/wagtail,jnns/wagtail,kaedroho/wagtail,zerolab/wagtail,nimasmi/wagtail,hanpama/wagtail,mixxorz/wagtail,wagtail/wagtail,wagtail/wagtail,nutztherookie/wagtail,m-sanders/wagtail,mjec/wagtail,inonit/wagtail,jordij/wagtail,gasman/wagtail,wagtail/wagtail,gasman/wagtail,Toshakins/wagtail,takeflight/wagtail,mixxorz/wagtail,nutztherookie/wagtail,Toshakins/wagtail,mephizzle/wagtail,rsalmaso/wagtail,hanpama/wagtail,rsalmaso/wagtail,taedori81/wagtail,Klaudit/wagtail,JoshBarr/wagtail,Tivix/wagtail,iansprice/wagtail,darith27/wagtail,timorieber/wagtail,taedori81/wagtail,torchbox/wagtail,jordij/wagtail,kaedroho/wagtail,inonit/wagtail,nimasmi/wagtail,stevenewey/wagtail,darith27/wagtail,quru/wagtail,hanpama/wagtail,mephizzle/wagtail,nealtodd/wagtail,KimGlazebrook/wagtail-experiment,KimGlazebrook/wagtail-experiment,nrsimha/wagtail,Klaudit/wagtail,Toshakins/wagtail,KimGlazebrook/wagtail-experiment,nrsimha/wagtail,zerolab/wagtail,kurtw/wagtail,mjec/wagtail,chrxr/wagtail,mjec/wagtail,thenewguy/wagtail,iansprice/wagtail,gasman/wagtail,m-sanders/wagtail,Pennebaker/wagtail,takeshineshiro/wagtail,kaedroho/wagtail,rv816/wagtail,kurtw/wagtail,Pennebaker/wagtail,JoshBarr/wagtail,wagtail/wagtail,janusnic/wagtail,kurtrwall/wagtail,zerolab/wagtail,janusnic/wagtail,takeflight/wagtail,WQuanfeng/wagtail,kaedroho/wagtail,hamsterbacke23/wagtail,serzans/wagtail,thenewguy/wagtail,mikedingjan/wagtail,Tivix/wagtail,WQuanfeng/wagtail | ---
+++
@@ -8,14 +8,12 @@
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
- @property
- def subpage_urls(self):
- return (
- url(r'^$', self.main, name='main'),
- url(r'^archive/year/(\d+)/$', self.archive_by_year, name='archive_by_year'),
- url(r'^archive/author/(?P<author_slug>.+)/$', self.archive_by_author, name='archive_by_author'),
- url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
- )
+ subpage_urls = (
+ url(r'^$', 'main', name='main'),
+ url(r'^archive/year/(\d+)/$', 'archive_by_year', name='archive_by_year'),
+ url(r'^archive/author/(?P<author_slug>.+)/$', 'archive_by_author', name='archive_by_author'),
+ url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
+ )
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year)) |
758621d6b44ea546d96d631417088ef3eaed08a6 | tvnamer/unicode_helper.py | tvnamer/unicode_helper.py | #!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvnamer
#repository:http://github.com/dbr/tvnamer
#license:Creative Commons GNU GPL v2
# http://creativecommons.org/licenses/GPL/2.0/
"""Helpers to deal with strings, unicode objects and terminal output
"""
import sys
def unicodify(obj, encoding = "utf-8"):
if isinstance(obj, basestring):
if not isinstance(obj, unicode):
object = unicode(obj, encoding)
return obj
def p(*args, **kw):
"""Rough implementation of the Python 3 print function,
http://www.python.org/dev/peps/pep-3105/
def print(*args, sep=' ', end='\n', file=None)
"""
kw.setdefault('encoding', 'utf-8')
kw.setdefault('sep', ' ')
kw.setdefault('end', '\n')
kw.setdefault('file', sys.stdout)
new_args = []
for x in args:
if not isinstance(x, basestring):
new_args.append(repr(x))
else:
new_args.append(x)
out = kw['sep'].join(x.encode(kw['encoding']) for x in new_args)
kw['file'].write(out + kw['end'])
| #!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvnamer
#repository:http://github.com/dbr/tvnamer
#license:Creative Commons GNU GPL v2
# http://creativecommons.org/licenses/GPL/2.0/
"""Helpers to deal with strings, unicode objects and terminal output
"""
import sys
def unicodify(obj, encoding = "utf-8"):
if isinstance(obj, basestring):
if not isinstance(obj, unicode):
object = unicode(obj, encoding)
return obj
def p(*args, **kw):
"""Rough implementation of the Python 3 print function,
http://www.python.org/dev/peps/pep-3105/
def print(*args, sep=' ', end='\n', file=None)
"""
kw.setdefault('encoding', 'utf-8')
kw.setdefault('sep', ' ')
kw.setdefault('end', '\n')
kw.setdefault('file', sys.stdout)
new_args = []
for x in args:
if not isinstance(x, basestring):
new_args.append(repr(x))
else:
if kw['encoding'] is not None:
new_args.append(x.encode(kw['encoding']))
else:
new_args.append(x)
out = kw['sep'].join(new_args)
kw['file'].write(out + kw['end'])
| Support "encoding = None" argument | Support "encoding = None" argument | Python | unlicense | lahwaacz/tvnamer,dbr/tvnamer,m42e/tvnamer | ---
+++
@@ -36,8 +36,11 @@
if not isinstance(x, basestring):
new_args.append(repr(x))
else:
- new_args.append(x)
+ if kw['encoding'] is not None:
+ new_args.append(x.encode(kw['encoding']))
+ else:
+ new_args.append(x)
- out = kw['sep'].join(x.encode(kw['encoding']) for x in new_args)
+ out = kw['sep'].join(new_args)
kw['file'].write(out + kw['end']) |
5510f0990712381391dbffc38ae1bc796e2babf0 | txircd/modules/umode_i.py | txircd/modules/umode_i.py | from txircd.modbase import Mode
class InvisibleMode(Mode):
def namesListEntry(self, recipient, channel, user, representation):
if channel.name not in recipient.channels and "i" in user.mode:
return ""
return representation
def checkWhoVisible(self, user, targetUser, filters, fields, channel, udata):
destination = udata["dest"]
if destination[0] == "#":
if destination not in user.channels and "i" in targetUser.mode:
return {}
if "i" in targetUser.mode:
share_channel = False
for chan in user.channels:
if chan in targetUser.channels:
share_channel = True
break
if not share_channel:
return {}
return udata
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.invisible_mode = None
def spawn(self):
self.invisible_mode = InvisibleMode()
return {
"modes": {
"uni": self.invisible_mode
},
"actions": {
"wholinemodify": [self.invisible_mode.checkWhoVisible]
}
}
def cleanup(self):
self.ircd.removeMode("uni")
self.ircd.actions["wholinemodify"].remove(self.invisible_mode.checkWhoVisible) | from txircd.modbase import Mode
class InvisibleMode(Mode):
def namesListEntry(self, recipient, channel, user, representation):
if channel.name not in recipient.channels and "i" in user.mode:
return ""
return representation
def checkWhoVisible(self, user, targetUser, filters, fields, channel, udata):
if channel:
if channel.name not in user.channels and "i" in targetUser.mode:
return {}
if "i" in targetUser.mode:
share_channel = False
for chan in user.channels:
if chan in targetUser.channels:
share_channel = True
break
if not share_channel:
return {}
return udata
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.invisible_mode = None
def spawn(self):
self.invisible_mode = InvisibleMode()
return {
"modes": {
"uni": self.invisible_mode
},
"actions": {
"wholinemodify": [self.invisible_mode.checkWhoVisible]
}
}
def cleanup(self):
self.ircd.removeMode("uni")
self.ircd.actions["wholinemodify"].remove(self.invisible_mode.checkWhoVisible) | Make the usermode +i check for WHO slightly neater. | Make the usermode +i check for WHO slightly neater.
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd | ---
+++
@@ -7,9 +7,8 @@
return representation
def checkWhoVisible(self, user, targetUser, filters, fields, channel, udata):
- destination = udata["dest"]
- if destination[0] == "#":
- if destination not in user.channels and "i" in targetUser.mode:
+ if channel:
+ if channel.name not in user.channels and "i" in targetUser.mode:
return {}
if "i" in targetUser.mode:
share_channel = False |
cc006a07a486ec6c88cd2b4deb929a3c723c5a2c | cupyx/fallback_mode/__init__.py | cupyx/fallback_mode/__init__.py | # Attributes and Methods for fallback_mode
# Auto-execute numpy method when corresponding cupy method is not found
# "NOQA" to suppress flake8 warning
from cupyx.fallback_mode.fallback import numpy # NOQA
| from cupy import util as _util
# Attributes and Methods for fallback_mode
# Auto-execute numpy method when corresponding cupy method is not found
# "NOQA" to suppress flake8 warning
from cupyx.fallback_mode.fallback import numpy # NOQA
_util.experimental('cupyx.fallback_mode.numpy')
| Support fallback-mode as an experimental feature | Support fallback-mode as an experimental feature
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | ---
+++
@@ -1,5 +1,10 @@
+from cupy import util as _util
+
# Attributes and Methods for fallback_mode
# Auto-execute numpy method when corresponding cupy method is not found
# "NOQA" to suppress flake8 warning
from cupyx.fallback_mode.fallback import numpy # NOQA
+
+
+_util.experimental('cupyx.fallback_mode.numpy') |
ec410ee0d8d51f2c12b4e8d52369956d6e846662 | src/puzzle/problems/anagram_problem.py | src/puzzle/problems/anagram_problem.py | import collections
from data import warehouse
from puzzle.heuristics import analyze_word
from puzzle.problems import problem
class AnagramProblem(problem.Problem):
@staticmethod
def score(lines):
# TODO: Support more input.
if len(lines) > 1:
return 0
return analyze_word.score_anagram(lines[0])
def _solve(self):
index = warehouse.get('/words/unigram/anagram_index')
if self.lines[0] not in index:
return {}
results = collections.OrderedDict()
for index, word in enumerate(index[self.lines[0]]):
# TODO: Use frequency for score.
results[word] = 1 / (index + 1)
return results
| import collections
from data import warehouse
from puzzle.heuristics import analyze_word
from puzzle.problems import problem
class AnagramProblem(problem.Problem):
@staticmethod
def score(lines):
if len(lines) > 1:
return 0
return analyze_word.score_anagram(lines[0])
def _solve(self):
index = warehouse.get('/words/unigram/anagram_index')
if self.lines[0] not in index:
return {}
results = collections.OrderedDict()
for index, word in enumerate(index[self.lines[0]]):
results[word] = 1 / (index + 1)
return results
| Delete some TODOs of little value. | TODOs: Delete some TODOs of little value.
| Python | mit | PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge | ---
+++
@@ -9,7 +9,6 @@
@staticmethod
def score(lines):
- # TODO: Support more input.
if len(lines) > 1:
return 0
return analyze_word.score_anagram(lines[0])
@@ -20,6 +19,5 @@
return {}
results = collections.OrderedDict()
for index, word in enumerate(index[self.lines[0]]):
- # TODO: Use frequency for score.
results[word] = 1 / (index + 1)
return results |
29ef482dc43b2f4927a02b13adf9b24402ddb949 | test_project/adam.py | test_project/adam.py | # A set of function which exercise specific mutation operators. This
# is paired up with a test suite. The idea is that cosmic-ray should
# kill every mutant when that suite is run; if it doesn't, then we've
# got a problem.
def constant_number():
return 42
def constant_true():
return True
def constant_false():
return False
def unary_sub():
return -1
def unary_add():
return +1
def equals(vals):
def constraint(x, y):
return (x == y) ^ (x != y)
return all([constraint(x, y)
for x in vals
for y in vals])
def use_break(limit):
for x in range(limit):
break
return x
def use_continue(limit):
for x in range(limit):
continue
return x
def trigger_infinite_loop():
# When `break` becomes `continue`, this should enter an infinite loop. This
# helps us test timeouts.
while True:
break
| # A set of function which exercise specific mutation operators. This
# is paired up with a test suite. The idea is that cosmic-ray should
# kill every mutant when that suite is run; if it doesn't, then we've
# got a problem.
def constant_number():
return 42
def constant_true():
return True
def constant_false():
return False
def unary_sub():
return -1
def unary_add():
return +1
def equals(vals):
def constraint(x, y):
return (x == y) ^ (x != y)
return all([constraint(x, y)
for x in vals
for y in vals])
def use_break(limit):
for x in range(limit):
break
return x
def use_continue(limit):
for x in range(limit):
continue
return x
def trigger_infinite_loop():
# When `break` becomes `continue`, this should enter an infinite loop. This
# helps us test timeouts.
# Any object which isn't None passes the truth value testing so here
# we use `while object()` instead of `while True` b/c the later becomes
# `while False` when BooleanReplacer is applied and we don't trigger an
# infinite loop.
while object():
break
| Modify the infinite loop function | Modify the infinite loop function
Don't use `while True` b/c BooleanReplacer breaks this function's
test. This is a bit ugly but until Issue #97 is fixed there is
no other way around it.
| Python | mit | sixty-north/cosmic-ray | ---
+++
@@ -47,5 +47,9 @@
def trigger_infinite_loop():
# When `break` becomes `continue`, this should enter an infinite loop. This
# helps us test timeouts.
- while True:
+ # Any object which isn't None passes the truth value testing so here
+ # we use `while object()` instead of `while True` b/c the later becomes
+ # `while False` when BooleanReplacer is applied and we don't trigger an
+ # infinite loop.
+ while object():
break |
9145bf291ffbe1ec43345aff53ac17ad5de38e4e | IPython/html/widgets/widget_image.py | IPython/html/widgets/widget_image.py | """ButtonWidget class.
Represents a button in the frontend using a widget. Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import base64
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Bytes
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ImageWidget(DOMWidget):
view_name = Unicode('ImageView', sync=True)
# Define the custom state properties to sync with the front-end
format = Unicode('png', sync=True)
width = Unicode(sync=True) # TODO: C unicode
height = Unicode(sync=True)
_b64value = Unicode(sync=True)
value = Bytes()
def _value_changed(self, name, old, new):
self._b64value = base64.b64encode(new) | """ButtonWidget class.
Represents a button in the frontend using a widget. Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import base64
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, CUnicode, Bytes
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ImageWidget(DOMWidget):
view_name = Unicode('ImageView', sync=True)
# Define the custom state properties to sync with the front-end
format = Unicode('png', sync=True)
width = CUnicode(sync=True)
height = CUnicode(sync=True)
_b64value = Unicode(sync=True)
value = Bytes()
def _value_changed(self, name, old, new):
self._b64value = base64.b64encode(new) | Use CUnicode for width and height in ImageWidget | Use CUnicode for width and height in ImageWidget
| Python | bsd-3-clause | jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets | ---
+++
@@ -17,7 +17,7 @@
import base64
from .widget import DOMWidget
-from IPython.utils.traitlets import Unicode, Bytes
+from IPython.utils.traitlets import Unicode, CUnicode, Bytes
#-----------------------------------------------------------------------------
# Classes
@@ -27,8 +27,8 @@
# Define the custom state properties to sync with the front-end
format = Unicode('png', sync=True)
- width = Unicode(sync=True) # TODO: C unicode
- height = Unicode(sync=True)
+ width = CUnicode(sync=True)
+ height = CUnicode(sync=True)
_b64value = Unicode(sync=True)
value = Bytes() |
7c1612d954c38ea86d2dff91537a4103f15cc0cb | statsmodels/tsa/api.py | statsmodels/tsa/api.py | from .ar_model import AR
from .arima_model import ARMA, ARIMA
import vector_ar as var
from .vector_ar.var_model import VAR
from .vector_ar.svar_model import SVAR
from .vector_ar.dynamic import DynamicVAR
import filters
import tsatools
from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag)
import interp
import stattools
from .stattools import (adfuller, acovf, q_stat, acf, pacf_yw, pacf_ols, pacf,
ccovf, ccf, periodogram, grangercausalitytests)
from .base import datetools
| from .ar_model import AR
from .arima_model import ARMA, ARIMA
import vector_ar as var
from .vector_ar.var_model import VAR
from .vector_ar.svar_model import SVAR
from .vector_ar.dynamic import DynamicVAR
import filters
import tsatools
from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag)
import interp
import stattools
from .stattools import *
from .base import datetools
| Use import * since __all__ is defined. | REF: Use import * since __all__ is defined.
| Python | bsd-3-clause | josef-pkt/statsmodels,bert9bert/statsmodels,ChadFulton/statsmodels,statsmodels/statsmodels,musically-ut/statsmodels,wwf5067/statsmodels,DonBeo/statsmodels,huongttlan/statsmodels,astocko/statsmodels,jstoxrocky/statsmodels,bashtage/statsmodels,wkfwkf/statsmodels,Averroes/statsmodels,bashtage/statsmodels,nvoron23/statsmodels,huongttlan/statsmodels,bert9bert/statsmodels,yl565/statsmodels,waynenilsen/statsmodels,josef-pkt/statsmodels,DonBeo/statsmodels,nguyentu1602/statsmodels,wdurhamh/statsmodels,bert9bert/statsmodels,kiyoto/statsmodels,bzero/statsmodels,bashtage/statsmodels,wwf5067/statsmodels,alekz112/statsmodels,rgommers/statsmodels,statsmodels/statsmodels,saketkc/statsmodels,YihaoLu/statsmodels,wkfwkf/statsmodels,wkfwkf/statsmodels,huongttlan/statsmodels,yl565/statsmodels,wzbozon/statsmodels,josef-pkt/statsmodels,bert9bert/statsmodels,phobson/statsmodels,bashtage/statsmodels,phobson/statsmodels,jseabold/statsmodels,wzbozon/statsmodels,bzero/statsmodels,detrout/debian-statsmodels,waynenilsen/statsmodels,rgommers/statsmodels,yl565/statsmodels,cbmoore/statsmodels,Averroes/statsmodels,cbmoore/statsmodels,saketkc/statsmodels,saketkc/statsmodels,alekz112/statsmodels,huongttlan/statsmodels,astocko/statsmodels,josef-pkt/statsmodels,gef756/statsmodels,waynenilsen/statsmodels,bsipocz/statsmodels,phobson/statsmodels,detrout/debian-statsmodels,edhuckle/statsmodels,adammenges/statsmodels,nvoron23/statsmodels,waynenilsen/statsmodels,nvoron23/statsmodels,phobson/statsmodels,jstoxrocky/statsmodels,edhuckle/statsmodels,rgommers/statsmodels,cbmoore/statsmodels,jseabold/statsmodels,ChadFulton/statsmodels,ChadFulton/statsmodels,bsipocz/statsmodels,detrout/debian-statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,nguyentu1602/statsmodels,DonBeo/statsmodels,detrout/debian-statsmodels,bert9bert/statsmodels,bsipocz/statsmodels,gef756/statsmodels,statsmodels/statsmodels,yl565/statsmodels,nguyentu1602/statsmodels,DonBeo/statsmodels,kiyoto/statsmodels,wdurhamh/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,astocko/statsmodels,saketkc/statsmodels,hlin117/statsmodels,hainm/statsmodels,bzero/statsmodels,wwf5067/statsmodels,wzbozon/statsmodels,phobson/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,rgommers/statsmodels,Averroes/statsmodels,alekz112/statsmodels,Averroes/statsmodels,kiyoto/statsmodels,adammenges/statsmodels,wzbozon/statsmodels,gef756/statsmodels,jstoxrocky/statsmodels,edhuckle/statsmodels,wwf5067/statsmodels,hlin117/statsmodels,wkfwkf/statsmodels,hlin117/statsmodels,adammenges/statsmodels,DonBeo/statsmodels,nvoron23/statsmodels,bzero/statsmodels,nvoron23/statsmodels,kiyoto/statsmodels,wkfwkf/statsmodels,musically-ut/statsmodels,gef756/statsmodels,rgommers/statsmodels,musically-ut/statsmodels,jseabold/statsmodels,cbmoore/statsmodels,nguyentu1602/statsmodels,YihaoLu/statsmodels,hainm/statsmodels,hlin117/statsmodels,ChadFulton/statsmodels,bzero/statsmodels,josef-pkt/statsmodels,astocko/statsmodels,alekz112/statsmodels,YihaoLu/statsmodels,wdurhamh/statsmodels,wdurhamh/statsmodels,kiyoto/statsmodels,musically-ut/statsmodels,ChadFulton/statsmodels,gef756/statsmodels,jstoxrocky/statsmodels,YihaoLu/statsmodels,hainm/statsmodels,bsipocz/statsmodels,hainm/statsmodels,ChadFulton/statsmodels,jseabold/statsmodels,jseabold/statsmodels,wdurhamh/statsmodels,YihaoLu/statsmodels,saketkc/statsmodels,bashtage/statsmodels,yl565/statsmodels,adammenges/statsmodels,edhuckle/statsmodels,wzbozon/statsmodels | ---
+++
@@ -9,6 +9,5 @@
from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag)
import interp
import stattools
-from .stattools import (adfuller, acovf, q_stat, acf, pacf_yw, pacf_ols, pacf,
- ccovf, ccf, periodogram, grangercausalitytests)
+from .stattools import *
from .base import datetools |
43b5da74b17e313115e0576dbae2dd0e869b88af | course_discovery/apps/publisher/api/permissions.py | course_discovery/apps/publisher/api/permissions.py | from rest_framework.permissions import BasePermission
from course_discovery.apps.publisher.mixins import check_course_organization_permission, check_roles_access
from course_discovery.apps.publisher.models import OrganizationExtension
from course_discovery.apps.publisher.utils import is_internal_user, is_publisher_user
class CanViewAssociatedCourse(BasePermission):
""" Permission class to check user can view a publisher course or also if
user has view permission on organization.
"""
def has_object_permission(self, request, view, obj):
user = request.user
return (
check_roles_access(user) or
check_course_organization_permission(user, obj.course, OrganizationExtension.VIEW_COURSE)
)
class InternalUserPermission(BasePermission):
""" Permission class to check user is an internal user. """
def has_object_permission(self, request, view, obj):
return is_internal_user(request.user)
class PublisherUserPermission(BasePermission):
""" Permission class to check user is a publisher user. """
def has_object_permission(self, request, view, obj):
return is_publisher_user(request.user)
def has_permission(self, request, view):
return is_publisher_user(request.user)
| from rest_framework.permissions import BasePermission
from course_discovery.apps.publisher.mixins import check_course_organization_permission, check_roles_access
from course_discovery.apps.publisher.models import OrganizationExtension
from course_discovery.apps.publisher.utils import is_internal_user, is_publisher_user
class CanViewAssociatedCourse(BasePermission):
""" Permission class to check user can view a publisher course or also if
user has view permission on organization.
"""
def has_object_permission(self, request, view, obj):
user = request.user
return (
check_roles_access(user) or
check_course_organization_permission(user, obj.course, OrganizationExtension.VIEW_COURSE)
)
class InternalUserPermission(BasePermission):
""" Permission class to check user is an internal user. """
def has_object_permission(self, request, view, obj):
return request.user.is_staff or is_internal_user(request.user)
class PublisherUserPermission(BasePermission):
""" Permission class to check user is a publisher user. """
def has_object_permission(self, request, view, obj):
return request.user.is_staff or is_publisher_user(request.user)
def has_permission(self, request, view):
return request.user.is_staff or is_publisher_user(request.user)
| Allow staff access to Publisher APIs | Allow staff access to Publisher APIs
A few Publisher APIs were marked as only allowing publisher users.
We should also let staff in.
DISCO-1365
| Python | agpl-3.0 | edx/course-discovery,edx/course-discovery,edx/course-discovery,edx/course-discovery | ---
+++
@@ -22,14 +22,14 @@
""" Permission class to check user is an internal user. """
def has_object_permission(self, request, view, obj):
- return is_internal_user(request.user)
+ return request.user.is_staff or is_internal_user(request.user)
class PublisherUserPermission(BasePermission):
""" Permission class to check user is a publisher user. """
def has_object_permission(self, request, view, obj):
- return is_publisher_user(request.user)
+ return request.user.is_staff or is_publisher_user(request.user)
def has_permission(self, request, view):
- return is_publisher_user(request.user)
+ return request.user.is_staff or is_publisher_user(request.user) |
07710f97883452cbe472ae9735700773aa59f492 | falmer/content/models/selection_grid.py | falmer/content/models/selection_grid.py | from wagtail.core import blocks
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList
from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock
from falmer.content.models.core import Page
class GridItem(blocks.StructBlock):
title = blocks.CharBlock(required=True)
link = blocks.URLBlock()
image = FalmerImageChooserBlock()
class Meta:
icon = 'item'
class SelectionGridPage(Page):
parent_page_types = []
body = StreamField([
('heading_hero', HeroImageBlock()),
('selection_grid', blocks.ListBlock(GridItem)),
])
content_panels = Page.content_panels + [
StreamFieldPanel('body'),
]
edit_handler = TabbedInterface([
ObjectList(content_panels, heading='Content'),
ObjectList(Page.promote_panels, heading='Promote'),
ObjectList(Page.settings_panels, heading='Settings', classname="settings"),
])
type_fields = (
'body',
)
| from wagtail.core import blocks
from wagtail.core.blocks import RichTextBlock
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList
from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock
from falmer.content.models.core import Page
class GridItem(blocks.StructBlock):
title = blocks.CharBlock(required=True)
link = blocks.URLBlock()
image = FalmerImageChooserBlock()
description = RichTextBlock(required=False)
class Meta:
icon = 'item'
class SelectionGridPage(Page):
body = StreamField([
('heading_hero', HeroImageBlock()),
('selection_grid', blocks.ListBlock(GridItem)),
])
content_panels = Page.content_panels + [
StreamFieldPanel('body'),
]
edit_handler = TabbedInterface([
ObjectList(content_panels, heading='Content'),
ObjectList(Page.promote_panels, heading='Promote'),
ObjectList(Page.settings_panels, heading='Settings', classname="settings"),
])
type_fields = (
'body',
)
| Add description to selectiongrid items | Add description to selectiongrid items
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer | ---
+++
@@ -1,4 +1,5 @@
from wagtail.core import blocks
+from wagtail.core.blocks import RichTextBlock
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList
@@ -10,14 +11,13 @@
title = blocks.CharBlock(required=True)
link = blocks.URLBlock()
image = FalmerImageChooserBlock()
+ description = RichTextBlock(required=False)
class Meta:
icon = 'item'
class SelectionGridPage(Page):
- parent_page_types = []
-
body = StreamField([
('heading_hero', HeroImageBlock()),
('selection_grid', blocks.ListBlock(GridItem)), |
a71ebcb1f2a855be0c5675c38a275a0835887c88 | examples/tutorial_pandas.py | examples/tutorial_pandas.py | import argparse
import pandas as pd
from influxdb import DataFrameClient
def main(host='localhost', port=8086):
user = 'root'
password = 'root'
dbname = 'example'
client = DataFrameClient(host, port, user, password, dbname)
print("Create pandas DataFrame")
df = pd.DataFrame(data=list(range(30)),
index=pd.date_range(start='2014-11-16',
periods=30, freq='H'))
print("Create database: " + dbname)
client.create_database(dbname)
print("Write DataFrame")
client.write_points(df, 'demo')
print("Write DataFrame with Tags")
client.write_points(df, 'demo', {'k1': 'v1', 'k2': 'v2'})
print("Read DataFrame")
client.query("select * from demo")
print("Delete database: " + dbname)
client.delete_database(dbname)
def parse_args():
parser = argparse.ArgumentParser(
description='example code to play with InfluxDB')
parser.add_argument('--host', type=str, required=False,
default='localhost',
help='hostname of InfluxDB http API')
parser.add_argument('--port', type=int, required=False, default=8086,
help='port of InfluxDB http API')
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
main(host=args.host, port=args.port)
| import argparse
import pandas as pd
from influxdb import DataFrameClient
def main(host='localhost', port=8086):
user = 'root'
password = 'root'
dbname = 'example'
client = DataFrameClient(host, port, user, password, dbname)
print("Create pandas DataFrame")
df = pd.DataFrame(data=list(range(30)),
index=pd.date_range(start='2014-11-16',
periods=30, freq='H'))
print("Create database: " + dbname)
client.create_database(dbname)
print("Write DataFrame")
client.write_points(df, 'demo')
print("Write DataFrame with Tags")
client.write_points(df, 'demo', {'k1': 'v1', 'k2': 'v2'})
print("Read DataFrame")
client.query("select * from demo")
print("Delete database: " + dbname)
client.drop_database(dbname)
def parse_args():
parser = argparse.ArgumentParser(
description='example code to play with InfluxDB')
parser.add_argument('--host', type=str, required=False,
default='localhost',
help='hostname of InfluxDB http API')
parser.add_argument('--port', type=int, required=False, default=8086,
help='port of InfluxDB http API')
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
main(host=args.host, port=args.port)
| Fix method name in example | Fix method name in example | Python | mit | BenHewins/influxdb-python,influxdata/influxdb-python,influxdb/influxdb-python,influxdb/influxdb-python,omki2005/influxdb-python,omki2005/influxdb-python,BenHewins/influxdb-python,influxdata/influxdb-python,tzonghao/influxdb-python,tzonghao/influxdb-python | ---
+++
@@ -29,7 +29,7 @@
client.query("select * from demo")
print("Delete database: " + dbname)
- client.delete_database(dbname)
+ client.drop_database(dbname)
def parse_args(): |
04bfb5cf06cf70754e10e4a9a02cdbdf830356cd | registration/__init__.py | registration/__init__.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.core.exceptions.ImproperlyConfigured`` if the specified
backend cannot be located.
"""
i = settings.REGISTRATION_BACKEND.rfind('.')
module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
| from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
# TODO: When Python 2.7 is released this becomes a try/except falling
# back to Django's implementation.
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.core.exceptions.ImproperlyConfigured`` if the specified
backend cannot be located.
"""
i = settings.REGISTRATION_BACKEND.rfind('.')
module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
| Add reminder to myself to to importlib fallback. | Add reminder to myself to to importlib fallback.
| Python | bsd-3-clause | remarkablerocket/django-mailinglist-registration,remarkablerocket/django-mailinglist-registration | ---
+++
@@ -1,5 +1,8 @@
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
+
+# TODO: When Python 2.7 is released this becomes a try/except falling
+# back to Django's implementation.
from django.utils.importlib import import_module
def get_backend(): |
a13dd09a1f205fbd5aa997c2efcd0fee401f91f0 | utils/utils_debug.py | utils/utils_debug.py | """Function for Debuging."""
import inspect
def pv(name):
# type: (str) -> str
"""Analysis an expresion 'expresion : evaulation'.
Used to help debuging values.
"""
frame = inspect.currentframe().f_back
val = eval(name, frame.f_globals, frame.f_locals)
return '{0}: {1}'.format(name, val)
| """Function for Debuging."""
import inspect
def pv(name):
# type: (str) -> str
"""Analysis an expresion 'expresion : evaulation'.
Used to help debuging values.
"""
if "__" in name:
raise ValueError("Double underscores not allowed for saftey reasons.")
frame = inspect.currentframe().f_back
val = eval(name, frame.f_globals, frame.f_locals)
return '{0}: {1}'.format(name, val)
| Disable dunder evaluation in debuging tool. | Disable dunder evaluation in debuging tool.
| Python | mit | iastro-pt/ObservationTools,DanielAndreasen/ObservationTools | ---
+++
@@ -8,6 +8,8 @@
Used to help debuging values.
"""
+ if "__" in name:
+ raise ValueError("Double underscores not allowed for saftey reasons.")
frame = inspect.currentframe().f_back
val = eval(name, frame.f_globals, frame.f_locals)
return '{0}: {1}'.format(name, val) |
f3508aa348aa6f560953cbf48c6671ccf8558410 | tests/test_forms.py | tests/test_forms.py |
from django.template.loader import get_template
from django.test import SimpleTestCase
from .utils import TemplateTestMixin
class TestFieldTag(TemplateTestMixin, SimpleTestCase):
TEMPLATES = {
'field': '{% load sniplates %}{% form_field form.field %}'
}
def test_field_tag(self):
'''
Make sure the field tag is usable.
'''
tmpl = get_template('field')
output = tmpl.render(self.ctx)
|
from django import forms
from django.template.loader import get_template
from django.test import SimpleTestCase
from .utils import TemplateTestMixin
class TestForm(forms.Form):
char = forms.CharField()
class TestFieldTag(TemplateTestMixin, SimpleTestCase):
TEMPLATES = {
'widgets': '''{% block CharField %}<input type="text" name="{{ name }}" value="{{ value|default:'' }}>{% endblock %}''',
'field': '{% load sniplates %}{% load_widgets form="widgets" %}{% form_field form.char %}'
}
def setUp(self):
super(TestFieldTag, self).setUp()
self.ctx['form'] = TestForm()
def test_field_tag(self):
'''
Make sure the field tag is usable.
'''
tmpl = get_template('field')
output = tmpl.render(self.ctx)
| Make first field test work | Make first field test work
| Python | mit | kezabelle/django-sniplates,funkybob/django-sniplates,funkybob/django-sniplates,sergei-maertens/django-sniplates,wengole/django-sniplates,sergei-maertens/django-sniplates,wengole/django-sniplates,kezabelle/django-sniplates,kezabelle/django-sniplates,sergei-maertens/django-sniplates | ---
+++
@@ -1,14 +1,23 @@
+from django import forms
from django.template.loader import get_template
from django.test import SimpleTestCase
from .utils import TemplateTestMixin
+class TestForm(forms.Form):
+ char = forms.CharField()
+
+
class TestFieldTag(TemplateTestMixin, SimpleTestCase):
TEMPLATES = {
- 'field': '{% load sniplates %}{% form_field form.field %}'
+ 'widgets': '''{% block CharField %}<input type="text" name="{{ name }}" value="{{ value|default:'' }}>{% endblock %}''',
+ 'field': '{% load sniplates %}{% load_widgets form="widgets" %}{% form_field form.char %}'
}
+ def setUp(self):
+ super(TestFieldTag, self).setUp()
+ self.ctx['form'] = TestForm()
def test_field_tag(self):
''' |
cebf3fa5cf428659960a547780e53a247a2322e8 | lib/custom_data/settings_manager.py | lib/custom_data/settings_manager.py | """This module provides functions for saving to and loading data from
the settings XML file.
Attributes:
SETTINGS_PATH (String): The file path for the settings file.
SETTINGS_SCHEMA_PATH (String): The file path for the settings'
XML Schema.
"""
from lib.custom_data.xml_ops import load_xml_doc_as_object
SETTINGS_PATH = 'settings.xml'
SETTINGS_SCHEMA_PATH = 'settings.xsd'
def load_settings():
"""Load all Settings data from the settings file and return it as a
SettingsData object.
Returns:
A SettingsData object, or None if errors were encountered while
reading the settings file.
"""
return load_xml_doc_as_object(SETTINGS_PATH, SETTINGS_SCHEMA_PATH)
| """This module provides functions for saving to and loading data from
the settings XML file.
Attributes:
SETTINGS_PATH (String): The file path for the settings file.
SETTINGS_SCHEMA_PATH (String): The file path for the settings'
XML Schema.
"""
from lib.custom_data.settings_data import SettingsData
from lib.custom_data.xml_ops import load_xml_doc_as_object
SETTINGS_PATH = 'settings.xml'
SETTINGS_SCHEMA_PATH = 'settings.xsd'
def load_settings():
"""Load all Settings data from the settings file and return it as a
SettingsData object.
If errors were encountered while reading the settings file, a
SettingsData object with default values is returned instead.
"""
settings = load_xml_doc_as_object(SETTINGS_PATH, SETTINGS_SCHEMA_PATH)
if settings is None:
return SettingsData()
else:
return settings
| Use default settings in case of file read errors | Use default settings in case of file read errors
| Python | unlicense | MarquisLP/Sidewalk-Champion | ---
+++
@@ -6,6 +6,7 @@
SETTINGS_SCHEMA_PATH (String): The file path for the settings'
XML Schema.
"""
+from lib.custom_data.settings_data import SettingsData
from lib.custom_data.xml_ops import load_xml_doc_as_object
@@ -17,8 +18,11 @@
"""Load all Settings data from the settings file and return it as a
SettingsData object.
- Returns:
- A SettingsData object, or None if errors were encountered while
- reading the settings file.
+ If errors were encountered while reading the settings file, a
+ SettingsData object with default values is returned instead.
"""
- return load_xml_doc_as_object(SETTINGS_PATH, SETTINGS_SCHEMA_PATH)
+ settings = load_xml_doc_as_object(SETTINGS_PATH, SETTINGS_SCHEMA_PATH)
+ if settings is None:
+ return SettingsData()
+ else:
+ return settings |
7015766b70bf56f9338713c4302aa3cba75510c5 | app/tests/test_views.py | app/tests/test_views.py | from django.test import TestCase
from django.core.urlresolvers import reverse
class IndexViewCase(TestCase):
"""Index view case"""
def setUp(self):
self.url = reverse('home')
def test_get_ok(self):
"""Test status=200"""
response = self.client.get(self.url)
self.assertEqual(response.status_code, 200)
| import sure
from django.test import TestCase
from django.core.urlresolvers import reverse
class IndexViewCase(TestCase):
"""Index view case"""
def setUp(self):
self.url = reverse('home')
def test_get_ok(self):
"""Test status=200"""
response = self.client.get(self.url)
response.status_code.should.be.equal(200)
| Use sure in app tests | Use sure in app tests
| Python | mit | nvbn/coviolations_web,nvbn/coviolations_web | ---
+++
@@ -1,3 +1,4 @@
+import sure
from django.test import TestCase
from django.core.urlresolvers import reverse
@@ -11,4 +12,4 @@
def test_get_ok(self):
"""Test status=200"""
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
+ response.status_code.should.be.equal(200) |
d8e054df4810ad2c32cd61c41391e0ee1b542a66 | ipython_widgets/__init__.py | ipython_widgets/__init__.py | from .widgets import *
# Register a comm target for Javascript initialized widgets..
from IPython import get_ipython
ip = get_ipython()
if ip is not None:
ip.kernel.comm_manager.register_target('ipython.widget', Widget.handle_comm_opened)
| from .widgets import *
# Register a comm target for Javascript initialized widgets..
from IPython import get_ipython
ip = get_ipython()
if ip is not None and hasattr(ip, 'kernel') and hasattr(ip.kernel, 'comm_manager'):
ip.kernel.comm_manager.register_target('ipython.widget', Widget.handle_comm_opened)
| Make it possible to import ipython_widgets without having a kernel or comm manager | Make it possible to import ipython_widgets without having a kernel or comm manager
| Python | bsd-3-clause | ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets | ---
+++
@@ -3,5 +3,5 @@
# Register a comm target for Javascript initialized widgets..
from IPython import get_ipython
ip = get_ipython()
-if ip is not None:
+if ip is not None and hasattr(ip, 'kernel') and hasattr(ip.kernel, 'comm_manager'):
ip.kernel.comm_manager.register_target('ipython.widget', Widget.handle_comm_opened) |
03491b6c11964f18f7c1867ef9f2612761a006ae | test/config/nsuserdefaults_config.py | test/config/nsuserdefaults_config.py | import unittest
if sys.platform.startswith('darwin'):
from nativeconfig.config import NSUserDefaultsConfig
from test.config import TestConfigMixin
class MyNSUserDefaultsConfig(NSUserDefaultsConfig):
pass
class TestMemoryConfig(unittest.TestCase, TestConfigMixin):
CONFIG_TYPE = MyNSUserDefaultsConfig
def tearDown(self):
try:
c = self.CONFIG_TYPE.get_instance()
c.del_value_for_option_name('FirstName')
c.del_value_for_option_name('LastName')
c.del_value_for_option_name('LuckyNumber')
except OSError:
pass
TestConfigMixin.tearDown(self)
def test_config_is_created_if_not_found(self):
pass
| import sys
import unittest
if sys.platform.startswith('darwin'):
from nativeconfig.config import NSUserDefaultsConfig
from test.config import TestConfigMixin
class MyNSUserDefaultsConfig(NSUserDefaultsConfig):
pass
class TestMemoryConfig(unittest.TestCase, TestConfigMixin):
CONFIG_TYPE = MyNSUserDefaultsConfig
def tearDown(self):
try:
c = self.CONFIG_TYPE.get_instance()
c.del_value_for_option_name('FirstName')
c.del_value_for_option_name('LastName')
c.del_value_for_option_name('LuckyNumber')
except OSError:
pass
TestConfigMixin.tearDown(self)
def test_config_is_created_if_not_found(self):
pass
| Add missing import of sys. | Add missing import of sys.
| Python | mit | GreatFruitOmsk/nativeconfig | ---
+++
@@ -1,3 +1,4 @@
+import sys
import unittest
if sys.platform.startswith('darwin'): |
66a7e939fece2e7ddeff7b0ac858459e93a6a3d6 | tests/interval_test.py | tests/interval_test.py | from timewreport.interval import TimeWarriorInterval
def test_interval_should_be_hashable():
a = TimeWarriorInterval("20180816T100209Z", "20180816T110209Z", [], None)
b = TimeWarriorInterval("20180816T090319Z", "20180816T100700Z", [], None)
set([a, b])
| from timewreport.interval import TimeWarriorInterval
def test_interval_should_be_hashable():
a = TimeWarriorInterval("20180816T100209Z", "20180816T110209Z", [], None)
b = TimeWarriorInterval("20180816T090319Z", "20180816T100700Z", [], None)
assert {a, b}
| Replace function call with set literal | Replace function call with set literal
- Add assert statement so we do not have a "statement with no effect"
| Python | mit | lauft/timew-report | ---
+++
@@ -5,4 +5,4 @@
a = TimeWarriorInterval("20180816T100209Z", "20180816T110209Z", [], None)
b = TimeWarriorInterval("20180816T090319Z", "20180816T100700Z", [], None)
- set([a, b])
+ assert {a, b} |
3f5a73f39451e73b2f32fe3a05888f118952e591 | ppp_datamodel/utils.py | ppp_datamodel/utils.py | """Utilities for using the PPP datamodel."""
from . import Resource, Triple, Missing, Intersection, List, Union, And, Or, Exists, First, Last, Sort
def contains_missing(tree):
def predicate(node, childs):
if isinstance(node, Missing):
return True
else:
return any(childs.values())
return tree.fold(predicate)
def isincluded(tree1,tree2):
"""
Return True if and only if tree1 is included in tree2.
"""
if isinstance(tree1,Resource):
tree1=List([tree1])
if isinstance(tree2,Resource):
tree2=List([tree2])
if type(tree1) != type(tree2):
return False
if isinstance(tree1,Missing):
return True
if isinstance(tree1,List):
return set(tree1.list).issubset(set(tree2.list))
if isinstance(tree1,Triple):
return isincluded(tree1.subject,tree2.subject) and\
isincluded(tree1.predicate,tree2.predicate) and\
isincluded(tree1.object,tree2.object)
if isinstance(tree1,Sort):
return tree1.predicate == tree2.predicate and isincluded(tree1.list,tree2.list)
return isincluded(tree1.list,tree2.list)
| """Utilities for using the PPP datamodel."""
from . import Resource, Triple, Missing, Intersection, List, Union, And, Or, Exists, First, Last, Sort
def contains_missing(tree):
def predicate(node, childs):
if isinstance(node, Missing):
return True
else:
return any(childs.values())
return tree.fold(predicate)
def isincluded(tree1,tree2):
"""
Return True if and only if tree1 is included in tree2.
"""
if isinstance(tree1,Resource):
tree1=List([tree1])
if isinstance(tree2,Resource):
tree2=List([tree2])
if type(tree1) != type(tree2):
return False
if isinstance(tree1,Missing):
return True
if isinstance(tree1,List):
return set(tree1.list).issubset(set(tree2.list))
if isinstance(tree1,Triple):
return isincluded(tree1.subject,tree2.subject) and\
isincluded(tree1.predicate,tree2.predicate) and\
isincluded(tree1.object,tree2.object)
if isinstance(tree1,Sort):
return tree1.predicate == tree2.predicate and isincluded(tree1.list,tree2.list)
if isinstance(tree1,First) or isinstance(tree1,Last) or isinstance(tree1,Exists):
return isincluded(tree1.list,tree2.list)
# Intersection, Union, And, Or
for elt in tree1.list:
if not any(isincluded(elt,x) for x in tree2.list):
return False
return True
| Fix isincluded for List operators. | Fix isincluded for List operators.
| Python | agpl-3.0 | ProjetPP/PPP-datamodel-Python,ProjetPP/PPP-datamodel-Python | ---
+++
@@ -30,4 +30,10 @@
isincluded(tree1.object,tree2.object)
if isinstance(tree1,Sort):
return tree1.predicate == tree2.predicate and isincluded(tree1.list,tree2.list)
- return isincluded(tree1.list,tree2.list)
+ if isinstance(tree1,First) or isinstance(tree1,Last) or isinstance(tree1,Exists):
+ return isincluded(tree1.list,tree2.list)
+ # Intersection, Union, And, Or
+ for elt in tree1.list:
+ if not any(isincluded(elt,x) for x in tree2.list):
+ return False
+ return True |
3a61d30972093d72e06d0c6bd760764d473b1dee | pygotham/frontend/speakers.py | pygotham/frontend/speakers.py | """PyGotha speakers."""
from flask import abort, Blueprint, g, render_template
from pygotham.frontend import route
from pygotham.models import User
__all__ = ('blueprint',)
blueprint = Blueprint(
'speakers',
__name__,
subdomain='<event_slug>',
url_prefix='/speakers',
)
@route(blueprint, '/profile/<int:pk>/')
def profile(pk):
"""Return the speaker profile view."""
if not g.current_event.talks_are_published:
abort(404)
# TODO: Filter by event.
user = User.query.get_or_404(pk)
if not user.has_accepted_talks:
abort(404)
return render_template('speakers/profile.html', user=user)
| """PyGotham speakers."""
from flask import abort, Blueprint, g, render_template
from pygotham.frontend import route
from pygotham.models import User
__all__ = ('blueprint',)
blueprint = Blueprint(
'speakers',
__name__,
subdomain='<event_slug>',
url_prefix='/speakers',
)
@route(blueprint, '/profile/<int:pk>/')
def profile(pk):
"""Return the speaker profile view."""
if not g.current_event.talks_are_published:
abort(404)
# TODO: Filter by event.
user = User.query.get_or_404(pk)
if not user.has_accepted_talks:
abort(404)
return render_template('speakers/profile.html', user=user)
| Fix a typo in a docstring | Fix a typo in a docstring
| Python | bsd-3-clause | pathunstrom/pygotham,PyGotham/pygotham,pathunstrom/pygotham,pathunstrom/pygotham,PyGotham/pygotham,PyGotham/pygotham,PyGotham/pygotham,pathunstrom/pygotham,PyGotham/pygotham,pathunstrom/pygotham | ---
+++
@@ -1,4 +1,4 @@
-"""PyGotha speakers."""
+"""PyGotham speakers."""
from flask import abort, Blueprint, g, render_template
|
c37cafb9c83e9f9bcc806cdb979f127fe924fa00 | tools/get_binary.py | tools/get_binary.py | #!/usr/bin/env python
import os
import sys
import shutil
from version import full_version
from optparse import OptionParser
import pkgutils
def main():
usage = "usage: %prog [destination path]"
parser = OptionParser(usage=usage)
(options, args) = parser.parse_args()
if len(args) != 1:
parser.print_usage()
sys.exit(1)
dest = args[0]
shutil.rmtree(dest, True)
os.mkdir(dest)
build_dir = pkgutils.package_builder_dir()
binary_name = pkgutils.package_binary()
binary = os.path.join(build_dir, binary_name)
dest = os.path.join(dest, '%s-monitoring-agent-%s' % (pkgutils.pkg_dir(),
full_version))
if pkgutils.pkg_type() == 'windows':
dest += '.msi'
print("Moving %s to %s" % (binary, dest))
shutil.move(binary, dest)
if pkgutils.pkg_type() != 'windows':
shutil.move(binary + ".sig", dest + ".sig")
if __name__ == "__main__":
main()
| #!/usr/bin/env python
import os
import sys
import shutil
from version import full_version
from optparse import OptionParser
import pkgutils
def main():
usage = "usage: %prog [destination path]"
parser = OptionParser(usage=usage)
(options, args) = parser.parse_args()
if len(args) != 1:
parser.print_usage()
sys.exit(1)
dest = args[0]
build_dir = pkgutils.package_builder_dir()
binary_name = pkgutils.package_binary()
binary = os.path.join(build_dir, binary_name)
dest = os.path.join(dest, '%s-monitoring-agent-%s' % (pkgutils.pkg_dir(),
full_version))
if pkgutils.pkg_type() == 'windows':
dest += '.msi'
print("Moving %s to %s" % (binary, dest))
shutil.move(binary, dest)
if pkgutils.pkg_type() != 'windows':
shutil.move(binary + ".sig", dest + ".sig")
if __name__ == "__main__":
main()
| Revert "remove the dest tree and recreate it" | Revert "remove the dest tree and recreate it"
This reverts commit becc4657acea505594836e62c49de2b4cb0160a9.
| Python | apache-2.0 | christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent | ---
+++
@@ -20,10 +20,6 @@
sys.exit(1)
dest = args[0]
-
- shutil.rmtree(dest, True)
- os.mkdir(dest)
-
build_dir = pkgutils.package_builder_dir()
binary_name = pkgutils.package_binary()
binary = os.path.join(build_dir, binary_name) |
db580bc3a433f15b31c21fbeac39fc2e40e85cdd | km3pipe/io/tests/test_ch.py | km3pipe/io/tests/test_ch.py | # Filename: test_ch.py
# pylint: disable=locally-disabled,C0111,R0904,C0301,C0103,W0212
from km3pipe.testing import TestCase, patch, Mock
from km3pipe.io.ch import CHPump
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2018, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "Development"
class TestCHPump(TestCase):
def test_init(self):
pass
| # Filename: test_ch.py
# pylint: disable=locally-disabled,C0111,R0904,C0301,C0103,W0212
from km3pipe.testing import TestCase, patch, Mock
from km3pipe.io.ch import CHPump
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2018, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "Development"
class TestCHPump(TestCase):
@patch("km3pipe.io.ch.CHPump._init_controlhost")
@patch("km3pipe.io.ch.CHPump._start_thread")
def test_init(self, init_controlhost_mock, start_thread_mock):
CHPump()
init_controlhost_mock.assert_called_once()
start_thread_mock.assert_called_once()
| Add a test for CHPump | Add a test for CHPump
| Python | mit | tamasgal/km3pipe,tamasgal/km3pipe | ---
+++
@@ -13,5 +13,9 @@
class TestCHPump(TestCase):
- def test_init(self):
- pass
+ @patch("km3pipe.io.ch.CHPump._init_controlhost")
+ @patch("km3pipe.io.ch.CHPump._start_thread")
+ def test_init(self, init_controlhost_mock, start_thread_mock):
+ CHPump()
+ init_controlhost_mock.assert_called_once()
+ start_thread_mock.assert_called_once() |
072944268a5932875532d53237f9fdfd26406c2d | thrive_refugee/urls.py | thrive_refugee/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'thrive_refugee.views.home', name='home'),
# url(r'^thrive_refugee/', include('thrive_refugee.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'thrive_refugee.views.home', name='home'),
# url(r'^thrive_refugee/', include('thrive_refugee.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', include(admin.site.urls)),
)
| Set root route to point to admin | Set root route to point to admin
| Python | mit | thrive-refugee/thrive-refugee,thrive-refugee/thrive-refugee,thrive-refugee/thrive-refugee | ---
+++
@@ -12,4 +12,5 @@
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
+ url(r'^$', include(admin.site.urls)),
) |
411b6548d2ccc49e323b34ce8ace79ba8d330229 | patches/sitecustomize.py | patches/sitecustomize.py | import os
kaggle_proxy_token = os.getenv("KAGGLE_DATA_PROXY_TOKEN")
bq_user_jwt = os.getenv("KAGGLE_BQ_USER_JWT")
if kaggle_proxy_token or bq_user_jwt:
from google.auth import credentials
from google.cloud import bigquery
from google.cloud.bigquery._http import Connection
from kaggle_gcp import PublicBigqueryClient
def monkeypatch_bq(bq_client, *args, **kwargs):
data_proxy_project = os.getenv("KAGGLE_DATA_PROXY_PROJECT")
specified_project = kwargs.get('project')
specified_credentials = kwargs.get('credentials')
if specified_project is None and specified_credentials is None:
print("Using Kaggle's public dataset BigQuery integration.")
return PublicBigqueryClient(*args, **kwargs)
else:
return bq_client(*args, **kwargs)
# Monkey patches BigQuery client creation to use proxy or user-connected GCP account.
# Deprecated in favor of Kaggle.DataProxyClient().
# TODO: Remove this once uses have migrated to that new interface.
bq_client = bigquery.Client
bigquery.Client = lambda *args, **kwargs: monkeypatch_bq(
bq_client, *args, **kwargs)
| import os
kaggle_proxy_token = os.getenv("KAGGLE_DATA_PROXY_TOKEN")
bq_user_jwt = os.getenv("KAGGLE_BQ_USER_JWT")
if kaggle_proxy_token or bq_user_jwt:
from google.auth import credentials
from google.cloud import bigquery
from google.cloud.bigquery._http import Connection
# TODO: Update this to the correct kaggle.gcp path once we no longer inject modules
# from the worker.
from kaggle_gcp import PublicBigqueryClient
def monkeypatch_bq(bq_client, *args, **kwargs):
data_proxy_project = os.getenv("KAGGLE_DATA_PROXY_PROJECT")
specified_project = kwargs.get('project')
specified_credentials = kwargs.get('credentials')
if specified_project is None and specified_credentials is None:
print("Using Kaggle's public dataset BigQuery integration.")
return PublicBigqueryClient(*args, **kwargs)
else:
return bq_client(*args, **kwargs)
# Monkey patches BigQuery client creation to use proxy or user-connected GCP account.
# Deprecated in favor of Kaggle.DataProxyClient().
# TODO: Remove this once uses have migrated to that new interface.
bq_client = bigquery.Client
bigquery.Client = lambda *args, **kwargs: monkeypatch_bq(
bq_client, *args, **kwargs)
| Add comment about kaggle_gcp module path. | Add comment about kaggle_gcp module path.
| Python | apache-2.0 | Kaggle/docker-python,Kaggle/docker-python | ---
+++
@@ -6,6 +6,8 @@
from google.auth import credentials
from google.cloud import bigquery
from google.cloud.bigquery._http import Connection
+ # TODO: Update this to the correct kaggle.gcp path once we no longer inject modules
+ # from the worker.
from kaggle_gcp import PublicBigqueryClient
def monkeypatch_bq(bq_client, *args, **kwargs): |
21424e243542a9e548a79bf28fbcfa31cc24b36f | angus/services/dummy.py | angus/services/dummy.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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.
import logging
import os
import angus.service
import angus.storage
PORT = os.environ.get('PORT', 9000)
LOGGER = logging.getLogger('dummy')
def compute(resource, data):
if 'echo' in data:
resource['echo'] = data['echo']
else:
resource['echo'] = "echo"
def main():
logging.basicConfig(level=logging.DEBUG)
service = angus.service.Service(
'dummy', 1,
PORT,
compute,
resource_storage=angus.storage.MemoryStorage, threads=1
)
service.start()
if __name__ == '__main__':
main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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.
import logging
import os
import angus.service
import angus.storage
PORT = os.environ.get('PORT', 9000)
LOGGER = logging.getLogger('dummy')
def compute(resource, data):
if 'echo' in data:
resource['echo'] = data['echo']
else:
resource['echo'] = "echo"
def main():
logging.basicConfig(level=logging.DEBUG)
service = angus.service.Service(
'dummy', 1,
PORT,
compute,
resource_storage=angus.storage.MemoryStorage(), threads=1
)
service.start()
if __name__ == '__main__':
main()
| Fix bug, use instance and not classes as storage | Fix bug, use instance and not classes as storage
| Python | apache-2.0 | angus-ai/angus-service-dummy,angus-ai/angus-service-dummy | ---
+++
@@ -43,7 +43,7 @@
'dummy', 1,
PORT,
compute,
- resource_storage=angus.storage.MemoryStorage, threads=1
+ resource_storage=angus.storage.MemoryStorage(), threads=1
)
service.start()
|
6ff07265feaf40e20fe0fbd23df2747660dd0483 | trex/serializers.py | trex/serializers.py | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from rest_framework.serializers import (
HyperlinkedModelSerializer, HyperlinkedIdentityField,
)
from trex.models.project import Project, Entry
class ProjectSerializer(HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ("url", "id", "name", "description", "active", "created")
class ProjectDetailSerializer(HyperlinkedModelSerializer):
entries = HyperlinkedIdentityField(view_name="project-entries-list")
class Meta:
model = Project
fields = ("id", "name", "description", "active", "created", "entries")
class EntryDetailSerializer(HyperlinkedModelSerializer):
class Meta:
model = Entry
fields = ("date", "duration", "description", "state", "user", "created")
| # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from rest_framework.serializers import (
HyperlinkedModelSerializer, HyperlinkedIdentityField,
)
from trex.models.project import Project, Entry
class ProjectSerializer(HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ("url", "id", "name", "description", "active", "created")
class ProjectDetailSerializer(HyperlinkedModelSerializer):
entries = HyperlinkedIdentityField(view_name="project-entries-list")
class Meta:
model = Project
fields = ("id", "name", "description", "active", "created", "entries")
class EntryDetailSerializer(HyperlinkedModelSerializer):
class Meta:
model = Entry
fields = ("url", "id", "date", "duration", "description", "state",
"user_abbr", "user", "created", "tags")
| Add url, id and trags to the EntriesSerializer | Add url, id and trags to the EntriesSerializer
| Python | mit | bjoernricks/trex,bjoernricks/trex | ---
+++
@@ -32,4 +32,5 @@
class Meta:
model = Entry
- fields = ("date", "duration", "description", "state", "user", "created")
+ fields = ("url", "id", "date", "duration", "description", "state",
+ "user_abbr", "user", "created", "tags") |
aac11d0d9805559000635b24227a8d13314feaa1 | booksforcha/booksforcha.py | booksforcha/booksforcha.py | # -*- coding: utf-8 -*-
import schedule
from feed import load_feed
from twitter import send_queued_tweet
import time
import os
RSS_FEED_LIST = os.environ['RSS_FEED_LIST']
LOAD_FEED_SECONDS = int(os.environ['LOAD_FEED_SECONDS'])
SEND_QUEUED_TWEET_SECONDS = int(os.environ['SEND_QUEUED_TWEET_SECONDS'])
def parse_feed_list(s):
parsed = s.split(',')
if parsed == ['']:
return []
else:
return parsed
def main():
rsslist = parse_feed_list(RSS_FEED_LIST)
schedule.every(LOAD_FEED_SECONDS).seconds.do(load_feed, rsslist)
schedule.every(SEND_QUEUED_TWEET_SECONDS).seconds.do(send_queued_tweet)
while True:
schedule.run_pending()
time.sleep(1)
def __main__():
main()
if __name__ == "__main__":
try:
__main__()
except (KeyboardInterrupt):
exit('Received Ctrl+C. Stopping application.', 1)
| # -*- coding: utf-8 -*-
import schedule
from feed import load_feed
from twitter import send_queued_tweet
import time
import os
RSS_FEED_LIST = os.environ['RSS_FEED_LIST']
LOAD_FEED_SECONDS = int(os.environ['LOAD_FEED_SECONDS'])
SEND_QUEUED_TWEET_SECONDS = int(os.environ['SEND_QUEUED_TWEET_SECONDS'])
def parse_feed_list(s):
parsed = s.split(',')
if parsed == ['']:
return []
else:
return parsed
schedule.every(LOAD_FEED_SECONDS).seconds.do(
load_feed, parse_feed_list(RSS_FEED_LIST))
schedule.every(SEND_QUEUED_TWEET_SECONDS).seconds.do(send_queued_tweet)
def main():
while True:
schedule.run_pending()
time.sleep(1)
def __main__():
main()
if __name__ == "__main__":
try:
__main__()
except (KeyboardInterrupt):
exit('Received Ctrl+C. Stopping application.', 1)
| Move process scheduling out of main. | Move process scheduling out of main.
| Python | mit | ChattanoogaPublicLibrary/booksforcha | ---
+++
@@ -20,12 +20,12 @@
else:
return parsed
+schedule.every(LOAD_FEED_SECONDS).seconds.do(
+ load_feed, parse_feed_list(RSS_FEED_LIST))
+schedule.every(SEND_QUEUED_TWEET_SECONDS).seconds.do(send_queued_tweet)
+
def main():
- rsslist = parse_feed_list(RSS_FEED_LIST)
- schedule.every(LOAD_FEED_SECONDS).seconds.do(load_feed, rsslist)
- schedule.every(SEND_QUEUED_TWEET_SECONDS).seconds.do(send_queued_tweet)
-
while True:
schedule.run_pending()
time.sleep(1) |
017b01a1df6e7095aac78d2c859125bf7107095a | plugins/random/plugin.py | plugins/random/plugin.py | import random
import re
from cardinal.decorators import command
def parse_roll(arg):
# some people might separate with commas
arg = arg.rstrip(',')
if match := re.match(r'^(\d+)?d(\d+)$', arg):
num_dice = match.group(1)
sides = match.group(2)
elif match := re.match(r'^d?(\d+)$', arg):
num_dice = 1
sides = match.group(1)
else:
return []
return [int(sides)] * int(num_dice)
class RandomPlugin:
@command('roll')
def roll(self, cardinal, user, channel, msg):
args = msg.split(' ')
args.pop(0)
dice = []
for arg in args:
dice = dice + parse_roll(arg)
results = []
limit = 10
for sides in dice:
if sides < 2 or sides > 120:
continue
limit -= 1
# Don't allow more than ten dice rolled at a time
if limit < 0:
break
results.append((sides, random.randint(1, sides)))
messages = ', '.join(
[f"d{sides}: {result}" for sides, result in results]
)
cardinal.sendMsg(channel, messages)
entrypoint = RandomPlugin
| import random
import re
from cardinal.decorators import command, help
def parse_roll(arg):
# some people might separate with commas
arg = arg.rstrip(',')
if match := re.match(r'^(\d+)?d(\d+)$', arg):
num_dice = match.group(1)
sides = match.group(2)
elif match := re.match(r'^d?(\d+)$', arg):
num_dice = 1
sides = match.group(1)
else:
return []
return [int(sides)] * int(num_dice)
class RandomPlugin:
@command('roll')
@help("Roll dice")
@help("Syntax: .roll #d# (e.g. .roll 2d6)")
def roll(self, cardinal, user, channel, msg):
args = msg.split(' ')
args.pop(0)
if not args:
return
dice = []
for arg in args:
dice = dice + parse_roll(arg)
results = []
limit = 10
for sides in dice:
if sides < 2 or sides > 120:
continue
limit -= 1
# Don't allow more than ten dice rolled at a time
if limit < 0:
break
results.append((sides, random.randint(1, sides)))
messages = ', '.join(
[f"d{sides}: {result}" for sides, result in results]
)
cardinal.sendMsg(channel, messages)
entrypoint = RandomPlugin
| Add help text for roll command | Add help text for roll command
| Python | mit | JohnMaguire/Cardinal | ---
+++
@@ -1,7 +1,7 @@
import random
import re
-from cardinal.decorators import command
+from cardinal.decorators import command, help
def parse_roll(arg):
@@ -22,9 +22,13 @@
class RandomPlugin:
@command('roll')
+ @help("Roll dice")
+ @help("Syntax: .roll #d# (e.g. .roll 2d6)")
def roll(self, cardinal, user, channel, msg):
args = msg.split(' ')
args.pop(0)
+ if not args:
+ return
dice = []
for arg in args: |
948e5b89db6056cd6a5065f8a5411113f6b320a7 | zc-list.py | zc-list.py | #!/usr/bin/env python
import client_wrap
def main():
client = client_wrap.ClientWrap("get_test.log", "ipc:///var/run/zero-cache/0", 0)
key_str = client.GetKeys()
keys = key_str.split (';')
del keys[-1]
if len(keys) == 0:
return
print keys
if __name__ == "__main__":
main()
| #!/usr/bin/env python
import sys
import client_wrap
def get_keys(client):
key_str = client.GetKeys()
keys = key_str.split (';')
del keys[-1]
if len(keys) == 0:
sys.exit()
return keys
def print_keys(client, keys):
for key in keys:
value = client.ReadLong(key)
print "%s = %d" % (key, value)
def main():
client = client_wrap.ClientWrap("get_test.log", "ipc:///var/run/zero-cache/0", 0)
keys = get_keys(client)
print_keys(client, keys)
if __name__ == "__main__":
main()
| Implement formatted list of keys and values in output | Implement formatted list of keys and values in output
| Python | agpl-3.0 | ellysh/zero-cache-utils,ellysh/zero-cache-utils | ---
+++
@@ -1,18 +1,29 @@
#!/usr/bin/env python
+import sys
import client_wrap
-def main():
- client = client_wrap.ClientWrap("get_test.log", "ipc:///var/run/zero-cache/0", 0)
-
+def get_keys(client):
key_str = client.GetKeys()
keys = key_str.split (';')
del keys[-1]
if len(keys) == 0:
- return
+ sys.exit()
- print keys
+ return keys
+
+def print_keys(client, keys):
+ for key in keys:
+ value = client.ReadLong(key)
+ print "%s = %d" % (key, value)
+
+def main():
+ client = client_wrap.ClientWrap("get_test.log", "ipc:///var/run/zero-cache/0", 0)
+
+ keys = get_keys(client)
+
+ print_keys(client, keys)
if __name__ == "__main__":
main() |
4987275ab868aa98359d6583c7817c4adf09000b | zipeggs.py | zipeggs.py | import logging, os, zc.buildout, sys, shutil
class ZipEggs:
def __init__(self, buildout, name, options):
self.name, self.options = name, options
if options['target'] is None:
raise zc.buildout.UserError('Invalid Target')
if options['source'] is None:
raise zc.buildout.UserError('Invalid Source')
def zipit(self):
target = self.options['target']
if not os.path.exists(target):
os.mkdir(target)
path = self.options['source']
for dirs in os.listdir(path):
try:
source = os.path.join(path, dirs)
dist = "%s/%s" % (target, dirs)
print "%s > %s" % (source, dist)
shutil.make_archive(dist, "zip", source)
os.rename(dist+".zip", dist)
except OSError:
print "ignore %s" % dirs
return []
def install(self):
return self.zipit()
def update(self):
return self.zipit()
| import logging, os, zc.buildout, sys, shutil
class ZipEggs:
def __init__(self, buildout, name, options):
self.name, self.options = name, options
if options['target'] is None:
raise zc.buildout.UserError('Invalid Target')
if options['source'] is None:
raise zc.buildout.UserError('Invalid Source')
def zipit(self):
target_dir = self.options['target']
if not os.path.exists(target_dir):
os.mkdir(target_dir)
source_dir = self.options['source']
for entry in os.listdir(source_dir):
try:
source = os.path.join(source_dir, entry)
target = "%s/%s" % (target_dir, entry)
print "%s > %s" % (source, target)
shutil.make_archive(target, "zip", source)
os.rename(target+".zip", target)
except OSError:
print "ignore %s" % entry
return []
def install(self):
return self.zipit()
def update(self):
return self.zipit()
| Improve variable names for clarity | Improve variable names for clarity
| Python | apache-2.0 | tamizhgeek/zipeggs | ---
+++
@@ -10,19 +10,19 @@
def zipit(self):
- target = self.options['target']
- if not os.path.exists(target):
- os.mkdir(target)
- path = self.options['source']
- for dirs in os.listdir(path):
+ target_dir = self.options['target']
+ if not os.path.exists(target_dir):
+ os.mkdir(target_dir)
+ source_dir = self.options['source']
+ for entry in os.listdir(source_dir):
try:
- source = os.path.join(path, dirs)
- dist = "%s/%s" % (target, dirs)
- print "%s > %s" % (source, dist)
- shutil.make_archive(dist, "zip", source)
- os.rename(dist+".zip", dist)
+ source = os.path.join(source_dir, entry)
+ target = "%s/%s" % (target_dir, entry)
+ print "%s > %s" % (source, target)
+ shutil.make_archive(target, "zip", source)
+ os.rename(target+".zip", target)
except OSError:
- print "ignore %s" % dirs
+ print "ignore %s" % entry
return []
def install(self): |
7396b20c3ee1b037580463c9a653e782c197e536 | xdocker/run_worker.py | xdocker/run_worker.py | from rq import Connection, Queue, Worker
def worker_exc_handler(job, exc_type, exc_value, traceback):
job.meta['exc_code'] = exc_type.code
job.meta['exc_message'] = exc_type.message
return True
def main():
with Connection():
q = Queue()
worker = Worker([q])
worker.push_exc_handler(worker_exc_handler)
worker.work()
if __name__ == '__main__':
main()
| from rq import Connection, Queue, Worker
from worker.exceptions import WorkerException
def worker_exc_handler(job, exc_type, exc_value, traceback):
if isinstance(exc_type, WorkerException):
job.meta['exc_code'] = exc_type.code
job.meta['exc_message'] = exc_type.message
return True
def main():
with Connection():
q = Queue()
worker = Worker([q])
worker.push_exc_handler(worker_exc_handler)
worker.work()
if __name__ == '__main__':
main()
| Fix worker exception handler for non workerexceptions | Fix worker exception handler for non workerexceptions
| Python | apache-2.0 | XDocker/Engine,XDocker/Engine | ---
+++
@@ -1,9 +1,11 @@
from rq import Connection, Queue, Worker
+from worker.exceptions import WorkerException
def worker_exc_handler(job, exc_type, exc_value, traceback):
- job.meta['exc_code'] = exc_type.code
- job.meta['exc_message'] = exc_type.message
+ if isinstance(exc_type, WorkerException):
+ job.meta['exc_code'] = exc_type.code
+ job.meta['exc_message'] = exc_type.message
return True
|
e2a6fe346a8fac07c9c7bd4166ed45fd641faaf6 | royalfilms/movies/api.py | royalfilms/movies/api.py | from .serializers import MovieSerializer
from .models import Movie
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework import permissions
class MovieList(generics.ListCreateAPIView):
"""
API class for list all Movies from a thread, or create a new Movie.
"""
permission_classes = (permissions.IsAdminUser,)
queryset = Movie.objects.all()
serializer_class = MovieSerializer | from .serializers import MovieSerializer
from .models import Movie
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework import permissions
class MovieList(generics.ListAPIView):
"""
API class for list all Movies from a thread, or create a new Movie.
"""
# permission_classes = (permissions.IsAdminUser,)
queryset = Movie.objects.all()
serializer_class = MovieSerializer | Remove admin restictions to movies endpoint | Remove admin restictions to movies endpoint
| Python | mit | juliancantillo/royal-films,juliancantillo/royal-films,juliancantillo/royal-films,juliancantillo/royal-films | ---
+++
@@ -8,10 +8,10 @@
from rest_framework import permissions
-class MovieList(generics.ListCreateAPIView):
+class MovieList(generics.ListAPIView):
"""
API class for list all Movies from a thread, or create a new Movie.
"""
- permission_classes = (permissions.IsAdminUser,)
+ # permission_classes = (permissions.IsAdminUser,)
queryset = Movie.objects.all()
serializer_class = MovieSerializer |
260cb862f5324387d796826d76ff224c01ca5036 | localore/localore_admin/migrations/0003_auto_20160316_1646.py | localore/localore_admin/migrations/0003_auto_20160316_1646.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('localore_admin', '0002_auto_20160316_1444'),
]
operations = [
migrations.RenameField(
model_name='localoreimage',
old_name='alt',
new_name='alt_text',
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('localore_admin', '0002_auto_20160316_1444'),
]
run_before = [
('home', '0002_create_homepage'),
]
operations = [
migrations.RenameField(
model_name='localoreimage',
old_name='alt',
new_name='alt_text',
),
]
| Fix migrations dependency issue caused by 990563e. | Fix migrations dependency issue caused by 990563e.
| Python | mpl-2.0 | ghostwords/localore,ghostwords/localore,ghostwords/localore | ---
+++
@@ -10,6 +10,10 @@
('localore_admin', '0002_auto_20160316_1444'),
]
+ run_before = [
+ ('home', '0002_create_homepage'),
+ ]
+
operations = [
migrations.RenameField(
model_name='localoreimage', |
3d5902b341e15a6d5f8ba1599902b6f9327a021b | typedjsonrpc/errors.py | typedjsonrpc/errors.py | """This module defines error classes for typedjsonrpc."""
class Error(Exception):
"""Base class for all errors."""
code = 0
message = None
data = None
def __init__(self, data=None):
super(Error, self).__init__()
self.data = data
def as_error_object(self):
"""Turns the error into an error object."""
return {
"code": self.code,
"message": self.message,
"data": self.data
}
class ParseError(Error):
"""Invalid JSON was received by the server / JSON could not be parsed."""
code = -32700
message = "Parse error"
class InvalidRequestError(Error):
"""The JSON sent is not a valid request object."""
code = -32600
message = "Invalid request"
class MethodNotFoundError(Error):
"""The method does not exist."""
code = -32601
message = "Method not found"
class InvalidParamsError(Error):
"""Invalid method parameter(s)."""
code = -32602
message = "Invalid params"
class InternalError(Error):
"""Internal JSON-RPC error."""
code = -32603
message = "Internal error"
class ServerError(Error):
"""Something else went wrong."""
code = -32000
message = "Server error"
| """This module defines error classes for typedjsonrpc."""
class Error(Exception):
"""Base class for all errors."""
code = 0
message = None
data = None
def __init__(self, data=None):
super(Error, self).__init__(self.code, self.message, data)
self.data = data
def as_error_object(self):
"""Turns the error into an error object."""
return {
"code": self.code,
"message": self.message,
"data": self.data
}
class ParseError(Error):
"""Invalid JSON was received by the server / JSON could not be parsed."""
code = -32700
message = "Parse error"
class InvalidRequestError(Error):
"""The JSON sent is not a valid request object."""
code = -32600
message = "Invalid request"
class MethodNotFoundError(Error):
"""The method does not exist."""
code = -32601
message = "Method not found"
class InvalidParamsError(Error):
"""Invalid method parameter(s)."""
code = -32602
message = "Invalid params"
class InternalError(Error):
"""Internal JSON-RPC error."""
code = -32603
message = "Internal error"
class ServerError(Error):
"""Something else went wrong."""
code = -32000
message = "Server error"
| Make exception messages more descriptive | Make exception messages more descriptive
| Python | apache-2.0 | palantir/typedjsonrpc,palantir/typedjsonrpc | ---
+++
@@ -8,7 +8,7 @@
data = None
def __init__(self, data=None):
- super(Error, self).__init__()
+ super(Error, self).__init__(self.code, self.message, data)
self.data = data
def as_error_object(self): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.