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 |
|---|---|---|---|---|---|---|---|---|---|---|
17c9256000f78fd8fc52f86729dcbb39cb80b3a3 | src/mcedit2/widgets/nbttree/nbttreeview.py | src/mcedit2/widgets/nbttree/nbttreeview.py | """
nbttreewidget
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from PySide import QtGui
from PySide.QtCore import Qt
from mcedit2.widgets.nbttree.nbttreemodel import NBTFilterProxyModel
from mcedit2.util.load_ui import registerCustomWidget
from mcedit2.widg... | """
nbttreewidget
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from PySide import QtGui
from PySide.QtCore import Qt
from mcedit2.widgets.nbttree.nbttreemodel import NBTFilterProxyModel
from mcedit2.util.load_ui import registerCustomWidget
from mcedit2.widg... | Set NBT tree view with correct proxy model (oops) | Set NBT tree view with correct proxy model (oops)
| Python | bsd-3-clause | Rubisk/mcedit2,Rubisk/mcedit2,vorburger/mcedit2,vorburger/mcedit2 | ---
+++
@@ -28,7 +28,7 @@
proxyModel.setSourceModel(model)
proxyModel.setDynamicSortFilter(True)
- self.treeView.setModel(model)
+ self.treeView.setModel(proxyModel)
self.treeView.sortByColumn(0, Qt.AscendingOrder)
self.treeView.expandToDepth(0) |
91faf4fd5fa3d5878e2792bcd87f81c261ec5033 | wagtail/wagtailadmin/edit_bird.py | wagtail/wagtailadmin/edit_bird.py | from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.template.loader import render_to_string
class BaseItem(object):
template = 'wagtailadmin/edit_bird/base_item.html'
@property
def can_render(self):
return True
def render(self, request):
... | from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.template.loader import render_to_string
class BaseItem(object):
template = 'wagtailadmin/edit_bird/base_item.html'
def render(self, request):
return render_to_string(self.template, dict(self=self, requ... | Edit bird: Clean up render method of EditPageItem | Edit bird: Clean up render method of EditPageItem
| Python | bsd-3-clause | takeflight/wagtail,FlipperPA/wagtail,stevenewey/wagtail,jorge-marques/wagtail,kurtw/wagtail,Pennebaker/wagtail,janusnic/wagtail,gogobook/wagtail,hamsterbacke23/wagtail,m-sanders/wagtail,mayapurmedia/wagtail,zerolab/wagtail,bjesus/wagtail,Tivix/wagtail,JoshBarr/wagtail,takeshineshiro/wagtail,chimeno/wagtail,benemery/wag... | ---
+++
@@ -6,13 +6,8 @@
class BaseItem(object):
template = 'wagtailadmin/edit_bird/base_item.html'
- @property
- def can_render(self):
- return True
-
def render(self, request):
- if self.can_render:
- return render_to_string(self.template, dict(self=self, request=request)... |
079e347bf7f05e01824a6c05495b42015e672423 | keepsimplecms/jinja/globals.py | keepsimplecms/jinja/globals.py | # -*- coding: utf-8 -*-
from jinja2.utils import Markup
from pprint import pformat
import sys
import types
def global_node(node_value):
"""
Used for the inclusion of a node in a template.
It just marks the node value `node_value` as safe.
"""
return Markup(node_value)
def global_dump(value):
... | # -*- coding: utf-8 -*-
from jinja2 import Environment
from jinja2.utils import Markup
from pprint import pformat
import sys
import types
env = Environment()
def global_node(node_value, indent=0, indent_first=False):
"""
Used for the inclusion of a node in a template by indenting and flagging
the HTML ... | Add some indent options in the node Jinja macro. | Add some indent options in the node Jinja macro.
| Python | bsd-3-clause | cr0cK/keepsimple.cms,cr0cK/keepsimple.cms,cr0cK/keepsimple.cms | ---
+++
@@ -1,17 +1,23 @@
# -*- coding: utf-8 -*-
+from jinja2 import Environment
from jinja2.utils import Markup
from pprint import pformat
import sys
import types
-def global_node(node_value):
+env = Environment()
+
+
+def global_node(node_value, indent=0, indent_first=False):
"""
- Used for the ... |
fdfb2b1da5e7cea83bd4189bb9d998273c03a7cd | SlugifyCommand.py | SlugifyCommand.py | # encoding: utf-8
'''This adds a "slugify" command to be invoked by Sublime Text. It is made
available as "Slugify" in the command palette by Default.sublime-commands.
Parts of these commands are borrowed from the sublime-slug package:
https://github.com/madeingnecca/sublime-slug
'''
from __future__ import unicode_li... | # encoding: utf-8
'''This adds a "slugify" command to be invoked by Sublime Text. It is made
available as "Slugify" in the command palette by Default.sublime-commands.
Parts of these commands are borrowed from the sublime-slug package:
https://github.com/madeingnecca/sublime-slug
'''
from __future__ import unicode_li... | Fix broken import in Sublime Text 2. | Fix broken import in Sublime Text 2. | Python | mit | alimony/sublime-slugify | ---
+++
@@ -12,7 +12,7 @@
import sublime_plugin
try:
# This import method works in Sublime Text 2.
- import slugify
+ from slugify import slugify
except ImportError:
# While this works in Sublime Text 3.
from .slugify import slugify |
1d486d8035e918a83dce5a70c83149a06d982a9f | Instanssi/admin_calendar/models.py | Instanssi/admin_calendar/models.py | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User
from imagekit.models import ImageSpec
from imagekit.processors import resize
class CalendarEvent(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
start = mod... | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
class CalendarEvent(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
... | Fix to work on the latest django-imagekit | admin_calendar: Fix to work on the latest django-imagekit
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | ---
+++
@@ -3,8 +3,8 @@
from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User
-from imagekit.models import ImageSpec
-from imagekit.processors import resize
+from imagekit.models import ImageSpecField
+from imagekit.processors import ResizeToFill
class Calenda... |
bd79e3741e03a25b17670f6529e4d98bb97fa3ae | scikits/image/__init__.py | scikits/image/__init__.py | """Image Processing SciKit (Toolbox for SciPy)"""
import os.path as _osp
data_dir = _osp.join(_osp.dirname(__file__), 'data')
from version import version as __version__
def _setup_test():
import functools
basedir = _osp.dirname(_osp.join(__file__, '../'))
args = ['', '--exe', '-w', '%s' % basedir]
... | """Image Processing SciKit (Toolbox for SciPy)"""
import os.path as _osp
data_dir = _osp.join(_osp.dirname(__file__), 'data')
from version import version as __version__
def _setup_test():
import functools
basedir = _osp.dirname(_osp.join(__file__, '../'))
args = ['', '--exe', '-w', '%s' % basedir]
... | Add easy way to grab a logger. | Add easy way to grab a logger.
| Python | bsd-3-clause | dpshelio/scikit-image,emon10005/scikit-image,chriscrosscutler/scikit-image,jwiggins/scikit-image,almarklein/scikit-image,oew1v07/scikit-image,warmspringwinds/scikit-image,Britefury/scikit-image,ofgulban/scikit-image,vighneshbirodkar/scikit-image,ClinicalGraphics/scikit-image,paalge/scikit-image,blink1073/scikit-image,e... | ---
+++
@@ -25,3 +25,7 @@
if test is None:
del test
+def get_log(name):
+ import logging, sys
+ logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
+ return logging.getLogger(name) |
005ff4e6584727ba6ca61b49a57621dd7f17cd6a | examples/client.py | examples/client.py | from socketio_client.manager import Manager
import gevent
from gevent import monkey
monkey.patch_socket()
import logging
logging.basicConfig(level=logging.DEBUG)
io = Manager('localhost', 8000, auto_connect=False)
chat = io.socket('/chat')
@chat.on('welcome')
def on_hello(*args, **kwargs):
print args
kwargs... | from socketio_client.manager import Manager
import gevent
from gevent import monkey
monkey.patch_socket()
import logging
logging.basicConfig(level=logging.DEBUG)
io = Manager('http', 'localhost', 8000, auto_connect=False)
chat = io.socket('/chat')
@chat.on('welcome')
def on_hello(*args, **kwargs):
print args
... | Update example according to modified Manager constructor. | Update example according to modified Manager constructor.
A scheme parameter is now required on Manager instantiation | Python | mit | veo-labs/python-socketio-client | ---
+++
@@ -7,7 +7,7 @@
import logging
logging.basicConfig(level=logging.DEBUG)
-io = Manager('localhost', 8000, auto_connect=False)
+io = Manager('http', 'localhost', 8000, auto_connect=False)
chat = io.socket('/chat')
@chat.on('welcome') |
ddcf3490990f9b78f0009937bc9ddc2df0331b8e | lib/booki/account/templatetags/profile.py | lib/booki/account/templatetags/profile.py | import os
from django.db.models import get_model
from django.template import Library, Node, TemplateSyntaxError, resolve_variable
from django.conf import settings
from booki.account.models import UserProfile
register = Library()
class ProfileImageNode(Node):
def __init__(self, user):
self.user = user
... | import os
from django.db.models import get_model
from django.template import Library, Node, TemplateSyntaxError, resolve_variable
from django.conf import settings
from booki.account.models import UserProfile
register = Library()
class ProfileImageNode(Node):
def __init__(self, user):
self.user = user
... | Fix image link to anonymous user. | Fix image link to anonymous user.
| Python | agpl-3.0 | kronoscode/Booktype,MiczFlor/Booktype,rob-hills/Booktype,ride90/Booktype,okffi/booktype,kronoscode/Booktype,danielhjames/Booktype,danielhjames/Booktype,eos87/Booktype,ride90/Booktype,MiczFlor/Booktype,danielhjames/Booktype,kronoscode/Booktype,btat/Booktype,ride90/Booktype,aerkalov/Booktype,danielhjames/Booktype,btat/Bo... | ---
+++
@@ -19,7 +19,7 @@
profile = UserProfile.objects.get(user=user)
if not profile.image:
- return """<img src="%s/profile_images/_anonymous.jpg"/>""" % settings.DATA_URL
+ return """<img src="%s/images/anonymous.jpg"/>""" % settings.SITE_STATIC_URL
filename = p... |
7fb284ad29098a4397c7ac953e2d9acb89cf089e | notification/backends/email.py | notification/backends/email.py | from django.conf import settings
from django.core.mail import EmailMessage
from notification.backends.base import NotificationBackend
class EmailBackend(NotificationBackend):
slug = u'email'
display_name = u'E-mail'
formats = ['short.txt', 'full.txt']
def email_for_user(self, recipient):
ret... | from django.conf import settings
from django.core.mail import EmailMessage
from notification.backends.base import NotificationBackend
class EmailBackend(NotificationBackend):
sensitivity = 2
slug = u'email'
display_name = u'E-mail'
formats = ['short.txt', 'full.txt']
def email_for_user(self, rec... | Set sensitivity of e-mail backend to 2, so notifications with 1 aren't mailed. | Set sensitivity of e-mail backend to 2, so notifications with 1 aren't mailed.
| Python | mit | theatlantic/django-notification,theatlantic/django-notification | ---
+++
@@ -5,6 +5,7 @@
class EmailBackend(NotificationBackend):
+ sensitivity = 2
slug = u'email'
display_name = u'E-mail'
formats = ['short.txt', 'full.txt'] |
b28ceb8631446b57abb48be6c76db843ec747221 | demo/set-sas-token.py | demo/set-sas-token.py | #!/usr/bin/env python
from __future__ import print_function
import os
from subprocess import check_output
from sys import argv, stdout
RSGRP = "travistestresourcegroup"
STACC = "travistestresourcegr3014"
def run(command):
command = command.replace('az ', '', 1)
cmd = 'python -m azure.cli {}'.format(command)... | #!/usr/bin/env python
from __future__ import print_function
import os
from subprocess import check_output
from sys import argv, stdout
RSGRP = "travistestresourcegroup"
STACC = "travistestresourcegr3014"
def cmd(command):
""" Accepts a command line command as a string and returns stdout in UTF-8 format """
... | Update python scripts to run on OSX. | Update python scripts to run on OSX.
| Python | mit | QingChenmsft/azure-cli,yugangw-msft/azure-cli,QingChenmsft/azure-cli,yugangw-msft/azure-cli,samedder/azure-cli,samedder/azure-cli,yugangw-msft/azure-cli,BurtBiel/azure-cli,BurtBiel/azure-cli,yugangw-msft/azure-cli,QingChenmsft/azure-cli,samedder/azure-cli,yugangw-msft/azure-cli,yugangw-msft/azure-cli,QingChenmsft/azure... | ---
+++
@@ -9,29 +9,26 @@
RSGRP = "travistestresourcegroup"
STACC = "travistestresourcegr3014"
-def run(command):
- command = command.replace('az ', '', 1)
- cmd = 'python -m azure.cli {}'.format(command)
- print(cmd)
- out = check_output(cmd)
- return out.decode('utf-8')
+def cmd(command):
+ ""... |
5d65b35623d2dbdb518a6e4a7f95ec224bf879a1 | ros_start/scritps/service_client.py | ros_start/scritps/service_client.py | #!/usr/bin/env python
import rospy
from std_srvs.srv import Empty
def service_client():
rospy.loginfo('waiting service')
rospy.wait_for_service('call_me')
try:
service = rospy.ServiceProxy('call_me', Empty)
response = service()
except rospy.ServiceException, e:
print "Service c... | #!/usr/bin/env python
import rospy
from std_srvs.srv import Empty
def call_service():
rospy.loginfo('waiting service')
rospy.wait_for_service('call_me')
try:
service = rospy.ServiceProxy('call_me', Empty)
response = service()
except rospy.ServiceException, e:
print "Service ca... | Add initialization of the service client node. | Add initialization of the service client node.
| Python | bsd-2-clause | OTL/ros_book_programs,OTL/ros_book_programs | ---
+++
@@ -3,14 +3,20 @@
import rospy
from std_srvs.srv import Empty
-def service_client():
+def call_service():
rospy.loginfo('waiting service')
rospy.wait_for_service('call_me')
+
try:
service = rospy.ServiceProxy('call_me', Empty)
response = service()
except rospy.Service... |
3f7a9d900a1f2cd2f5522735815c999040a920e0 | pajbot/web/routes/api/users.py | pajbot/web/routes/api/users.py | from flask_restful import Resource
from pajbot.managers.redis import RedisManager
from pajbot.managers.user import UserManager
from pajbot.streamhelper import StreamHelper
class APIUser(Resource):
@staticmethod
def get(username):
user = UserManager.find_static(username)
if not user:
... | from flask_restful import Resource
from pajbot.managers.redis import RedisManager
from pajbot.managers.user import UserManager
from pajbot.streamhelper import StreamHelper
class APIUser(Resource):
@staticmethod
def get(username):
user = UserManager.find_static(username)
if not user:
... | Remove dead code in get user API endpoint | Remove dead code in get user API endpoint
| Python | mit | pajlada/tyggbot,pajlada/tyggbot,pajlada/pajbot,pajlada/pajbot,pajlada/pajbot,pajlada/tyggbot,pajlada/pajbot,pajlada/tyggbot | ---
+++
@@ -12,14 +12,6 @@
if not user:
return {"error": "Not found"}, 404
- redis = RedisManager.get()
- key = "{streamer}:users:num_lines".format(streamer=StreamHelper.get_streamer())
- rank = redis.zrevrank(key, user.username)
- if rank is None:
- rank... |
ddfdddad65a96198d6949c138ad9980188250b92 | alembic/versions/35597d56e8d_add_ckan_boolean_to_mod_table.py | alembic/versions/35597d56e8d_add_ckan_boolean_to_mod_table.py | """Add ckan boolean to mod table
Revision ID: 35597d56e8d
Revises: 18af22fa9e4
Create Date: 2014-12-12 20:11:22.250080
"""
# revision identifiers, used by Alembic.
revision = '35597d56e8d'
down_revision = '18af22fa9e4'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated b... | """Add ckan boolean to mod table
Revision ID: 35597d56e8d
Revises: 18af22fa9e4
Create Date: 2014-12-12 20:11:22.250080
"""
# revision identifiers, used by Alembic.
revision = '35597d56e8d'
down_revision = '50b5a95300c'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated b... | Fix loop in alembic history | Fix loop in alembic history
| Python | mit | Kerbas-ad-astra/KerbalStuff,Kerbas-ad-astra/KerbalStuff,toadicus/KerbalStuff,KerbalStuff/KerbalStuff,EIREXE/SpaceDock,ModulousSmash/Modulous,KerbalStuff/KerbalStuff,ModulousSmash/Modulous,ModulousSmash/Modulous,toadicus/KerbalStuff,ModulousSmash/Modulous,EIREXE/SpaceDock,EIREXE/SpaceDock,toadicus/KerbalStuff,Kerbas-ad-... | ---
+++
@@ -8,7 +8,7 @@
# revision identifiers, used by Alembic.
revision = '35597d56e8d'
-down_revision = '18af22fa9e4'
+down_revision = '50b5a95300c'
from alembic import op
import sqlalchemy as sa |
89112aa8e5ffda6763db2f49a2d32cff5f6b15fd | lib/storage/gcs.py | lib/storage/gcs.py |
import gevent.monkey
gevent.monkey.patch_all()
import logging
import boto.gs.connection
import boto.gs.key
import cache
from boto_base import BotoStorage
logger = logging.getLogger(__name__)
class GSStorage(BotoStorage):
def __init__(self, config):
BotoStorage.__init__(self, config)
def makeC... |
import gevent.monkey
gevent.monkey.patch_all()
import logging
import boto.gs.connection
import boto.gs.key
import cache
from boto_base import BotoStorage
logger = logging.getLogger(__name__)
class GSStorage(BotoStorage):
def __init__(self, config):
BotoStorage.__init__(self, config)
def makeC... | Fix up some key construction. | Fix up some key construction.
| Python | apache-2.0 | depay/docker-registry,alephcloud/docker-registry,HubSpot/docker-registry,dhiltgen/docker-registry,catalyst-zero/docker-registry,ewindisch/docker-registry,hex108/docker-registry,scrapinghub/docker-registry,ewindisch/docker-registry,shipyard/docker-registry,mdshuai/docker-registry,OnePaaS/docker-registry,nunogt/docker-re... | ---
+++
@@ -42,6 +42,5 @@
if self.buffer_size > buffer_size:
buffer_size = self.buffer_size
path = self._init_path(path)
- key = boto.gs.key.Key(self._boto_bucket)
- key.key = path
+ key = self.makeKey(path)
key.set_contents_from_string(fp.read()) |
e9a11dac0d125d90d5e0b1783b215b9007334d02 | contentstore/management/commands/tests/test_sync_schedules.py | contentstore/management/commands/tests/test_sync_schedules.py | from io import BytesIO
from django.core.management import call_command
from django.test import TestCase
from mock import patch
from contentstore.models import Schedule
from seed_stage_based_messaging import test_utils as utils
class SyncSchedulesTests(TestCase):
@patch('contentstore.management.commands.sync_sche... | from six import BytesIO
from django.core.management import call_command
from django.test import TestCase
from mock import patch
from contentstore.models import Schedule
from seed_stage_based_messaging import test_utils as utils
class SyncSchedulesTests(TestCase):
@patch('contentstore.management.commands.sync_sch... | Use six for python 2/3 bytes | Use six for python 2/3 bytes
| Python | bsd-3-clause | praekelt/seed-stage-based-messaging,praekelt/seed-stage-based-messaging,praekelt/seed-staged-based-messaging | ---
+++
@@ -1,4 +1,4 @@
-from io import BytesIO
+from six import BytesIO
from django.core.management import call_command
from django.test import TestCase
from mock import patch |
293b1d492cfd3c5542c78acffbbdebf4933b6d85 | django_db_geventpool/backends/postgresql_psycopg2/creation.py | django_db_geventpool/backends/postgresql_psycopg2/creation.py | # coding=utf-8
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation
class DatabaseCreation(OriginalDatabaseCreation):
def _destroy_test_db(self, test_database_name, verbosity):
self.connection.closeall()
return super(DatabaseCreation, self)._des... | # coding=utf-8
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation
class DatabaseCreation(OriginalDatabaseCreation):
def _destroy_test_db(self, test_database_name, verbosity):
self.connection.closeall()
return super(DatabaseCreation, self)._des... | Handle open connections when creating the test database | Handle open connections when creating the test database
| Python | apache-2.0 | jneight/django-db-geventpool,PreppyLLC-opensource/django-db-geventpool | ---
+++
@@ -7,4 +7,6 @@
def _destroy_test_db(self, test_database_name, verbosity):
self.connection.closeall()
return super(DatabaseCreation, self)._destroy_test_db(test_database_name, verbosity)
-
+ def _create_test_db(self, verbosity, autoclobber):
+ self.connection.closeall()
+ ... |
0aff137a210debd9ea18793a98c043a5151d9524 | src/Compiler/VM/arithmetic_exprs.py | src/Compiler/VM/arithmetic_exprs.py | from Helpers.string import *
def binop_aexp(commands, env, op, left, right):
left.compile_vm(commands, env)
right.compile_vm(commands, env)
if op == '+':
value = assemble(Add)
elif op == '-':
value = assemble(Sub)
elif op == '*':
value = assemble(Mul)
elif op == '/':
... | from Helpers.string import *
def binop_aexp(commands, env, op, left, right):
left.compile_vm(commands, env)
right.compile_vm(commands, env)
if op == '+':
value = assemble(Add)
elif op == '-':
value = assemble(Sub)
elif op == '*':
value = assemble(Mul)
elif op == '/':
... | Fix compiling problem for runtime variables | Fix compiling problem for runtime variables
| Python | mit | PetukhovVictor/compiler,PetukhovVictor/compiler | ---
+++
@@ -23,9 +23,7 @@
def var_aexp(commands, env, name):
var_type = Environment.get_var_type(env, name)
var_value = Environment.get_var(env, name)
- if var_type == 'IntAexp':
+ if var_type == 'String':
+ String.compile_get(commands, env, var_value)
+ else:
commands.append(assem... |
be9614da32a3c626d2a8e434a43d411d30451f7f | mopidy/__main__.py | mopidy/__main__.py | import asyncore
import logging
import os
import sys
sys.path.insert(0,
os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
from mopidy import get_class, settings, SettingsError
from mopidy.mpd.server import MpdServer
logger = logging.getLogger('mopidy')
def main():
_setup_logging(2)
mixer =... | import asyncore
import logging
import os
import sys
sys.path.insert(0,
os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
from mopidy import get_class, settings, SettingsError
from mopidy.mpd.server import MpdServer
logger = logging.getLogger('mopidy')
def main():
_setup_logging(2)
# mult... | Add todo list for multiprocessing branch | Add todo list for multiprocessing branch
| Python | apache-2.0 | quartz55/mopidy,mopidy/mopidy,jmarsik/mopidy,tkem/mopidy,quartz55/mopidy,rawdlite/mopidy,mopidy/mopidy,ali/mopidy,woutervanwijk/mopidy,diandiankan/mopidy,dbrgn/mopidy,glogiotatidis/mopidy,pacificIT/mopidy,quartz55/mopidy,vrs01/mopidy,dbrgn/mopidy,mokieyue/mopidy,kingosticks/mopidy,tkem/mopidy,abarisain/mopidy,quartz55/... | ---
+++
@@ -13,6 +13,15 @@
def main():
_setup_logging(2)
+
+ # multiprocessing branch plan
+ # ---------------------------
+ #
+ # TODO Init backend in new Process (named core?)
+ # TODO Init mixer from backend
+ # TODO Init MpdHandler from backend/core
+ # TODO Init MpdServer in MainThre... |
c3bac71b19842d9010390996c094119ed25566ab | class_namespaces/scope_proxy.py | class_namespaces/scope_proxy.py | """Base class for Namespace proxies in class creation."""
import weakref
from . import ops
from .proxy import _Proxy
_PROXY_INFOS = weakref.WeakKeyDictionary()
class _ScopeProxy(_Proxy):
"""Proxy object for manipulating namespaces during class creation."""
__slots__ = '__weakref__',
def __init__(sel... | """Base class for Namespace proxies in class creation."""
import weakref
from . import ops
from .proxy import _Proxy
_PROXY_INFOS = weakref.WeakKeyDictionary()
class _ScopeProxy(_Proxy):
"""Proxy object for manipulating namespaces during class creation."""
__slots__ = '__weakref__',
def __init__(sel... | Fix for bug. Overall somewhat unfortunate. | Fix for bug. Overall somewhat unfortunate.
| Python | mit | mwchase/class-namespaces,mwchase/class-namespaces | ---
+++
@@ -23,13 +23,18 @@
return _PROXY_INFOS[self][self]
def __getattribute__(self, name):
+ # Have to add some dependencies back...
+ from .namespaces import Namespace
dct = _PROXY_INFOS[self][self]
try:
- return dct[name]
+ value = dct[name]
... |
2e95901ee37100f855a5f30e6143920ef2b56904 | odinweb/_compat.py | odinweb/_compat.py | # -*- coding: utf-8 -*-
"""
Py27 Support
~~~~~~~~~~~~
Like odin this library will support Python 2.7 through to version 2.0.
From this point onwards Python 3.5+ will be required.
"""
from __future__ import unicode_literals
import sys
__all__ = (
'PY2', 'PY3',
'string_types', 'integer_types', 'text_type', '... | # -*- coding: utf-8 -*-
"""
Py27 Support
~~~~~~~~~~~~
Like odin this library will support Python 2.7 through to version 2.0.
From this point onwards Python 3.5+ will be required.
"""
import sys
__all__ = (
'PY2', 'PY3',
'string_types', 'integer_types', 'text_type', 'binary_type',
'range', 'with_metaclas... | Remove unicode literals to fix with_metaclass method | Remove unicode literals to fix with_metaclass method
| Python | bsd-3-clause | python-odin/odinweb,python-odin/odinweb | ---
+++
@@ -8,8 +8,6 @@
From this point onwards Python 3.5+ will be required.
"""
-from __future__ import unicode_literals
-
import sys
__all__ = ( |
da59d4334eb1a6f77bd0a9599614a6289ef843e4 | pytest-server-fixtures/tests/integration/test_mongo_server.py | pytest-server-fixtures/tests/integration/test_mongo_server.py | import pytest
def test_mongo_server(mongo_server):
assert mongo_server.check_server_up()
assert mongo_server.delete
mongo_server.api.db.test.insert_one({'a': 'b', 'c': 'd'})
assert mongo_server.api.db.test.find_one({'a': 'b'}, {'_id': False}) == {'a': 'b', 'c': 'd'}
@pytest.mark.parametrize('count',... | import pytest
def test_mongo_server(mongo_server):
assert mongo_server.check_server_up()
assert mongo_server.delete
mongo_server.api.db.test.insert({'a': 'b', 'c': 'd'})
assert mongo_server.api.db.test.find_one({'a': 'b'}, {'_id': False}) == {'a': 'b', 'c': 'd'}
@pytest.mark.parametrize('count', ran... | Revert "fix deprecation warnings in mongo" | Revert "fix deprecation warnings in mongo"
This reverts commit 5d449ff9376e7c0a3c78f2b2d631ab0ecd08fe81.
| Python | mit | manahl/pytest-plugins,manahl/pytest-plugins | ---
+++
@@ -4,13 +4,13 @@
def test_mongo_server(mongo_server):
assert mongo_server.check_server_up()
assert mongo_server.delete
- mongo_server.api.db.test.insert_one({'a': 'b', 'c': 'd'})
+ mongo_server.api.db.test.insert({'a': 'b', 'c': 'd'})
assert mongo_server.api.db.test.find_one({'a': 'b'},... |
38365839856658bcf870e286a27f0de784a255a2 | test/tools/lldb-mi/TestMiLibraryLoaded.py | test/tools/lldb-mi/TestMiLibraryLoaded.py | """
Test lldb-mi =library-loaded notifications.
"""
import lldbmi_testcase
from lldbtest import *
import unittest2
class MiLibraryLoadedTestCase(lldbmi_testcase.MiTestCaseBase):
mydir = TestBase.compute_mydir(__file__)
@lldbmi_test
@expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement fo... | """
Test lldb-mi =library-loaded notifications.
"""
import lldbmi_testcase
from lldbtest import *
import unittest2
class MiLibraryLoadedTestCase(lldbmi_testcase.MiTestCaseBase):
mydir = TestBase.compute_mydir(__file__)
@lldbmi_test
@expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement fo... | Fix MiLibraryLoadedTestCase.test_lldbmi_library_loaded test on Linux (MI) | Fix MiLibraryLoadedTestCase.test_lldbmi_library_loaded test on Linux (MI)
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@236229 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb | ---
+++
@@ -26,8 +26,10 @@
import os
path = os.path.join(os.getcwd(), self.myexe)
symbols_path = os.path.join(path + ".dSYM", "Contents", "Resources", "DWARF", self.myexe)
- self.expect("=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"1\",symbols-path=\... |
1396a0f39ef46500ce1db499e905c1fca8fa5a5f | tests/bootstrapping/test_bootstrapping.py | tests/bootstrapping/test_bootstrapping.py | import unittest
from nala.bootstrapping import generate_documents
class TestBootstrapping(unittest.TestCase):
def test_generate_documents_number(self):
# commenting out for now since it takes about 6 mins on Travis CI
test_dataset = generate_documents(1)
self.assertEqual(len(test_dataset),... | import unittest
from nala.bootstrapping import generate_documents
class TestBootstrapping(unittest.TestCase):
def test_generate_documents_number(self):
# commenting out for now since it takes about 6 mins on Travis CI
# test_dataset = generate_documents(1)
# self.assertEqual(len(test_datas... | Remove long test for now | Remove long test for now
| Python | apache-2.0 | Rostlab/nalaf | ---
+++
@@ -5,8 +5,8 @@
class TestBootstrapping(unittest.TestCase):
def test_generate_documents_number(self):
# commenting out for now since it takes about 6 mins on Travis CI
- test_dataset = generate_documents(1)
- self.assertEqual(len(test_dataset), 1)
+ # test_dataset = generat... |
abe1727600eb1c83c196f9b7bd72e58e4df89c57 | feincms/views/base.py | feincms/views/base.py | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import translation
from feincms.module.page.models import Page
def handler(request, path=None):
if path is None:
path = request.path
page = Page.o... |
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from feincms.module.page.models import Page
def build_page_response(page, request):
response = page.setup_request(req... | Add a handler for previewing content (ignores active, publication dates, etc). | Add a handler for previewing content (ignores active, publication dates, etc).
| Python | bsd-3-clause | feincms/feincms,nickburlett/feincms,matthiask/django-content-editor,feincms/feincms,nickburlett/feincms,mjl/feincms,matthiask/feincms2-content,joshuajonah/feincms,joshuajonah/feincms,michaelkuty/feincms,hgrimelid/feincms,pjdelport/feincms,matthiask/feincms2-content,joshuajonah/feincms,nickburlett/feincms,feincms/feincm... | ---
+++
@@ -1,20 +1,36 @@
-from django.http import HttpResponseRedirect
+
+from django.shortcuts import get_object_or_404
+from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
-from django.utils import translation
fro... |
b2d1c701a0f74c569feb3f9e43ccc97366e5398d | backend/django/apps/accounts/serializers.py | backend/django/apps/accounts/serializers.py | from rest_framework import serializers
from .models import BaseAccount
class WholeAccountSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True, required=False)
class Meta:
model = BaseAccount
fields = ('id', 'first_name', 'last_name', 'email', 'password',
... | from rest_framework import serializers
from .models import BaseAccount
class WholeAccountSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True, required=False)
class Meta:
model = BaseAccount
fields = ('id', 'first_name', 'last_name', 'email', 'password',
... | Make the serializer use the new create_user method | Make the serializer use the new create_user method
| Python | mit | slavpetroff/sweetshop,slavpetroff/sweetshop | ---
+++
@@ -12,7 +12,7 @@
'last_activity_at',)
def create(self, validated_data):
- return BaseAccount.objects.create(**validated_data)
+ return BaseAccount.objects.create_user(**validated_data)
def update(self, instance, validated_data):
return BaseAccount.objec... |
16c71ce44836a3cea877475340cae7f96241fd5d | tests/test_person.py | tests/test_person.py | from copy import copy
from unittest import TestCase
from address_book import Person
class PersonTestCase(TestCase):
def test_get_groups(self):
pass
def test_add_address(self):
basic_address = ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42']
person = Pers... | from copy import copy
from unittest import TestCase
from address_book import Person
class PersonTestCase(TestCase):
def test_get_groups(self):
pass
def test_add_address(self):
basic_address = ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42']
person = Pers... | Test the ability to append new email address to the person | Test the ability to append new email address to the person
| Python | mit | dizpers/python-address-book-assignment | ---
+++
@@ -41,4 +41,16 @@
)
def test_add_email(self):
- pass
+ basic_email = ['john@gmail.com']
+ person = Person(
+ 'John',
+ 'Doe',
+ ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'],
+ ['+79834772053'],
+ ... |
2811edf8908c680b80e6534444cdc48feba9af12 | base/components/social/youtube/factories.py | base/components/social/youtube/factories.py | import factory
from . import models
class ChannelFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = models.Channel
class VideoFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = models.Video
| import factory
from . import models
class ChannelFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = models.Channel
class VideoFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = models.Video
channel = factory.SubFactory(ChannelFactory)
class ThumbnailFactory(factory.django.DjangoModelFa... | Create a factory for Thumbnails. | Create a factory for Thumbnails.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web | ---
+++
@@ -9,3 +9,11 @@
class VideoFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = models.Video
+
+ channel = factory.SubFactory(ChannelFactory)
+
+
+class ThumbnailFactory(factory.django.DjangoModelFactory):
+ FACTORY_FOR = models.Thumbnail
+
+ video = factory.SubFactory(VideoFactory) |
c92d9c6da02dacdd91a21c3c5675940154c0e21a | cla_backend/apps/reports/db/backend/base.py | cla_backend/apps/reports/db/backend/base.py | from django.db.backends.postgresql_psycopg2.base import * # noqa
class DynamicTimezoneDatabaseWrapper(DatabaseWrapper):
'''
This exists to allow report generation SQL to set the time zone of the
connection without interference from Django, which normally tries to
ensure that all connections are UTC i... | from django.db.backends.postgresql_psycopg2.base import * # noqa
import pytz
def local_tzinfo_factory(offset):
'''
Create a tzinfo object using the offset of the db connection. This ensures
that the datetimes returned are timezone aware and will be printed in the
reports with timezone information.
... | Add a tzinfo factory method to replica connection to create local tzinfos | Add a tzinfo factory method to replica connection to create local tzinfos
This is to ensure that the datetimes returned for report generation
are timezone aware and will thus be printed in the reports with
timezone information.
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | ---
+++
@@ -1,4 +1,14 @@
from django.db.backends.postgresql_psycopg2.base import * # noqa
+import pytz
+
+
+def local_tzinfo_factory(offset):
+ '''
+ Create a tzinfo object using the offset of the db connection. This ensures
+ that the datetimes returned are timezone aware and will be printed in the
+ r... |
eb4d278c061de82b0010eb40279e1dcd8408bd45 | test_runner/frameworks.py | test_runner/frameworks.py | import json
import logging
import os
import requests
from jinja2 import Template
from os.path import abspath, dirname, exists, join
from .utils import run_cmd
LOG = logging.getLogger(__name__)
class Framework(object):
def __init__(self, environment):
self.admin = environment.admin
self.guests ... | import json
import logging
import os
import requests
from jinja2 import Template
from os.path import abspath, dirname, exists, join
from .utils import run_cmd
LOG = logging.getLogger(__name__)
class Framework(object):
def __init__(self, environment):
self.admin = environment.admin
self.guests ... | Change directory of tempest config | Change directory of tempest config
| Python | mit | rcbops-qa/test_runner | ---
+++
@@ -45,5 +45,5 @@
network=self.network,
router=self.router)
- with open('/opt/tempest/tempest.conf', 'w') as fp:
+ with open('/etc/tempest/tempest.conf', 'w') as fp:
fp.write(self.config) |
d6eb55d2a2107e217935256667d4aef52bd64593 | data/hooks/diagnosis/18-mail.py | data/hooks/diagnosis/18-mail.py | #!/usr/bin/env python
import os
from yunohost.diagnosis import Diagnoser
class MailDiagnoser(Diagnoser):
id_ = os.path.splitext(os.path.basename(__file__))[0].split("-")[1]
cache_duration = 3600
dependencies = ["ip"]
def run(self):
return # TODO / FIXME TO BE IMPLEMETED in the future ...... | #!/usr/bin/env python
import os
from yunohost.diagnosis import Diagnoser
class MailDiagnoser(Diagnoser):
id_ = os.path.splitext(os.path.basename(__file__))[0].split("-")[1]
cache_duration = 3600
dependencies = ["ip"]
def run(self):
# TODO / FIXME TO BE IMPLEMETED in the future ...
... | Add tmp dummy mail report so that the diagnoser kinda works instead of failing miserably | Add tmp dummy mail report so that the diagnoser kinda works instead of failing miserably
| Python | agpl-3.0 | YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost | ---
+++
@@ -13,7 +13,11 @@
def run(self):
- return # TODO / FIXME TO BE IMPLEMETED in the future ...
+ # TODO / FIXME TO BE IMPLEMETED in the future ...
+
+ yield dict(meta={},
+ status="WARNING",
+ summary=("nothing_implemented_yet", {}))
... |
b72c7dedc1200d95310fb07bfeb6de8cc1663ffb | src/wirecloudcommons/utils/transaction.py | src/wirecloudcommons/utils/transaction.py | from django.db.transaction import is_dirty, leave_transaction_management, rollback, commit, enter_transaction_management, managed
from django.db import DEFAULT_DB_ALIAS
from django.http import HttpResponse
def commit_on_http_success(func, using=None):
"""
This decorator activates db commit on HTTP success res... | from django.db.transaction import is_dirty, leave_transaction_management, rollback, commit, enter_transaction_management, managed
from django.db import DEFAULT_DB_ALIAS
from django.http import HttpResponse
def commit_on_http_success(func, using=None):
"""
This decorator activates db commit on HTTP success res... | Fix commit_on_http_success when an exception is raised | Fix commit_on_http_success when an exception is raised
| Python | agpl-3.0 | jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud | ---
+++
@@ -33,8 +33,9 @@
except:
rollback(using=using)
raise
+ finally:
+ leave_transaction_management(using=using)
- leave_transaction_management(using=using)
return res
return wrapped_func |
8225105cf2e72560d8c53ec58c1b98683a613381 | util/versioncheck.py | util/versioncheck.py | #!/usr/bin/python
from subprocess import check_output as co
from sys import exit
# Actually run bin/mn rather than importing via python path
version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True )
version = version.strip()
# Find all Mininet path references
lines = co( "grep -or 'Mininet \w\+\.\w\+\... | #!/usr/bin/python
from subprocess import check_output as co
from sys import exit
# Actually run bin/mn rather than importing via python path
version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True )
version = version.strip()
# Find all Mininet path references
lines = co( "egrep -or 'Mininet [0-9\.]+\w... | Fix to allow more flexible version numbers | Fix to allow more flexible version numbers
| Python | bsd-3-clause | mininet/mininet,mininet/mininet,mininet/mininet | ---
+++
@@ -8,7 +8,7 @@
version = version.strip()
# Find all Mininet path references
-lines = co( "grep -or 'Mininet \w\+\.\w\+\.\w\+[+]*' *", shell=True )
+lines = co( "egrep -or 'Mininet [0-9\.]+\w*' *", shell=True )
error = False
|
895d51105cd51387e3ac5db595333ff794f3e2a7 | yotta/lib/ordered_json.py | yotta/lib/ordered_json.py | # Copyright 2014 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
# standard library modules, , ,
import json
import os
import stat
from collections import OrderedDict
# provide read & write methods for json files that maintain the order of
# dictionary keys, and indent c... | # Copyright 2014 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
# standard library modules, , ,
import json
import os
import stat
from collections import OrderedDict
# provide read & write methods for json files that maintain the order of
# dictionary keys, and indent c... | Add a newline at the end of json files when writing them. | Add a newline at the end of json files when writing them.
This fixes the really irritating ping-pong of newline/nonewline when editing
json files with an editor, and with `yotta version` commands.
| Python | apache-2.0 | BlackstoneEngineering/yotta,autopulated/yotta,ARMmbed/yotta,stevenewey/yotta,ARMmbed/yotta,autopulated/yotta,ntoll/yotta,BlackstoneEngineering/yotta,stevenewey/yotta,eyeye/yotta,ntoll/yotta,eyeye/yotta | ---
+++
@@ -23,6 +23,7 @@
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR), 'w') as f:
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
json.dump(obj, f, indent=2, separators=(',', ': '))
+ f.write(u'\n')
f.truncate()
def loads(string): |
3750bc289685fc243788ee3330676ef7e4387234 | apps/accounts/tests/test_user_landing.py | apps/accounts/tests/test_user_landing.py | # (c) Crown Owned Copyright, 2016. Dstl.
from django.core.urlresolvers import reverse
from django_webtest import WebTest
class KeycloakHeaderLandAtHome(WebTest):
def test_auto_login_on_landing(self):
headers = { 'KEYCLOAK_USERNAME' : 'user@0001.com' }
response = self.app.get(reverse('home'), head... | # (c) Crown Owned Copyright, 2016. Dstl.
from django.core.urlresolvers import reverse
from django_webtest import WebTest
class KeycloakHeaderLandAtHome(WebTest):
def test_auto_login_on_landing(self):
headers = { 'KEYCLOAK_USERNAME' : 'user@0001.com' }
response = self.app.get(reverse('home'), head... | Test for landing login now asserts against the correct path. | Test for landing login now asserts against the correct path.
| Python | mit | dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse | ---
+++
@@ -8,5 +8,5 @@
def test_auto_login_on_landing(self):
headers = { 'KEYCLOAK_USERNAME' : 'user@0001.com' }
response = self.app.get(reverse('home'), headers=headers)
- self.assertEqual(reverse('link-list'), response.location)
+ self.assertEqual('http://localhost:80/links', r... |
65f069c82beea8e96bce780add4f6c3637a0d549 | challenge_3/python/ning/challenge_3.py | challenge_3/python/ning/challenge_3.py | def find_majority(sequence):
item_counter = dict()
for item in sequence:
if item not in item_counter:
item_counter[item] = 1
else:
item_counter[item] += 1
for item, item_count in item_counter.items():
if item_count > len(sequence) / 2:
return ite... | def find_majority(sequence):
item_counter = dict()
for item in sequence:
if item not in item_counter:
item_counter[item] = 1
else:
item_counter[item] += 1
if item_counter[item] > len(sequence) / 2:
return item
test_sequence_list = [2,2,3,7,5,... | Include check majority in first loop rather than separate loop | Include check majority in first loop rather than separate loop
| Python | mit | mindm/2017Challenges,DakRomo/2017Challenges,DakRomo/2017Challenges,DakRomo/2017Challenges,erocs/2017Challenges,erocs/2017Challenges,erocs/2017Challenges,erocs/2017Challenges,erocs/2017Challenges,DakRomo/2017Challenges,erocs/2017Challenges,popcornanachronism/2017Challenges,popcornanachronism/2017Challenges,popcornanachr... | ---
+++
@@ -6,10 +6,8 @@
item_counter[item] = 1
else:
item_counter[item] += 1
-
- for item, item_count in item_counter.items():
- if item_count > len(sequence) / 2:
- return item
+ if item_counter[item] > len(sequence) / 2:
+ return ite... |
fb027f075c3745c5b14a5c611063d161a47f60e4 | oidc_apis/id_token.py | oidc_apis/id_token.py | import inspect
from .scopes import get_userinfo_by_scopes
def process_id_token(payload, user, scope=None):
if scope is None:
# HACK: Steal the scope argument from the locals dictionary of
# the caller, since it was not passed to us
scope = inspect.stack()[1][0].f_locals.get('scope', [])
... | import inspect
from .scopes import get_userinfo_by_scopes
def process_id_token(payload, user, scope=None):
if scope is None:
# HACK: Steal the scope argument from the locals dictionary of
# the caller, since it was not passed to us
scope = inspect.stack()[1][0].f_locals.get('scope', [])
... | Revert "Add username to ID Token" | Revert "Add username to ID Token"
This reverts commit 6e1126fe9a8269ff4489ee338000afc852bce922.
| Python | mit | mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo | ---
+++
@@ -10,5 +10,4 @@
scope = inspect.stack()[1][0].f_locals.get('scope', [])
payload.update(get_userinfo_by_scopes(user, scope))
- payload['preferred_username'] = user.username
return payload |
91fa1a8eec10b83aa5142d9519a3759b4e310cff | bluebottle/test/factory_models/accounts.py | bluebottle/test/factory_models/accounts.py | from builtins import object
import factory
from django.contrib.auth.models import Group
from bluebottle.members.models import Member
class BlueBottleUserFactory(factory.DjangoModelFactory):
class Meta(object):
model = Member
username = factory.Faker('email')
email = factory.Faker('email')
f... | from builtins import object
import factory
from django.contrib.auth.models import Group
from bluebottle.members.models import Member
class BlueBottleUserFactory(factory.DjangoModelFactory):
class Meta(object):
model = Member
username = factory.Sequence(lambda n: u'user_{0}'.format(n))
email = f... | Fix duplicate users during tests | Fix duplicate users during tests
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -10,8 +10,8 @@
class Meta(object):
model = Member
- username = factory.Faker('email')
- email = factory.Faker('email')
+ username = factory.Sequence(lambda n: u'user_{0}'.format(n))
+ email = factory.Sequence(lambda o: u'user_{0}@onepercentclub.com'.format(o))
first_name = ... |
4b6c27e02667fe6f5208b5b5dfa1f5dafe112c30 | luigi/tasks/export/search/chunk.py | luigi/tasks/export/search/chunk.py | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by... | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by... | Use new psql based export | Use new psql based export
This changes the function arguments to use.
| Python | apache-2.0 | RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline | ---
+++
@@ -21,7 +21,6 @@
from tasks.config import db
from tasks.config import output
-from rnacentral.db import cursor
from rnacentral.search import exporter
@@ -44,6 +43,5 @@
def run(self):
with self.output().open('w') as raw:
- with cursor(db()) as cur:
- results ... |
4cd345aa9a6b642af60529a94f047cf32847e262 | rplugin/python3/denite/source/gtags_path.py | rplugin/python3/denite/source/gtags_path.py | from .gtags_def import GtagsBase
class Source(GtagsBase):
def __init__(self, vim):
super().__init__(vim)
self.name = 'gtags_path'
self.kind = 'file'
@classmethod
def get_search_flags(cls):
return ['-P']
def gather_candidates(self, context):
tags = self.exec_g... | from .gtags_def import GtagsBase
class Source(GtagsBase):
def __init__(self, vim):
super().__init__(vim)
self.name = 'gtags_path'
self.kind = 'file'
@classmethod
def get_search_flags(cls):
return ['-P']
def gather_candidates(self, context):
tags = self.exec_g... | Fix missing parameter in path source | Fix missing parameter in path source
| Python | mit | ozelentok/denite-gtags | ---
+++
@@ -13,7 +13,7 @@
return ['-P']
def gather_candidates(self, context):
- tags = self.exec_global(self.get_search_flags())
+ tags = self.exec_global(self.get_search_flags(), context)
candidates = self._convert_to_candidates(tags)
return candidates
|
71aa5a7d665a432b6a01ec08bfba92e50d7fc29d | badgekit_webhooks/claimcode_views.py | badgekit_webhooks/claimcode_views.py | from __future__ import unicode_literals
from django.views.generic.edit import FormView
from .forms import SendClaimCodeForm
from .models import Badge
class SendClaimCodeView(FormView):
template_name = 'badgekit_webhooks/send_claim_code.html'
form_class = SendClaimCodeForm
success_url = '/' # TODO
def ... | from __future__ import unicode_literals
from django.views.generic.edit import FormMixin
from django.views.generic.base import View, TemplateResponseMixin
from .forms import SendClaimCodeForm
from .models import Badge
# This view starts as a copy of django.views.generic.edit.ProcessFormView
class SendClaimCodeView(Temp... | Refactor SendClaimCodeView to be more explict, will then modify | Refactor SendClaimCodeView to be more explict, will then modify
| Python | mit | tgs/django-badgekit-webhooks | ---
+++
@@ -1,18 +1,46 @@
from __future__ import unicode_literals
-from django.views.generic.edit import FormView
+from django.views.generic.edit import FormMixin
+from django.views.generic.base import View, TemplateResponseMixin
from .forms import SendClaimCodeForm
from .models import Badge
-class SendClaimCode... |
6d6b43ef861451e4d94acc5d7821b19734e60673 | apps/local_apps/account/context_processors.py | apps/local_apps/account/context_processors.py |
from account.models import Account, AnonymousAccount
def openid(request):
return {'openid': request.openid}
def account(request):
account = AnonymousAccount(request)
if request.user.is_authenticated():
try:
account = Account._default_manager.get(user=request.user)
except (Acco... |
from account.models import Account, AnonymousAccount
def openid(request):
return {'openid': request.openid}
def account(request):
if request.user.is_authenticated():
try:
account = Account._default_manager.get(user=request.user)
except (Account.DoesNotExist, Account.MultipleObject... | Handle the exception case in the account context_processor. | Handle the exception case in the account context_processor.
| Python | mit | ingenieroariel/pinax,ingenieroariel/pinax | ---
+++
@@ -5,10 +5,11 @@
return {'openid': request.openid}
def account(request):
- account = AnonymousAccount(request)
if request.user.is_authenticated():
try:
account = Account._default_manager.get(user=request.user)
except (Account.DoesNotExist, Account.MultipleObject... |
581285a6d887ab9beef3e2014db7f259109d1b5a | exercises/ex20.py | exercises/ex20.py | #!/usr/bin/python
def translate(translation_list):
trans_dict = {"merry":"god", "christmas":"jul", "and":"och",
"happy":"gott", "new":"nytt", "year":"år"}
final_translation_list = []
for word in translation_list:
if word in trans_dict:
final_translation_list.append... | # -*- coding: utf-8 -*-
#!/usr/bin/python
def translate(translation_list):
trans_dict = {"merry":"god", "christmas":"jul", "and":"och",
"happy":"gott", "new":"nytt", "year":"år"}
final_translation_list = []
for word in translation_list:
if word in trans_dict:
final... | Add some utf-8 encoding due to special chars. | Add some utf-8 encoding due to special chars.
| Python | mit | gravyboat/python-exercises | ---
+++
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
#!/usr/bin/python
|
b8ffeaa3274ead2c437526d507264af219929b61 | gerrit/plugins.py | gerrit/plugins.py | # -*- coding: utf-8 -*-
URLS = {
}
class Plugins(object):
""" This class provide plugin-related methods
Plugin related REST endpoints:
https://gerrit-review.googlesource.com/Documentation/rest-api-plugin.html
"""
def __init__(self, gerrit):
self.gerrit = gerrit
self.gerrit.URLS.u... | # -*- coding: utf-8 -*-
URLS = {
'LIST': 'plugins/',
'INSTALL': 'plugins/%(plugin_id)s',
'STATUS': 'plugins/%(plugin_id)s/gerrit~status',
'ENABLE': 'plugins/%(plugin_id)s/gerrit~enable',
'DISABLE': 'plugins/%(plugin_id)s/gerrit~disable',
'RELOAD': 'plugins/%(plugin_id)s/gerrit~reload',
}
clas... | Add methods for Plugin Endpoints | Add methods for Plugin Endpoints
Signed-off-by: Huang Yaming <ce2ec9fa26f071590d1a68b9e7447b51f2c76084@gmail.com>
| Python | apache-2.0 | yumminhuang/gerrit.py | ---
+++
@@ -1,6 +1,12 @@
# -*- coding: utf-8 -*-
URLS = {
+ 'LIST': 'plugins/',
+ 'INSTALL': 'plugins/%(plugin_id)s',
+ 'STATUS': 'plugins/%(plugin_id)s/gerrit~status',
+ 'ENABLE': 'plugins/%(plugin_id)s/gerrit~enable',
+ 'DISABLE': 'plugins/%(plugin_id)s/gerrit~disable',
+ 'RELOAD': 'plugins/%(... |
cf0850e23b07c656bd2bc56c88f9119dc4142931 | mooch/banktransfer.py | mooch/banktransfer.py | from django import http
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from mooch.base import BaseMoocher, require_POST_m
from mooch.signals imp... | from django import http
from django.conf.urls import url
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from mooch.base import BaseMoocher, require_POST_m
from mooch.signals imp... | Allow disabling the autocharging behavior of the bank transfer moocher | Allow disabling the autocharging behavior of the bank transfer moocher
| Python | mit | matthiask/django-mooch,matthiask/django-mooch,matthiask/django-mooch | ---
+++
@@ -12,6 +12,10 @@
class BankTransferMoocher(BaseMoocher):
identifier = 'banktransfer'
title = _('Pay by bank transfer')
+
+ def __init__(self, *, autocharge, **kw):
+ self.autocharge = autocharge
+ super(BankTransferMoocher, self).__init__(**kw)
def get_urls(self):
... |
b569ce0ae444e43cf6a64dd034186877cc259e2d | luigi/tasks/export/ftp/fasta/__init__.py | luigi/tasks/export/ftp/fasta/__init__.py | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by... | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by... | Clean up main fasta tasks | Clean up main fasta tasks
This removes the unneeded compress tasks as well as makes it easier to
know what task to run.
| Python | apache-2.0 | RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline | ---
+++
@@ -15,31 +15,12 @@
import luigi
-from tasks.utils.compress import GenericCompressTask
-
from .active import ActiveFastaExport
from .active import SpeciesSpecificFastaExport
from .inactive import InactiveFastaExport
from .nhmmer import NHmmerIncludedExport
from .nhmmer import NHmmerExcludedExport
f... |
1ffff2738c4ced2aedb8b63f5c729860aab1bac7 | marshmallow_jsonapi/__init__.py | marshmallow_jsonapi/__init__.py | from .schema import Schema, SchemaOpts
__version__ = "0.21.2"
__author__ = "Steven Loria"
__license__ = "MIT"
__all__ = ("Schema", "SchemaOpts")
| from .schema import Schema, SchemaOpts
__version__ = "0.21.2"
__all__ = ("Schema", "SchemaOpts")
| Remove unnecessary `__author__` and `__license__` | Remove unnecessary `__author__` and `__license__`
| Python | mit | marshmallow-code/marshmallow-jsonapi | ---
+++
@@ -1,7 +1,4 @@
from .schema import Schema, SchemaOpts
__version__ = "0.21.2"
-__author__ = "Steven Loria"
-__license__ = "MIT"
-
__all__ = ("Schema", "SchemaOpts") |
238b92a561f9285f7030b1dae51a3ffeb3de579e | tests/integrations/test_feedback_service.py | tests/integrations/test_feedback_service.py | # -*- coding: utf-8 -*-
import pytest
from junction.feedback import service
from .. import factories
pytestmark = pytest.mark.django_db
def test_get_feedback_questions_without_conference():
result = service.get_feedback_questions(conference_id=23)
assert result == {}
def test_get_feedback_questions_with... | # -*- coding: utf-8 -*-
import pytest
from junction.feedback import service
from .. import factories
pytestmark = pytest.mark.django_db
def test_get_feedback_questions_without_conference():
result = service.get_feedback_questions(conference_id=23)
assert result == {}
def test_get_feedback_questions_with... | Use set to compare list of values | Use set to compare list of values
| Python | mit | pythonindia/junction,ChillarAnand/junction,ChillarAnand/junction,pythonindia/junction,ChillarAnand/junction,ChillarAnand/junction,pythonindia/junction,pythonindia/junction | ---
+++
@@ -15,7 +15,7 @@
def test_get_feedback_questions_with_conference():
- schedule_item_types = ['Workshop', 'Talk']
+ schedule_item_types = set(['Workshop', 'Talk'])
num_choice_questions = 2
num_text_questions = 1
objects = factories.create_feedback_questions(
@@ -26,7 +26,7 @@
co... |
fc7323ddb0b2700ad459a8016fe4e56d9ac8e352 | morepath/tests/test_template.py | morepath/tests/test_template.py | import os
import morepath
from webtest import TestApp as Client
import pytest
from .fixtures import template
def setup_module(module):
morepath.disable_implicit()
def test_template():
config = morepath.setup()
config.scan(template)
config.commit()
c = Client(template.App())
response = c.get... | import os
import morepath
from webtest import TestApp as Client
import pytest
from .fixtures import template
def setup_module(module):
morepath.disable_implicit()
def test_template_fixture():
config = morepath.setup()
config.scan(template)
config.commit()
c = Client(template.App())
response... | Rename one test so it actually gets run. | Rename one test so it actually gets run.
| Python | bsd-3-clause | morepath/morepath,faassen/morepath,taschini/morepath | ---
+++
@@ -9,7 +9,7 @@
morepath.disable_implicit()
-def test_template():
+def test_template_fixture():
config = morepath.setup()
config.scan(template)
config.commit()
@@ -19,7 +19,7 @@
assert response.body == b'<p>Hello world!</p>\n'
-def test_template():
+def test_template_inline():... |
63130e4e438c34815bcd669d0088235140a62ced | readthedocs/core/utils/tasks/__init__.py | readthedocs/core/utils/tasks/__init__.py | from .permission_checks import *
from .public import *
from .retrieve import *
| from .permission_checks import user_id_matches
from .public import permission_check
from .public import get_public_task_data
from .retrieve import TaskNotFound
from .retrieve import get_task_data
| Remove star imports to remove pyflakes errors | Remove star imports to remove pyflakes errors
| Python | mit | safwanrahman/readthedocs.org,pombredanne/readthedocs.org,rtfd/readthedocs.org,tddv/readthedocs.org,safwanrahman/readthedocs.org,davidfischer/readthedocs.org,davidfischer/readthedocs.org,davidfischer/readthedocs.org,tddv/readthedocs.org,pombredanne/readthedocs.org,tddv/readthedocs.org,rtfd/readthedocs.org,safwanrahman/r... | ---
+++
@@ -1,3 +1,5 @@
-from .permission_checks import *
-from .public import *
-from .retrieve import *
+from .permission_checks import user_id_matches
+from .public import permission_check
+from .public import get_public_task_data
+from .retrieve import TaskNotFound
+from .retrieve import get_task_data |
cecea26672d74a026383c08ebf26bc72ab2ee66c | pingparsing/_pingtransmitter.py | pingparsing/_pingtransmitter.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import platform
import dataproperty
class PingTransmitter(object):
def __init__(self):
self.destination_host = ""
self.waittime = 1
... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
import platform
import dataproperty
PingResult = namedtuple("PingResult", "stdout stderr returncode")
class PingTrans... | Change ping result error handling to return values instead of raise exception | Change ping result error handling to return values instead of raise exception
| Python | mit | thombashi/pingparsing,thombashi/pingparsing | ---
+++
@@ -6,9 +6,13 @@
from __future__ import absolute_import
from __future__ import unicode_literals
+from collections import namedtuple
import platform
import dataproperty
+
+
+PingResult = namedtuple("PingResult", "stdout stderr returncode")
class PingTransmitter(object):
@@ -41,10 +45,7 @@
... |
9abcfcf971b053a5d3859faefc77a7622c00fc22 | gratipay/package_managers/readmes.py | gratipay/package_managers/readmes.py | from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import requests
from gratipay.utils import markdown
from gratipay.utils.threaded_map import threaded_map
from threading import Lock
log_lock = Lock()
def log(*a, **kw):
with log_lock:
print(*a, file=sys.stder... | from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import requests
from gratipay.utils import markdown
from gratipay.utils.threaded_map import threaded_map
from threading import Lock
log_lock = Lock()
def log(*a, **kw):
with log_lock:
print(*a, file=sys.stder... | Drop threads down to limit memory consumption | Drop threads down to limit memory consumption
| Python | mit | gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com | ---
+++
@@ -56,4 +56,4 @@
def sync_all(db):
dirty = db.all('SELECT package_manager, name FROM packages WHERE readme_raw IS NULL '
'ORDER BY package_manager DESC, name DESC')
- threaded_map(Syncer(db), dirty, 10)
+ threaded_map(Syncer(db), dirty, 4) |
760ba24c1413d4a0b7f68d8ce2d6a30df8ad8e4a | mothermayi/git.py | mothermayi/git.py | import contextlib
import logging
import subprocess
LOGGER = logging.getLogger(__name__)
def execute(command):
LOGGER.debug("Executing %s", ' '.join(command))
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate(input=None)
if proc.returncod... | import contextlib
import logging
import subprocess
LOGGER = logging.getLogger(__name__)
def execute(command):
LOGGER.debug("Executing %s", ' '.join(command))
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate(input=None)
if proc.returncod... | Put un-stash in finally block | Put un-stash in finally block
Without it a failure will lead to us not putting the user back in the
state they expect to be in
| Python | mit | EliRibble/mothermayi | ---
+++
@@ -16,6 +16,8 @@
@contextlib.contextmanager
def stash():
execute(['git', 'stash', '-u', '--keep-index'])
- yield
- execute(['git', 'reset', '--hard'])
- execute(['git', 'stash', 'pop', '--quiet', '--index'])
+ try:
+ yield
+ finally:
+ execute(['git', 'reset', '--hard'])
+ ... |
9db0f0430466b9d4d70c7803f7d39ecdeb85e375 | src/puzzle/problems/image/image_problem.py | src/puzzle/problems/image/image_problem.py | import numpy as np
from puzzle.problems import problem
class ImageProblem(problem.Problem):
def __init__(self, name: str, data: np.ndarray, *args, **kwargs) -> None:
super(ImageProblem, self).__init__(name, data, *args, **kwargs)
@staticmethod
def score(data: problem.ProblemData) -> float:
if not isin... | import numpy as np
from data.image import image
from puzzle.constraints.image import prepare_image_constraints
from puzzle.problems import problem
from puzzle.steps.image import prepare_image
class ImageProblem(problem.Problem):
_source_image: image.Image
_prepare_image: prepare_image.PrepareImage
def __init_... | Update ImageProblem to use PrepareImage step. | Update ImageProblem to use PrepareImage step.
| Python | mit | PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge | ---
+++
@@ -1,11 +1,21 @@
import numpy as np
+from data.image import image
+from puzzle.constraints.image import prepare_image_constraints
from puzzle.problems import problem
+from puzzle.steps.image import prepare_image
class ImageProblem(problem.Problem):
+ _source_image: image.Image
+ _prepare_image: pr... |
a5dee47e46d3bdc70a4fecf23e35d7e56c4c3177 | geotrek/common/management/commands/migrate.py | geotrek/common/management/commands/migrate.py | from django.apps import apps
from django.conf import settings
from django.contrib.gis.gdal import SpatialReference
from django.core.exceptions import ImproperlyConfigured
from django.core.management import call_command
from django.core.management.commands.migrate import Command as BaseCommand
from geotrek.common.utils... | from django.apps import apps
from django.conf import settings
from django.contrib.gis.gdal import SpatialReference
from django.core.exceptions import ImproperlyConfigured
from django.core.management import call_command
from django.core.management.commands.migrate import Command as BaseCommand
from geotrek.common.utils... | Fix no input call command | Fix no input call command
| Python | bsd-2-clause | GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin | ---
+++
@@ -24,7 +24,7 @@
move_models_to_schemas(app)
load_sql_files(app, 'pre')
super().handle(*args, **options)
- call_command('sync_translation_fields', noinput=True)
+ call_command('sync_translation_fields', '--noinput')
call_command('update_translation_fi... |
20c77152d1b81fd3ab42d9e563bb7170ef96906c | tools/misc/python/test-phenodata-output.py | tools/misc/python/test-phenodata-output.py | # TOOL test-phenodata-output.py: "Test phenodata output in Python" ()
# OUTPUT phenodata.tsv
# OUTPUT output.tsv
with open('output.tsv', 'w') as f:
f.write('test output\n')
f.write('test output\n')
with open('phenodata.tsv', 'w') as f:
f.write('sample original_name chiptype group\n')
f.write('microarray001.cel c... | # TOOL test-phenodata-output.py: "Test phenodata output in Python" ()
# INPUT input{...}.tsv TYPE GENERIC
# OUTPUT phenodata.tsv
# OUTPUT output.tsv
with open('output.tsv', 'w') as f:
f.write('identifier chip.sample1\n')
f.write('test output\n')
with open('phenodata.tsv', 'w') as f:
f.write('dataset column sample ... | Make output similar to Define NGS experiment tool | Make output similar to Define NGS experiment tool | Python | mit | chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools | ---
+++
@@ -1,12 +1,14 @@
-# TOOL test-phenodata-output.py: "Test phenodata output in Python" ()
+# TOOL test-phenodata-output.py: "Test phenodata output in Python" ()
+# INPUT input{...}.tsv TYPE GENERIC
# OUTPUT phenodata.tsv
# OUTPUT output.tsv
with open('output.tsv', 'w') as f:
- f.write('test output\n')
+ ... |
f96d2ceef6b15e397e82e310a3f369f61879a6d0 | ptpython/validator.py | ptpython/validator.py | from __future__ import unicode_literals
from prompt_toolkit.validation import Validator, ValidationError
__all__ = (
'PythonValidator',
)
class PythonValidator(Validator):
"""
Validation of Python input.
:param get_compiler_flags: Callable that returns the currently
active compiler flags.
... | from __future__ import unicode_literals
from prompt_toolkit.validation import Validator, ValidationError
__all__ = (
'PythonValidator',
)
class PythonValidator(Validator):
"""
Validation of Python input.
:param get_compiler_flags: Callable that returns the currently
active compiler flags.
... | Make get_compiler_flags optional for PythonValidator. (Fixes ptipython.) | Make get_compiler_flags optional for PythonValidator. (Fixes ptipython.)
| Python | bsd-3-clause | jonathanslenders/ptpython | ---
+++
@@ -14,7 +14,7 @@
:param get_compiler_flags: Callable that returns the currently
active compiler flags.
"""
- def __init__(self, get_compiler_flags):
+ def __init__(self, get_compiler_flags=None):
self.get_compiler_flags = get_compiler_flags
def validate(self, document... |
91a9da3bb1dda73add2a3040d35c9c58f7b5b4a5 | alg_lonely_integer.py | alg_lonely_integer.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def lonely_integer():
pass
def main():
pass
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def lonely_integer_naive(a_list):
"""Lonely integer by naive dictionary.
Time complexity: O(n).
Space complexity: O(n).
"""
integer_count_d = {}
for x in a_list:
if x in i... | Complete lonely int by naive dict & bit op | Complete lonely int by naive dict & bit op
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -2,13 +2,53 @@
from __future__ import division
from __future__ import print_function
-def lonely_integer():
- pass
+
+def lonely_integer_naive(a_list):
+ """Lonely integer by naive dictionary.
+
+ Time complexity: O(n).
+ Space complexity: O(n).
+ """
+ integer_count_d = {}
+
+ fo... |
5455a7796ece5a8987ef99f70d469ed3770f6a76 | server/src/weblab/db/gateway.py | server/src/weblab/db/gateway.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individuals,
# list... | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individuals,
# list... | Fix cfg_manager not existing in AbstractDatabaseGateway | Fix cfg_manager not existing in AbstractDatabaseGateway
| Python | bsd-2-clause | morelab/weblabdeusto,porduna/weblabdeusto,weblabdeusto/weblabdeusto,morelab/weblabdeusto,porduna/weblabdeusto,porduna/weblabdeusto,morelab/weblabdeusto,morelab/weblabdeusto,zstars/weblabdeusto,morelab/weblabdeusto,morelab/weblabdeusto,zstars/weblabdeusto,porduna/weblabdeusto,weblabdeusto/weblabdeusto,weblabdeusto/webla... | ---
+++
@@ -19,7 +19,7 @@
class AbstractDatabaseGateway(object):
def __init__(self, cfg_manager):
-
+ self.cfg_manager = cfg_manager
try:
self.host = cfg_manager.get_doc_value(configuration_doc.DB_HOST)
self.database_name = cfg_manager.get_doc_value(configura... |
7e97a1d060dc903f1e6a0c3f9f777edebabb99f7 | indra/tests/test_rlimsp.py | indra/tests/test_rlimsp.py | from indra.sources import rlimsp
def test_simple_usage():
rp = rlimsp.process_from_webservice('PMC3717945')
stmts = rp.statements
assert len(stmts) == 6, len(stmts)
for s in stmts:
assert len(s.evidence) == 1, "Wrong amount of evidence."
ev = s.evidence[0]
assert ev.annotations... | from indra.sources import rlimsp
def test_simple_usage():
rp = rlimsp.process_from_webservice('PMC3717945')
stmts = rp.statements
assert len(stmts) == 6, len(stmts)
for s in stmts:
assert len(s.evidence) == 1, "Wrong amount of evidence."
ev = s.evidence[0]
assert ev.annotations... | Check final count of statements. | Check final count of statements.
| Python | bsd-2-clause | pvtodorov/indra,sorgerlab/belpy,johnbachman/indra,pvtodorov/indra,johnbachman/indra,bgyori/indra,sorgerlab/indra,bgyori/indra,johnbachman/belpy,johnbachman/belpy,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/belpy,johnbachman/indra | ---
+++
@@ -20,7 +20,11 @@
def test_grounded_endpoint_with_pmids():
pmid_list = ['16403219', '22258404', '16961925', '22096607']
+ stmts = []
for pmid in pmid_list:
rp = rlimsp.process_from_webservice(pmid, id_type='pmid',
with_grounding=False)
... |
127a6d65b46e94f7698ae9739c1770903068351a | bempy/django/views.py | bempy/django/views.py | # -*- coding: utf-8 -*-
import os.path
from django.http import HttpResponse
from django.conf import settings
from functools import wraps
from bempy import ImmediateResponse
def returns_blocks(func):
@wraps(func)
def wrapper(request):
page = func(request)
try:
if isinstanc... | # -*- coding: utf-8 -*-
import os.path
from django.http import HttpResponse
from django.conf import settings
from functools import wraps
from bempy import ImmediateResponse
def returns_blocks(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
page = func(request, *args, **kwargs)
try... | Make wrapper returned by `returns_blocks` decorator, understand additional `args` and `kwargs` arguments. | Make wrapper returned by `returns_blocks` decorator, understand additional `args` and `kwargs` arguments.
| Python | bsd-3-clause | svetlyak40wt/bempy,svetlyak40wt/bempy,svetlyak40wt/bempy | ---
+++
@@ -9,9 +9,9 @@
def returns_blocks(func):
@wraps(func)
- def wrapper(request):
- page = func(request)
-
+ def wrapper(request, *args, **kwargs):
+ page = func(request, *args, **kwargs)
+
try:
if isinstance(page, HttpResponse):
return p... |
6ed4aa25d5e7113df75a622f6e86e83e9ace1390 | djangoautoconf/cmd_handler_base/database_connection_maintainer.py | djangoautoconf/cmd_handler_base/database_connection_maintainer.py | import thread
import time
from django.db import close_old_connections
class DatabaseConnectionMaintainer(object):
def __init__(self):
self.clients = set()
# self.device_to_protocol = {}
self.is_recent_db_change_occurred = False
self.delay_and_execute(3600, self.close_db_connection... | import thread
import time
from django.db import close_old_connections
class DatabaseConnectionMaintainer(object):
DB_TIMEOUT_SECONDS = 5*60
def __init__(self):
self.clients = set()
# self.device_to_protocol = {}
self.is_recent_db_change_occurred = False
self.delay_and_execute... | Update database close timeout value. | Update database close timeout value.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | ---
+++
@@ -5,18 +5,20 @@
class DatabaseConnectionMaintainer(object):
+ DB_TIMEOUT_SECONDS = 5*60
+
def __init__(self):
self.clients = set()
# self.device_to_protocol = {}
self.is_recent_db_change_occurred = False
- self.delay_and_execute(3600, self.close_db_connection_i... |
2c502a77ad18d34470e2be89ed1c7a38e6f3799d | tests/test_drogher.py | tests/test_drogher.py | import pytest
import drogher
from drogher.exceptions import InvalidBarcode
class TestDrogher:
def test_barcode(self):
shipper = drogher.barcode('1Z999AA10123456784')
assert shipper.shipper == 'UPS'
def test_invalid_barcode(self):
with pytest.raises(InvalidBarcode):
droghe... | import pytest
import drogher
from drogher.exceptions import InvalidBarcode
class TestDrogher:
def test_dhl_barcode(self):
shipper = drogher.barcode('1656740256')
assert shipper.shipper == 'DHL'
def test_fedex_express_barcode(self):
shipper = drogher.barcode('9632001960000000000400152... | Test barcode function with all shippers | Test barcode function with all shippers
| Python | bsd-3-clause | jbittel/drogher | ---
+++
@@ -5,9 +5,25 @@
class TestDrogher:
- def test_barcode(self):
+ def test_dhl_barcode(self):
+ shipper = drogher.barcode('1656740256')
+ assert shipper.shipper == 'DHL'
+
+ def test_fedex_express_barcode(self):
+ shipper = drogher.barcode('9632001960000000000400152152152158')... |
cca4f761ed39bd970c76c3b4ca581511bfe0130d | web/app/djrq/templates/letterscountsbar.py | web/app/djrq/templates/letterscountsbar.py | # encoding: cinje
: from cinje.std.html import link, div, span
: from urllib.parse import urlencode, quote_plus
: def letterscountsbar ctx, letterscountslist
: try
: selected_letter = ctx.selected_letter
: except AttributeError
: selected_letter = None
: end
<div class="col-sm-1 list-grou... | # encoding: cinje
: from cinje.std.html import link, div, span
: from urllib.parse import urlencode, quote_plus
: def letterscountsbar ctx, letterscountslist
: try
: selected_letter = ctx.selected_letter
: except AttributeError
: selected_letter = None
: end
<div class="col-sm-1 list-grou... | Fix problem on letter list display when the letter is a <space> | Fix problem on letter list display when the letter is a <space>
Work around for now for issue #10. And will need to be permanant, since
the real fix to the database import would make removing the space
optional.
| Python | mit | bmillham/djrq2,bmillham/djrq2,bmillham/djrq2 | ---
+++
@@ -20,7 +20,13 @@
<a href="/${ctx.resource.__resource__}/?letter=${l}"
tip='${row.count}'
class='list-group-item #{"active" if selected_letter == row.letter else ""}'>
- ${row.letter} <span class='badge'>${row.count}</span>
+ : if row.letter == ' '
+ ... |
d80c726fcf36a2dc439ce12717f9e88161501358 | gather/node/models.py | gather/node/models.py | # -*- coding:utf-8 -*-
from flask.ext.sqlalchemy import models_committed
from gather.extensions import db, cache
class Node(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False, unique=True, index=True)
slug = db.Column(db.String(100), nullable=False, un... | # -*- coding:utf-8 -*-
from flask.ext.sqlalchemy import models_committed
from gather.extensions import db, cache
class Node(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False, unique=True, index=True)
slug = db.Column(db.String(100), nullable=False, un... | Add order in nodes in topic creation form | Add order in nodes in topic creation form
| Python | mit | whtsky/Gather,whtsky/Gather | ---
+++
@@ -19,7 +19,7 @@
@classmethod
def query_all(cls):
- return cls.query.all()
+ return cls.query.order_by(Node.name.asc()).all()
def to_dict(self):
return dict( |
5d70735ab4254509e1efed73be4eecf77629063e | github_hook_server.py | github_hook_server.py | #! /usr/bin/env python
""" Our github hook receiving server. """
import os
from flask import Flask
from flask_hookserver import Hooks
from github import validate_review_request
from slack import notify_reviewer
app = Flask(__name__)
app.config['GITHUB_WEBHOOKS_KEY'] = os.environ.get('GITHUB_WEBHOOKS_KEY')
app.confi... | #! /usr/bin/env python
""" Our github hook receiving server. """
import os
from flask import Flask
from flask_hookserver import Hooks
from github import validate_review_request
from slack import notify_reviewer
app = Flask(__name__)
app.config['GITHUB_WEBHOOKS_KEY'] = os.environ.get('GITHUB_WEBHOOKS_KEY')
if os.env... | Fix env vars always evaluating as true | Fix env vars always evaluating as true
Env vars come through as strings. Which are true. The default on our
values is also true. Meaning it would never change. So we have to do
special string checking to get it to actually change. Yay.
| Python | mit | DobaTech/github-review-slack-notifier | ---
+++
@@ -11,8 +11,10 @@
app = Flask(__name__)
app.config['GITHUB_WEBHOOKS_KEY'] = os.environ.get('GITHUB_WEBHOOKS_KEY')
-app.config['VALIDATE_IP'] = os.environ.get('GIT_HOOK_VALIDATE_IP', True)
-app.config['VALIDATE_SIGNATURE'] = os.environ.get('GIT_HOOK_VALIDATE_SIGNATURE', True)
+if os.environ.get('GIT_HOOK_... |
93081d423a73a6b16e5adfb94247ffec23ef667c | api/base/authentication/backends.py | api/base/authentication/backends.py | from osf.models.user import OSFUser
from framework.auth.core import get_user
from django.contrib.auth.backends import ModelBackend
# https://docs.djangoproject.com/en/1.8/topics/auth/customizing/
class ODMBackend(ModelBackend):
def authenticate(self, username=None, password=None):
return get_user(email=us... | from osf.models.user import OSFUser
from framework.auth.core import get_user
from django.contrib.auth.backends import ModelBackend
# https://docs.djangoproject.com/en/3.2/topics/auth/customizing/
class ODMBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
retu... | Fix admin login failure for django upgrade | Fix admin login failure for django upgrade
| Python | apache-2.0 | Johnetordoff/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io | ---
+++
@@ -2,10 +2,11 @@
from framework.auth.core import get_user
from django.contrib.auth.backends import ModelBackend
-# https://docs.djangoproject.com/en/1.8/topics/auth/customizing/
+
+# https://docs.djangoproject.com/en/3.2/topics/auth/customizing/
class ODMBackend(ModelBackend):
- def authenticate(se... |
47ea8ca6034bfbb16e9049081b5158d9b01833fc | pytest_ansible/__init__.py | pytest_ansible/__init__.py | __version__ = '1.4.0'
__author__ = "James Laska"
__author_email__ = "<jlaska@ansible.com>"
| __version__ = '2.0.0'
__author__ = "James Laska"
__author_email__ = "<jlaska@ansible.com>"
| Prepare for next major release | Prepare for next major release
| Python | mit | jlaska/pytest-ansible | ---
+++
@@ -1,3 +1,3 @@
-__version__ = '1.4.0'
+__version__ = '2.0.0'
__author__ = "James Laska"
__author_email__ = "<jlaska@ansible.com>" |
db4355ce0345df9dd23b937370f5f0d4cb2164e9 | zc_common/remote_resource/filters.py | zc_common/remote_resource/filters.py | import re
from django.db.models.fields.related import ManyToManyField
from rest_framework import filters
class JSONAPIFilterBackend(filters.DjangoFilterBackend):
def filter_queryset(self, request, queryset, view):
filter_class = self.get_filter_class(view, queryset)
primary_key = queryset.model._... | import re
from distutils.util import strtobool
from django.db.models import BooleanField, FieldDoesNotExist
from django.db.models.fields.related import ManyToManyField
from rest_framework import filters
class JSONAPIFilterBackend(filters.DjangoFilterBackend):
def filter_queryset(self, request, queryset, view):
... | Use 'true' while filtering a boolean as opposed to 'True' | Use 'true' while filtering a boolean as opposed to 'True'
| Python | mit | ZeroCater/zc_common,ZeroCater/zc_common | ---
+++
@@ -1,5 +1,7 @@
import re
+from distutils.util import strtobool
+from django.db.models import BooleanField, FieldDoesNotExist
from django.db.models.fields.related import ManyToManyField
from rest_framework import filters
@@ -27,6 +29,14 @@
if hasattr(queryset.model, field_name)\
... |
a789f05ac157effabe3426611b3ea7e6cef5fb3d | makahiki/apps/managers/team_mgr/team_mgr.py | makahiki/apps/managers/team_mgr/team_mgr.py | """The manager for managing team."""
from apps.managers.score_mgr import score_mgr
from apps.managers.team_mgr.models import Team
def team_members(team):
"""Get the team members."""
return team.profile_set()
def team_points_leader(round_name="Overall"):
"""Returns the team points leader (the first place... | """The manager for managing team."""
from apps.managers.score_mgr import score_mgr
from apps.managers.team_mgr.models import Team
def team_members(team):
"""Get the team members."""
return team.profile_set.all()
def team_points_leader(round_name="Overall"):
"""Returns the team points leader (the first p... | Fix for all members in the news page. | Fix for all members in the news page.
| Python | mit | jtakayama/makahiki-draft,yongwen/makahiki,jtakayama/makahiki-draft,jtakayama/ics691-setupbooster,yongwen/makahiki,jtakayama/ics691-setupbooster,yongwen/makahiki,yongwen/makahiki,jtakayama/makahiki-draft,jtakayama/makahiki-draft,jtakayama/ics691-setupbooster,csdl/makahiki,csdl/makahiki,csdl/makahiki,justinslee/Wai-Not-M... | ---
+++
@@ -5,7 +5,7 @@
def team_members(team):
"""Get the team members."""
- return team.profile_set()
+ return team.profile_set.all()
def team_points_leader(round_name="Overall"): |
583ea6c1a234ab9d484b1e80e7f567d9a5d2fb71 | shopify/resources/image.py | shopify/resources/image.py | from ..base import ShopifyResource
import base64
import re
class Image(ShopifyResource):
_prefix_source = "/admin/products/$product_id/"
def __getattr__(self, name):
if name in ["pico", "icon", "thumb", "small", "compact", "medium", "large", "grande", "original"]:
return re.sub(r"/(.*)\.(... | from ..base import ShopifyResource
from ..resources import Metafield
from six.moves import urllib
import base64
import re
class Image(ShopifyResource):
_prefix_source = "/admin/products/$product_id/"
def __getattr__(self, name):
if name in ["pico", "icon", "thumb", "small", "compact", "medium", "larg... | Add `metafields()` method to `Image` resource. | Add `metafields()` method to `Image` resource. | Python | mit | asiviero/shopify_python_api,SmileyJames/shopify_python_api,Shopify/shopify_python_api,metric-collective/shopify_python_api,gavinballard/shopify_python_api,ifnull/shopify_python_api | ---
+++
@@ -1,4 +1,6 @@
from ..base import ShopifyResource
+from ..resources import Metafield
+from six.moves import urllib
import base64
import re
@@ -16,3 +18,9 @@
self.attributes["attachment"] = base64.b64encode(data)
if filename:
self.attributes["filename"] = filename
+
+ de... |
b771fd2a463266e1c80b1b4cccfe78d822c391a2 | byceps/blueprints/admin/shop/order/forms.py | byceps/blueprints/admin/shop/order/forms.py | """
byceps.blueprints.admin.shop.order.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from flask_babel import lazy_gettext
from wtforms import BooleanField, RadioField, StringField, TextAreaField
from wtforms.validat... | """
byceps.blueprints.admin.shop.order.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from flask_babel import lazy_gettext
from wtforms import BooleanField, RadioField, StringField, TextAreaField
from wtforms.validat... | Stabilize order of payment methods in mark-as-paid form | Stabilize order of payment methods in mark-as-paid form
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -30,10 +30,12 @@
def _get_payment_method_choices():
- return [
+ choices = [
(pm, order_service.find_payment_method_label(pm) or pm)
for pm in PAYMENT_METHODS
]
+ choices.sort()
+ return choices
class MarkAsPaidForm(LocalizedForm): |
ef7ac85615d9790525a6e5364105613905cae859 | tests/test_backend.py | tests/test_backend.py | from datetime import datetime
import pytest
import pytz
from todoman.model import Todo, VtodoWritter
def test_serialize_created_at(todo_factory):
now = datetime.now(tz=pytz.UTC)
todo = todo_factory(created_at=now)
vtodo = VtodoWritter(todo).serialize()
assert vtodo.get('created') is not None
def ... | from datetime import datetime
import pytest
import pytz
from dateutil.tz import tzlocal
from todoman.model import Todo, VtodoWritter
def test_serialize_created_at(todo_factory):
now = datetime.now(tz=pytz.UTC)
todo = todo_factory(created_at=now)
vtodo = VtodoWritter(todo).serialize()
assert vtodo.g... | Test VTODO serialization for all data types | Test VTODO serialization for all data types
| Python | isc | pimutils/todoman,AnubhaAgrawal/todoman,Sakshisaraswat/todoman,hobarrera/todoman | ---
+++
@@ -2,6 +2,7 @@
import pytest
import pytz
+from dateutil.tz import tzlocal
from todoman.model import Todo, VtodoWritter
@@ -35,3 +36,24 @@
serialized_fields = set(VtodoWritter.FIELD_MAP.keys())
assert supported_fields == serialized_fields
+
+
+def test_vtodo_serialization(todo_factory):
+... |
216a52d52fdbfca959946434a81f4d42270bfd95 | bluebottle/organizations/serializers.py | bluebottle/organizations/serializers.py | from rest_framework import serializers
from bluebottle.organizations.models import Organization
from bluebottle.utils.serializers import URLField
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'slug', 'address_line1', 'address_l... | from rest_framework import serializers
from bluebottle.organizations.models import Organization
from bluebottle.utils.serializers import URLField
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'slug', 'address_line1', 'address_l... | Make the name of an organization required | Make the name of an organization required
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle | ---
+++
@@ -14,7 +14,7 @@
class ManageOrganizationSerializer(serializers.ModelSerializer):
slug = serializers.SlugField(required=False, allow_null=True)
- name = serializers.CharField(required=True, allow_blank=True)
+ name = serializers.CharField(required=True)
website = URLField(required=False, a... |
bf5518f2f181879141279d9322fe75f3163d438d | byceps/services/news/transfer/models.py | byceps/services/news/transfer/models.py | """
byceps.services.news.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from dataclasses import dataclass
from datetime import datetime
from typing import List, NewType
from uuid import UUID
from ....typing import B... | """
byceps.services.news.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from dataclasses import dataclass
from datetime import datetime
from typing import List, NewType, Optional
from uuid import UUID
from ....typin... | Mark optional news image and item fields as such | Mark optional news image and item fields as such
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -8,7 +8,7 @@
from dataclasses import dataclass
from datetime import datetime
-from typing import List, NewType
+from typing import List, NewType, Optional
from uuid import UUID
from ....typing import BrandID, UserID
@@ -41,9 +41,9 @@
item_id: ItemID
number: int
filename: str
- alt... |
c2a0b4c99f515a6fafae85d72be9d54b3c92c0b3 | databench/__init__.py | databench/__init__.py | """Databench module."""
__version__ = "0.3.0"
# Need to make sure monkey.patch_all() is applied before any
# 'import threading', but cannot raise error because building the Sphinx
# documentation also suffers from this problem, but there it can be ignored.
import sys
if 'threading' in sys.modules:
print 'WARNING:... | """Databench module."""
__version__ = "0.3.0"
# Need to make sure monkey.patch_all() is applied before any
# 'import threading', but cannot raise error because building the Sphinx
# documentation also suffers from this problem, but there it can be ignored.
import sys
if 'threading' in sys.modules:
print 'WARNING:... | Change all instances list of Meta from a global to a class variable. | Change all instances list of Meta from a global to a class variable.
| Python | mit | svenkreiss/databench,svenkreiss/databench,svenkreiss/databench,svenkreiss/databench | ---
+++
@@ -12,5 +12,5 @@
import gevent.monkey
gevent.monkey.patch_all()
-from .analysis import LIST_ALL_META, Meta, Analysis, MetaZMQ, AnalysisZMQ
+from .analysis import Meta, Analysis, MetaZMQ, AnalysisZMQ
from .app import run |
e16960eaaf38513e80fb18580c3e4320978407e4 | chainer/training/triggers/__init__.py | chainer/training/triggers/__init__.py | from chainer.training.triggers import interval_trigger # NOQA
from chainer.training.triggers import minmax_value_trigger # NOQA
# import class and function
from chainer.training.triggers.early_stopping_trigger import EarlyStoppingTrigger # NOQA
from chainer.training.triggers.interval_trigger import IntervalTrigger... | from chainer.training.triggers import interval_trigger # NOQA
from chainer.training.triggers import minmax_value_trigger # NOQA
# import class and function
from chainer.training.triggers.early_stopping_trigger import EarlyStoppingTrigger # NOQA
from chainer.training.triggers.interval_trigger import IntervalTrigger... | Fix the order of importing | Fix the order of importing
| Python | mit | wkentaro/chainer,ktnyt/chainer,chainer/chainer,ktnyt/chainer,jnishi/chainer,jnishi/chainer,wkentaro/chainer,chainer/chainer,ktnyt/chainer,ktnyt/chainer,niboshi/chainer,jnishi/chainer,hvy/chainer,chainer/chainer,pfnet/chainer,niboshi/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,hvy/chainer,keisuke-umezawa/cha... | ---
+++
@@ -9,4 +9,3 @@
from chainer.training.triggers.minmax_value_trigger import BestValueTrigger # NOQA
from chainer.training.triggers.minmax_value_trigger import MaxValueTrigger # NOQA
from chainer.training.triggers.minmax_value_trigger import MinValueTrigger # NOQA
-from chainer.training.triggers.early_sto... |
b60fbc21271a7efa09d256debb17f583ec83fdf2 | MMCorePy_wrap/setup.py | MMCorePy_wrap/setup.py | #!/usr/bin/env python
"""
setup.py file for SWIG example
"""
from distutils.core import setup, Extension
import numpy.distutils.misc_util
import os
os.environ['CC'] = 'g++'
#os.environ['CXX'] = 'g++'
#os.environ['CPP'] = 'g++'
#os.environ['LDSHARED'] = 'g++'
mmcorepy_module = Extension('_MMCorePy',
... | #!/usr/bin/env python
"""
This setup.py is intended for use from the Autoconf/Automake build system.
It makes a number of assumtions, including that the SWIG sources have already
been generated.
"""
from distutils.core import setup, Extension
import numpy.distutils.misc_util
import os
os.environ['CC'] = 'g++'
#os.en... | Add MMCore/Host.cpp to Unix build. | MMCorePy: Add MMCore/Host.cpp to Unix build.
Was missing. Note that build is still broken (even though it does not
explicitly fail), at least on Mac OS X, because of missing libraries
(IOKit, CoreFoundation, and boost.system, I think).
Also removed MMDevice/Property.cpp, which is not needed here.
git-svn-id: 03a8048... | Python | mit | kmdouglass/Micro-Manager,kmdouglass/Micro-Manager | ---
+++
@@ -1,7 +1,9 @@
#!/usr/bin/env python
"""
-setup.py file for SWIG example
+This setup.py is intended for use from the Autoconf/Automake build system.
+It makes a number of assumtions, including that the SWIG sources have already
+been generated.
"""
from distutils.core import setup, Extension
@@ -15,2... |
8ae6cfd75d5dc6b775aa80dcc91874c3a9ee7758 | WebSphere/changeUID.py | WebSphere/changeUID.py | # Script to change the UID of Users
#
# Author: Christoph Stoettner
# E-Mail: christoph.stoettner@stoeps.de
#
# example: wsadmin.sh -lang jython -f changeUID.py file.csv
#
# Format of CSV-File:
# uid;mailaddress
#
import sys
import os
# Check OS on windows .strip('\n') is not required
# Import Connections Admin Comma... | # Script to change the UID of Users
#
# Author: Christoph Stoettner
# E-Mail: christoph.stoettner@stoeps.de
#
# example: wsadmin.sh -lang jython -f changeUID.py file.csv
#
# Format of CSV-File:
# uid;mailaddress
# don't mask strings with "
#
import sys
import os
# Check OS on windows .strip('\n') is not required
# I... | Change some comments as documentation | Change some comments as documentation | Python | apache-2.0 | stoeps13/ibmcnxscripting,stoeps13/ibmcnxscripting,stoeps13/ibmcnxscripting | ---
+++
@@ -6,7 +6,8 @@
# example: wsadmin.sh -lang jython -f changeUID.py file.csv
#
# Format of CSV-File:
-# uid;mailaddress
+# uid;mailaddress
+# don't mask strings with "
#
import sys
import os |
010444e37787582788268ccea860ae6bb97bd4b1 | enthought/traits/ui/editors/date_editor.py | enthought/traits/ui/editors/date_editor.py | #------------------------------------------------------------------------------
#
# Copyright (c) 2008, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions... | #------------------------------------------------------------------------------
#
# Copyright (c) 2008, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions... | Allow shift to be required using a factory trait. | Allow shift to be required using a factory trait.
| Python | bsd-3-clause | burnpanck/traits,burnpanck/traits | ---
+++
@@ -33,7 +33,7 @@
#-- CustomEditor traits ----------------------------------------------------
- # True: Must be a List of Dates. False: A Date instance.
+ # True: Must be a List of Dates. False: Must be a Date instance.
multi_select = Bool(False)
# Should users be ab... |
d3cb08d45af60aaf06757ad230a2a33bc3615543 | apps/organizations/middleware.py | apps/organizations/middleware.py | from django.http import Http404
from .models import Organization
class OrganizationMiddleware(object):
def process_request(self, request):
try:
request.organization = Organization.objects.get(
slug__iexact=request.subdomain
)
except Organization.DoesNotExi... | from django.http import Http404
from .models import Organization
class OrganizationMiddleware(object):
def process_request(self, request):
if request.subdomain is None:
return
try:
request.organization = Organization.objects.get(
slug__iexact=request.subdo... | Remove subdomain check on pages where subdomain is none | Remove subdomain check on pages where subdomain is none
| Python | mit | xobb1t/ddash2013,xobb1t/ddash2013 | ---
+++
@@ -6,6 +6,8 @@
class OrganizationMiddleware(object):
def process_request(self, request):
+ if request.subdomain is None:
+ return
try:
request.organization = Organization.objects.get(
slug__iexact=request.subdomain |
cbf4d85092232051cd7643d74e003b86f24ba571 | feincms/templatetags/feincms_admin_tags.py | feincms/templatetags/feincms_admin_tags.py | from django import template
register = template.Library()
@register.filter
def post_process_fieldsets(fieldset):
"""
Removes a few fields from FeinCMS admin inlines, those being
``id``, ``DELETE`` and ``ORDER`` currently.
"""
process = fieldset.model_admin.verbose_name_plural.startswith('Feincm... | from django import template
register = template.Library()
@register.filter
def post_process_fieldsets(fieldset):
"""
Removes a few fields from FeinCMS admin inlines, those being
``id``, ``DELETE`` and ``ORDER`` currently.
"""
excluded_fields = ('id', 'DELETE', 'ORDER')
fieldset.fields = [f ... | Fix post_process_fieldsets: This filter is only called for FeinCMS inlines anyway | Fix post_process_fieldsets: This filter is only called for FeinCMS inlines anyway
Thanks to mjl for the report and help in fixing the issue.
| Python | bsd-3-clause | matthiask/django-content-editor,matthiask/feincms2-content,joshuajonah/feincms,matthiask/feincms2-content,matthiask/django-content-editor,mjl/feincms,feincms/feincms,nickburlett/feincms,mjl/feincms,nickburlett/feincms,feincms/feincms,pjdelport/feincms,pjdelport/feincms,mjl/feincms,nickburlett/feincms,michaelkuty/feincm... | ---
+++
@@ -11,11 +11,8 @@
``id``, ``DELETE`` and ``ORDER`` currently.
"""
- process = fieldset.model_admin.verbose_name_plural.startswith('Feincms_Inline:')
- if process:
- # Exclude special fields and the primary key
- excluded_fields = ('id', 'DELETE', 'ORDER')
- fieldset.fie... |
42592f3f990ccd111244a8be90513aa4cf35f678 | fireplace/cards/classic/neutral_epic.py | fireplace/cards/classic/neutral_epic.py | from ..utils import *
# Big Game Hunter
class EX1_005:
action = [Destroy(TARGET)]
# Mountain Giant
class EX1_105:
def cost(self, value):
return value - (len(self.controller.hand) - 1)
# Sea Giant
class EX1_586:
def cost(self, value):
return value - len(self.game.board)
# Blood Knight
class EX1_590:
def ... | from ..utils import *
# Big Game Hunter
class EX1_005:
action = [Destroy(TARGET)]
# Mountain Giant
class EX1_105:
def cost(self, value):
return value - (len(self.controller.hand) - 1)
# Sea Giant
class EX1_586:
def cost(self, value):
return value - len(self.game.board)
# Blood Knight
class EX1_590:
acti... | Use Count() in Blood Knight | Use Count() in Blood Knight
| Python | agpl-3.0 | liujimj/fireplace,Ragowit/fireplace,jleclanche/fireplace,butozerca/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,liujimj/fireplace,Meerkov/fireplace,smallnamespace/fireplace,butozerca/fireplace,NightKev/fireplace,smallnamespace/fireplace,amw2104/fireplace,oftc-ftw/fireplace,amw2104/fireplace,beheh/fireplace,Ragowit/fi... | ---
+++
@@ -20,12 +20,10 @@
# Blood Knight
class EX1_590:
- def action(self):
- count = len(self.game.board.filter(divine_shield=True))
- return [
- SetTag(ALL_MINIONS, {GameTag.DIVINE_SHIELD: False}),
- Buff(self, "EX1_590e") * count,
- ]
+ action = [
+ Buff(SELF, "EX1_590e") * Count(ALL_MINIONS + DIVINE... |
64d6a44ecbbaa7d8ac2c79bd95827ced66254bcf | fireplace/carddata/minions/warlock.py | fireplace/carddata/minions/warlock.py | import random
from ..card import *
# Blood Imp
class CS2_059(Card):
def endTurn(self):
if self.game.currentPlayer is self.owner:
if self.owner.field:
random.choice(self.owner.field).buff("CS2_059o")
class CS2_059o(Card):
health = 1
# Felguard
class EX1_301(Card):
def activate(self):
self.owner.loseMa... | import random
from ..card import *
# Blood Imp
class CS2_059(Card):
def endTurn(self):
if self.game.currentPlayer is self.owner:
if self.owner.field:
random.choice(self.owner.field).buff("CS2_059o")
class CS2_059o(Card):
health = 1
# Felguard
class EX1_301(Card):
def activate(self):
self.owner.loseMa... | IMPLEMENT JARAXXUS, EREDAR LORD OF THE BURNING LEGION | IMPLEMENT JARAXXUS, EREDAR LORD OF THE BURNING LEGION
| Python | agpl-3.0 | butozerca/fireplace,jleclanche/fireplace,amw2104/fireplace,NightKev/fireplace,liujimj/fireplace,amw2104/fireplace,smallnamespace/fireplace,butozerca/fireplace,oftc-ftw/fireplace,beheh/fireplace,Ragowit/fireplace,Meerkov/fireplace,Meerkov/fireplace,oftc-ftw/fireplace,liujimj/fireplace,smallnamespace/fireplace,Ragowit/fi... | ---
+++
@@ -39,3 +39,10 @@
class EX1_319(Card):
def activate(self):
self.owner.hero.damage(3)
+
+
+# Lord Jaraxxus
+class EX1_323(Card):
+ def activate(self):
+ self.removeFromField()
+ self.owner.setHero("EX1_323h") |
49dc93d0fd2ab58815d91aba8afc6796cf45ce98 | migrations/versions/0093_data_gov_uk.py | migrations/versions/0093_data_gov_uk.py | """empty message
Revision ID: 0093_data_gov_uk
Revises: 0092_add_inbound_provider
Create Date: 2017-06-05 16:15:17.744908
"""
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects imp... | """empty message
Revision ID: 0093_data_gov_uk
Revises: 0092_add_inbound_provider
Create Date: 2017-06-05 16:15:17.744908
"""
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects imp... | Revert "Remove name from organisation" | Revert "Remove name from organisation"
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | ---
+++
@@ -21,7 +21,7 @@
op.execute("""INSERT INTO organisation VALUES (
'{}',
'',
- '',
+ 'data_gov_uk_x2.png',
''
)""".format(DATA_GOV_UK_ID))
|
4e135d1e40499f06b81d4ec3b427462c9b4ba2ee | test/cli/test_cmd_piper.py | test/cli/test_cmd_piper.py | from piper import build
from piper.db import core as db
from piper.cli import cmd_piper
from piper.cli.cli import CLIBase
import mock
class TestEntry(object):
@mock.patch('piper.cli.cmd_piper.CLIBase')
def test_calls(self, clibase):
self.mock = mock.Mock()
cmd_piper.entry(self.mock)
c... | from piper import build
from piper.db import core as db
from piper.cli import cmd_piper
from piper.cli.cli import CLIBase
import mock
class TestEntry(object):
@mock.patch('piper.cli.cmd_piper.CLIBase')
def test_calls(self, clibase):
self.mock = mock.Mock()
cmd_piper.entry(self.mock)
c... | Add short integration test for ExecCLI.build | Add short integration test for ExecCLI.build
| Python | mit | thiderman/piper | ---
+++
@@ -32,3 +32,11 @@
db.DbCLI.db = mock.Mock()
cli.entry()
db.DbCLI.db.init.assert_called_once_with(cli.config)
+
+ @mock.patch('piper.build.Build.run')
+ def test_exec(self, run):
+ args = ['exec']
+ cli = CLIBase('piper', (build.ExecCLI,), args=args)
+
+ c... |
cfd2312ae81dd79832d4b03717278a79bc8705d1 | brte/converters/btf.py | brte/converters/btf.py | if 'imported' in locals():
import imp
import bpy
imp.reload(blendergltf)
else:
imported = True
from . import blendergltf
import json
import math
import bpy
class BTFConverter:
def convert(self, add_delta, update_delta, remove_delta, view_delta):
for key, value in update_delta.items(... | if 'imported' in locals():
import imp
import bpy
imp.reload(blendergltf)
else:
imported = True
from . import blendergltf
import json
import math
import bpy
def togl(matrix):
return [i for col in matrix.col for i in col]
class BTFConverter:
def convert(self, add_delta, update_delta, re... | Fix JSON serialization issue with view and projection matrices | Fix JSON serialization issue with view and projection matrices
| Python | mit | Kupoman/BlenderRealtimeEngineAddon | ---
+++
@@ -11,6 +11,10 @@
import math
import bpy
+
+
+def togl(matrix):
+ return [i for col in matrix.col for i in col]
class BTFConverter:
@@ -33,6 +37,6 @@
gltf['extras']['view'] = {
'width' : view_delta['viewport'].width,
'height' : view_delta['viewport']... |
d7a434de8926162adeff6e6934dde7eb771baf8d | custom/enikshay/reports/views.py | custom/enikshay/reports/views.py | from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.locations.permissions import location_safe
from corehq.apps.userreports.reports.filters.choi... | from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.locations.permissions import location_safe
from corehq.apps.userreports.reports.filters.choi... | Fix pagination of locations filter | Fix pagination of locations filter
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -32,6 +32,6 @@
{'id': location.value, 'text': location.display}
for location in location_choice_provider.query(query_context)
],
- 'total': location_choice_provider.query_count(query_context, user)
+ 'total': location_... |
efca073ec2c15bb2d60c5c8b1e675dcdcbc51ed1 | fade/fade/__init__.py | fade/fade/__init__.py | #!/usr/bin/env python
"""
See LICENSE.txt file for copyright and license details.
"""
from flask import Flask
from app import views
import sys
app = Flask(__name__)
app.config.from_object('config')
def adjust_system_path():
"""
Adjust the system path, so we can search in custom dirs for modu... | Move to run.py at higher level. | Move to run.py at higher level. | Python | bsd-3-clause | rockwolf/python,rockwolf/python,rockwolf/python,rockwolf/python,rockwolf/python,rockwolf/python | ---
+++
@@ -1,29 +1 @@
-#!/usr/bin/env python
-"""
- See LICENSE.txt file for copyright and license details.
-"""
-from flask import Flask
-from app import views
-import sys
-
-app = Flask(__name__)
-app.config.from_object('config')
-
-
-def adjust_system_path():
- """
- Adjust the system path,... | |
097d2b7b3de6593a0aac8e82418c0dcadc299542 | tests/unit/test_context.py | tests/unit/test_context.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apac... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apac... | Replace using tests.utils with openstack.common.test | Replace using tests.utils with openstack.common.test
It is the first step to replace using tests.utils with openstack.common.test.
All these tests don't use mock objects, stubs, config files and use only
BaseTestCase class.
Change-Id: I511816b5c9e6c5c34ebff199296ee4fc8b84c672
bp: common-unit-tests
| Python | apache-2.0 | openstack/oslo.context,dims/oslo.context,varunarya10/oslo.context,yanheven/oslo.middleware,JioCloud/oslo.context,citrix-openstack-build/oslo.context | ---
+++
@@ -16,10 +16,10 @@
# under the License.
from openstack.common import context
-from tests import utils
+from openstack.common import test
-class ContextTest(utils.BaseTestCase):
+class ContextTest(test.BaseTestCase):
def test_context(self):
ctx = context.RequestContext() |
2057b76908c8875fd58d3027a89e43584ee57025 | service/opencv.py | service/opencv.py | __author__ = 'paulo'
import cv2
class OpenCVIntegration(object):
@staticmethod
def adaptive_threshold(filename_in, filename_out):
img = cv2.imread(filename_in)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_B... | __author__ = 'paulo'
import cv2
class OpenCVIntegration(object):
@staticmethod
def adaptive_threshold(filename_in, filename_out):
img = cv2.imread(filename_in)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_B... | Fix IMWRITE_JPEG_QUALITY ref for the newest OpenCV | Fix IMWRITE_JPEG_QUALITY ref for the newest OpenCV | Python | mit | nfscan/ocr-process-service,nfscan/ocr-process-service,PauloMigAlmeida/ocr-process-service,PauloMigAlmeida/ocr-process-service | ---
+++
@@ -11,12 +11,12 @@
img = cv2.imread(filename_in)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)
- params = [cv2.cv.CV_IMWRITE_JPEG_QUALITY, 100]
+ params = [cv2.IMWRITE_JPEG_QUALIT... |
0562f34398041e6696f6e9bad56ea2a135968b77 | paratemp/sim_setup/pt_simulation.py | paratemp/sim_setup/pt_simulation.py | """This contains code for setting up parallel tempering calcs"""
########################################################################
# #
# This script was written by Thomas Heavey in 2019. #
# theavey@bu.edu thomasj... | """This contains code for setting up parallel tempering calcs"""
########################################################################
# #
# This script was written by Thomas Heavey in 2019. #
# theavey@bu.edu thomasj... | Fix typo in inheritence/super call | Fix typo in inheritence/super call
| Python | apache-2.0 | theavey/ParaTemp,theavey/ParaTemp | ---
+++
@@ -28,4 +28,4 @@
class PTSimulation(Simulation):
def __init__(self, *args, **kwargs):
- super(Simulation, self).__init__(*args, **kwargs)
+ super(PTSimulation, self).__init__(*args, **kwargs) |
1c6b190a91823a6731083b3e8a415277e0352e19 | python_apps/airtime_analyzer/setup.py | python_apps/airtime_analyzer/setup.py | import os
from setuptools import setup
# Change directory since setuptools uses relative paths
os.chdir(os.path.dirname(os.path.realpath(__file__)))
setup(
name="libretime-analyzer",
version="0.1",
description="Libretime Analyzer Worker and File Importer",
url="https://libretime.org",
author="Lib... | import os
from setuptools import setup
# Change directory since setuptools uses relative paths
os.chdir(os.path.dirname(os.path.realpath(__file__)))
setup(
name="libretime-analyzer",
version="0.1",
description="Libretime Analyzer Worker and File Importer",
url="https://libretime.org",
author="Lib... | Update pika requirement in /python_apps/airtime_analyzer | Update pika requirement in /python_apps/airtime_analyzer
Updates the requirements on [pika](https://github.com/pika/pika) to permit the latest version.
- [Release notes](https://github.com/pika/pika/releases)
- [Commits](https://github.com/pika/pika/compare/1.1.0...1.2.0)
---
updated-dependencies:
- dependency-name: ... | Python | agpl-3.0 | LibreTime/libretime,LibreTime/libretime,LibreTime/libretime,LibreTime/libretime,LibreTime/libretime,LibreTime/libretime | ---
+++
@@ -20,7 +20,7 @@
},
install_requires=[
"mutagen==1.42.0",
- "pika~=1.1.0",
+ "pika>=1.0.0",
"file-magic",
"requests>=2.7.0",
"rgain3==1.0.0", |
e230837f473808b3c136862feefdd6660ebb77e8 | scripts/examples/14-WiFi-Shield/mqtt.py | scripts/examples/14-WiFi-Shield/mqtt.py | # MQTT Example.
# This example shows how to use the MQTT library.
#
# 1) Copy the mqtt.py library to OpenMV storage.
# 2) Install the mosquitto client on PC and run the following command:
# mosquitto_sub -h test.mosquitto.org -t "openmv/test" -v
#
import time, network
from mqtt import MQTTClient
SSID='mux' # Networ... | # MQTT Example.
# This example shows how to use the MQTT library.
#
# 1) Copy the mqtt.py library to OpenMV storage.
# 2) Install the mosquitto client on PC and run the following command:
# mosquitto_sub -h test.mosquitto.org -t "openmv/test" -v
#
import time, network
from mqtt import MQTTClient
SSID='' # Network S... | Remove ssid/key from example script. | Remove ssid/key from example script.
| Python | mit | kwagyeman/openmv,iabdalkader/openmv,iabdalkader/openmv,openmv/openmv,iabdalkader/openmv,iabdalkader/openmv,kwagyeman/openmv,kwagyeman/openmv,openmv/openmv,openmv/openmv,openmv/openmv,kwagyeman/openmv | ---
+++
@@ -8,8 +8,8 @@
import time, network
from mqtt import MQTTClient
-SSID='mux' # Network SSID
-KEY='j806fVnT7tObdCYE' # Network key
+SSID='' # Network SSID
+KEY='' # Network key
# Init wlan module and connect to network
print("Trying to connect... (may take a while)...") |
e0c3fe2b1ecb4caf33b9ba3dafabe4eedae97c5e | spiralgalaxygame/tests/test_sentinel.py | spiralgalaxygame/tests/test_sentinel.py | import unittest
from spiralgalaxygame.sentinel import Sentinel, Enum
class SentinelTests (unittest.TestCase):
def setUp(self):
self.s = Sentinel('thingy')
def test_name(self):
self.assertIs(self.s.name, 'thingy')
def test_repr(self):
self.assertEqual(repr(self.s), '<Sentinel thi... | import unittest
from spiralgalaxygame.sentinel import Sentinel, Enum
class SentinelTests (unittest.TestCase):
def setUp(self):
self.s = Sentinel('thingy')
def test_name(self):
self.assertIs(self.s.name, 'thingy')
def test_repr(self):
self.assertEqual(repr(self.s), '<Sentinel thi... | Add a test for ``Enum.__repr__``; ``spiralgalaxygame.sentinel`` now has full coverage. | Add a test for ``Enum.__repr__``; ``spiralgalaxygame.sentinel`` now has full coverage.
| Python | agpl-3.0 | nejucomo/sgg,nejucomo/sgg,nejucomo/sgg | ---
+++
@@ -22,6 +22,9 @@
def setUp(self):
self.e = Enum('red', 'green', 'blue')
+ def test_repr(self):
+ self.assertEqual(repr(self.e), '<Enum blue, green, red>')
+
def test_iter_and_members_are_sentinels(self):
for member in self.e:
self.assertIsInstance(member, ... |
56c3a5e4b29fb5f198f133e06e92ab5af72d62dd | conda_tools/package.py | conda_tools/package.py | import tarfile
import os
import json
class Package(object):
def __init__(self, path, mode='r'):
self.path = path
self.mode = mode
self._tarfile = tarfile.open(path, mode=mode)
| import tarfile
import json
from pathlib import PurePath, PureWindowsPat
from os.path import realpath, abspath, join
from hashlib import md5
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from .common import lazyproperty
class BadLinkError(Exception):
pass
... | Add pacakge object for working with conda compressed archives. | Add pacakge object for working with conda compressed archives.
| Python | bsd-3-clause | groutr/conda-tools,groutr/conda-tools | ---
+++
@@ -1,12 +1,73 @@
import tarfile
-import os
import json
+from pathlib import PurePath, PureWindowsPat
+from os.path import realpath, abspath, join
+from hashlib import md5
+
+try:
+ from collections.abc import Iterable
+except ImportError:
+ from collections import Iterable
+
+from .common import lazy... |
70be059480af2eaac8a0b7afdd91f7ca86b94c05 | src/azure/cli/commands/resourcegroup.py | src/azure/cli/commands/resourcegroup.py | from .._util import TableOutput
from ..commands import command, description, option
from .._profile import Profile
@command('resource group list')
@description('List resource groups')
# TODO: waiting on Python Azure SDK bug fixes
#@option('--tag-name -g <tagName>', _("the resource group's tag name"))
#@option('--tag-v... | from msrest import Serializer
from ..commands import command, description, option
from .._profile import Profile
@command('resource group list')
@description('List resource groups')
# TODO: waiting on Python Azure SDK bug fixes
#@option('--tag-name -g <tagName>', _("the resource group's tag name"))
#@option('--tag-va... | Return a serialized object instead of creating the table output in the command | Return a serialized object instead of creating the table output in the command
| Python | mit | yugangw-msft/azure-cli,yugangw-msft/azure-cli,BurtBiel/azure-cli,samedder/azure-cli,QingChenmsft/azure-cli,yugangw-msft/azure-cli,BurtBiel/azure-cli,samedder/azure-cli,QingChenmsft/azure-cli,samedder/azure-cli,QingChenmsft/azure-cli,yugangw-msft/azure-cli,QingChenmsft/azure-cli,yugangw-msft/azure-cli,yugangw-msft/azure... | ---
+++
@@ -1,4 +1,5 @@
-from .._util import TableOutput
+from msrest import Serializer
+
from ..commands import command, description, option
from .._profile import Profile
@@ -19,14 +20,5 @@
#groups = rmc.resource_groups.list(filter=None, top=args.get('top'))
groups = rmc.resource_groups.list()
- ... |
afdfcef3cf7f390dd0fc7eac0806272742ffa479 | core/models/payment.py | core/models/payment.py | from django.db import models
from django.db.models import signals
from django.utils.translation import ugettext_lazy as _
from core.mixins import AuditableMixin
from .invoice import Invoice
class Payment(AuditableMixin, models.Model):
invoice = models.ForeignKey(
Invoice, editable=False, on_delete=models... | from django.db import models
from django.db.models import signals
from django.utils.translation import ugettext_lazy as _
from core.mixins import AuditableMixin
class Payment(AuditableMixin, models.Model):
invoice = models.ForeignKey(
'core.Invoice', editable=False, on_delete=models.CASCADE,
verb... | Use string instead of class | Use string instead of class
| Python | bsd-3-clause | ikcam/django-skeleton,ikcam/django-skeleton,ikcam/django-skeleton,ikcam/django-skeleton | ---
+++
@@ -3,12 +3,11 @@
from django.utils.translation import ugettext_lazy as _
from core.mixins import AuditableMixin
-from .invoice import Invoice
class Payment(AuditableMixin, models.Model):
invoice = models.ForeignKey(
- Invoice, editable=False, on_delete=models.CASCADE,
+ 'core.Invo... |
55a330149a05c456012f2570c2151a82ac8435b2 | images/singleuser/user-config.py | images/singleuser/user-config.py | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to he... | import os
mylang = 'test'
family = 'wikipedia'
custom_path = os.path.expanduser('~/user-config.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to he... | Revert to previous way of setting 'authenticate' | Revert to previous way of setting 'authenticate'
This reverts commit a055f97a342f670171f30095cabfd4ba1bfdad17.
This reverts commit 4cec5250a3f9058fea5af5ef432a5b230ca94963.
| Python | mit | yuvipanda/paws,yuvipanda/paws | ---
+++
@@ -20,16 +20,15 @@
'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity',
'wikidata', 'mediawiki'
):
-
usernames[fam]['*'] = os.environ['USER']
- if 'ACCESS_KEY' in os.environ:
- # If OAuth integration is available, take it
- authenticate.setdefault(fam... |
208c4d9e18301a85bca5d64a1e2abb95a6865fe9 | students/psbriant/session08/circle.py | students/psbriant/session08/circle.py | """
Name: Paul Briant
Date: 11/29/16
Class: Introduction to Python
Session: 08
Assignment: Circle Lab
Description:
Classes for Circle Lab
"""
import math
class Circle:
def __init__(self, radius):
"""
"""
self.radius = radius
self.diameter = radius * 2
@classmethod
... | """
Name: Paul Briant
Date: 11/29/16
Class: Introduction to Python
Session: 08
Assignment: Circle Lab
Description:
Classes for Circle Lab
"""
import math
class Circle:
def __init__(self, radius):
""" Initialize circle attributes radius and diameter"""
self.radius = radius
self.diameter ... | Add Docstrings for class methods. | Add Docstrings for class methods.
| Python | unlicense | weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016 | ---
+++
@@ -11,17 +11,17 @@
import math
+
class Circle:
def __init__(self, radius):
- """
-
- """
+ """ Initialize circle attributes radius and diameter"""
self.radius = radius
self.diameter = radius * 2
@classmethod
def from_diameter(cls, diamet... |
4dd488634aa030a8e9a1404e5fe026265dd07a75 | tailor/tests/utils/charformat_test.py | tailor/tests/utils/charformat_test.py | import unittest
from tailor.utils import charformat
class MyTestCase(unittest.TestCase):
def is_upper_camel_case_test_upper_camel_case_name(self):
self.assertTrue(charformat.is_upper_camel_case('HelloWorld'))
def is_upper_camel_case_test_lower_camel_case_name(self):
self.assertFalse(charform... | import unittest
from tailor.utils import charformat
class MyTestCase(unittest.TestCase):
def is_upper_camel_case_test_upper_camel_case_name(self):
self.assertTrue(charformat.is_upper_camel_case('HelloWorld'))
def is_upper_camel_case_test_lower_camel_case_name(self):
self.assertFalse(charform... | Add numeric name test case | Add numeric name test case
| Python | mit | sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor | ---
+++
@@ -16,6 +16,8 @@
def is_upper_camel_case_test_snake_case_name(self):
self.assertFalse(charformat.is_upper_camel_case('Hello_World'))
+ def is_upper_camel_case_test_numeric_name(self):
+ self.assertFalse(charformat.is_upper_camel_case('1ello_world'))
if __name__ == '__main__':
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.