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 |
|---|---|---|---|---|---|---|---|---|---|---|
04fc49427a1288b259610c98d7cd82b21e1a79a4 | artists/views.py | artists/views.py | from django.shortcuts import get_object_or_404
from rest_framework import permissions, viewsets
from similarities.utils import get_similar
from .models import Artist
from similarities.models import UserSimilarity
from .serializers import ArtistSerializer, SimilaritySerializer
class ArtistViewSet(viewsets.ModelViewSe... | from django.shortcuts import get_object_or_404
from rest_framework import permissions, viewsets
from similarities.utils import get_similar
from .models import Artist
from similarities.models import UserSimilarity
from .serializers import ArtistSerializer, SimilaritySerializer
class ArtistViewSet(viewsets.ModelViewSe... | Allow PUT request to /similarities/:id | Allow PUT request to /similarities/:id
| Python | bsd-3-clause | FreeMusicNinja/api.freemusic.ninja | ---
+++
@@ -29,7 +29,7 @@
queryset = UserSimilarity.objects.all()
serializer_class = SimilaritySerializer
permission_classes = (permissions.IsAuthenticated,)
- http_method_names = ['get', 'post', 'delete']
+ http_method_names = ['get', 'post', 'put', 'delete']
filter_fields = ['cc_artist']
... |
2566b5698b17ca0d193ef6bf3b22aca91b711222 | alembic/env.py | alembic/env.py | from __future__ import with_statement
from alembic import context
import sqlalchemy
import logging
logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s")
target_metadata = None
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the contex... | from __future__ import with_statement
from alembic import context
import sqlalchemy
import logging
logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s")
target_metadata = None
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the contex... | Fix more db connection strings | Fix more db connection strings
| Python | apache-2.0 | mrphlip/lrrbot,mrphlip/lrrbot,andreasots/lrrbot,andreasots/lrrbot,andreasots/lrrbot,mrphlip/lrrbot | ---
+++
@@ -19,7 +19,7 @@
script output.
"""
- context.configure(url=context.config.get_section_option("lrrbot", "postgres", 'postgres:///lrrbot'),
+ context.configure(url=context.config.get_section_option("lrrbot", "postgres", 'postgresql:///lrrbot'),
target_metadata=target_metadata, literal_binds=True)
... |
567a786e9d20c4519d72c37531d99e8d33b178af | my_module/metadata.py | my_module/metadata.py | # -*- coding: utf-8 -*-
"""Project metadata
Information describing the project.
"""
# The package name, which is also the "UNIX name" for the project.
package = 'my_module'
project = "My Awesome Module"
project_no_spaces = project.replace(' ', '')
version = '0.1'
description = 'It does cool things'
authors = ['Foo Ba... | # -*- coding: utf-8 -*-
"""Project metadata
Information describing the project.
"""
# The package name, which is also the "UNIX name" for the project.
package = 'my_module'
project = "My Awesome Module"
project_no_spaces = project.replace(' ', '')
version = '0.1'
description = 'It does cool things'
authors = ['Foo Ba... | Update copyright date to 2015. | Update copyright date to 2015. | Python | mit | mishin/python-project-template,seanfisk/python-project-template,seanfisk/python-project-template,shekkbuilder/python-project-template,mishin/python-project-template,shekkbuilder/python-project-template | ---
+++
@@ -14,5 +14,5 @@
authors_string = ', '.join(authors)
emails = ['foobar@example.com', 'johndoe@thisisfake.org']
license = 'MIT'
-copyright = '2013 ' + authors_string
+copyright = '2015 ' + authors_string
url = 'http://example.com/' |
6427ef6e05e3add17533c0a86603943c85020eb6 | inonemonth/challenges/templatetags/challenges_extras.py | inonemonth/challenges/templatetags/challenges_extras.py | from django.template import Library
register = Library()
@register.filter
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
return "Clencher (de.rouck.robrecht@gmail.com)"
elif role.type == "juror":
if role == user_r... | from django.template import Library
register = Library()
@register.filter
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
return "{0} ({1})".format(role.type.capitalize(), role.user.email)
elif role.type == "juror":
... | Increase abstractness for one test method | Increase abstractness for one test method
| Python | mit | robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth | ---
+++
@@ -6,7 +6,7 @@
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
- return "Clencher (de.rouck.robrecht@gmail.com)"
+ return "{0} ({1})".format(role.type.capitalize(), role.user.email)
elif role.type == "ju... |
bd3ff327bd04a6688ce7f39964394f921dec6705 | RevitPyCVC/Outils/copier_type_vues.py | RevitPyCVC/Outils/copier_type_vues.py | from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Architecture import *
from Autodesk.Revit.DB.Analysis import *
from System.Collections.Generic import *
uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document
getselection = uidoc.Selection.GetElementIds
app = __revit__.Application
from Aut... | from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Architecture import *
from Autodesk.Revit.DB.Analysis import *
from System.Collections.Generic import *
uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document
getselection = uidoc.Selection.GetElementIds
app = __revit__.Application
from Aut... | Add GUI for 3D Rotation script | Add GUI for 3D Rotation script
| Python | mit | Nahouhak/pythoncvc.net,Nahouhak/pythoncvc.net | ---
+++
@@ -33,7 +33,6 @@
cp_opts = CopyPasteOptions()
ElementTransformUtils.CopyElements(doc, ids, autreDoc, Transform.Identity, cp_opts)
- t.Commit()
except:
# print a stack trace and error messages for debugging
import traceback
@@ -41,4 +40,4 @@
t.RollBack()
else:
# no errors, so just ... |
b158de35c08aa78578f374f125884607468e67d1 | glance/registry/__init__.py | glance/registry/__init__.py | # Copyright 2010-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.apache.org/licenses/LICENSE-2.0
#
# Unless... | # Copyright 2010-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.apache.org/licenses/LICENSE-2.0
#
# Unless... | Improve help text of registry server opts | Improve help text of registry server opts
Partial-Bug: #1570946
Change-Id: Iad255d3ab5d96b91f897731f4f29cd804d6b1840
| Python | apache-2.0 | openstack/glance,rajalokan/glance,rajalokan/glance,stevelle/glance,openstack/glance,openstack/glance,stevelle/glance | ---
+++
@@ -24,9 +24,27 @@
registry_addr_opts = [
cfg.StrOpt('registry_host', default='0.0.0.0',
- help=_('Address to find the registry server.')),
+ help=_("""
+Address the registry server is hosted on.
+
+Possible values:
+ * A valid IP or hostname
+
+Related options:
+ * N... |
e8d2d067c79bf133f98312c328a0e72af6b65f96 | go/apps/jsbox/definition.py | go/apps/jsbox/definition.py | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
co... | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
co... | Implement extra endpoints for Javascript apps. | Implement extra endpoints for Javascript apps.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -15,4 +15,15 @@
actions = (ViewLogsAction,)
def configured_endpoints(self, config):
- return []
+ # TODO: make jsbox apps define these explicitly and
+ # update the outbound resource to check and
+ # complain if a jsbox app sends on an endpoint
+ #... |
62c573fadad1b0268353c2dc21c35ac5b645052a | go/dashboard/tests/utils.py | go/dashboard/tests/utils.py | import json
from go.dashboard import DiamondashApiError, DiamondashApiClient
class FakeDiamondashApiClient(DiamondashApiClient):
def __init__(self):
self.requests = []
self.response = None
def get_requests(self):
return self.requests
def set_error_response(self, code, message):
... | import json
from go.dashboard import DiamondashApiError, DiamondashApiClient
class FakeDiamondashApiClient(DiamondashApiClient):
def __init__(self):
self.requests = []
self._response = None
@property
def response(self):
if isinstance(self._response, Exception):
raise ... | Add raw_request method for FakeDiamondashApiClient to correspond to the recently added DiamondashApiClient.raw_request() | Add raw_request method for FakeDiamondashApiClient to correspond to the recently added DiamondashApiClient.raw_request()
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -6,10 +6,14 @@
class FakeDiamondashApiClient(DiamondashApiClient):
def __init__(self):
self.requests = []
- self.response = None
+ self._response = None
- def get_requests(self):
- return self.requests
+ @property
+ def response(self):
+ if isinstance(s... |
17a18f72e9e2a7df43d2dafe77a17bfe4777d7aa | avena/image.py | avena/image.py | #!/usr/bin/env python2
'''Read and write image files as NumPy arrays'''
from numpy import asarray, float32
from PIL import Image
from . import np
from . import utils
_DEFAULT_DTYPE = float32
_PIL_RGB = {
'R': 0,
'G': 1,
'B': 2,
}
def get_channels(img):
'''Return a list of channels of an image a... | #!/usr/bin/env python2
'''Read and write image files as NumPy arrays'''
from numpy import asarray, float32
from PIL import Image
from . import np
from . import utils
_DEFAULT_DTYPE = float32
_PIL_RGB = {
'R': 0,
'G': 1,
'B': 2,
}
def get_channels(img):
'''Return a list of channels of an image a... | Add an extension parameter to the save function. | Add an extension parameter to the save function.
| Python | isc | eliteraspberries/avena | ---
+++
@@ -42,10 +42,10 @@
return
-def save(img, filename, random=False):
+def save(img, filename, random=False, ext=None):
'''Save an image array and return its path.'''
if random:
- newfile = utils.rand_filename(filename)
+ newfile = utils.rand_filename(filename, ext=ext)
else... |
719ae63a28a0fdbb379a5ee61a9bb3216ef283bc | awx/main/ha.py | awx/main/ha.py | # Copyright (c) 2014 Ansible, Inc.
# All Rights Reserved.
from django.conf import settings
from awx.main.models import Instance
def is_ha_environment():
"""Return True if this is an HA environment, and False
otherwise.
"""
# If there are two or more instances, then we are in an HA environment.
i... | # Copyright (c) 2014 Ansible, Inc.
# All Rights Reserved.
from django.conf import settings
from awx.main.models import Instance
def is_ha_environment():
"""Return True if this is an HA environment, and False
otherwise.
"""
# If there are two or more instances, then we are in an HA environment.
i... | Fix error causing single-host HA environments to report not HA. | Fix error causing single-host HA environments to report not HA.
| Python | apache-2.0 | snahelou/awx,snahelou/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx | ---
+++
@@ -15,7 +15,7 @@
return True
# If the database is not local, then we are in an HA environment.
- host = settings.DATABASES['default'].get('host', 'localhost')
+ host = settings.DATABASES['default'].get('HOST', 'localhost')
if host and host.lower() not in ('127.0.0.1', 'localhost'):... |
c0e77cca647232810299c251ecfc96c0c1e4e12e | funfactory/monkeypatches.py | funfactory/monkeypatches.py | import logging
from django.conf import settings
__all__ = ['patch']
# Idempotence! http://en.wikipedia.org/wiki/Idempotence
_has_patched = False
def patch():
global _has_patched
if _has_patched:
return
# Import for side-effect: configures logging handlers.
# pylint: disable-msg=W0611
... | import logging
from django.conf import settings
__all__ = ['patch']
# Idempotence! http://en.wikipedia.org/wiki/Idempotence
_has_patched = False
def patch():
global _has_patched
if _has_patched:
return
# Import for side-effect: configures logging handlers.
# pylint: disable-msg=W0611
... | Use jingo.monkey if it exists | Use jingo.monkey if it exists
This changes funfactory to use jingo.monkey which monkey patches Django
form fields so you don't have to do |safe all the time.
If the available jingo isn't recent enough, then it defaults to using
nuggets safe_django_forms which don't appear to work with Django 1.5
or later.
| Python | bsd-3-clause | mozilla/funfactory,mozilla/funfactory | ---
+++
@@ -20,8 +20,14 @@
# Monkey-patch django forms to avoid having to use Jinja2's |safe
# everywhere.
- import safe_django_forms
- safe_django_forms.monkeypatch()
+ try:
+ import jingo.monkey
+ jingo.monkey.patch()
+ except ImportError:
+ # If we can't import jingo.mo... |
0501eaca73638ae9c19cd7db2946e28b0a40153e | glaciercmd/cli.py | glaciercmd/cli.py | import logging
import sys
from glaciercmd.gcconfig import GCConfig
def run():
logging.basicConfig(format="%(asctime)s %(levelname)s %(module)s: %(message)s", level=logging.DEBUG)
config = GCConfig()
if config.has_errors():
config.log_errors()
sys.exit(1)
if __name__ == '__main__':
run()
| import logging
import sys
import argparse
import glob
import os
from glaciercmd.gcconfig import GCConfig
def load_commands():
commands = []
command_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'command_*.py')
command_files = glob.glob(command_dir)
for command_file in command_files:
com... | Use command to list vaults | Use command to list vaults
| Python | mit | carsonmcdonald/glacier-cmd | ---
+++
@@ -1,15 +1,45 @@
import logging
import sys
+import argparse
+import glob
+import os
from glaciercmd.gcconfig import GCConfig
+def load_commands():
+ commands = []
+
+ command_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'command_*.py')
+ command_files = glob.glob(command_dir)
+ ... |
8810bd03df781e7ec20fcc2d0fcc7cbf423e9cdc | conda_kapsel/internal/py2_compat.py | conda_kapsel/internal/py2_compat.py | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2016, Continuum Analytics, Inc. All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------------------------------------------------------... | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2016, Continuum Analytics, Inc. All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------------------------------------------------------... | Add more assertions about types in environment | Add more assertions about types in environment
Trying to figure out why things are still failing on windows/py27
| Python | bsd-3-clause | conda/kapsel,conda/kapsel | ---
+++
@@ -24,8 +24,13 @@
if _PY2 and platform.system() == 'Windows': # pragma: no cover (py2/py3)
environ_copy = dict()
for key, value in environ.items():
+ assert isinstance(key, basestring) # noqa
+ assert isinstance(key, str)
if isinstance(value, unicod... |
2c3ddc18477561f4880c2b857c4aa8a0f8478dfd | src/psycholinguistic_db/psycholinguistic_db_creator.py | src/psycholinguistic_db/psycholinguistic_db_creator.py | #!/usr/bin/env python
# Creates a CSV of psycholinguistic dictionary
# downloaded from web
# Headers
__author__ = 'Somsubhra Bairi'
__email__ = 'somsubhra.bairi@gmail.com'
# All imports
from logger import Logger
# The psycholinguistic database creator
class PsycholinguisticDbCreator:
# Constructor for the da... | #!/usr/bin/env python
# Creates a CSV of psycholinguistic dictionary
# downloaded from web
# Headers
__author__ = 'Somsubhra Bairi'
__email__ = 'somsubhra.bairi@gmail.com'
# All imports
from logger import Logger
from nltk import PorterStemmer
# The psycholinguistic database creator
class PsycholinguisticDbCreato... | Create the psycholinguistic_db according to our needs | Create the psycholinguistic_db according to our needs
| Python | mit | Somsubhra/Enrich,Somsubhra/Enrich,Somsubhra/Enrich | ---
+++
@@ -11,6 +11,8 @@
# All imports
from logger import Logger
+from nltk import PorterStemmer
+
# The psycholinguistic database creator
class PsycholinguisticDbCreator:
@@ -19,6 +21,8 @@
def __init__(self, in_file, out_file):
self.in_file = in_file
self.out_file = out_file
+ ... |
f55a00cfd81f8f3c88aaaa5a4b3d63ceb4364a11 | books/views.py | books/views.py | from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from .models import BookIndex, Book
@csrf_exempt
def book_index(request):
page = BookIndex.objects.all()[0]
return redirect('/api/v2/pages/{}'.format(page.pk))
@csrf_exempt
def book_detail(request, slug):
page = B... | from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from .models import BookIndex, Book
@csrf_exempt
def book_index(request):
page = BookIndex.objects.all()[0]
return redirect('/api/v2/pages/{}'.format(page.pk))
@csrf_exempt
def book_detail(request, slug):
try:
... | Return book index page if book not found by slug | Return book index page if book not found by slug
| Python | agpl-3.0 | openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms | ---
+++
@@ -11,5 +11,10 @@
@csrf_exempt
def book_detail(request, slug):
- page = Book.objects.get(slug=slug)
- return redirect('/api/v2/pages/{}'.format(page.pk))
+ try:
+ page = Book.objects.get(slug=slug)
+ return redirect('/api/v2/pages/{}'.format(page.pk))
+ except Book.DoesNotExist:... |
ba57cf57d3e075d5260fb19304ec0e9f903c3ed0 | pajbot/actions.py | pajbot/actions.py | import logging
import queue
import threading
log = logging.getLogger(__name__)
class Action:
func = None
args = []
kwargs = {}
def __init__(self, func=None, args=[], kwargs={}):
self.func = func
self.args = args
self.kwargs = kwargs
def run(self):
self.func(*self... | import logging
import queue
import threading
log = logging.getLogger(__name__)
class Action:
func = None
args = []
kwargs = {}
def __init__(self, func=None, args=[], kwargs={}):
self.func = func
self.args = args
self.kwargs = kwargs
def run(self):
self.func(*self... | Rename f to func in one last place (ActionQueue) | Rename f to func in one last place (ActionQueue)
| Python | mit | pajlada/tyggbot,pajlada/tyggbot,pajlada/pajbot,pajlada/pajbot,pajlada/pajbot,pajlada/pajbot,pajlada/tyggbot,pajlada/tyggbot | ---
+++
@@ -50,8 +50,8 @@
action = self.queue.get()
action.run()
- def add(self, f, args=[], kwargs={}):
- action = Action(f, args, kwargs)
+ def add(self, func, args=[], kwargs={}):
+ action = Action(func, args, kwargs)
self._add(action)
def _add(self, ... |
e388099f6fcc0fbc1904bb24f050d7106204e58c | src/zeit/campus/article.py | src/zeit/campus/article.py | import zope.interface
import zeit.cms.content.reference
import zeit.campus.interfaces
class TopicpageLink(zeit.cms.related.related.RelatedBase):
zope.interface.implements(zeit.campus.interfaces.ITopicpageLink)
topicpagelink = zeit.cms.content.reference.SingleResource(
'.head.topicpagelink.url', 'r... | import zope.interface
import zeit.cms.content.reference
import zeit.campus.interfaces
class TopicpageLink(zeit.cms.related.related.RelatedBase):
zope.interface.implements(zeit.campus.interfaces.ITopicpageLink)
topicpagelink = zeit.cms.content.reference.SingleResource(
'.head.topicpagelink', 'relat... | Fix xml path to topcpagelink | ZON-2838: Fix xml path to topcpagelink
| Python | bsd-3-clause | ZeitOnline/zeit.campus | ---
+++
@@ -10,7 +10,7 @@
zope.interface.implements(zeit.campus.interfaces.ITopicpageLink)
topicpagelink = zeit.cms.content.reference.SingleResource(
- '.head.topicpagelink.url', 'related')
+ '.head.topicpagelink', 'related')
topicpagelink_label = zeit.cms.content.dav.mapProperties(
... |
bf36e307b13148d40e978ebb32151a3ea0e32cf9 | stampman/tests/test_api.py | stampman/tests/test_api.py | import unittest
from stampman.services import pool
class TestAPIEndpoint(unittest.TestCase):
pass
| import unittest
import json
import requests
from stampman import main
class TestAPIRoot(unittest.TestCase):
def setUp(self):
self._port = "8000"
self._path = "http://0.0.0.0"
main.app.config['TESTING'] = True
self._app = main.app.test_client()
def testGetJson(self):
r... | Add unit test for testing flask endpoint | Add unit test for testing flask endpoint
Test GET on the `/` endpoint
| Python | mit | thunderboltsid/stampman | ---
+++
@@ -1,6 +1,36 @@
import unittest
-from stampman.services import pool
+import json
+
+import requests
+from stampman import main
-class TestAPIEndpoint(unittest.TestCase):
- pass
+class TestAPIRoot(unittest.TestCase):
+ def setUp(self):
+ self._port = "8000"
+ self._path = "http://0.0.... |
485c722010882f5273b2cca77305b499cd4674c5 | astropy/tests/tests/test_run_tests.py | astropy/tests/tests/test_run_tests.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# test helper.run_tests function
import warnings
from .. import helper
from ... import _get_test_runner
from .. helper import pytest
# run_test... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# test helper.run_tests function
import warnings
from .. import helper
from ... import _get_test_runner
from .. helper import pytest
# run_test... | Disable test that is non-deterministically failing. | Disable test that is non-deterministically failing.
| Python | bsd-3-clause | DougBurke/astropy,dhomeier/astropy,kelle/astropy,aleksandr-bakanov/astropy,AustereCuriosity/astropy,kelle/astropy,saimn/astropy,StuartLittlefair/astropy,lpsinger/astropy,DougBurke/astropy,StuartLittlefair/astropy,AustereCuriosity/astropy,dhomeier/astropy,larrybradley/astropy,stargaser/astropy,dhomeier/astropy,astropy/a... | ---
+++
@@ -31,6 +31,7 @@
helper.pytest.fail("Not running the 2to3'd tests!")
-def test_deprecation_warning():
- with pytest.raises(DeprecationWarning):
- warnings.warn('test warning', DeprecationWarning)
+# TODO: Temporarily disabled, as this seems to non-deterministically fail
+# def test_dep... |
20ccdd67d7e398fc4e4b5f72f723da31346e66a7 | graphene/traversal/query.py | graphene/traversal/query.py | class Query:
def __init__(self, ident, name, oper, value):
self.ident = ident
self.name = name
self.oper = oper
self.value = value
def test(self, prop_dict):
if self.ident is not None:
key = "%s.%s" % (self.ident, self.name)
else:
key = se... | class Query:
def __init__(self, ident, name, oper, value):
self.ident = ident
self.name = name
self.oper = oper
self.value = value
def test(self, prop_dict):
if self.ident is not None:
key = "%s.%s" % (self.ident, self.name)
else:
key = se... | Fix issue with Query.parse_chain being broken in InsertRelationCommand | Fix issue with Query.parse_chain being broken in InsertRelationCommand
| Python | apache-2.0 | PHB-CS123/graphene,PHB-CS123/graphene,PHB-CS123/graphene | ---
+++
@@ -29,7 +29,7 @@
return False
@staticmethod
- def parse_chain(storage_manager, chain, type_schema, alias):
+ def parse_chain(storage_manager, chain, type_schema, alias=None):
qc = []
for q in chain:
if type(q) == tuple: |
149c1257f4af4c6962c61e74bddbdddfcc741524 | cbagent/collectors/libstats/psstats.py | cbagent/collectors/libstats/psstats.py | from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task
class PSStats(RemoteStats):
METRICS = (
("rss", 1024), # kB -> B
("vsize", 1024),
)
PS_CMD = "ps -eo pid,rss,vsize,comm | " \
"grep {} | grep -v grep | sort -n -k 2 | tail -n 1"
TOP_CMD = "top ... | from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task
class PSStats(RemoteStats):
METRICS = (
("rss", 1024), # kB -> B
("vsize", 1024),
)
PS_CMD = "ps -eo pid,rss,vsize,comm | " \
"grep {} | grep -v grep | sort -n -k 2 | tail -n 1"
TOP_CMD = "top ... | Use more precise grep expression | Use more precise grep expression
Otherwise we match wrong lines when memory stats contain PID.
Change-Id: I924c1b151ddaad8209445a514bf02a7af5d2e0e0
Reviewed-on: http://review.couchbase.org/79848
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
Tested-by: Pavel Paulau <dd88eded64e90046a68... | Python | apache-2.0 | couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner | ---
+++
@@ -11,7 +11,7 @@
PS_CMD = "ps -eo pid,rss,vsize,comm | " \
"grep {} | grep -v grep | sort -n -k 2 | tail -n 1"
- TOP_CMD = "top -b n2 -d1 -p {0} | grep {0}"
+ TOP_CMD = "top -b n2 -d1 -p {0} | grep ^{0}"
@parallel_task(server_side=True)
def get_server_samples(self, process): |
18ea019bd77d605c367265080aa40382399b324b | test/integration/ggrc/converters/test_import_update.py | test/integration/ggrc/converters/test_import_update.py | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from integration.ggrc.converters import TestCase
from ggrc import models
class TestImportUpdates(TestCase):
""" Test importing of already existing objects """
def setUp(self):
TestCase.setUp(sel... | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from integration.ggrc.converters import TestCase
from ggrc import models
class TestImportUpdates(TestCase):
""" Test importing of already existing objects """
def setUp(self):
TestCase.setUp(sel... | Use check response for import update tests | Use check response for import update tests
| Python | apache-2.0 | selahssea/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,andrei-karalionak/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,j0gu... | ---
+++
@@ -17,22 +17,17 @@
def test_policy_basic_update(self):
""" Test simple policy title update """
- messages = ("block_errors", "block_warnings", "row_errors", "row_warnings")
-
filename = "policy_basic_import.csv"
response = self.import_file(filename)
- for block in response:
- f... |
f9aae4320522af94dde78bac0c30e909ef4ef4e2 | blockbuster/bb_dbconnector_factory.py | blockbuster/bb_dbconnector_factory.py | import logging
import bb_dbconnector_pg
log = logging.getLogger('bb_log.' + __name__)
class DBConnectorInterfaceFactory:
def __init__(self):
pass
@staticmethod
def create():
return bb_dbconnector_pg.PostgresConnector() | import bb_dbconnector_pg
class DBConnectorInterfaceFactory:
def __init__(self):
pass
@staticmethod
def create():
return bb_dbconnector_pg.PostgresConnector() | Remove logger as not used in module | Remove logger as not used in module
| Python | mit | mattstibbs/blockbuster-server,mattstibbs/blockbuster-server | ---
+++
@@ -1,8 +1,4 @@
-import logging
import bb_dbconnector_pg
-
-log = logging.getLogger('bb_log.' + __name__)
-
class DBConnectorInterfaceFactory:
|
7972c0fbaf8b46810dd36e0d824c341ea4234b47 | swampdragon_live/models.py | swampdragon_live/models.py | # -*- coding: utf-8 -*-
from django.db.models.signals import post_save, pre_delete
from django.contrib.contenttypes.models import ContentType
from django.dispatch import receiver
from .pushers import push_new_content_for_instance
from .pushers import push_new_content_for_queryset
@receiver(post_save)
def post_save_ha... | # -*- coding: utf-8 -*-
from django.db.models.signals import post_save, pre_delete
from django.contrib.contenttypes.models import ContentType
from django.dispatch import receiver
from .pushers import push_new_content_for_instance
from .pushers import push_new_content_for_queryset
@receiver(post_save)
def post_save_ha... | Optimize number of updates for queryset and instance listeners | Optimize number of updates for queryset and instance listeners
Only push additions to queryset listeners, not instance changes.
Only push changes to instance listeners, not queryset additions.
| Python | mit | mback2k/swampdragon-live,mback2k/swampdragon-live | ---
+++
@@ -7,15 +7,16 @@
from .pushers import push_new_content_for_queryset
@receiver(post_save)
-def post_save_handler(sender, instance, **kwargs):
+def post_save_handler(sender, instance, created, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instan... |
f14df4ae507f3161f00ac28648bd53f2bb0bd7c3 | collect_district_court_case_details.py | collect_district_court_case_details.py | import datetime
import pymongo
import os
import sys
import time
from courtreader import readers
# Connect to database
client = pymongo.MongoClient(os.environ['DISTRICT_DB'])
db = client.va_district_court_cases
# Connect to District Court Reader
reader = readers.DistrictCourtReader()
reader.connect()
# Fill in cases
... | import boto.utils
import datetime
import pymongo
import os
import sys
import time
import uuid
from courtreader import readers
# Connect to database
client = pymongo.MongoClient(os.environ['DISTRICT_DB'])
db = client.va_district_court_cases
# Connect to District Court Reader
reader = readers.DistrictCourtReader()
read... | Save scraper settings to database | Save scraper settings to database
This is the first step in allowing multiple processes to run on
different servers. Coming in the next commit!
| Python | mit | bschoenfeld/va-court-scraper,bschoenfeld/va-court-scraper | ---
+++
@@ -1,8 +1,10 @@
+import boto.utils
import datetime
import pymongo
import os
import sys
import time
+import uuid
from courtreader import readers
# Connect to database
@@ -13,10 +15,28 @@
reader = readers.DistrictCourtReader()
reader.connect()
+# get some info about this process
+process_id = str(... |
1b70aee665720ce10e2e0437fb462745adbd6799 | changes/api/serializer/models/task.py | changes/api/serializer/models/task.py | from changes.api.serializer import Serializer, register
from changes.models import Task
@register(Task)
class TaskSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'objectID': instance.task_id,
'parentObjectID': instance.paren... | from changes.api.serializer import Serializer, register
from changes.models import Task
@register(Task)
class TaskSerializer(Serializer):
def serialize(self, instance, attrs):
if instance.data:
args = instance.data.get('kwargs') or {}
else:
args = {}
return {
... | Fix args when Task.data is empty | Fix args when Task.data is empty
| Python | apache-2.0 | bowlofstew/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes | ---
+++
@@ -5,12 +5,17 @@
@register(Task)
class TaskSerializer(Serializer):
def serialize(self, instance, attrs):
+ if instance.data:
+ args = instance.data.get('kwargs') or {}
+ else:
+ args = {}
+
return {
'id': instance.id.hex,
'objectID... |
33e17ebd7046e0968db2ee01f9e2759a382b62d9 | packages/pango.py | packages/pango.py | class PangoPackage (GnomePackage):
def __init__ (self):
GnomePackage.__init__ (self,
'pango',
version_major = '1.28',
version_minor = '4',
configure_flags = [
'--without-x'
]
)
self.sources.extend ([
# patch from bgo#321419
'http://bugzilla-attachments.gnome.org/attachment.cgi?id=96023'... | class PangoPackage (GnomePackage):
def __init__ (self):
GnomePackage.__init__ (self,
'pango',
version_major = '1.29',
version_minor = '4',
configure_flags = [
'--without-x'
]
)
self.sources.extend ([
# patch from bgo#321419
'http://bugzilla-attachments.gnome.org/attachment.cgi?id=96023'... | Update Pango to use CoreText | Update Pango to use CoreText | Python | mit | bl8/bockbuild,bl8/bockbuild,BansheeMediaPlayer/bockbuild,mono/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,bl8/bockbuild | ---
+++
@@ -2,7 +2,7 @@
def __init__ (self):
GnomePackage.__init__ (self,
'pango',
- version_major = '1.28',
+ version_major = '1.29',
version_minor = '4',
configure_flags = [
'--without-x'
@@ -11,11 +11,21 @@
self.sources.extend ([
# patch from bgo#321419
- 'http://bugzilla-attac... |
0372de11f91e0018eb122f9a6543ecf7cc9e086b | parliament/search/management/commands/consume_indexing_queue.py | parliament/search/management/commands/consume_indexing_queue.py | import itertools
import logging
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from haystack import site
import pysolr
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Runs any queued-up search indexing tasks."
def handle(self, **o... | import itertools
import logging
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from haystack import site
import pysolr
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Runs any queued-up search indexing tasks."
def handle(self, **o... | Use pysolr instead of haystack in indexing job | Use pysolr instead of haystack in indexing job
| Python | agpl-3.0 | twhyte/openparliament,rhymeswithcycle/openparliament,litui/openparliament,rhymeswithcycle/openparliament,litui/openparliament,rhymeswithcycle/openparliament,litui/openparliament,twhyte/openparliament,twhyte/openparliament | ---
+++
@@ -24,6 +24,8 @@
IndexingTask.objects.filter(action='update').prefetch_related('content_object')
)
+ solr = pysolr.Solr(settings.HAYSTACK_SOLR_URL)
+
if update_tasks:
update_objs = [t.content_object for t in update_tasks if t.content_object]
@@ -31,12 +3... |
ee82b77f562ee1d49c2fc724a3fc58b101c0dd2b | src/devilry_qualifiesforexam/devilry_qualifiesforexam/urls.py | src/devilry_qualifiesforexam/devilry_qualifiesforexam/urls.py | from django.conf.urls import patterns, url, include
from django.contrib.auth.decorators import login_required
from django.views.i18n import javascript_catalog
from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
from devilry_settings.i18n import get_javascript_catalog_packages
from .views import ... | from django.conf.urls import patterns, url, include
from django.contrib.auth.decorators import login_required
from django.views.i18n import javascript_catalog
from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
from devilry_settings.i18n import get_javascript_catalog_packages
from .views import ... | Remove period id from app url. | devilry_qualfiesforexam: Remove period id from app url.
| Python | bsd-3-clause | devilry/devilry-django,devilry/devilry-django,devilry/devilry-django,devilry/devilry-django | ---
+++
@@ -14,8 +14,7 @@
urlpatterns = patterns('devilry_qualifiesforexam',
url('^rest/', include('devilry_qualifiesforexam.rest.urls')),
- url('^wizard/(?P<periodid>\d+)/$',
- login_required(csrf_protect(ensure_csrf_cookie(AppView.as_view()))),
+ url('^$', login_required(csrf_protect(ensure_csr... |
edbcfbf83ab79fff7de00c7a6310c9fceb17df91 | accelerator/migrations/0099_update_program_model.py | accelerator/migrations/0099_update_program_model.py | # Generated by Django 2.2.28 on 2022-04-20 13:05
from django.db import (
migrations,
models,
)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0098_update_startup_update_20220408_0441'),
]
operations = [
migrations.AddField(
model_name='progr... | # Generated by Django 2.2.28 on 2022-04-20 13:05
import sorl.thumbnail.fields
from django.db import (
migrations,
models,
)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0098_update_startup_update_20220408_0441'),
]
operations = [
migrations.AddField(
... | Fix image field import and migration | [AC-9452] Fix image field import and migration
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator | ---
+++
@@ -1,5 +1,6 @@
# Generated by Django 2.2.28 on 2022-04-20 13:05
+import sorl.thumbnail.fields
from django.db import (
migrations,
models,
@@ -21,6 +22,8 @@
migrations.AddField(
model_name='program',
name='program_image',
- field=models.ImageField(nu... |
54454f7f963730aa3fc91c5b1baf44762b07fb47 | contrib/linux/tests/test_action_dig.py | contrib/linux/tests/test_action_dig.py | #!/usr/bin/env python
# Copyright 2020 The StackStorm Developers
#
# 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 app... | #!/usr/bin/env python
# Copyright 2020 The StackStorm Authors.
#
# 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 appli... | Use "The StackStorm Authors" in copyright | Use "The StackStorm Authors" in copyright
Co-authored-by: Eugen C. <67cac084fbaf94f499d5252e3cb50165dbf6e026@armab.io> | Python | apache-2.0 | StackStorm/st2,Plexxi/st2,StackStorm/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2 | ---
+++
@@ -1,6 +1,6 @@
#!/usr/bin/env python
-# Copyright 2020 The StackStorm Developers
+# Copyright 2020 The StackStorm Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. |
3f2c13ecc64c84b51ecc5867004b9cbc32e375ac | Discord/utilities/errors.py | Discord/utilities/errors.py |
from discord.ext.commands.errors import CommandError
class NotServerOwner(CommandError):
'''Not Server Owner'''
pass
class VoiceNotConnected(CommandError):
'''Voice Not Connected'''
pass
class PermittedVoiceNotConnected(VoiceNotConnected):
'''Permitted, but Voice Not Connected'''
pass
class NotPermittedVoice... |
from discord.ext.commands.errors import CommandError
class NotServerOwner(CommandError):
'''Not Server Owner'''
pass
class VoiceNotConnected(CommandError):
'''Voice Not Connected'''
pass
class PermittedVoiceNotConnected(VoiceNotConnected):
'''Permitted, but Voice Not Connected'''
pass
class NotPermittedVoice... | Remove Audio Not Playing error | [Discord] Remove Audio Not Playing error
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot | ---
+++
@@ -34,7 +34,3 @@
'''Audio Error'''
pass
-class AudioNotPlaying(AudioError):
- '''Audio Not Playing'''
- pass
- |
6dfa381b26948b97b7abc3de9f1a02618fd5ad0f | src/geoserver/style.py | src/geoserver/style.py | from geoserver.support import ResourceInfo, atom_link
class Style(ResourceInfo):
def __init__(self,catalog, node):
self.catalog = catalog
self.name = node.find("name").text
self.href = atom_link(node)
self.update()
def update(self):
ResourceInfo.update(self)
self.name = self.metadata.f... | from geoserver.support import ResourceInfo, atom_link
import re
class Style(ResourceInfo):
def __init__(self,catalog, node):
self.catalog = catalog
self.name = node.find("name").text
self.href = atom_link(node)
self.update()
def update(self):
ResourceInfo.update(self)
self.name = self.... | Add body_href method for getting a public url for a Style's body. | Add body_href method for getting a public url for a Style's body.
| Python | mit | cristianzamar/gsconfig,scottp-dpaw/gsconfig,boundlessgeo/gsconfig,Geode/gsconfig,afabiani/gsconfig,garnertb/gsconfig.py | ---
+++
@@ -1,4 +1,5 @@
from geoserver.support import ResourceInfo, atom_link
+import re
class Style(ResourceInfo):
def __init__(self,catalog, node):
@@ -23,5 +24,9 @@
self.sld_name = name_node.text if hasattr(name_node, 'text') else None
self.sld_title = title_node.text if hasattr(title_node, 'text'... |
115dbdecabc74f4f08d07099a4997860ebe5278b | telemetry/telemetry/core/platform/profiler/android_screen_recorder_profiler.py | telemetry/telemetry/core/platform/profiler/android_screen_recorder_profiler.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
from telemetry.core import util
from telemetry.core.backends.chrome import android_browser_finder
from telemetry.core.platform i... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
from telemetry.core import util
from telemetry.core.backends.chrome import android_browser_finder
from telemetry.core.platform i... | Fix screen recording with multiple connected devices | telemetry: Fix screen recording with multiple connected devices
Make it possible to use the Android screen recording profiler with
multiple connected devices. Only the screen on the device that is
actually running the telemetry test will get recorded.
BUG=331435
TEST=tools/perf/run_benchmark smoothness.key_mobile_sit... | Python | bsd-3-clause | SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,benschmaus/catapult,sahiljain/catapult,SummerLW... | ---
+++
@@ -18,8 +18,11 @@
self._output_path = output_path + '.mp4'
self._recorder = subprocess.Popen(
[os.path.join(util.GetChromiumSrcDir(), 'build', 'android',
- 'screenshot.py'), '--video', '--file',
- self._output_path], stdin=subprocess.PIPE, stdout=subprocess.PIP... |
c76734ea034f2a48de0eab995c5db5667086e0c8 | common/util/log.py | common/util/log.py | import sublime
def universal_newlines(string):
return string.replace('\r\n', '\n').replace('\r', '\n')
def panel(message, run_async=True):
message = universal_newlines(str(message))
view = sublime.active_window().active_view()
if run_async:
sublime.set_timeout_async(
lambda: view... | import re
import sublime
ANSI_ESCAPE_RE = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
def normalize(string):
return ANSI_ESCAPE_RE.sub('', string.replace('\r\n', '\n').replace('\r', '\n'))
def panel(message, run_async=True):
message = normalize(str(message))
view = sublime.active_window().active_view()
... | Remove ANSI escape sequences from panel output | Remove ANSI escape sequences from panel output
| Python | mit | divmain/GitSavvy,divmain/GitSavvy,divmain/GitSavvy | ---
+++
@@ -1,12 +1,16 @@
+import re
import sublime
-def universal_newlines(string):
- return string.replace('\r\n', '\n').replace('\r', '\n')
+ANSI_ESCAPE_RE = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
+
+
+def normalize(string):
+ return ANSI_ESCAPE_RE.sub('', string.replace('\r\n', '\n').replace('\r', '\n'... |
a610faf9d64c062ed2dd44a818acc0d12d1f6e0b | django_evolution/compat/picklers.py | django_evolution/compat/picklers.py | """Picklers for working with serialized data."""
from __future__ import unicode_literals
import pickle
class DjangoCompatUnpickler(pickle.Unpickler):
"""Unpickler compatible with changes to Django class/module paths.
This provides compatibility across Django versions for various field types,
updating r... | """Picklers for working with serialized data."""
from __future__ import unicode_literals
import pickle
from django_evolution.compat.datastructures import OrderedDict
class SortedDict(dict):
"""Compatibility for unpickling a SortedDict.
Old signatures may use an old Django ``SortedDict`` structure, which d... | Support loading pickled data referencing SortedDict. | Support loading pickled data referencing SortedDict.
Django used to provide a class called `SortedDict`, which has long been
deprecated in favor of Python's own `OrderedDict`. However, due to the
way that pickling works, older signatures would still attempt to loading
a `SortedDict` class.
This change adds a compatib... | Python | bsd-3-clause | beanbaginc/django-evolution | ---
+++
@@ -4,8 +4,35 @@
import pickle
+from django_evolution.compat.datastructures import OrderedDict
-class DjangoCompatUnpickler(pickle.Unpickler):
+
+class SortedDict(dict):
+ """Compatibility for unpickling a SortedDict.
+
+ Old signatures may use an old Django ``SortedDict`` structure, which does
+... |
4640b75fdb794e29cb6e7bdc03a6697d8f9f3483 | emu/processes/wps_ultimate_question.py | emu/processes/wps_ultimate_question.py | from pywps import Process, LiteralOutput
from pywps.app.Common import Metadata
class UltimateQuestion(Process):
def __init__(self):
inputs = []
outputs = [LiteralOutput('answer', 'Answer to Ultimate Question', data_type='string')]
super(UltimateQuestion, self).__init__(
self._... | from pywps import Process, LiteralOutput
from pywps.app.Common import Metadata
class UltimateQuestion(Process):
def __init__(self):
inputs = []
outputs = [LiteralOutput('answer', 'Answer to Ultimate Question', data_type='string')]
super(UltimateQuestion, self).__init__(
self._... | Make ultimate question ever more ultimate | Make ultimate question ever more ultimate
| Python | apache-2.0 | bird-house/emu | ---
+++
@@ -12,7 +12,7 @@
identifier='ultimate_question',
version='2.0',
title='Answer to the ultimate question',
- abstract='This process gives the answer to the ultimate question of "What is the meaning of life?"',
+ abstract='This process gives the answe... |
bf0043ac102cc9eddf03c8db493ae1a985c6a30a | src/nyc_trees/apps/home/urls.py | src/nyc_trees/apps/home/urls.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from apps.home import routes as r
urlpatterns = patterns(
'',
url(r'^$', r.home_page, name='home_page'),
url(r'^progr... | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from apps.home import routes as r
urlpatterns = patterns(
'',
url(r'^$', r.home_page, name='home_page'),
url(r'^progr... | Fix trailing slash 404 for flat pages and co | Fix trailing slash 404 for flat pages and co
By modifying the URL, flatpage requests without a trailing slash will
always fail, triggering the redirect provided by `APPEND_SLASH`.
This is important because urls that share a common endpoint path were
404ing on a flatpage not found when not constructed with a slash.
| Python | agpl-3.0 | azavea/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,kdeloach/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,azavea/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,RickMohr/ny... | ---
+++
@@ -23,5 +23,5 @@
# "training" instead of "training/" because the flatpages admin interface
# insists that the "URL" (really a URL segment) start with a leading slash
- url(r'^training', include('django.contrib.flatpages.urls')),
+ url(r'^training(?P<url>.*/)$', include('django.contrib.flatp... |
cebe1c3b72eb9e0fd4114d5664e269a73bdc06a1 | examples/many_pairwise_correlations.py | examples/many_pairwise_correlations.py | """
Plotting a diagonal correlation matrix
======================================
_thumb: .3, .6
"""
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white")
# Generate a large random dataset
rs = np.random.RandomState(33)
d = rs.normal(size=(30, 100))
# Compute the correlatio... | """
Plotting a diagonal correlation matrix
======================================
_thumb: .3, .6
"""
from string import letters
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white")
# Generate a large random dataset
rs = np.random.RandomState(33)
d = pd.D... | Use dataframe to show how semantic information is used | Use dataframe to show how semantic information is used
| Python | bsd-3-clause | mia1rab/seaborn,muku42/seaborn,JWarmenhoven/seaborn,mwaskom/seaborn,drewokane/seaborn,jat255/seaborn,phobson/seaborn,bsipocz/seaborn,uhjish/seaborn,arokem/seaborn,tim777z/seaborn,q1ang/seaborn,clarkfitzg/seaborn,dhimmel/seaborn,olgabot/seaborn,Lx37/seaborn,anntzer/seaborn,kyleam/seaborn,oesteban/seaborn,sinhrks/seaborn... | ---
+++
@@ -4,7 +4,9 @@
_thumb: .3, .6
"""
+from string import letters
import numpy as np
+import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
@@ -12,10 +14,11 @@
# Generate a large random dataset
rs = np.random.RandomState(33)
-d = rs.normal(size=(30, 100))
+d = pd.DataFrame(data=r... |
5fe71408c740697ebe0b268e9fbac93f5932ef63 | froide/foirequest/search_indexes.py | froide/foirequest/search_indexes.py | from haystack import indexes
from haystack import site
from foirequest.models import FoiRequest
class FoiRequestIndex(indexes.SearchIndex):
text = indexes.EdgeNgramField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
description = indexes.CharField(model_attr='description... | from haystack import indexes
from haystack import site
from foirequest.models import FoiRequest
class FoiRequestIndex(indexes.SearchIndex):
text = indexes.EdgeNgramField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
description = indexes.CharField(model_attr='description... | Add summary to foirequest search | Add summary to foirequest search | Python | mit | ryankanno/froide,stefanw/froide,LilithWittmann/froide,LilithWittmann/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,catcosmo/froide,stefanw/froide,CodeforHawaii/froide,okfse/froide,LilithWittmann/froide,ryankanno/froide,catcosmo/froide,CodeforHawaii/froide,ryankanno/froide,catcosmo/froide,ryankanno/froide,c... | ---
+++
@@ -8,6 +8,7 @@
text = indexes.EdgeNgramField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
description = indexes.CharField(model_attr='description')
+ summary = indexes.CharField(model_attr='summary')
status = indexes.CharField(model_attr='status')
... |
99aac92ca2a4958b7daff7b64d52c0e58db3554c | opal/tests/test_core_views.py | opal/tests/test_core_views.py | """
Unittests for opal.core.views
"""
from opal.core import test
from opal.core import views
class SerializerTestCase(test.OpalTestCase):
def test_serializer_default_will_super(self):
s = views.OpalSerializer()
with self.assertRaises(TypeError):
s.default(None)
| """
Unittests for opal.core.views
"""
import warnings
from opal.core import test
from opal.core import views
class SerializerTestCase(test.OpalTestCase):
def test_serializer_default_will_super(self):
s = views.OpalSerializer()
with self.assertRaises(TypeError):
s.default(None)
clas... | Add test for warn spelling of build_json_response | Add test for warn spelling of build_json_response
| Python | agpl-3.0 | khchine5/opal,khchine5/opal,khchine5/opal | ---
+++
@@ -1,6 +1,8 @@
"""
Unittests for opal.core.views
"""
+import warnings
+
from opal.core import test
from opal.core import views
@@ -11,3 +13,15 @@
s = views.OpalSerializer()
with self.assertRaises(TypeError):
s.default(None)
+
+
+class BuildJSONResponseTestCase(test.OpalT... |
452bad78228f5cb26c0ed9cc7aa48497f1d3f7f0 | apps/tasks/signals.py | apps/tasks/signals.py | import logging
import django.dispatch
from django.dispatch import receiver
logger = logging.getLogger(__name__)
__all__ = ['task_status_changed', 'celery_request_status_update']
task_status_changed = django.dispatch.Signal(providing_args=['instance', ])
celery_request_status_update = django.dispatch.Signal(providing... | import logging
import django.dispatch
from django.dispatch import receiver
import requests
from common.utils import build_absolute_uri
logger = logging.getLogger(__name__)
__all__ = ['task_status_changed', 'celery_request_status_update']
task_status_changed = django.dispatch.Signal(providing_args=['instance', ])
cel... | Update status using API instead of direct db access | Update status using API instead of direct db access
| Python | mit | Wikia/sparrow,harnash/sparrow,Wikia/sparrow,Wikia/sparrow | ---
+++
@@ -1,6 +1,8 @@
import logging
import django.dispatch
from django.dispatch import receiver
+import requests
+from common.utils import build_absolute_uri
logger = logging.getLogger(__name__)
@@ -14,14 +16,14 @@
def on_task_manager_request_status_update(sender, task_id, job_id, status, **kwargs):
... |
057ddbf6ee529fff9f511a9cc8bc8c1a20a91833 | helpers.py | helpers.py | import os
from collections import namedtuple
Response = namedtuple('Response', 'command_status message')
# Allows use of `environ_or_none("foo") or "default"` shorthand
# noinspection PyBroadException
def environ_or_none(key):
try:
return os.environ[key]
except:
return None
# Checks that all... | import os
from collections import namedtuple
Response = namedtuple('Response', 'command_status message')
# Allows use of `environ_or_none("foo") or "default"` shorthand
# noinspection PyBroadException
def environ_or_none(key):
try:
return os.environ[key]
except:
return None
# Checks that al... | Add another blank line (thanks flake) --autopull | Add another blank line (thanks flake) --autopull | Python | apache-2.0 | Charcoal-SE/SmokeDetector,Charcoal-SE/SmokeDetector | ---
+++
@@ -12,6 +12,7 @@
except:
return None
+
# Checks that all items in a pattern-matching product name are unique
def all_matches_unique(match):
return len(match[0][1::2]) == len(set(match[0][1::2])) |
a0e432b0ac31ed74256197b1d5df8b6f8a0987db | product/models.py | product/models.py | from django.db import models
from django.utils.translation import pgettext as _
from django_prices.models import PriceField
from satchless.util.models import Subtyped
from satchless.item import ItemRange
from mptt.models import MPTTModel
class Category(MPTTModel):
name = models.CharField(_('Category field', 'nam... | from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import pgettext as _
from django_prices.models import PriceField
from mptt.models import MPTTModel
from satchless.item import ItemRange
from satchless.util.models import Subtyped
from unidecode import unidecode
impo... | Replace slug field with get_slug function | Replace slug field with get_slug function
| Python | bsd-3-clause | laosunhust/saleor,mociepka/saleor,paweltin/saleor,mociepka/saleor,jreigel/saleor,taedori81/saleor,UITools/saleor,UITools/saleor,spartonia/saleor,car3oon/saleor,Drekscott/Motlaesaleor,UITools/saleor,HyperManTT/ECommerceSaleor,paweltin/saleor,maferelo/saleor,dashmug/saleor,rodrigozn/CW-Shop,laosunhust/saleor,avorio/saleo... | ---
+++
@@ -1,9 +1,12 @@
from django.db import models
+from django.utils.safestring import mark_safe
from django.utils.translation import pgettext as _
from django_prices.models import PriceField
+from mptt.models import MPTTModel
+from satchless.item import ItemRange
from satchless.util.models import Subtyped
-f... |
66a5c4199d3e8bbea5ed40e92fef4be60425f827 | pmxbot/dictlib.py | pmxbot/dictlib.py | import yaml
from jaraco.collections import ItemsAsAttributes
class ConfigDict(ItemsAsAttributes, dict):
@classmethod
def from_yaml(cls, filename):
with open(filename) as f:
return cls(yaml.load(f))
def to_yaml(self, filename):
dumper = getattr(yaml, 'danger_dump', yaml.dump)
with open(filename, 'w') as f... | import yaml
from jaraco.collections import ItemsAsAttributes
class ConfigDict(ItemsAsAttributes, dict):
@classmethod
def from_yaml(cls, filename):
with open(filename) as f:
return cls(yaml.safe_load(f))
def to_yaml(self, filename):
dumper = getattr(yaml, 'danger_dump', yaml.dump)
with open(filename, 'w')... | Use safe-load when loading configuration to avoid deprecation warning | Use safe-load when loading configuration to avoid deprecation warning
| Python | mit | yougov/pmxbot,yougov/pmxbot,yougov/pmxbot | ---
+++
@@ -6,7 +6,7 @@
@classmethod
def from_yaml(cls, filename):
with open(filename) as f:
- return cls(yaml.load(f))
+ return cls(yaml.safe_load(f))
def to_yaml(self, filename):
dumper = getattr(yaml, 'danger_dump', yaml.dump) |
c08013dc2fc32582e8636d84be3e2f68dafe11a0 | controller.py | controller.py | """NM-Controller accounts are used to provide secure access to the XMLRPC API. They are normal Unix accounts with a shell that tunnels XMLRPC requests to the API server."""
import accounts
import logger
import tools
class Controller(accounts.Account):
SHELL = '/usr/bin/forward_api_calls' # tunneling shell
... | """NM-Controller accounts are used to provide secure access to the XMLRPC API. They are normal Unix accounts with a shell that tunnels XMLRPC requests to the API server."""
import accounts
import logger
import tools
class Controller(accounts.Account):
SHELL = '/usr/bin/forward_api_calls' # tunneling shell
... | Change to Controller from Delegate shell | Change to Controller from Delegate shell
| Python | bsd-3-clause | dreibh/planetlab-lxc-nodemanager,planetlab/NodeManager,planetlab/NodeManager,planetlab/NodeManager,dreibh/planetlab-lxc-nodemanager,planetlab/NodeManager,dreibh/planetlab-lxc-nodemanager | ---
+++
@@ -11,8 +11,8 @@
@staticmethod
def create(name, vref = None):
- add_shell(Delegate.SHELL)
- logger.log_call('/usr/sbin/useradd', '-p', '*', '-s', Delegate.SHELL, name)
+ add_shell(Controller.SHELL)
+ logger.log_call('/usr/sbin/useradd', '-p', '*', '-s', Controller.SHEL... |
21f27eecae407e3baa8f55effd7b19ef2fa9ca6d | jug.py | jug.py | from store import create_directories
import options
import task
def parse_jugfile():
import jugfile
def print_tasks():
for i,t in enumerate(task.alltasks):
print 'Task %s: %s' % (i,t.name)
def execute_tasks():
tasks = task.alltasks
while tasks:
ready = [t for t in tasks if t.can_run()... | from collections import defaultdict
from store import create_directories
import options
import task
import jugfile
def print_tasks():
task_counts = defaultdict(int)
for t in task.alltasks:
task_counts[t.name] += 1
for tnc in task_counts.items():
print 'Task %s: %s' % tnc
task_names = set(t... | Print a little summary when you're done | Print a little summary when you're done
| Python | mit | unode/jug,unode/jug,luispedro/jug,luispedro/jug | ---
+++
@@ -1,14 +1,19 @@
+from collections import defaultdict
from store import create_directories
import options
import task
-
-def parse_jugfile():
- import jugfile
+import jugfile
def print_tasks():
- for i,t in enumerate(task.alltasks):
- print 'Task %s: %s' % (i,t.name)
+ task_counts = def... |
d2730af02bf9032ec5bb10b07f8fae6fab2bba52 | fellowms/management/commands/applicants_data.py | fellowms/management/commands/applicants_data.py | import pandas as pd
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ObjectDoesNotExist
from fellowms.models import Fellow
class Command(BaseCommand):
help = "Add old information to database."
# TODO Make use of args and options.
def handle(self, *args... | import pandas as pd
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ObjectDoesNotExist
from fellowms.models import Fellow
class Command(BaseCommand):
help = "Add old information to database."
# TODO Make use of args and options.
def handle(self, *args... | Fix fellowship_grant when upload data | Fix fellowship_grant when upload data
| Python | bsd-3-clause | softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat | ---
+++
@@ -29,6 +29,7 @@
"gender": line["Gender"] if line["Gender"] else 'R',
"work_description": line["Work area"],
"funding": "{}, {}".format(line["Primary funder"],line["Additional funder"]),
+ "fellowship_grant": 3000 if is_fellow ... |
9f9d78fd7a5011f24b5e12249f1276010293d877 | bin/upload_version.py | bin/upload_version.py | #!python
import os
import sys
import json
import requests
if __name__ == '__main__':
version = sys.argv[1]
filepath = sys.argv[2]
filename = filepath.split('/')[-1]
github_token = os.environ['GITHUB_TOKEN']
auth = (github_token, 'x-oauth-basic')
commit_sha = os.environ['CIRCLE_SHA1']
params = json.dumps... | #!python
import os
import sys
import json
import requests
import subprocess
def capture_output(command):
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
return proc.stdout.read()
if __name__ == '__main__':
version = sys.argv[1]
filepath = sys.argv[2]
filename = filepath.split('/')[-1]
... | Update upload script to include checksums | Update upload script to include checksums
| Python | bsd-2-clause | useabode/redash,pubnative/redash,rockwotj/redash,chriszs/redash,getredash/redash,44px/redash,hudl/redash,moritz9/redash,imsally/redash,getredash/redash,alexanderlz/redash,akariv/redash,rockwotj/redash,alexanderlz/redash,44px/redash,guaguadev/redash,vishesh92/redash,imsally/redash,pubnative/redash,easytaxibr/redash,Ever... | ---
+++
@@ -3,30 +3,44 @@
import sys
import json
import requests
+import subprocess
+
+
+def capture_output(command):
+ proc = subprocess.Popen(command, stdout=subprocess.PIPE)
+ return proc.stdout.read()
+
if __name__ == '__main__':
- version = sys.argv[1]
- filepath = sys.argv[2]
- filename = filepat... |
b295e3e64367073550ceb00faa72e6564f08dd55 | pytest_cookies.py | pytest_cookies.py | # -*- coding: utf-8 -*-
import pytest
from cookiecutter.main import cookiecutter
class Cookies(object):
"""Class to provide convenient access to the cookiecutter API."""
error = None
project = None
def __init__(self, template, output_dir):
self._template = template
self._output_dir ... | # -*- coding: utf-8 -*-
import pytest
from cookiecutter.main import cookiecutter
class Cookies(object):
"""Class to provide convenient access to the cookiecutter API."""
exception = None
exit_code = 0
project = None
def __init__(self, template, output_dir):
self._template = template
... | Handle SystemExit errors and add exit_code | Handle SystemExit errors and add exit_code
| Python | mit | hackebrot/pytest-cookies | ---
+++
@@ -7,7 +7,8 @@
class Cookies(object):
"""Class to provide convenient access to the cookiecutter API."""
- error = None
+ exception = None
+ exit_code = 0
project = None
def __init__(self, template, output_dir):
@@ -22,8 +23,13 @@
extra_context=extra_context,
... |
4baa59fd3ea90b604a8cdb5f4daf9ddb61f2e34a | aybu/manager/cli/task.py | aybu/manager/cli/task.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.
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 app... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.
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 app... | Fix error on connection failures | Fix error on connection failures
| Python | apache-2.0 | asidev/aybu-manager-cli,asidev/aybu-manager-cli | ---
+++
@@ -25,13 +25,9 @@
name = 'tasks'
def logs(self, task):
- try:
- response, content = self.api.get(self.get_url(task, 'logs'))
+ response, content = self.api.get(self.get_url(task, 'logs'))
- except ValueError:
- pass
-
- else:
+ if content... |
f696e320d66f375779692ec073f15d3d6d466059 | edx_data_research/parsing/parse_sql.py | edx_data_research/parsing/parse_sql.py | import subprocess
from edx_data_research.parsing.parse import Parse
class SQL(Parse):
def __init__(self, args):
super(SQL, self).__init__(args)
self._collections = args.collection
self.sql_file = args.sql_file
def migrate(self):
subprocess.check_call(['mongoimport', '-d', sel... | import subprocess
from edx_data_research.parsing.parse import Parse
class SQL(Parse):
def __init__(self, args):
super(SQL, self).__init__(args)
self._collections = args.collection
self.sql_file = args.sql_file
def migrate(self):
subprocess.check_call(['mongoimport', '-d', sel... | Update mongo import of files to drop existing collection first | Update mongo import of files to drop existing collection first
| Python | mit | McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research | ---
+++
@@ -12,4 +12,4 @@
def migrate(self):
subprocess.check_call(['mongoimport', '-d', self.db_name, '-c',
self._collections, '--type', 'tsv', '--file',
- self.sql_file, '--headerline'])
+ self.sql_file, '--hea... |
8a44705413d3a01e897d4a922e7c1383b60a2927 | plugins/VersionUpgrade/VersionUpgrade21to22/__init__.py | plugins/VersionUpgrade/VersionUpgrade21to22/__init__.py | # Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import VersionUpgrade21to22
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "Version Upgrade 2.1 to 2.2"... | # Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import VersionUpgrade21to22
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "Version Upgrade 2.1 to 2.2"... | Update metadata with dynamic config types | Update metadata with dynamic config types
After settings rework, we decided to make the upgrade plug-ins define their own configuration types. This is basically the definition for these configuration types. Only the get_version function is not yet implemented.
Contributes to issue CURA-844.
| Python | agpl-3.0 | Curahelper/Cura,ynotstartups/Wanhao,hmflash/Cura,totalretribution/Cura,hmflash/Cura,Curahelper/Cura,senttech/Cura,fieldOfView/Cura,senttech/Cura,fieldOfView/Cura,totalretribution/Cura,ynotstartups/Wanhao | ---
+++
@@ -16,13 +16,23 @@
"api": 2
},
"version_upgrade": {
+ # From To Upgrade function
+ ("profile", 1): ("instance_container", 2, VersionUpgrade21to22.upgradeProfile),
+ ("machine_instance", 1): ("con... |
3e2c7ca2147b28403761cf57dad6d9173a28dc3d | docs/tasks.py | docs/tasks.py | import invoke
import livereload
import shutil
server = livereload.Server()
@invoke.task
def clean():
shutil.rmtree('./build')
@invoke.task(pre=[clean])
def build():
invoke.run('sphinx-build ./source ./build', pty=True)
@invoke.task(pre=[build])
def serve():
server.watch('./source/*', build)
serve... | import invoke
import livereload
import shutil
server = livereload.Server()
@invoke.task
def clean():
shutil.rmtree('./build')
@invoke.task(pre=[clean])
def build():
invoke.run('sphinx-build ./source ./build', pty=True)
@invoke.task(pre=[build])
def serve():
server.watch('../reqon/', build)
server... | Fix directory watching when serving the docs. | Fix directory watching when serving the docs.
| Python | mit | dmpayton/reqon | ---
+++
@@ -17,8 +17,8 @@
@invoke.task(pre=[build])
def serve():
- server.watch('./source/*', build)
- server.watch('./source/**/*', build)
+ server.watch('../reqon/', build)
+ server.watch('./source/', build)
server.serve(
root='./build',
host='localhost', |
808434912ceb176793a559464f767e2eb52b889d | sanic_limiter/util.py | sanic_limiter/util.py | """
"""
def get_remote_address(request):
"""
:param: request: request object of sanic
:return: the ip address of given request (or 127.0.0.1 if none found)
"""
return request.ip[0] or '127.0.0.1'
| """
"""
def get_remote_address(request):
"""
:param: request: request object of sanic
:return: the ip address of given request (or 127.0.0.1 if none found)
"""
return request.remote_addr or request.ip
| Fix IP keyfunc for reverse proxies | Fix IP keyfunc for reverse proxies
| Python | mit | bohea/sanic-limiter | ---
+++
@@ -8,4 +8,4 @@
:param: request: request object of sanic
:return: the ip address of given request (or 127.0.0.1 if none found)
"""
- return request.ip[0] or '127.0.0.1'
+ return request.remote_addr or request.ip |
093c8ac40ba6154ee4a3d3d1430e5b05e68b2e9e | timpani/webserver/webhelpers.py | timpani/webserver/webhelpers.py | import flask
from .. import auth
import urllib.parse
def checkForSession():
if "uid" in flask.session:
session = auth.validateSession(flask.session["uid"])
if session != None:
return session
return None
def redirectAndSave(path):
flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path
re... | import flask
from .. import auth
import urllib.parse
def checkForSession():
if "uid" in flask.session:
session = auth.validateSession(flask.session["uid"])
if session != None:
return session
return None
def redirectAndSave(path):
flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path
re... | Fix legacy return in redirectAndSave | Fix legacy return in redirectAndSave
| Python | mit | ollien/Timpani,ollien/Timpani,ollien/Timpani | ---
+++
@@ -11,7 +11,7 @@
def redirectAndSave(path):
flask.session["donePage"] = urllib.parse.urlparse(flask.request.url).path
- return response
+ return flask.redirect(path)
def markRedirectAsRecovered():
if "donePage" in flask.session: |
788ca6bbd25bcdb55dc92739e7d08b201344b10b | tools/glidein_top.py | tools/glidein_top.py | #!/bin/env python
#
# glidein_top
#
# Execute a top command in the same glidein as the user job
#
# Usage:
# glidein_top.py <cluster>.<process> [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs>
#
import os
import stat
import sys
sys.path.append("lib")
sys.path.append("../lib")
import glideinMonitor
def... | #!/bin/env python
#
# glidein_top.py
#
# Description:
# Execute a top command on a condor job
#
# Usage:
# glidein_top.py <cluster>.<process> [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs>]
#
# Author:
# Igor Sfiligoi (May 2007)
#
# License:
# Fermitools
#
import sys,os.path
sys.path.append(os.pa... | Change rel paths into abspaths and use helper module | Change rel paths into abspaths and use helper module
| Python | bsd-3-clause | holzman/glideinwms-old,bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS | ---
+++
@@ -1,38 +1,29 @@
#!/bin/env python
#
-# glidein_top
+# glidein_top.py
#
-# Execute a top command in the same glidein as the user job
+# Description:
+# Execute a top command on a condor job
#
# Usage:
-# glidein_top.py <cluster>.<process> [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs>... |
7a4398f6e60b53626a2586cc4df3b7f5fb2a6aff | mysite/profile/management/commands/profile_ten_minutely_tasks.py | mysite/profile/management/commands/profile_ten_minutely_tasks.py | # This file is part of OpenHatch.
# Copyright (C) 2010 OpenHatch, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | # This file is part of OpenHatch.
# Copyright (C) 2010 OpenHatch, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | Use /projects/ not /+projects/ when caching | Use /projects/ not /+projects/ when caching
This prevents staticgenerator from sending out an annoying email
every 10 minutes.
| Python | agpl-3.0 | vipul-sharma20/oh-mainline,SnappleCap/oh-mainline,waseem18/oh-mainline,willingc/oh-mainline,Changaco/oh-mainline,nirmeshk/oh-mainline,heeraj123/oh-mainline,waseem18/oh-mainline,sudheesh001/oh-mainline,waseem18/oh-mainline,nirmeshk/oh-mainline,vipul-sharma20/oh-mainline,vipul-sharma20/oh-mainline,nirmeshk/oh-mainline,mo... | ---
+++
@@ -25,8 +25,8 @@
help = "Run this once every 10 minutes for the OpenHatch profile app."
def handle(self, *args, **options):
- # Every 10 minutes, refresh /+projects/
+ # Every 10 minutes, refresh /projects/
root_logger = logging.getLogger('')
root_logger.setLevel(l... |
85d800d9979fa122e0888af48c2e6a697f9da458 | test/test_sc2replay.py | test/test_sc2replay.py | #!/usr/bin/env python
# coding: utf-8
import os
import unittest
from adjutant import SC2Replay
TEST_DIR = os.path.realpath(os.path.dirname(__file__)) + '/'
class TestSC2Replay(unittest.TestCase):
def setUp(self):
self.replay = SC2Replay(TEST_DIR + 'test.SC2Replay')
def test_init(self):
self... | #!/usr/bin/env python
# coding: utf-8
import os
import unittest
from adjutant import SC2Replay
TEST_DIR = os.path.realpath(os.path.dirname(__file__)) + '/'
class TestSC2Replay(unittest.TestCase):
def setUp(self):
self.replay = SC2Replay(TEST_DIR + 'test.SC2Replay')
def test_init(self):
self... | Add a small test for init with a file arg. | Add a small test for init with a file arg.
| Python | bsd-2-clause | eagleflo/adjutant | ---
+++
@@ -17,3 +17,7 @@
self.assertEqual(self.replay.duration, '26m 17s')
self.assertEqual(self.replay.version, '1.0.2.16223')
self.assertEqual(len(self.replay.players), 8)
+
+ def test_init_with_a_file_arg(self):
+ self.replay = SC2Replay(open(TEST_DIR + 'test.SC2Replay', 'rb')... |
295e356af1e4422fd8e2af9a44b46f5976a5ec39 | tools/test_sneeze.py | tools/test_sneeze.py |
import os
from tempfile import mkdtemp
from shutil import rmtree
from nipy.testing import *
from sneeze import find_pkg, run_nose
import_strings = ["from nipype.interfaces.afni import To3d",
"from nipype.interfaces import afni",
"import nipype.interfaces.afni"]
def test_from_name... |
import os
from tempfile import mkdtemp
from shutil import rmtree
from nipy.testing import *
from sneeze import find_pkg, run_nose
import_strings = ["from nipype.interfaces.afni import To3d, ThreeDRefit",
"from nipype.interfaces import afni",
"import nipype.interfaces.afni",
... | Add more tests for sneeze. | Add more tests for sneeze. | Python | bsd-3-clause | nipy/nipy-labs,alexis-roche/niseg,nipy/nireg,alexis-roche/nipy,alexis-roche/nipy,alexis-roche/nireg,arokem/nipy,bthirion/nipy,alexis-roche/register,nipy/nireg,bthirion/nipy,alexis-roche/nipy,bthirion/nipy,alexis-roche/nipy,arokem/nipy,alexis-roche/niseg,arokem/nipy,bthirion/nipy,arokem/nipy,alexis-roche/register,alexis... | ---
+++
@@ -6,21 +6,23 @@
from nipy.testing import *
from sneeze import find_pkg, run_nose
-import_strings = ["from nipype.interfaces.afni import To3d",
+import_strings = ["from nipype.interfaces.afni import To3d, ThreeDRefit",
"from nipype.interfaces import afni",
- "import ni... |
1f9486cff230beae00e5417d6ad2b1ba28526339 | pson/pson.py | pson/pson.py | import json
from pprint import pprint
def pathparser(path, separator="."):
return path.split(separator)
def pathquery(pson, path, separator=".", missing=None, iterate=True):
if isinstance(path,str) or isinstance(path, unicode):
path = pathparser(path, separator=separator)
coun... | import json
from pprint import pprint
def pathparser(path, separator="."):
return path.split(separator)
def pathquery(pson, path, separator=".", missing=None, iterate=True):
if isinstance(path,str) or isinstance(path, unicode):
path = pathparser(path, separator=separator)
counter = 0
for toke... | Add consistent 4 space indentation | Add consistent 4 space indentation
Applied 4 space indentation all along the main pson.py file.
| Python | mit | imranghory/pson | ---
+++
@@ -2,31 +2,31 @@
from pprint import pprint
def pathparser(path, separator="."):
- return path.split(separator)
+ return path.split(separator)
def pathquery(pson, path, separator=".", missing=None, iterate=True):
- if isinstance(path,str) or isinstance(path, unicode):
- ... |
da6e9416e12ce71cd3f23ded9bd75dccc62d26fe | fcn/config.py | fcn/config.py | import os.path as osp
def get_data_dir():
this_dir = osp.dirname(osp.abspath(__file__))
return osp.realpath(osp.join(this_dir, '../data'))
def get_logs_dir():
this_dir = osp.dirname(osp.abspath(__file__))
return osp.realpath(osp.join(this_dir, '../logs'))
| import os.path as osp
def get_data_dir():
this_dir = osp.dirname(osp.abspath(__file__))
return osp.realpath(osp.join(this_dir, '_data'))
| Move data directory in package | Move data directory in package
| Python | mit | wkentaro/fcn | ---
+++
@@ -3,9 +3,4 @@
def get_data_dir():
this_dir = osp.dirname(osp.abspath(__file__))
- return osp.realpath(osp.join(this_dir, '../data'))
-
-
-def get_logs_dir():
- this_dir = osp.dirname(osp.abspath(__file__))
- return osp.realpath(osp.join(this_dir, '../logs'))
+ return osp.realpath(osp.joi... |
945e978d3249762da9a47300cb43d86966de0354 | wanikani2anki.py | wanikani2anki.py | #! /usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
import json
from urllib.request import *
headers = {}
with open('apikey.txt', 'r') as f:
apike... | #! /usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
import json
from urllib.error import *
from urllib.request import *
headers = {}
with open('apikey... | Add error handling for GET request. | Add error handling for GET request.
| Python | mpl-2.0 | holocronweaver/wanikani2anki,holocronweaver/wanikani2anki,holocronweaver/wanikani2anki | ---
+++
@@ -3,6 +3,7 @@
# License, v2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
import json
+from urllib.error import *
from urllib.request import *
headers = {}
@@ -13,8 +14,15 @@
rooturl = 'https://www.wanikani.com/api/v2'
request = R... |
393743e391575d6cf4a3bfffb4f53cfa0848c49e | tests/test_donemail.py | tests/test_donemail.py | from mock import Mock
import pytest
import smtplib
from donemail import donemail
BOB = 'bob@example.com'
@pytest.fixture(autouse=True)
def monkeypatch_send_email(monkeypatch):
monkeypatch.setattr('smtplib.SMTP', Mock())
def test_context_manager():
assert_num_emails(0)
with donemail(BOB):
pass
... | from mock import ANY, Mock
import pytest
import smtplib
from donemail import donemail
BOB = 'bob@example.com'
@pytest.fixture(autouse=True)
def monkeypatch_send_email(monkeypatch):
mock_smtp_class = Mock()
mock_smtp_class.return_value = Mock()
monkeypatch.setattr('smtplib.SMTP', mock_smtp_class)
def t... | Check that test emails are sent to BOB | Check that test emails are sent to BOB
| Python | mit | alexandershov/donemail | ---
+++
@@ -1,4 +1,4 @@
-from mock import Mock
+from mock import ANY, Mock
import pytest
import smtplib
@@ -9,18 +9,28 @@
@pytest.fixture(autouse=True)
def monkeypatch_send_email(monkeypatch):
- monkeypatch.setattr('smtplib.SMTP', Mock())
+ mock_smtp_class = Mock()
+ mock_smtp_class.return_value = Mo... |
634ae735db61ebb211b9e3159ca4dac7861e5553 | cluster/update_jobs.py | cluster/update_jobs.py | from django.contrib.auth.models import User
from models import Job
from interface import get_all_jobs
def run_all():
for user in User.objects.all():
creds = user.credentials.all()
for i, cluster in enumerate(get_all_jobs(user)):
cred = creds[i]
jobs = {}
for jo... | from django.contrib.auth.models import User
from models import Job
from interface import get_all_jobs
def run_all():
for user in User.objects.all():
creds = user.credentials.all()
for i, cluster in enumerate(get_all_jobs(user)):
cred = creds[i]
jobs = {}
jobids... | Add updating of jobs if their state is now unknown | Add updating of jobs if their state is now unknown
| Python | mit | crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp | ---
+++
@@ -10,13 +10,19 @@
for i, cluster in enumerate(get_all_jobs(user)):
cred = creds[i]
jobs = {}
+ jobids = []
for job in cluster["jobs"]:
status = job[-1]
job_id = job[0]
+ jobids.append(job_id)
... |
27e2c86641bac1b2083a36d0eaf84e79553c39ce | pycom/objects.py | pycom/objects.py | # encoding: utf-8
### Attribute Wrapper
class AttrWrapper(object):
attrs = []
def __setattr__(self, name, value):
if name not in self.attrs:
raise AttributeError("'%s' is not supported" % name)
object.__setattr__(self, name, value)
def __repr__(self):
attrs = []
... | # encoding: utf-8
import six
### Attribute Wrapper
class AttrWrapper(object):
attrs = []
def __setattr__(self, name, value):
if name not in self.attrs:
raise AttributeError("'%s' is not supported" % name)
object.__setattr__(self, name, value)
def __repr__(self):
attrs ... | Fix a bug about the function, 'val'. | Fix a bug about the function, 'val'.
| Python | mit | xgfone/xutils,xgfone/pycom | ---
+++
@@ -1,5 +1,5 @@
# encoding: utf-8
-
+import six
### Attribute Wrapper
class AttrWrapper(object):
@@ -23,15 +23,11 @@
def val(obj, name, default=None):
- if hasattr(obj, name):
- return obj.name
- elif name in obj:
+ if isinstance(name, six.string_types) and hasattr(obj, name):
+ ... |
23ab67f74fc7c09310638529ccf804ec2271fd6c | pynads/writer.py | pynads/writer.py | from .monad import Monad
from .functor import fmap
class Writer(Monad):
"""Stores a value as well as a log of events that have transpired
with the value.
"""
def __init__(self, v, log):
self.v = v
if not isinstance(log, list):
self.log = [log]
else:
self... | from .utils import _iter_but_not_str_or_map
from .monad import Monad
from .functor import fmap
class Writer(Monad):
"""Stores a value as well as a log of events that have transpired
with the value.
"""
__slots__ = ('v', 'log')
def __init__(self, v, log):
self.v = v
if _iter_but_no... | Use utils._iter_but_not_str_or_map in Writer log creation. | Use utils._iter_but_not_str_or_map in Writer log creation.
| Python | mit | justanr/pynads | ---
+++
@@ -1,3 +1,4 @@
+from .utils import _iter_but_not_str_or_map
from .monad import Monad
from .functor import fmap
@@ -5,13 +6,17 @@
"""Stores a value as well as a log of events that have transpired
with the value.
"""
+ __slots__ = ('v', 'log')
+
def __init__(self, v, log):
s... |
2a06886077c05e1bfae7c28a09cf3489da6e450a | heat/utils.py | heat/utils.py | class LazyPluggable(object):
"""A pluggable backend loaded lazily based on some value."""
def __init__(self, pivot, **backends):
self.__backends = backends
self.__pivot = pivot
self.__backend = None
def __get_backend(self):
if not self.__backend:
print self.__ba... | class LazyPluggable(object):
"""A pluggable backend loaded lazily based on some value."""
def __init__(self, pivot, **backends):
self.__backends = backends
self.__pivot = pivot
self.__backend = None
def __get_backend(self):
if not self.__backend:
backend_name = ... | Remove stray print debug message | Remove stray print debug message
Signed-off-by: Steven Dake <8638f3fce5db0278cfbc239bd581dfc00c29ec9d@redhat.com>
| Python | apache-2.0 | rickerc/heat_audit,maestro-hybrid-cloud/heat,dims/heat,JioCloud/heat,cwolferh/heat-scratch,rh-s/heat,citrix-openstack-build/heat,steveb/heat,JioCloud/heat,steveb/heat-cfntools,Triv90/Heat,openstack/heat,dragorosson/heat,ntt-sic/heat,varunarya10/heat,miguelgrinberg/heat,rdo-management/heat,pratikmallya/heat,takeshineshi... | ---
+++
@@ -8,7 +8,6 @@
def __get_backend(self):
if not self.__backend:
- print self.__backends.values()
backend_name = 'sqlalchemy'
backend = self.__backends[backend_name]
if isinstance(backend, tuple): |
1b50b0e6d73e475172d6870ec34c308a9480586a | run_tests.py | run_tests.py | import sys
import os
import subprocess
def main():
executableName = 'CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPa... | import sys
import os
import subprocess
def main():
executableName = 'CuraEngine'
if len(sys.argv) > 1:
executableName = sys.argv[1]
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
ret = subprocess.call([executableName, os.path.join('testcase_models', subPa... | Add auto run test cases, just add STL files. | Add auto run test cases, just add STL files.
| Python | agpl-3.0 | alex1818/CuraEngine,Jwis921/PersonalCuraEngine,alephobjects/CuraEngine,ROBO3D/CuraEngine,markwal/CuraEngine,Jwis921/PersonalCuraEngine,derekhe/CuraEngine,patrick3coffee/CuraTinyG,foosel/CuraEngine,Skeen/CuraJS-Engine,fxtentacle/CuraEngine,electrocbd/CuraEngine,alephobjects/CuraEngine,electrocbd/CuraEngine,uus169/CuraEn... | ---
+++
@@ -10,7 +10,7 @@
exitValue = 0
for subPath in os.listdir('testcase_models'):
print 'Running test on %s' % (subPath)
- ret = subprocess.call([executableName, os.path.join('testcase_models', subPath))
+ ret = subprocess.call([executableName, os.path.join('testcase_models', subPath)])
if ret != 0:
... |
faf6f74348ed09f2ba0ebb5a133acc1a04edb737 | main.py | main.py | import cmd
import argparse
from Interface import *
class Lexeme(cmd.Cmd):
intro = "Welcome to Lexeme. Input ? for help and commands"
prompt = "(lexeme) "
def do_list(self, arg):
'List word database.'
listwords()
def do_quit(self, arg):
quit()
def do_add(self, arg):
... | import cmd
import argparse
from Interface import *
class Lexeme(cmd.Cmd):
intro = "Welcome to Lexeme! Input '?' for help and commands."
prompt = "Enter command: "
def do_list(self, arg):
'List word database.'
listwords()
def do_quit(self, arg):
quit()
def do_add(self, ar... | Change prompt and intro message | Change prompt and intro message
| Python | mit | kdelwat/Lexeme | ---
+++
@@ -4,8 +4,8 @@
class Lexeme(cmd.Cmd):
- intro = "Welcome to Lexeme. Input ? for help and commands"
- prompt = "(lexeme) "
+ intro = "Welcome to Lexeme! Input '?' for help and commands."
+ prompt = "Enter command: "
def do_list(self, arg):
'List word database.' |
aa4f8943616adce4dba826924b8d21e1e8164299 | eduid_signup_amp/__init__.py | eduid_signup_amp/__init__.py | from eduid_am.exceptions import UserDoesNotExist
def attribute_fetcher(db, user_id):
attributes = {}
user = db.registered.find_one({'_id': user_id})
if user is None:
raise UserDoesNotExist("No user matching _id='%s'" % user_id)
else:
# white list of valid attributes for security reas... | from eduid_am.exceptions import UserDoesNotExist
def attribute_fetcher(db, user_id):
attributes = {}
user = db.registered.find_one({'_id': user_id})
if user is None:
raise UserDoesNotExist("No user matching _id='%s'" % user_id)
else:
email = user.get('email', None)
if email:
... | Change fields to the schema agreed | Change fields to the schema agreed
| Python | bsd-3-clause | SUNET/eduid-signup-amp | ---
+++
@@ -9,14 +9,17 @@
raise UserDoesNotExist("No user matching _id='%s'" % user_id)
else:
- # white list of valid attributes for security reasons
- for attr in ('email', 'date', 'verified'):
- value = user.get(attr, None)
- if value is not None:
- ... |
7784186509e41c72bcf7a4ebbd9b268b49449d35 | user_clipboard/urls.py | user_clipboard/urls.py | from django.conf.urls import patterns, url
from .views import ClipboardFileAPIView, ClipboardImageAPIView
urlpatterns = patterns(
'',
url(r'^images/(?P<pk>\d+)$', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(r'^images/', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(... | from django.conf.urls import url
from .views import ClipboardFileAPIView, ClipboardImageAPIView
urlpatterns = [
url(r'^images/(?P<pk>\d+)$', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(r'^images/', ClipboardImageAPIView.as_view(), name="clipboard_images"),
url(r'^(?P<pk>\d+)$', Clipboar... | Define urlpatterns as a pure list (don't call patterns) | Define urlpatterns as a pure list (don't call patterns) | Python | mit | MagicSolutions/django-user-clipboard,IndustriaTech/django-user-clipboard,MagicSolutions/django-user-clipboard,IndustriaTech/django-user-clipboard | ---
+++
@@ -1,11 +1,10 @@
-from django.conf.urls import patterns, url
+from django.conf.urls import url
from .views import ClipboardFileAPIView, ClipboardImageAPIView
-urlpatterns = patterns(
- '',
+urlpatterns = [
url(r'^images/(?P<pk>\d+)$', ClipboardImageAPIView.as_view(), name="clipboard_images"),
... |
808fdc4351254c8f5b32d5997803562091121044 | cinderella/cinderella/settings/production.py | cinderella/cinderella/settings/production.py | from .base import *
DEBUG = False
ALLOWED_HOSTS = ['188.226.249.33', 'cinderella.li']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['DB_NAME'],
'USER': os.environ['DB_USER'],
'PASSWORD': os.environ['DB_PASSWORD'],
'HOST':... | from .base import *
DEBUG = False
ALLOWED_HOSTS = ['cinderella.li']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['DB_NAME'],
'USER': os.environ['DB_USER'],
'PASSWORD': os.environ['DB_PASSWORD'],
'HOST': '127.0.0.1',
... | Remove IP from allowed hosts | Remove IP from allowed hosts
| Python | mit | jasisz/cinderella,jasisz/cinderella | ---
+++
@@ -2,7 +2,7 @@
DEBUG = False
-ALLOWED_HOSTS = ['188.226.249.33', 'cinderella.li']
+ALLOWED_HOSTS = ['cinderella.li']
DATABASES = {
'default': { |
a56707d815271088c2c19f0c2c415d611886e859 | db/__init__.py | db/__init__.py | import categories # nopep8
import plugins # nopep8
import submitted_plugins # nopep8
import tags # nopep8
| import categories # NOQA: F401
import plugins # NOQA: F401
import submitted_plugins # NOQA: F401
import tags # NOQA: F401
| Update nopep8 instructions to NOQA | Update nopep8 instructions to NOQA
`flake8` seems to have dropped support for `# nopep8` in the 3.x
versions (confirmed by testing with latest and `<3`). This causes our
style checking tests to fail.
Replace these with `# NOQA` and pin them to the specific error we care
about here (F401 unused import).
| Python | mit | jonafato/vim-awesome,vim-awesome/vim-awesome,jonafato/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,jonafato/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,jonafato/vim-awesome,divad12/vim-awesome,vim-awesome/vim-awesome,divad12/vim-awesome,vim-awesome/vim-awesome | ---
+++
@@ -1,4 +1,4 @@
-import categories # nopep8
-import plugins # nopep8
-import submitted_plugins # nopep8
-import tags # nopep8
+import categories # NOQA: F401
+import plugins # NOQA: F401
+import submitted_plugins # NOQA: F401
+import tags # NOQA: F401 |
e33a68f14a13c0340b2dfcbb13931d2185735951 | scripts/nanopolish_makerange.py | scripts/nanopolish_makerange.py | from __future__ import print_function
import sys
import argparse
from Bio import SeqIO
parser = argparse.ArgumentParser(description='Partition a genome into a set of overlapping segments')
parser.add_argument('--segment-length', type=int, default=50000)
parser.add_argument('--overlap-length', type=int, default=200)
a... | from __future__ import print_function
import sys
import argparse
from Bio.SeqIO.FastaIO import SimpleFastaParser
parser = argparse.ArgumentParser(description='Partition a genome into a set of overlapping segments')
parser.add_argument('--segment-length', type=int, default=50000)
parser.add_argument('--overlap-length'... | Use Biopython's string based FASTA parser | Use Biopython's string based FASTA parser
This was introduced in Biopython 1.61 back in February 2013,
so the dependencies shouldn't matter.
You could go further here and use a generator expression
over a list comprehension? | Python | mit | jts/nanopolish,jts/nanopolish,jts/nanopolish,jts/nanopolish,jts/nanopolish | ---
+++
@@ -2,7 +2,7 @@
import sys
import argparse
-from Bio import SeqIO
+from Bio.SeqIO.FastaIO import SimpleFastaParser
parser = argparse.ArgumentParser(description='Partition a genome into a set of overlapping segments')
parser.add_argument('--segment-length', type=int, default=50000)
@@ -12,7 +12,9 @@
... |
945209957a26d8fc7673795b5bfc5c233ed00e0e | uchicagohvz/game/serializers.py | uchicagohvz/game/serializers.py | from rest_framework import serializers
from uchicagohvz.game.models import *
class KillSerializer(serializers.ModelSerializer):
class Meta:
model = Kill
fields = ('id', 'killer', 'victim', 'location', 'date', 'points')
killer = serializers.SerializerMethodField('get_killer')
victim = serializers.SerializerMeth... | from rest_framework import serializers
from uchicagohvz.game.models import *
class KillSerializer(serializers.ModelSerializer):
class Meta:
model = Kill
fields = ('id', 'killer', 'victim', 'location', 'date', 'points')
killer = serializers.SerializerMethodField()
victim = serializers.SerializerMethodField()
l... | Remove default method_name in SerializerMethodField | Remove default method_name in SerializerMethodField | Python | mit | kz26/uchicago-hvz,kz26/uchicago-hvz,kz26/uchicago-hvz | ---
+++
@@ -6,9 +6,9 @@
model = Kill
fields = ('id', 'killer', 'victim', 'location', 'date', 'points')
- killer = serializers.SerializerMethodField('get_killer')
- victim = serializers.SerializerMethodField('get_victim')
- location = serializers.SerializerMethodField('get_location')
+ killer = serializers.Ser... |
9c945162dfb60481c9f5d39c5e42617b030263a9 | mailgun/models.py | mailgun/models.py | import api
import db
from utils import parse_timestamp
import hashlib
import json
def download_logs():
""" Download mailgun logs and store them in the database """
logs = []
skip = 0
# Fetch all unsaved logs and add them to a LIFO queue
while True:
print("fecthing logs starting at {}... | import api
import db
from utils import parse_timestamp
from django.db import transaction
from collections import OrderedDict
import hashlib
import json
@transaction.commit_manually
def download_logs():
""" Download mailgun logs and store them in the database """
# use ordered dict to protect against new logs... | Handle transactions manually when saving downloaded logs | Handle transactions manually when saving downloaded logs
| Python | mit | p2pu/mechanical-mooc,p2pu/mechanical-mooc,p2pu/mechanical-mooc,p2pu/mechanical-mooc | ---
+++
@@ -1,33 +1,45 @@
import api
import db
from utils import parse_timestamp
+from django.db import transaction
+
+from collections import OrderedDict
import hashlib
import json
+@transaction.commit_manually
def download_logs():
""" Download mailgun logs and store them in the database """
- logs... |
1c4fbca7ce0b1ad16159f62e1485a3485f1878bb | oidstub.py | oidstub.py | """Stand-in module for those without the speed-enhanced tuple-OID implementation"""
def OID( value ):
"""Null function to pretend to be oid.OID"""
return str(value)
| """Stand-in module for those without the speed-enhanced tuple-OID implementation"""
USE_STRING_OIDS = True
def OID( value ):
"""Null function to pretend to be oid.OID"""
return str(value)
| Declare use of string OIDs | Declare use of string OIDs
| Python | bsd-3-clause | mmattice/TwistedSNMP | ---
+++
@@ -1,4 +1,5 @@
"""Stand-in module for those without the speed-enhanced tuple-OID implementation"""
+USE_STRING_OIDS = True
def OID( value ):
"""Null function to pretend to be oid.OID""" |
431fdabc5c103c9581758543359a54f650d24bcf | nodes/cpu_node.py | nodes/cpu_node.py | from node import Node
from model.cpu import CPU
from extraction.http.cpu_cw_http import CpuCwHTTP
class CPUNode(Node):
label = "CPU"
def __init__(self, service, timespan):
super(CPUNode, self).__init__(service, timespan)
def load_entities(self):
return CpuCwHTTP(self.service, self.timespan).load_ent... | from node import Node
from model.cpu import CPU
from extraction.http.cpu_cw_http import CpuCwHTTP
class CPUNode(Node):
label = "CPU"
def __init__(self, service, timespan):
super(CPUNode, self).__init__(service, timespan)
def load_entities(self):
return CpuCwHTTP(self.service, self.timespan).load_ent... | Remove CloudWave specific context expansion | Remove CloudWave specific context expansion
| Python | apache-2.0 | sealuzh/ContextBasedAnalytics,sealuzh/ContextBasedAnalytics,sealuzh/ContextBasedAnalytics | ---
+++
@@ -24,7 +24,7 @@
items[cpu.label].append(cpu.__dict__)
- return { 'expand_nodes' : [{"data" : {"id": 'code_fragment:validate', "name": 'func validate() (Go)'}}], 'data' : items }
+ return { 'expand_nodes' : [], 'data' : items }
def infer_context(self): |
8db347eaae51ea5f0a591bcecd5ba38263379aae | seqio/__init__.py | seqio/__init__.py | # Copyright 2021 The SeqIO Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | # Copyright 2021 The SeqIO Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | Make loggers part of the top-level SeqIO API. | Make loggers part of the top-level SeqIO API.
PiperOrigin-RevId: 400711636
| Python | apache-2.0 | google/seqio | ---
+++
@@ -19,7 +19,10 @@
from seqio import evaluation
from seqio import experimental
from seqio.evaluation import Evaluator
+from seqio.evaluation import JSONLogger
+from seqio.evaluation import Logger
from seqio.evaluation import TensorAndNumpyEncoder
+from seqio.evaluation import TensorBoardLogger
from seqio... |
484eaaf6349a631f483af12acd358bce5ca567d5 | zeeko/messages/setup_package.py | zeeko/messages/setup_package.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import glob
import os
import copy
import zmq
from distutils.core import Extension
def get_extensions(**kwargs):
"""Get the Cython extensions"""
this_directory = os.path.dirname(__file__)
this_name = __name__.split(".")[:-1]
extension... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import glob
import os
import copy
from distutils.core import Extension
def get_extensions(**kwargs):
"""Get the Cython extensions"""
import zmq
this_directory = os.path.dirname(__file__)
this_name = __name__.split(".")[:-1]
... | Fix stray zmq import in egg_info | Fix stray zmq import in egg_info
| Python | bsd-3-clause | alexrudy/Zeeko,alexrudy/Zeeko | ---
+++
@@ -5,11 +5,12 @@
import os
import copy
-import zmq
from distutils.core import Extension
def get_extensions(**kwargs):
"""Get the Cython extensions"""
+ import zmq
+
this_directory = os.path.dirname(__file__)
this_name = __name__.split(".")[:-1]
|
5c447d46a8a62407549650ada98131968ace9921 | spyc/scheduler.py | spyc/scheduler.py | from spyc.graph import Vertex, find_cycle, topological_sort
class Scheduler(object):
def __init__(self):
self.specs = {}
def ensure(self, spec):
"""Require that ``spec`` is satisfied."""
if spec.key() in self.specs:
self.specs[spec.key()].data.merge(spec)
else:
... | from spyc.graph import Vertex, find_cycle, topological_sort
class CircularDependency(Exception):
pass
class Scheduler(object):
def __init__(self):
self.specs = {}
def ensure(self, spec):
"""Require that ``spec`` is satisfied."""
if spec.key() in self.specs:
self.spe... | Raise a more useful error for circular deps. | Raise a more useful error for circular deps.
| Python | lgpl-2.1 | zenhack/spyc | ---
+++
@@ -1,4 +1,8 @@
from spyc.graph import Vertex, find_cycle, topological_sort
+
+
+class CircularDependency(Exception):
+ pass
class Scheduler(object):
@@ -26,6 +30,6 @@
verticies = set(self.specs.values())
cycle = find_cycle(verticies)
if cycle is not None:
- asse... |
01e629b43be83cd5ba37f7a3ecbf60c73d8ed2e6 | calexicon/internal/tests/test_julian.py | calexicon/internal/tests/test_julian.py | import unittest
from datetime import date as vanilla_date
from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian, is_julian_leap_year
class TestJulian(unittest.TestCase):
def test_is_gregorian_leap_year(self):
self.assertTrue(is_julian_leap_year(2000))
self.assert... | import unittest
from datetime import date as vanilla_date
from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian
from calexicon.internal.julian import is_julian_leap_year
class TestJulian(unittest.TestCase):
def test_is_gregorian_leap_year(self):
self.assertTrue(is_julian... | Split long import line up into two. | Split long import line up into two.
| Python | apache-2.0 | jwg4/calexicon,jwg4/qual | ---
+++
@@ -2,7 +2,8 @@
from datetime import date as vanilla_date
-from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian, is_julian_leap_year
+from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian
+from calexicon.internal.julian import is_julian_l... |
c0a74c86e772185d35f0e6049e0ce04fcdb30793 | chatterbot/adapters/io/multi_adapter.py | chatterbot/adapters/io/multi_adapter.py | from .io import IOAdapter
class MultiIOAdapter(IOAdapter):
def __init__(self, **kwargs):
super(MultiIOAdapter, self).__init__(**kwargs)
self.adapters = []
def process_input(self, *args, **kwargs):
"""
Returns data retrieved from the input source.
"""
if self.... | from .io import IOAdapter
class MultiIOAdapter(IOAdapter):
def __init__(self, **kwargs):
super(MultiIOAdapter, self).__init__(**kwargs)
self.adapters = []
def process_input(self, *args, **kwargs):
"""
Returns data retrieved from the input source.
"""
if self.... | Fix first io adapter being called twice. | Fix first io adapter being called twice.
| Python | bsd-3-clause | Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,Reinaesaya/OUIRL-ChatBot,Gustavo6046/ChatterBot,davizucon/ChatterBot,gunthercox/ChatterBot,vkosuri/ChatterBot | ---
+++
@@ -20,8 +20,8 @@
Takes an input value.
Returns an output value.
"""
- for adapter in self.adapters:
- adapter.process_response(statement)
+ for i in range(1, len(self.adapters)):
+ self.adapters[i].process_response(statement)
return se... |
5ae17b58d4823cb5e74ec1b7802c0debbc119dc9 | setuptools/command/bdist_wininst.py | setuptools/command/bdist_wininst.py | from distutils.command.bdist_wininst import bdist_wininst as _bdist_wininst
class bdist_wininst(_bdist_wininst):
_good_upload = _bad_upload = None
def create_exe(self, arcname, fullname, bitmap=None):
_bdist_wininst.create_exe(self, arcname, fullname, bitmap)
installer_name = self.get_installe... | from distutils.command.bdist_wininst import bdist_wininst as _bdist_wininst
class bdist_wininst(_bdist_wininst):
def reinitialize_command(self, command, reinit_subcommands=0):
cmd = self.distribution.reinitialize_command(
command, reinit_subcommands)
if command in ('install', 'install_l... | Remove patching of upload_names (dist_files) - Python 2.6 already does the right thing. | Remove patching of upload_names (dist_files) - Python 2.6 already does the right thing.
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -1,27 +1,6 @@
from distutils.command.bdist_wininst import bdist_wininst as _bdist_wininst
class bdist_wininst(_bdist_wininst):
- _good_upload = _bad_upload = None
-
- def create_exe(self, arcname, fullname, bitmap=None):
- _bdist_wininst.create_exe(self, arcname, fullname, bitmap)
- ... |
ec4b2fc266eb033dab9319c4d2f8ece6fd23170a | src/start_scraping.py | src/start_scraping.py | from main import initiate_shame
# Testing this
initiate_shame(1141922, 2016)
| from main import initiate_shame
initiate_shame(1141922, 2017)
initiate_shame(144768, 2017)
| Update script file for the season | Update script file for the season
| Python | mit | troym9731/fantasy_football | ---
+++
@@ -1,4 +1,4 @@
from main import initiate_shame
-# Testing this
-initiate_shame(1141922, 2016)
+initiate_shame(1141922, 2017)
+initiate_shame(144768, 2017) |
ffd4c59f4916087eac0977355a638508757c80fd | taskmonitor/models.py | taskmonitor/models.py | from celery import states
from django.db import models
STATES_CHOICES = zip(states.ALL_STATES, states.ALL_STATES)
class TaskStatus(models.Model):
"""
Task status.
With this the status of celery tasks can be monitored, more reliably than
depending on the broker or celery itself.
"""
status =... | from celery import states
from django.db import models
ALL_STATES = sorted(states.ALL_STATES)
STATES_CHOICES = zip(ALL_STATES, ALL_STATES)
class TaskStatus(models.Model):
"""
Task status.
With this the status of celery tasks can be monitored, more reliably than
depending on the broker or celery itse... | Fix neverending creation of migrations on heroku | Fix neverending creation of migrations on heroku
| Python | agpl-3.0 | HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily | ---
+++
@@ -1,8 +1,8 @@
from celery import states
from django.db import models
-
-STATES_CHOICES = zip(states.ALL_STATES, states.ALL_STATES)
+ALL_STATES = sorted(states.ALL_STATES)
+STATES_CHOICES = zip(ALL_STATES, ALL_STATES)
class TaskStatus(models.Model): |
227d4c152367292e8b0b8801d9ce6179af92432a | python/014_longest_common_prefix.py | python/014_longest_common_prefix.py | """
Write a function to find the longest common prefix string amongst an array of strings.
"""
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs)==0:
return ""
lcp=list(strs[0])
for i... | """
Write a function to find the longest common prefix string amongst an array of strings.
"""
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if strs is None or strs == "":
return ""
lcp = list(strs[0... | Add test case to 014 | Add test case to 014
| Python | mit | ufjfeng/leetcode-jf-soln,ufjfeng/leetcode-jf-soln | ---
+++
@@ -7,15 +7,18 @@
:type strs: List[str]
:rtype: str
"""
- if len(strs)==0:
+ if strs is None or strs == "":
return ""
- lcp=list(strs[0])
- for i,string in enumerate(strs):
- if list(string[0:len(lcp)])==lcp:
+ lcp = list(st... |
d7c293fb430c31c237e3aca7ba469f0237b18d8d | scikits/talkbox/linpred/__init__.py | scikits/talkbox/linpred/__init__.py | import levinson_lpc
from levinson_lpc import *
__all__ = levinson_lpc.__all__
| import levinson_lpc
from levinson_lpc import *
__all__ = levinson_lpc.__all__
from common import lpcres
__all__ += ['lpcres']
| Add lpcres in linpred namespace. | Add lpcres in linpred namespace.
| Python | mit | cournape/talkbox,cournape/talkbox | ---
+++
@@ -1,3 +1,6 @@
import levinson_lpc
from levinson_lpc import *
__all__ = levinson_lpc.__all__
+
+from common import lpcres
+__all__ += ['lpcres'] |
674fa7692c71524541d8797a65968e5e605454e7 | testrail/suite.py | testrail/suite.py | from datetime import datetime
import api
from project import Project
class Suite(object):
def __init__(self, content):
self._content = content
self.api = api.API()
@property
def id(self):
return self._content.get('id')
@property
def completed_on(self):
try:
... | from datetime import datetime
import api
from helper import TestRailError
from project import Project
class Suite(object):
def __init__(self, content):
self._content = content
self.api = api.API()
@property
def id(self):
return self._content.get('id')
@property
def compl... | Add setters for project, name, and description. | Add setters for project, name, and description.
| Python | mit | travispavek/testrail-python,travispavek/testrail | ---
+++
@@ -1,6 +1,7 @@
from datetime import datetime
import api
+from helper import TestRailError
from project import Project
@@ -25,6 +26,12 @@
def description(self):
return self._content.get('description')
+ @description.setter
+ def description(self, value):
+ if type(value) ... |
e704d8cb63e76bb1f5b1da6fec7ae4f65d7710f1 | tests/__init__.py | tests/__init__.py | import sys
try:
# noinspection PyPackageRequirements
import unittest2 as unittest
sys.modules['unittest'] = unittest
except ImportError:
import unittest
from goless.backends import current as be
class BaseTests(unittest.TestCase):
"""
Base class for unit tests.
Yields in setup and teardow... | import sys
try:
# noinspection PyPackageRequirements
import unittest2 as unittest
sys.modules['unittest'] = unittest
except ImportError:
import unittest
from goless.backends import current as be
class BaseTests(unittest.TestCase):
"""
Base class for unit tests.
Yields in setup and teardow... | Add comment in BaseTests tearDown | Add comment in BaseTests tearDown
| Python | apache-2.0 | rgalanakis/goless,rgalanakis/goless | ---
+++
@@ -22,4 +22,4 @@
def tearDown(self):
be.yield_()
- self.assertTrue(be.would_deadlock())
+ self.assertTrue(be.would_deadlock(), 'Task(s) still running after test finished') |
4d38b5e391e222c6da371bb100f0bd84c33e3435 | tests/test_cli.py | tests/test_cli.py | import unittest
from stun import cli
class TestCLI(unittest.TestCase):
"""Test the CLI API."""
def test_cli_parser(self):
cli.make_argument_parser()
# TODO: Verify default arguments
# TODO: Verify user arguments
if __name__ == '__main__':
unittest.main()
| import unittest
from stun import cli
class TestCLI(unittest.TestCase):
"""Test the CLI API."""
def test_cli_parser_default(self):
parser = cli.make_argument_parser()
options = parser.parse_args([])
self.assertEqual(options.source_ip, cli.DEFAULTS['source_ip'])
self.assertEqu... | Verify default arguments in parser. | Verify default arguments in parser.
| Python | mit | b1naryth1ef/pystun,jtriley/pystun | ---
+++
@@ -6,9 +6,14 @@
class TestCLI(unittest.TestCase):
"""Test the CLI API."""
- def test_cli_parser(self):
- cli.make_argument_parser()
- # TODO: Verify default arguments
+ def test_cli_parser_default(self):
+ parser = cli.make_argument_parser()
+ options = parser.parse_... |
c4e0a132461dba798739b752a04fe3ff66af17ab | tests/high_level_curl_test.py | tests/high_level_curl_test.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vi:ts=4:et
# uses the high level interface
import curl
import unittest
from . import appmanager
setup_module, teardown_module = appmanager.setup(('app', 8380))
class RelativeUrlTest(unittest.TestCase):
def setUp(self):
self.curl = curl.Curl('http://localh... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vi:ts=4:et
# uses the high level interface
import curl
import unittest
from . import appmanager
setup_module, teardown_module = appmanager.setup(('app', 8380))
class RelativeUrlTest(unittest.TestCase):
def setUp(self):
self.curl = curl.Curl('http://localh... | Fix test suite on python 3 - high level curl object returns result as bytes | Fix test suite on python 3 - high level curl object returns result as bytes
| Python | lgpl-2.1 | pycurl/pycurl,pycurl/pycurl,pycurl/pycurl | ---
+++
@@ -13,13 +13,13 @@
class RelativeUrlTest(unittest.TestCase):
def setUp(self):
self.curl = curl.Curl('http://localhost:8380/')
-
+
def tearDown(self):
self.curl.close()
-
+
def test_reuse(self):
result = self.curl.get('/success')
- self.assertEqual('su... |
17d91eff7de5517aa89330a08f3c84fa46d02538 | tests/test_exc.py | tests/test_exc.py | # -*- coding: utf-8 -*-
import pytest
from cihai import exc
def test_base_exception():
with pytest.raises(
exc.CihaiException,
message="Make sure no one removes or renames base CihaiException",
):
raise exc.CihaiException()
with pytest.raises(Exception, message="Extends python b... | # -*- coding: utf-8 -*-
import pytest
from cihai import exc
def test_base_exception():
with pytest.raises(exc.CihaiException):
raise exc.CihaiException() # Make sure its base of CihaiException
with pytest.raises(Exception):
raise exc.CihaiException() # Extends python base exception
| Update exception test for pytest 5+ | Update exception test for pytest 5+
pytest 3 had message for raises, this is removed in current versions.
| Python | mit | cihai/cihai,cihai/cihai | ---
+++
@@ -1,16 +1,12 @@
# -*- coding: utf-8 -*-
-
import pytest
from cihai import exc
def test_base_exception():
- with pytest.raises(
- exc.CihaiException,
- message="Make sure no one removes or renames base CihaiException",
- ):
- raise exc.CihaiException()
+ with pytest.ra... |
1d0e75959f4511cbca10cb223b01c3a29d3660ec | tmhmm/__init__.py | tmhmm/__init__.py | from collections import Counter, defaultdict
import numpy as np
from tmhmm.model import parse
from tmhmm.hmm import viterbi, forward, backward
__all__ = ['predict']
GROUP_NAMES = ('i', 'm', 'o')
def predict(sequence, header, model_or_filelike, compute_posterior=True):
if isinstance(model_or_filelike, tuple... | from collections import defaultdict
import numpy as np
from tmhmm.model import parse
from tmhmm.hmm import viterbi, forward, backward
__all__ = ['predict']
GROUP_NAMES = ('i', 'm', 'o')
def predict(sequence, header, model_or_filelike, compute_posterior=True):
if isinstance(model_or_filelike, tuple):
... | Remove unused group counts variable | Remove unused group counts variable
| Python | mit | dansondergaard/tmhmm.py | ---
+++
@@ -1,4 +1,4 @@
-from collections import Counter, defaultdict
+from collections import defaultdict
import numpy as np
@@ -29,9 +29,6 @@
observations = len(sequence)
states = len(name_map)
- # just counts how many states there are per label
- group_counts = Counter(label_... |
71e9b63f2c39e2b93bc570edc4214f4910b876f3 | ipkg/utils.py | ipkg/utils.py | import os
import json
import logging
LOGGER = logging.getLogger(__name__)
class DictFile(dict):
"""A ``dict``, storable as a JSON file.
"""
def __init__(self, file_path):
super(DictFile, self).__init__()
self.__file_path = file_path
self.reload()
def reload(self):
if... | import os
import json
import logging
from .vfiles import vopen
LOGGER = logging.getLogger(__name__)
class DictFile(dict):
"""A ``dict``, storable as a JSON file.
"""
def __init__(self, file_path):
super(DictFile, self).__init__()
self.__file_path = file_path
self.reload()
d... | Use vopen() to make DictFile works when reading remote repository meta data | Use vopen() to make DictFile works when reading remote repository meta data
| Python | mit | pmuller/ipkg | ---
+++
@@ -1,6 +1,8 @@
import os
import json
import logging
+
+from .vfiles import vopen
LOGGER = logging.getLogger(__name__)
@@ -17,8 +19,7 @@
def reload(self):
if os.path.isfile(self.__file_path):
LOGGER.debug('Loading %s', self.__file_path)
- with open(self.__file_pat... |
ff8f1067ac95a8f3fbb4c02e510da033623edeee | gargoyle/helpers.py | gargoyle/helpers.py | """
gargoyle.helpers
~~~~~~~~~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from django.http import HttpRequest
class MockRequest(HttpRequest):
"""
A mock request object which stores a user
instance and the ip address.
"""
def __init__(self, ... | """
gargoyle.helpers
~~~~~~~~~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from django.http import HttpRequest
class MockRequest(HttpRequest):
"""
A mock request object which stores a user
instance and the ip address.
"""
def __init__(self, ... | Set POST/GET/COOKIES on MockRequest so repr works | Set POST/GET/COOKIES on MockRequest so repr works
| Python | apache-2.0 | disqus/gutter-django,nkovshov/gargoyle,nkovshov/gargoyle,nkovshov/gargoyle,frewsxcv/gargoyle,brilliant-org/gargoyle,frewsxcv/gargoyle,YPlan/gargoyle,roverdotcom/gargoyle,monokrome/gargoyle,monokrome/gargoyle,disqus/gutter,vikingco/gargoyle,disqus/gutter-django,blueprinthealth/gargoyle,YPlan/gargoyle,graingert/gutter-dj... | ---
+++
@@ -17,6 +17,9 @@
from django.contrib.auth.models import AnonymousUser
self.user = user or AnonymousUser()
+ self.GET = {}
+ self.POST = {}
+ self.COOKIES = {}
self.META = {
'REMOTE_ADDR': ip_address,
} |
347e3f9092bf1f48e116cafceef8db255e293b1f | test/test_packages.py | test/test_packages.py | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("atsar"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cron"),
("curl"),
("diod"),
("docker-engine"),
("git"),
("gnupg"),
("handbrake"),
("handbrake-cli"),
("haveged"),
("htop"),
("i... | import pytest
@pytest.mark.parametrize("name", [
("apt-file"),
("apt-transport-https"),
("atsar"),
("blktrace"),
("ca-certificates"),
("chromium-browser"),
("cron"),
("curl"),
("diod"),
("docker-engine"),
("fonts-font-awesome"),
("git"),
("gnupg"),
("handbrake"),
("handbrake-cli"),
("ha... | Add new packages to tests | Add new packages to tests
| Python | mit | wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build | ---
+++
@@ -11,6 +11,7 @@
("curl"),
("diod"),
("docker-engine"),
+ ("fonts-font-awesome"),
("git"),
("gnupg"),
("handbrake"),
@@ -30,6 +31,7 @@
("openssl"),
("python"),
("python-pip"),
+ ("suckless-tools"),
("sysstat"),
("tree"),
("vagrant"),
@@ -42,6 +44,8 @@
("wget"),
("w... |
7c1a6fdc82ccdf8469d95e1e77897fab6e25d551 | hammock/__init__.py | hammock/__init__.py | import types
from version import __version__
from .model import Model
from .collection import Collection
class Hammock(object):
def __init__(self, collections=(), authenticators=(), storage=None):
if type(collections) == types.ModuleType:
collection_classes = []
for k,v in collections.__dict__.items():
... | import types
from version import __version__
from .model import Model
from .collection import Collection
class Hammock(object):
def __init__(self, collections=(), authenticators=(), storage=None):
if type(collections) == types.ModuleType:
collection_classes = []
for k,v in collections.__dict__.items():
... | Make sure we don't include Collection when pulling collections from a module | Make sure we don't include Collection when pulling collections from a module
| Python | mit | cooper-software/cellardoor | ---
+++
@@ -11,7 +11,7 @@
collection_classes = []
for k,v in collections.__dict__.items():
try:
- if issubclass(v, Collection):
+ if issubclass(v, Collection) and v != Collection:
collection_classes.append(v)
except TypeError:
pass |
714611e3fdddc4f2cacb5be4753d22322cafd312 | rest.py | rest.py | import json
import httplib2
from config import SERVER
http = httplib2.Http()
# print json.loads(http.request("http://172.28.101.30:8080/api/v1/family/1/?format=json", 'GET')[1])
def json_result(url, method='GET'):
response = http.request('http://%s%s?format=json' % (SERVER, url), method)[1]
# print 'URL', ur... | import json
import httplib2
from config import SERVER
http = httplib2.Http()
# print json.loads(http.request("http://172.28.101.30:8080/api/v1/family/1/?format=json", 'GET')[1])
def json_result(url, method='GET'):
response = http.request('http://%s%s?format=json' % (SERVER, url), method)[1]
# print 'URL', ur... | Set it to consume rewards | Set it to consume rewards
| Python | mit | iuliux/FamilyQuest-RPi | ---
+++
@@ -23,7 +23,7 @@
rewards = filter(lambda r: not r[u'consumed'],
[json_result(r) for r in member[u'rewards']])
for r in rewards:
- # json_result(r[u'resource_uri'] + 'consume/')
+ json_result(r[u'resource_uri'] + 'consume/')
pass
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.