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 |
|---|---|---|---|---|---|---|---|---|---|---|
78b82b0c5e074c279288b9d53fe9cb5cfe1381ae | fabfile.py | fabfile.py | # -*- coding: utf-8 -*-
from fabric.api import (
lcd,
local,
task)
@task
def clean():
local('rm -rf wheelhouse')
local('rm -rf dist')
local('rm -rf build')
with lcd('doc'):
local('make clean')
@task
def docs():
with lcd('doc'):
local('make html')
| # -*- coding: utf-8 -*-
from fabric.api import (
lcd,
local,
task)
@task
def clean():
local('rm -rf wheelhouse')
local('rm -rf dist')
local('rm -rf build')
local('rm -rf test/unit/__pycache__')
local('rm -rf test/integration/__pycache__')
with lcd('doc'):
local('make clea... | Kill __pycache__ directories in tests | Kill __pycache__ directories in tests
| Python | mit | smarter-travel-media/stac | ---
+++
@@ -11,6 +11,8 @@
local('rm -rf wheelhouse')
local('rm -rf dist')
local('rm -rf build')
+ local('rm -rf test/unit/__pycache__')
+ local('rm -rf test/integration/__pycache__')
with lcd('doc'):
local('make clean') |
b1890ccd9946054cde25bbd511e317ec0b844b9a | webserver/hermes/models.py | webserver/hermes/models.py | from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.conf import settings
from competition.models import Team
import json
class TeamStats(models.Model):
team = models.OneToOneField(Team)
data_field = models.TextField(null=True... | from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.conf import settings
from competition.models import Team
import json
class TeamStats(models.Model):
team = models.OneToOneField(Team)
data_field = models.TextField(null=True... | Add str method to TeamStats | Add str method to TeamStats
| Python | bsd-3-clause | siggame/webserver,siggame/webserver,siggame/webserver | ---
+++
@@ -12,6 +12,8 @@
team = models.OneToOneField(Team)
data_field = models.TextField(null=True, default="null")
+ def __str__(self):
+ return self.team.name
@property
def data(self): |
8cf555f2c8424cc8460228bac07940a19cf1a6a5 | zinnia_akismet/__init__.py | zinnia_akismet/__init__.py | """Spam checker backends for Zinnia based on Akismet"""
| """Spam checker backends for Zinnia based on Akismet"""
__version__ = '1.0.dev'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'
__url__ = 'https://github.com/Fantomas42/zinnia-spam-checker-akismet'
| Move package metadatas at the code level | Move package metadatas at the code level
| Python | bsd-3-clause | django-blog-zinnia/zinnia-spam-checker-akismet | ---
+++
@@ -1 +1,8 @@
"""Spam checker backends for Zinnia based on Akismet"""
+__version__ = '1.0.dev'
+__license__ = 'BSD License'
+
+__author__ = 'Fantomas42'
+__email__ = 'fantomas42@gmail.com'
+
+__url__ = 'https://github.com/Fantomas42/zinnia-spam-checker-akismet' |
43b00bdb18131c49a6e52d752aeb0549298d8cda | avena/tests/test-image.py | avena/tests/test-image.py | #!/usr/bin/env python
from numpy import all, array, dstack
from .. import image
def test_get_channels():
x = array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
y = dstack((x, x, x))
for z in image.get_channels(y):
assert all(z == x)
def test_map_to_channels():
def f(x):
return x + 1
x = ... | #!/usr/bin/env python
from numpy import all, allclose, array, dstack
from os import remove
from os.path import sep, split
from .. import image, utils
def test_get_channels():
x = array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
y = dstack((x, x, x))
for z in image.get_channels(y):
assert all(z == x)
d... | Add more unit tests for the image module. | Add more unit tests for the image module.
| Python | isc | eliteraspberries/avena | ---
+++
@@ -1,8 +1,10 @@
#!/usr/bin/env python
-from numpy import all, array, dstack
+from numpy import all, allclose, array, dstack
+from os import remove
+from os.path import sep, split
-from .. import image
+from .. import image, utils
def test_get_channels():
@@ -25,5 +27,17 @@
assert all(z == y + ... |
30674fb6e244373bb8b1ed74b7a38e5cc2ed19a7 | ibmcnx/doc/Documentation.py | ibmcnx/doc/Documentation.py | ######
# Create a file (html or markdown) with the output of
# - JVMHeap
# - LogFiles
# - Ports
# - Variables
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-08
... | ######
# Create a file (html or markdown) with the output of
# - JVMHeap
# - LogFiles
# - Ports
# - Variables
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-08
... | Create script to save documentation to a file | 4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -20,7 +20,9 @@
import ibmcnx.filehandle
import sys
-sys.stdout = open("/tmp/documentation.txt", "w")
+emp1 = ibmcnx.filehandle.Ibmcnxfile()
+
+sys.stdout = emp1
print '# JVM Settings of all AppServers:'
execfile( 'ibmcnx/doc/JVMSettings.py' ) |
9236ac7c0893cc1c4cf19755683d4ab38590de7d | spym-as.py | spym-as.py | #!/usr/bin/env python2.7
import argparse
from util.assemble import assemble
from util.hexdump import hexdump
def get_args():
parser = argparse.ArgumentParser(description='Spym MIPS Assembler. Generates "spym" format binaries.')
parser.add_argument('file', metavar='FILE', type=str,
he... | #!/usr/bin/env python2.7
import argparse
from util.assemble import assemble
def get_args():
parser = argparse.ArgumentParser(description='Spym MIPS Assembler. Generates "spym" format binaries.')
parser.add_argument('file', metavar='FILE', type=str,
help='MIPS source file')
parser... | Write to file instead of hexdump | Write to file instead of hexdump
| Python | mit | mossberg/spym,mossberg/spym | ---
+++
@@ -3,25 +3,22 @@
import argparse
from util.assemble import assemble
-from util.hexdump import hexdump
def get_args():
parser = argparse.ArgumentParser(description='Spym MIPS Assembler. Generates "spym" format binaries.')
parser.add_argument('file', metavar='FILE', type=str,
... |
de06a96af887b2bbfa6589b2881606c29000398e | cabot/cabotapp/jenkins.py | cabot/cabotapp/jenkins.py | from os import environ as env
from django.conf import settings
import requests
from datetime import datetime
from django.utils import timezone
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
auth = (settings.JENKINS_USER, settings.JENKINS_PASS)
def get_job_status(jobname):
ret =... | from os import environ as env
from django.conf import settings
import requests
from datetime import datetime
from django.utils import timezone
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
auth = (settings.JENKINS_USER, settings.JENKINS_PASS)
def get_job_status(jobname):
ret =... | Add check for "green" status for Hudson | Add check for "green" status for Hudson
Hudson and Jenkins have extremely similar APIs, one of the main differences is that Jenkins uses "blue" but Hudson uses "green" for a successful last build. Adding the option to check for "green" status allows the Jenkins checks to also work for checking Hudson jobs.
Jenkins... | Python | mit | arachnys/cabot,cmclaughlin/cabot,cmclaughlin/cabot,arachnys/cabot,maks-us/cabot,cmclaughlin/cabot,bonniejools/cabot,arachnys/cabot,bonniejools/cabot,bonniejools/cabot,bonniejools/cabot,maks-us/cabot,arachnys/cabot,maks-us/cabot,maks-us/cabot,cmclaughlin/cabot | ---
+++
@@ -23,7 +23,7 @@
status = resp.json()
ret['status_code'] = resp.status_code
ret['job_number'] = status['lastBuild'].get('number', None)
- if status['color'].startswith('blue'):
+ if status['color'].startswith('blue') or status['color'].startswith('green'): # Jenkins uses "blue" for succe... |
29564aca770969c0ff75413f059e5db7d33a69a7 | blog/utils.py | blog/utils.py | from django.shortcuts import get_object_or_404
from .models import Post
class PostGetMixin:
errors = {
'url_kwargs':
"Generic view {} must be called with "
"year, month, and slug.",
}
def get_object(self, queryset=None):
year = self.kwargs.get('year')
mon... | from django.shortcuts import get_object_or_404
from .models import Post
class PostGetMixin:
month_url_kwarg = 'month'
year_url_kwarg = 'year'
errors = {
'url_kwargs':
"Generic view {} must be called with "
"year, month, and slug.",
}
def get_object(self, queryset... | Add date URL kwarg options to PostGetMixin. | Ch18: Add date URL kwarg options to PostGetMixin.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | ---
+++
@@ -4,6 +4,8 @@
class PostGetMixin:
+ month_url_kwarg = 'month'
+ year_url_kwarg = 'year'
errors = {
'url_kwargs':
@@ -12,9 +14,12 @@
}
def get_object(self, queryset=None):
- year = self.kwargs.get('year')
- month = self.kwargs.get('month')
- slug = ... |
601b3d7db3bedd090291f1a52f22f6daee9987fd | imapbox.py | imapbox.py | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# import mailboxresource
from mailboxresource import MailboxClient
import argparse
def main():
argparser = argparse.ArgumentParser(description="Dump a IMAP folder into .eml files")
argparser.add_argument('-s', dest='host', help="IMAP host, like imap.gmail.com", req... | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# import mailboxresource
from mailboxresource import MailboxClient
import argparse
import ConfigParser, os
def load_configuration(args):
config = ConfigParser.ConfigParser(allow_no_value=True)
config.read(['/etc/imapbox/config.cfg', os.path.expanduser('~/.config/im... | Load multiple accounts using a config file | Load multiple accounts using a config file
| Python | mit | polo2ro/imapbox | ---
+++
@@ -4,20 +4,61 @@
# import mailboxresource
from mailboxresource import MailboxClient
import argparse
+import ConfigParser, os
+
+
+def load_configuration(args):
+ config = ConfigParser.ConfigParser(allow_no_value=True)
+ config.read(['/etc/imapbox/config.cfg', os.path.expanduser('~/.config/imapbox/co... |
80d5fc4ec2711dde9bd7cf775e9376190c46f9f7 | aeromancer/project_filter.py | aeromancer/project_filter.py | import argparse
from aeromancer.db.models import Project
class ProjectFilter(object):
"""Manage the arguments for filtering queries by project.
"""
@staticmethod
def add_arguments(parser):
"""Given an argparse.ArgumentParser add arguments.
"""
grp = parser.add_argument_group... | import argparse
import logging
from aeromancer.db.models import Project
LOG = logging.getLogger(__name__)
class ProjectFilter(object):
"""Manage the arguments for filtering queries by project.
"""
@staticmethod
def add_arguments(parser):
"""Given an argparse.ArgumentParser add arguments.
... | Support project filter with wildcard | Support project filter with wildcard
Translate glob-style wildcards to ILIKE comparisons for the database.
| Python | apache-2.0 | openstack/aeromancer,stackforge/aeromancer,dhellmann/aeromancer | ---
+++
@@ -1,7 +1,9 @@
import argparse
-
+import logging
from aeromancer.db.models import Project
+
+LOG = logging.getLogger(__name__)
class ProjectFilter(object):
@@ -18,7 +20,8 @@
action='append',
default=[],
dest='projects',
- help='projects to limit sear... |
f4f529aca5a37a19c3445ec7fc572ece08ba4293 | examples/hosts-production.py | examples/hosts-production.py | #!/usr/bin/env python3
# (c) 2014 Brainly.com, Pawel Rozlach <pawel.rozlach@brainly.com>
# This script is intended to only find "where it is" and invoke the inventory
# tool with correct inventory path basing on it's name.
import os.path as op
import sys
# Configuration:
backend_domain = 'example.com'
ipaddress_key... | #!/usr/bin/env python3
# Copyright (c) 2014 Pawel Rozlach, Brainly.com sp. z o.o.
#
# 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 re... | Add missing preamble for wrapper script | Add missing preamble for wrapper script
Change-Id: I26d002ca739544bc3d431a6cdb6b441bd33deb5a
| Python | apache-2.0 | brainly/inventory_tool,vespian/inventory_tool | ---
+++
@@ -1,9 +1,18 @@
#!/usr/bin/env python3
-# (c) 2014 Brainly.com, Pawel Rozlach <pawel.rozlach@brainly.com>
-
-# This script is intended to only find "where it is" and invoke the inventory
-# tool with correct inventory path basing on it's name.
+# Copyright (c) 2014 Pawel Rozlach, Brainly.com sp. z o.o.
+#... |
b856207fe42d480975618f5749ef9febc84f0363 | geolocation_helper/models.py | geolocation_helper/models.py | from django.contrib.gis.db import models as geomodels
from django.contrib.gis.geos.point import Point
from geopy import geocoders
class GeoLocatedModel(geomodels.Model):
geom = geomodels.PointField(null=True, blank=True)
objects = geomodels.GeoManager()
def get_location_as_string(self):
... | from django.contrib.gis.db import models as geomodels
from django.contrib.gis.geos.point import Point
from geopy import geocoders
class GeoLocatedModel(geomodels.Model):
geom = geomodels.PointField(null=True, blank=True)
objects = geomodels.GeoManager()
def get_location_as_string(self):
... | Add is_geolocated property for admin purpuse | Add is_geolocated property for admin purpuse
| Python | bsd-2-clause | atiberghien/django-geolocation-helper,atiberghien/django-geolocation-helper | ---
+++
@@ -14,6 +14,13 @@
"""
raise NotImplementedError
+ def is_geolocated(self):
+ """
+ Usefull for example in the admin in order to easily identify non geolocated object
+ """
+ return self.geom is not None
+ is_geolocated.boolean = True
+
class ... |
7bace98978e0058489b4872d7af300d91fe7f55d | createAdminOnce.py | createAdminOnce.py | #!/usr/bin/env python
import django
django.setup()
import sys,os
from django.contrib.auth.models import User
from django.core.management import call_command
admin_username = os.getenv('WEBLATE_ADMIN_NAME', 'admin')
try:
user = User.objects.get(username=admin_username)
except:
print 'Creating Admin...'
User.ob... | #!/usr/bin/env python
import django
django.setup()
import sys,os
from django.contrib.auth.models import User
from django.core.management import call_command
admin_username = os.getenv('WEBLATE_ADMIN_NAME', 'admin')
try:
user = User.objects.get(username=admin_username)
except:
print 'Creating Admin...'
User.ob... | Clarify admin user creation message | Clarify admin user creation message
| Python | mit | beevelop/docker-weblate,beevelop/docker-weblate | ---
+++
@@ -14,7 +14,7 @@
except:
print 'Creating Admin...'
User.objects.create_superuser(admin_username, os.getenv('WEBLATE_ADMIN_EMAIL', 'admin@example.com'), os.getenv('ADMIN_PASSWORD', 'Un1c0rn'))
- # call_command('createadmin', password=os.getenv('ADMIN_PASSWORD', 'Un1c0rn'))
+ print 'Admin user has bee... |
ed05dbf4dc231ea659b19310e6065d4781bd18bc | code/tests/test_smoothing.py | code/tests/test_smoothing.py | """
Tests functions in smoothing.py
Run with:
nosetests test_smoothing.py
"""
# Test method .smooth()
smooth1, smooth2 = subtest_runtest1.smooth(0), subtest_runtest1.smooth(1, 5)
smooth3 = subtest_runtest1.smooth(2, 0.25)
assert [smooth1.max(), smooth1.shape, smooth1.sum()] == [0, (3, 3, 3), 0]
assert [smooth2.ma... | """
==================Test file for smoothing.py======================
Test convolution module, hrf function and convolve function
Run with:
nosetests nosetests code/tests/test_smoothing.py
"""
from __future__ import absolute_import, division, print_function
from nose.tools import assert_equal
from numpy.testing... | Add seperate test function for smoothing.py | Add seperate test function for smoothing.py
| Python | bsd-3-clause | berkeley-stat159/project-delta | ---
+++
@@ -1,8 +1,25 @@
"""
-Tests functions in smoothing.py
+==================Test file for smoothing.py======================
+
+Test convolution module, hrf function and convolve function
+
Run with:
- nosetests test_smoothing.py
-"""
+ nosetests nosetests code/tests/test_smoothing.py
+
+
+"""
+
+from __f... |
e9171e8d77b457e2c96fca37c89d68c518bec5f7 | src/urllib3/util/util.py | src/urllib3/util/util.py | from types import TracebackType
from typing import NoReturn, Optional, Type, Union
def to_bytes(
x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> bytes:
if isinstance(x, bytes):
return x
elif not isinstance(x, str):
raise TypeError(f"not expecting typ... | from types import TracebackType
from typing import NoReturn, Optional, Type, Union
def to_bytes(
x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> bytes:
if isinstance(x, bytes):
return x
elif not isinstance(x, str):
raise TypeError(f"not expecting typ... | Bring coverage back to 100% | Bring coverage back to 100%
All calls to reraise() are in branches where value is truthy, so we
can't reach that code. | Python | mit | sigmavirus24/urllib3,sigmavirus24/urllib3,urllib3/urllib3,urllib3/urllib3 | ---
+++
@@ -32,8 +32,6 @@
tb: Optional[TracebackType] = None,
) -> NoReturn:
try:
- if value is None:
- value = tp()
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value |
80e67ffa99cc911219b316b172d7c74e1ede5c50 | camera_selection/scripts/camera_selection.py | camera_selection/scripts/camera_selection.py | #!/usr/bin/env python
import rospy
import Adafruit_BBIO.GPIO as GPIO
from vortex_msgs.msg import CameraFeedSelection
GPIO_PIN_MAP = rospy.get_param('/camera/pin_map')
class CameraSelection(object):
def __init__(self):
rospy.init_node('camera_selection')
self.cam_select_sub = rospy.Subscriber('came... | #!/usr/bin/env python
import rospy
import Adafruit_BBIO.GPIO as GPIO
from vortex_msgs.msg import CameraFeedSelection
PIN_MAP_FEED0 = rospy.get_param('/camera/pin_map_feed0')
PIN_MAP_FEED1 = rospy.get_param('/camera/pin_map_feed1')
PIN_MAP_FEED2 = rospy.get_param('/camera/pin_map_feed2')
PIN_MAP_LIST = [PIN_MAP_FEED0,P... | Add callback, set camera feed selection pins based on msg | Add callback, set camera feed selection pins based on msg
| Python | mit | vortexntnu/rov-control,vortexntnu/rov-control,vortexntnu/rov-control | ---
+++
@@ -3,7 +3,10 @@
import Adafruit_BBIO.GPIO as GPIO
from vortex_msgs.msg import CameraFeedSelection
-GPIO_PIN_MAP = rospy.get_param('/camera/pin_map')
+PIN_MAP_FEED0 = rospy.get_param('/camera/pin_map_feed0')
+PIN_MAP_FEED1 = rospy.get_param('/camera/pin_map_feed1')
+PIN_MAP_FEED2 = rospy.get_param('/camer... |
262bfb89311b51ce2de74271c4717282d53cedc6 | sandbox/sandbox/urls.py | sandbox/sandbox/urls.py | from django.conf import settings
from django.contrib import admin
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from oscar.app import shop
from stores.app import application as stores_app
from stores.da... | from django.conf import settings
from django.contrib import admin
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from oscar.app import shop
from stores.app import application as stores_app
from stores.da... | Switch order of store URLs | Switch order of store URLs
| Python | bsd-3-clause | django-oscar/django-oscar-stores,django-oscar/django-oscar-stores,django-oscar/django-oscar-stores | ---
+++
@@ -11,9 +11,9 @@
admin.autodiscover()
urlpatterns = patterns('',
- url(r'', include(shop.urls)),
url(r'^dashboard/stores/', include(dashboard_app.urls)),
url(r'^stores/', include(stores_app.urls)),
+ url(r'^', include(shop.urls)),
url(r'^admin/', include(admin.site.urls)),
)
|
f9572834538d40f5ae58e2f611fed7bf22af6311 | templatemailer/mailer.py | templatemailer/mailer.py | import logging
from django.core import mail
from .tasks import task_email_user
logger = logging.getLogger(__name__)
def email_user(user, template, context, attachments=None, delete_attachments_after_send=False, send_to=None,
language_code=None):
'''
Send email to user
:param user: User ... | import logging
from django.core import mail
from .tasks import task_email_user
logger = logging.getLogger(__name__)
def send_email(user, template, context, attachments=None, delete_attachments_after_send=False,
language_code=None):
'''
Send email to user
:param user: User instance or re... | Rename email_user method to send_email and fix parameters | Rename email_user method to send_email and fix parameters
| Python | mit | tuomasjaanu/django-templatemailer | ---
+++
@@ -7,17 +7,16 @@
logger = logging.getLogger(__name__)
-def email_user(user, template, context, attachments=None, delete_attachments_after_send=False, send_to=None,
+def send_email(user, template, context, attachments=None, delete_attachments_after_send=False,
language_code=None):
''... |
4b34053ce422e9be15e0ac386a591f8052a778b1 | vcs/models.py | vcs/models.py | from django.db import models
class Activity(models.Model):
group = models.CharField(max_length=4)
grouptype = models.TextField()
groupdetail = models.TextField()
details = models.TextField()
disabled = models.BooleanField()
time = models.DecimalField(decimal_places=2, max_digits=10)
unique_... | from django.db import models
class Activity(models.Model):
group = models.CharField(max_length=4)
grouptype = models.TextField()
groupdetail = models.TextField()
details = models.TextField()
disabled = models.BooleanField()
time = models.DecimalField(decimal_places=2, max_digits=10)
unique_... | Use the app string version of foreign keying. It prevents a circular import. | Use the app string version of foreign keying. It prevents a circular import.
| Python | bsd-3-clause | AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker | ---
+++
@@ -10,9 +10,8 @@
unique_together = (("group", "grouptype", "disabled", "time"),)
class ActivityEntry(models.Model):
- from timetracker.tracker.models import Tbluser
user = models.ManyToManyField(
- Tbluser,
+ 'tracker.Tbluser',
related_name="user_foreign"
)
ac... |
eef628750711b8bb4b08eb5f913b731d76541ab1 | shop_catalog/filters.py | shop_catalog/filters.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext_lazy as _
from shop_catalog.models import Product
class ProductParentListFilter(SimpleListFilter):
title = _('Parent')
parameter_name = 'parent'
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db.models import Q
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext_lazy as _
from shop_catalog.models import Product
class ProductParentListFilter(SimpleListFilter):
title = _('Parent')
... | Modify parent filter to return variants and self | Modify parent filter to return variants and self
| Python | bsd-3-clause | dinoperovic/django-shop-catalog,dinoperovic/django-shop-catalog | ---
+++
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
+from django.db.models import Q
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext_lazy as _
@@ -22,8 +23,7 @@
def queryset(self, request, queryset):
if self.val... |
ae201ae3c8b3f25f96bea55f9a69c3612a74c7cf | inboxen/tests/settings.py | inboxen/tests/settings.py | from __future__ import absolute_import
import os
os.environ['INBOX_TESTING'] = '1'
from settings import *
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.dummy.DummyCache"
}
}
db = os.environ.get('DB')
SECRET_KEY = "This is a test, you don't need secrets"
if db == "sqlite":
DATAB... | from __future__ import absolute_import
import os
os.environ['INBOX_TESTING'] = '1'
from settings import *
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache"
}
}
db = os.environ.get('DB')
SECRET_KEY = "This is a test, you don't need secrets"
if db == "sqlite":
DAT... | Use local memory as cache so ratelimit tests don't fail | Use local memory as cache so ratelimit tests don't fail
| Python | agpl-3.0 | Inboxen/Inboxen,Inboxen/infrastructure,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen | ---
+++
@@ -6,7 +6,7 @@
CACHES = {
"default": {
- "BACKEND": "django.core.cache.backends.dummy.DummyCache"
+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache"
}
}
|
371fb9b90d452f8893446e4968659d2e1ff58676 | mopidy/backends/spotify/container_manager.py | mopidy/backends/spotify/container_manager.py | import logging
from spotify.manager import SpotifyContainerManager as \
PyspotifyContainerManager
logger = logging.getLogger('mopidy.backends.spotify.container_manager')
class SpotifyContainerManager(PyspotifyContainerManager):
def __init__(self, session_manager):
PyspotifyContainerManager.__init__(s... | import logging
from spotify.manager import SpotifyContainerManager as \
PyspotifyContainerManager
logger = logging.getLogger('mopidy.backends.spotify.container_manager')
class SpotifyContainerManager(PyspotifyContainerManager):
def __init__(self, session_manager):
PyspotifyContainerManager.__init__(s... | Add missing container callbacks with debug log statements | Add missing container callbacks with debug log statements
| Python | apache-2.0 | swak/mopidy,dbrgn/mopidy,rawdlite/mopidy,jmarsik/mopidy,ZenithDK/mopidy,SuperStarPL/mopidy,quartz55/mopidy,bacontext/mopidy,dbrgn/mopidy,pacificIT/mopidy,diandiankan/mopidy,mokieyue/mopidy,swak/mopidy,jodal/mopidy,mokieyue/mopidy,tkem/mopidy,SuperStarPL/mopidy,kingosticks/mopidy,SuperStarPL/mopidy,ali/mopidy,mokieyue/m... | ---
+++
@@ -11,6 +11,30 @@
self.session_manager = session_manager
def container_loaded(self, container, userdata):
- """Callback used by pyspotify."""
- logger.debug(u'Container loaded')
+ """Callback used by pyspotify"""
+ logger.debug(u'Callback called: playlist container... |
758f59f9167bb49102679ad95d074bf22b4a62f4 | fixedwidthwriter/__init__.py | fixedwidthwriter/__init__.py | # coding: utf-8
from decimal import Decimal
class FixedWidthWriter():
def __init__(self, fd, fields, line_ending='linux'):
self.fd = fd
self.fields = fields
if line_ending == 'linux':
self.line_ending = '\n'
elif line_ending == 'windows':
self.line_ending =... | # coding: utf-8
from decimal import Decimal
class FixedWidthWriter():
def __init__(self, fd, fields, line_endings='linux'):
self.fd = fd
self.fields = fields
if line_endings == 'linux':
self.line_endings = '\n'
elif line_endings == 'windows':
self.line_endi... | Rename the 'line_ending' argument to 'line_endings'. Breaking change. | Rename the 'line_ending' argument to 'line_endings'. Breaking change.
| Python | mit | HardDiskD/py-fixedwidthwriter,ArthurPBressan/py-fixedwidthwriter | ---
+++
@@ -4,13 +4,13 @@
class FixedWidthWriter():
- def __init__(self, fd, fields, line_ending='linux'):
+ def __init__(self, fd, fields, line_endings='linux'):
self.fd = fd
self.fields = fields
- if line_ending == 'linux':
- self.line_ending = '\n'
- elif line_... |
4d95f634dd7f856fa4fbaf4a20bda58c01fa58b4 | tests/test_epubcheck.py | tests/test_epubcheck.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import epubcheck
from epubcheck import samples
from epubcheck.cli import main
def test_valid():
assert epubcheck.validate(samples.EPUB3_VALID)
def test_invalid():
assert not epubcheck.validate(samples.EPUB3_INVALID)
def test_main_valid(capsys... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import pytest
import tablib
import epubcheck
from epubcheck import samples
from epubcheck.cli import main
def test_valid():
assert epubcheck.validate(samples.EPUB3_VALID)
def test_invalid():
assert not epubcheck.validate(samples.EP... | Add tests for CSV and XLS reporting | Add tests for CSV and XLS reporting
CSV export currently fails due to epubcheck passing the delimiting
character as bytes although Tablib expects it to be of type str.
The issue will not be fixed as Python 2 has reached end of life [1].
[1] https://github.com/jazzband/tablib/issues/369
| Python | bsd-2-clause | titusz/epubcheck | ---
+++
@@ -1,5 +1,10 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
+import sys
+
+import pytest
+import tablib
+
import epubcheck
from epubcheck import samples
from epubcheck.cli import main
@@ -27,3 +32,21 @@
out, err = capsys.readouterr()
assert 'ERROR' in err and 'WARNING' in o... |
e16a292d027f07c1f425229bdb8b74e0d2c66e1f | aws_roleshell.py | aws_roleshell.py | import argparse
from awscli.customizations.commands import BasicCommand
import os
def awscli_initialize(event_hooks):
event_hooks.register('building-command-table.main', inject_commands)
def inject_commands(command_table, session, **kwargs):
command_table['roleshell'] = RoleShell(session)
def get_exec_args... | import argparse
import os
import shlex
import textwrap
from awscli.customizations.commands import BasicCommand
def awscli_initialize(event_hooks):
event_hooks.register('building-command-table.main', inject_commands)
def inject_commands(command_table, session, **kwargs):
command_table['roleshell'] = RoleShe... | Make it possible to eval() output instead of execing another shell. | Make it possible to eval() output instead of execing another shell.
| Python | mit | hashbrowncipher/aws-roleshell | ---
+++
@@ -1,14 +1,29 @@
import argparse
+import os
+import shlex
+import textwrap
from awscli.customizations.commands import BasicCommand
-import os
def awscli_initialize(event_hooks):
event_hooks.register('building-command-table.main', inject_commands)
+
def inject_commands(command_table, session,... |
7a8112249de859a5ef73fe07eb6029aeb1266f35 | tob-api/tob_api/urls.py | tob-api/tob_api/urls.py | """
Definition of urls for tob_api.
"""
from django.conf.urls import include, url
from django.views.generic import RedirectView
from . import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
url(r"^$", RedirectView.as_view(url="ap... | """
Definition of urls for tob_api.
"""
from django.conf.urls import include, url
from django.views.generic import RedirectView
from . import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
url(r"^$", RedirectView.as_view(url="ap... | Remove commented-out reference to v1 | Remove commented-out reference to v1
Signed-off-by: Nicholas Rempel <b7f0f2181f2dc324d159332b253a82a715a40706@gmail.com>
| Python | apache-2.0 | swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook | ---
+++
@@ -16,7 +16,6 @@
r"^api-auth/",
include("rest_framework.urls", namespace="rest_framework"),
),
- # url(r"^api/v1/", include("api.urls")),
url(r"^api/v2/", include("api_v2.urls")),
url(r"^health$", views.health),
] |
8b80b8b82400bd78d72158471b5030309075310c | rdd/api.py | rdd/api.py | # -*- coding: utf-8 -*-
"""Python implementation of the Readability Shortener API"""
import requests
try:
import simplejson as json
except ImportError:
import json
class Readability(object):
def __init__(self, url=None, verbose=None):
self.url = url or 'https://readability.com/api/shortener/v1'... | # -*- coding: utf-8 -*-
"""Python implementation of the Readability Shortener API"""
import requests
try:
import simplejson as json
except ImportError:
import json
class Readability(object):
def __init__(self, url=None, verbose=None):
self.url = url or 'https://readability.com/api/shortener/v1'... | Print HTTP content in verbose mode | Print HTTP content in verbose mode
| Python | mit | mlafeldt/rdd.py,mlafeldt/rdd.py,mlafeldt/rdd.py | ---
+++
@@ -13,20 +13,29 @@
def __init__(self, url=None, verbose=None):
self.url = url or 'https://readability.com/api/shortener/v1'
- self.config = {}
- if verbose is not None:
- self.config['verbose'] = verbose
+ self.verbose = verbose
def _request(self, method... |
eb2699b6050534045b95e5ea78cb0ea68de474ed | website/members/apps.py | website/members/apps.py | from django.apps import AppConfig
class MembersConfig(AppConfig):
name = 'members'
verbose_name = 'UTN Member Management'
| from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class MembersConfig(AppConfig):
name = 'members'
verbose_name = _('UTN Member Management')
| Make members verbose name translatable | :speech_balloon: Make members verbose name translatable
| Python | agpl-3.0 | Dekker1/moore,UTNkar/moore,Dekker1/moore,Dekker1/moore,UTNkar/moore,UTNkar/moore,UTNkar/moore,Dekker1/moore | ---
+++
@@ -1,6 +1,7 @@
from django.apps import AppConfig
+from django.utils.translation import ugettext_lazy as _
class MembersConfig(AppConfig):
name = 'members'
- verbose_name = 'UTN Member Management'
+ verbose_name = _('UTN Member Management') |
b545ebcd2b604bf293bfbbb1af5a9ab2ba6965c7 | wayback3/wayback3.py | wayback3/wayback3.py | """
Simple Python 3-safe package for accessing Wayback Machine archives
via its JSON API
"""
import datetime
import requests
FORMAT_STRING = "%Y%m%d%H%M%S" # Looks like "20130919044612"
AVAILABILITY_URL = "http://archive.org/wayback/available?url=%s"
def availability(url):
response = requests.get(AVAILABILITY_... | """
Simple Python 3-safe package for accessing Wayback Machine archives
via its JSON API
"""
import datetime
import requests
FORMAT_STRING = "%Y%m%d%H%M%S" # Looks like "20130919044612"
AVAILABILITY_URL = "http://archive.org/wayback/available?url=%s"
WAYBACK_URL_ROOT = "http://web.archive.org"
def availability(url... | Add a constant for WB root URL | Add a constant for WB root URL
| Python | agpl-3.0 | OpenSSR/openssr-parser,OpenSSR/openssr-parser | ---
+++
@@ -8,6 +8,7 @@
FORMAT_STRING = "%Y%m%d%H%M%S" # Looks like "20130919044612"
AVAILABILITY_URL = "http://archive.org/wayback/available?url=%s"
+WAYBACK_URL_ROOT = "http://web.archive.org"
def availability(url): |
cb7b51414a034d50e44fb30c6528b878aa9c64ee | web_ui/opensesame.py | web_ui/opensesame.py | # Enter the password of the email address you intend to send emails from
password = "" | # Enter the password of the email address you intend to send emails from
email_address = ""
email_password = ""
# Enter the login information for the EPNM API Account
API_username = ""
API_password = ""
| Add email and API template | Add email and API template | Python | apache-2.0 | cisco-gve/epnm_alarm_report,cisco-gve/epnm_alarm_report,cisco-gve/epnm_alarm_report,cisco-gve/epnm_alarm_report | ---
+++
@@ -1,2 +1,6 @@
# Enter the password of the email address you intend to send emails from
-password = ""
+email_address = ""
+email_password = ""
+# Enter the login information for the EPNM API Account
+API_username = ""
+API_password = "" |
ce8dc3daa6a4af3c5ed743fb2b5c4470bff7647b | test_knot.py | test_knot.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import knot
class TestContainer(unittest.TestCase):
def test_wrapper_looks_like_service(self):
c = knot.Container()
@c.service('service')
def service(container):
"""Docstring."""
pass
self.asse... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import knot
class TestContainer(unittest.TestCase):
def test_wrapper_looks_like_service(self):
c = knot.Container()
@c.service('service')
def service(container):
"""Docstring."""
pass
self.asse... | Add test for default values. | Add test for default values.
| Python | mit | jaapverloop/knot | ---
+++
@@ -31,6 +31,12 @@
self.assertEqual(c('service'), 'foobar')
+ def test_returns_default_with_unknown_key(self):
+ c = knot.Container()
+
+ self.assertEqual(c('service', 'foobar'), 'foobar')
+ self.assertEqual(c('service', lambda c: 'foobar'), 'foobar')
+
def test_share... |
3a7612925905f129c247f4c139aa0b896499346d | dsmtpd/__init__.py | dsmtpd/__init__.py | # -*- coding: utf-8 -*-
"""
dsmtpd
~~~~~~
:copyright: (c) 2013 by Stephane Wirtel <stephane@wirtel.be>
:license: BSD, see LICENSE for more details
"""
__name__ = "dsmtpd"
__version__ = "0.3git"
__author__ = ("Stephane Wirtel",)
__author_email__ = "stephane@wirtel.be"
| # -*- coding: utf-8 -*-
"""
dsmtpd
~~~~~~
:copyright: (c) 2013 by Stephane Wirtel <stephane@wirtel.be>
:license: BSD, see LICENSE for more details
"""
__name__ = "dsmtpd"
__version__ = "0.3"
__author__ = "Stephane Wirtel"
__author_email__ = "stephane@wirtel.be"
| Use a single string for the author | Use a single string for the author
| Python | bsd-2-clause | matrixise/dsmtpd | ---
+++
@@ -7,6 +7,6 @@
:license: BSD, see LICENSE for more details
"""
__name__ = "dsmtpd"
-__version__ = "0.3git"
-__author__ = ("Stephane Wirtel",)
+__version__ = "0.3"
+__author__ = "Stephane Wirtel"
__author_email__ = "stephane@wirtel.be" |
05fa3c4c6ab1d7619281399bb5f1db89e55c6fa8 | einops/__init__.py | einops/__init__.py | __author__ = 'Alex Rogozhnikov'
__version__ = '0.4.1'
class EinopsError(RuntimeError):
""" Runtime error thrown by einops """
pass
__all__ = ['rearrange', 'reduce', 'repeat', 'parse_shape', 'asnumpy', 'EinopsError']
from .einops import rearrange, reduce, repeat, parse_shape, asnumpy
| __author__ = 'Alex Rogozhnikov'
__version__ = '0.4.1'
class EinopsError(RuntimeError):
""" Runtime error thrown by einops """
pass
__all__ = ['rearrange', 'reduce', 'repeat', 'einsum',
'parse_shape', 'asnumpy', 'EinopsError']
from .einops import rearrange, reduce, repeat, einsum, parse_shape, as... | Include einsum in main library | Include einsum in main library
| Python | mit | arogozhnikov/einops | ---
+++
@@ -7,6 +7,7 @@
pass
-__all__ = ['rearrange', 'reduce', 'repeat', 'parse_shape', 'asnumpy', 'EinopsError']
+__all__ = ['rearrange', 'reduce', 'repeat', 'einsum',
+ 'parse_shape', 'asnumpy', 'EinopsError']
-from .einops import rearrange, reduce, repeat, parse_shape, asnumpy
+from .einops i... |
5f9dcf6e277f3a2136840c56fbf3c117319cc41b | pyjokes/__init__.py | pyjokes/__init__.py | from __future__ import absolute_import
from .pyjokes import get_local_joke
from .chuck import get_chuck_nerd_joke
from .jokes import jokes
__version__ = '0.1.1'
| Make jokes and functions available globally in the module | Make jokes and functions available globally in the module
| Python | bsd-3-clause | birdsarah/pyjokes,gmarkall/pyjokes,trojjer/pyjokes,pyjokes/pyjokes,borjaayerdi/pyjokes,Wren6991/pyjokes,martinohanlon/pyjokes,ElectronicsGeek/pyjokes,bennuttall/pyjokes | ---
+++
@@ -0,0 +1,7 @@
+from __future__ import absolute_import
+from .pyjokes import get_local_joke
+from .chuck import get_chuck_nerd_joke
+from .jokes import jokes
+
+
+__version__ = '0.1.1' | |
b18ab0218fe221dc71047b68a4016b9c107e3664 | python/src/setup.py | python/src/setup.py | #!/usr/bin/env python
"""Setup specs for packaging, distributing, and installing Pipeline lib."""
import setuptools
# To debug, set DISTUTILS_DEBUG env var to anything.
setuptools.setup(
name="GoogleAppEnginePipeline",
version="1.9.21.1",
packages=setuptools.find_packages(),
author="Google App Engine"... | #!/usr/bin/env python
"""Setup specs for packaging, distributing, and installing Pipeline lib."""
import setuptools
# To debug, set DISTUTILS_DEBUG env var to anything.
setuptools.setup(
name="GoogleAppEnginePipeline",
version="1.9.22.1",
packages=setuptools.find_packages(),
author="Google App Engine"... | Bump version to 1.9.22.1 and depend on the CloudStorageClient 1.9.22.1 | Bump version to 1.9.22.1 and depend on the CloudStorageClient 1.9.22.1
| Python | apache-2.0 | VirusTotal/appengine-pipelines,aozarov/appengine-pipelines,vendasta/appengine-pipelines,vendasta/appengine-pipelines,Loudr/appengine-pipelines,vendasta/appengine-pipelines,googlecloudplatform/appengine-pipelines,Loudr/appengine-pipelines,googlecloudplatform/appengine-pipelines,VirusTotal/appengine-pipelines,GoogleCloud... | ---
+++
@@ -6,7 +6,7 @@
# To debug, set DISTUTILS_DEBUG env var to anything.
setuptools.setup(
name="GoogleAppEnginePipeline",
- version="1.9.21.1",
+ version="1.9.22.1",
packages=setuptools.find_packages(),
author="Google App Engine",
author_email="app-engine-pipeline-api@googlegroups.com... |
948dc7e7e6d54e4f4e41288ab014cc2e0aa53e98 | scraper.py | scraper.py | """
Interface for web scraping
"""
import os
import sys
from selenium import webdriver
def scrape():
browser = webdriver.Chrome('/home/lowercase/Desktop/scheduler/chromedriver')
if __name__ == "__main__":
scrape()
| """
Interface for web scraping
"""
import os
import sys
import getpass
from selenium import webdriver
def scrape():
browser = webdriver.Chrome('/home/lowercase/Desktop/scheduler/chromedriver')
browser.get('https://my.unt.edu/psp/papd01/EMPLOYEE/EMPL/h/?tab=NTPA_GUEST')
euid = input('What is your EUI... | Load sign in page and collect password. | Load sign in page and collect password.
| Python | mit | undercase/scheduler | ---
+++
@@ -4,10 +4,22 @@
import os
import sys
+import getpass
+
from selenium import webdriver
def scrape():
browser = webdriver.Chrome('/home/lowercase/Desktop/scheduler/chromedriver')
+ browser.get('https://my.unt.edu/psp/papd01/EMPLOYEE/EMPL/h/?tab=NTPA_GUEST')
+
+ euid = input('What is you... |
fc87264fec2b13afb04fb89bfc7b2d4bbe2debdf | src/arc_utilities/ros_helpers.py | src/arc_utilities/ros_helpers.py | #! /usr/bin/env python
import rospy
from threading import Lock
class Listener:
def __init__(self, topic_name, topic_type, lock=None):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Parameters:
topic_name (str): name of topic to... | #! /usr/bin/env python
import rospy
from threading import Lock
class Listener:
def __init__(self, topic_name, topic_type):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Listener does not consume the message
(for consuming beh... | Remove optional lock input (I can't see when it would be useful) Document when Listener should be used | Remove optional lock input (I can't see when it would be useful)
Document when Listener should be used
| Python | bsd-2-clause | WPI-ARC/arc_utilities,UM-ARM-Lab/arc_utilities,UM-ARM-Lab/arc_utilities,WPI-ARC/arc_utilities,UM-ARM-Lab/arc_utilities,WPI-ARC/arc_utilities | ---
+++
@@ -5,9 +5,13 @@
class Listener:
- def __init__(self, topic_name, topic_type, lock=None):
+ def __init__(self, topic_name, topic_type):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
+
+ Listener does not consume the message ... |
cc3f363c1fefb758302b82e7d0ddff69d55a8261 | recognition/scrobbleTrack.py | recognition/scrobbleTrack.py | import os, sys, json, pylast, calendar
from datetime import datetime
resultJson = json.loads(sys.stdin.read())
# exit immediately if recognition failed
if resultJson["status"]["msg"] != "Success":
print "Recognition failed."
sys.exit(2)
# load Last.fm auth details into environment variables
apiKey = os.environ["LAS... | import os, sys, json, pylast, calendar
from datetime import datetime
resultJson = json.loads(sys.stdin.read())
# exit immediately if recognition failed
if resultJson["status"]["msg"] != "Success":
print "Recognition failed."
sys.exit(2)
# load Last.fm auth details into environment variables
apiKey = os.environ["LAS... | Check for existing Last.fm creds before scrobbling | Check for existing Last.fm creds before scrobbling
| Python | mit | jeffstephens/pi-resto,jeffstephens/pi-resto | ---
+++
@@ -14,6 +14,22 @@
password = os.environ["LASTFM_PASSWORD"]
passwordHash = pylast.md5(password)
+if not apiKey:
+ print "No Last.fm API Key was found."
+ sys.exit(3)
+
+if not apiSecret:
+ print "No Last.fm API Secret was found."
+ sys.exit(3)
+
+if not username:
+ print "No Last.fm username was found."
+... |
4c9e5df1bd52b0bad6fcfb2ac599999a00c8f413 | __init__.py | __init__.py | """distutils
The main package for the Python Module Distribution Utilities. Normally
used from a setup script as
from distutils.core import setup
setup (...)
"""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id$"
import sys
__version__ = "%d.%d.%d" % sys.version_info[:3]
del sys... | """distutils
The main package for the Python Module Distribution Utilities. Normally
used from a setup script as
from distutils.core import setup
setup (...)
"""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id$"
# Distutils version
#
# Please coordinate with Marc-Andre Lemburg ... | Revert to having static version numbers again. | Revert to having static version numbers again.
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -12,6 +12,12 @@
__revision__ = "$Id$"
-import sys
-__version__ = "%d.%d.%d" % sys.version_info[:3]
-del sys
+# Distutils version
+#
+# Please coordinate with Marc-Andre Lemburg <mal@egenix.com> when adding
+# new features to distutils that would warrant bumping the version number.
+#
+# In general, ma... |
ca584c5ddf942d867585de00ee786101d8ab7438 | playa/web/templatetags.py | playa/web/templatetags.py | import urllib
from playa import app
@app.template_filter('duration')
def duration(seconds):
return '%s:%s' % (int(seconds / 60), ('0' + str(int(seconds % 60)))[-2:])
@app.template_filter('song_title')
def song_title(metadata):
if 'artist' in metadata:
return '%s - %s' % (metdata['artist'], metadata['... | import urllib
from playa import app
@app.template_filter('duration')
def duration(seconds):
return '%s:%s' % (int(seconds / 60), ('0' + str(int(seconds % 60)))[-2:])
@app.template_filter('song_title')
def song_title(metadata):
if 'artist' in metadata:
return '%s - %s' % (metadata['artist'], metadata[... | Correct bug with metadata ref | Correct bug with metadata ref
| Python | apache-2.0 | disqus/playa,disqus/playa | ---
+++
@@ -9,7 +9,7 @@
@app.template_filter('song_title')
def song_title(metadata):
if 'artist' in metadata:
- return '%s - %s' % (metdata['artist'], metadata['title'])
+ return '%s - %s' % (metadata['artist'], metadata['title'])
return metadata['title']
app.template_filter('urlquote')(u... |
e6210531dac1d7efd5fd4d343dcac74a0b74515e | request_profiler/settings.py | request_profiler/settings.py | # -*- coding: utf-8 -*-
# models definitions for request_profiler
from django.conf import settings
# cache key used to store enabled rulesets.
RULESET_CACHE_KEY = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_KEY', "request_profiler__rulesets") # noqa
# how long to cache them for - defaults to 10s
RULESET_CACHE_T... | # -*- coding: utf-8 -*-
# models definitions for request_profiler
from django.conf import settings
# cache key used to store enabled rulesets.
RULESET_CACHE_KEY = getattr(settings, 'REQUEST_PROFILER_RULESET_CACHE_KEY', "request_profiler__rulesets") # noqa
# how long to cache them for - defaults to 10s
RULESET_CACHE_T... | Update GLOBAL_EXCLUDE_FUNC default to exclude admins | Update GLOBAL_EXCLUDE_FUNC default to exclude admins
| Python | mit | yunojuno/django-request-profiler,yunojuno/django-request-profiler,sigshen/django-request-profiler,sigshen/django-request-profiler | ---
+++
@@ -9,4 +9,7 @@
# This is a function that can be used to override all rules to exclude requests from profiling
# e.g. you can use this to ignore staff, or search engine bots, etc.
-GLOBAL_EXCLUDE_FUNC = getattr(settings, 'REQUEST_PROFILER_GLOBAL_EXCLUDE_FUNC', lambda r: True)
+GLOBAL_EXCLUDE_FUNC = getatt... |
8e202175767660bd90c4a894953d2553eec1a1d3 | pythonx/completers/common/__init__.py | pythonx/completers/common/__init__.py | # -*- coding: utf-8 -*-
import completor
import itertools
import re
from completor.compat import text_type
from .filename import Filename # noqa
from .buffer import Buffer # noqa
from .omni import Omni # noqa
try:
from UltiSnips import UltiSnips_Manager # noqa
from .ultisnips import Ultisnips # noqa
ex... | # -*- coding: utf-8 -*-
import completor
import itertools
import re
from completor.compat import text_type
from .filename import Filename # noqa
from .buffer import Buffer # noqa
from .omni import Omni # noqa
try:
from UltiSnips import UltiSnips_Manager # noqa
from .ultisnips import Ultisnips # noqa
ex... | Make it possible to extend common completions | Make it possible to extend common completions
| Python | mit | maralla/completor.vim,maralla/completor.vim | ---
+++
@@ -23,6 +23,8 @@
filetype = 'common'
sync = True
+ hooks = ['ultisnips', 'buffer']
+
def completions(self, completer, base):
com = completor.get(completer)
if not com:
@@ -44,4 +46,4 @@
return []
return list(itertools.chain(
- *[self.co... |
536bed6c3ff0a819075a04e14296518f1368cc74 | rest_framework_json_api/exceptions.py | rest_framework_json_api/exceptions.py | from django.utils import encoding
from django.utils.translation import ugettext_lazy as _
from rest_framework import status
from rest_framework.exceptions import APIException
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework_json_api.utils import format_value
def excepti... | from django.utils import encoding
from django.utils.translation import ugettext_lazy as _
from rest_framework import status
from rest_framework.exceptions import APIException
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework_json_api.utils import format_value
def excepti... | Modify exception_handler for a string error like AuthenticationError | Modify exception_handler for a string error like AuthenticationError
| Python | bsd-2-clause | leo-naeka/django-rest-framework-json-api,Instawork/django-rest-framework-json-api,pombredanne/django-rest-framework-json-api,grapo/django-rest-framework-json-api,hnakamur/django-rest-framework-json-api,leo-naeka/rest_framework_ember,django-json-api/django-rest-framework-json-api,abdulhaq-e/django-rest-framework-json-ap... | ---
+++
@@ -27,7 +27,8 @@
field = format_value(field)
pointer = '/data/attributes/{}'.format(field)
# see if they passed a dictionary to ValidationError manually
- if isinstance(error, dict):
+ # or a string in case of AuthenticationError
+ if is... |
9569a37369e37dbb2a567423fa20a76948439e21 | api/BucketListAPI.py | api/BucketListAPI.py | from flask import Flask, jsonify, request
from modals.modals import User
from api import create_app, db
from validate_email import validate_email
app = create_app('DevelopmentEnv')
@app.route('/')
def index():
response = jsonify({'Welcome Message': 'Hello'})
response.status_code = 201
return response
@... | from flask import jsonify, request
from api import create_app
from classes.user import User
app = create_app('DevelopmentEnv')
@app.route('/')
def index():
response = jsonify({'Welcome Message': 'Hello'})
response.status_code = 201
return response
@app.route('/auth/register', methods=['POST'])
def regi... | Move register code to User class | Move register code to User class
| Python | mit | patlub/BucketListAPI,patlub/BucketListAPI | ---
+++
@@ -1,7 +1,6 @@
-from flask import Flask, jsonify, request
-from modals.modals import User
-from api import create_app, db
-from validate_email import validate_email
+from flask import jsonify, request
+from api import create_app
+from classes.user import User
app = create_app('DevelopmentEnv')
@@ -20,36... |
3ad37c4acfb1d34978941cea2663cb31f1460503 | spotify.py | spotify.py | from willie import web
from willie import module
import time
import json
import urllib
@module.rule('.*(play.spotify.com\/track\/)([\w-]+).*')
def spotify(bot, trigger, found_match=None):
match = found_match or trigger
resp = web.get('https://api.spotify.com/v1/tracks/%s' % match.group(2))
result = json... | from willie import web
from willie import module
import time
import json
import re
regex = re.compile('(play.spotify.com\/track\/)([\w-]+)')
def setup(bot):
if not bot.memory.contains('url_callbacks'):
bot.memory['url_callbacks'] = tools.WillieMemory()
bot.memory['url_callbacks'][regex] = spotify
def... | Add callback to url_callbacks so url module doesn't query it | Add callback to url_callbacks so url module doesn't query it
| Python | mit | Metastruct/hal1320 | ---
+++
@@ -2,8 +2,17 @@
from willie import module
import time
import json
+import re
-import urllib
+regex = re.compile('(play.spotify.com\/track\/)([\w-]+)')
+
+def setup(bot):
+ if not bot.memory.contains('url_callbacks'):
+ bot.memory['url_callbacks'] = tools.WillieMemory()
+ bot.memory['url_cal... |
ff4204659b158827070fbb4bdf9bfc1f263e8b33 | fanstatic/registry.py | fanstatic/registry.py | import pkg_resources
ENTRY_POINT = 'fanstatic.libraries'
class LibraryRegistry(dict):
"""A dictionary-like registry of libraries.
This is a dictionary that mains libraries. A value is
a :py:class:`Library` instance, and a key is its
library ``name``.
Normally there is only a single global Librar... | import pkg_resources
ENTRY_POINT = 'fanstatic.libraries'
class LibraryRegistry(dict):
"""A dictionary-like registry of libraries.
This is a dictionary that mains libraries. A value is
a :py:class:`Library` instance, and a key is its
library ``name``.
Normally there is only a single global Librar... | Remove some code that wasn't in use anymore. | Remove some code that wasn't in use anymore.
| Python | bsd-3-clause | fanstatic/fanstatic,fanstatic/fanstatic | ---
+++
@@ -15,8 +15,6 @@
:param libraries: a sequence of libraries
"""
def __init__(self, libraries):
- if libraries is None:
- return
for library in libraries:
self[library.name] = library
|
45cfd59f5bc8e91a88e54fda83f868f7bb3c4884 | examples/wsgi_app.py | examples/wsgi_app.py | import guv
guv.monkey_patch()
import json
import bottle
import guv.wsgi
import logger
logger.configure()
app = bottle.Bottle()
@app.route('/')
def index():
data = json.dumps({'status': True})
return data
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(serve... | import guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', co... | Use bare WSGI application for testing and benchmarking | Use bare WSGI application for testing and benchmarking
| Python | mit | veegee/guv,veegee/guv | ---
+++
@@ -1,22 +1,23 @@
import guv
guv.monkey_patch()
-import json
-
-import bottle
-
import guv.wsgi
import logger
logger.configure()
-app = bottle.Bottle()
+def app(environ, start_response):
+ status = '200 OK'
+ output = [b'Hello World!']
+ content_length = str(len(b''.join(output)))
-@ap... |
3f747610f080879774720aa1efe38f40364ea151 | raco/myrial/type_tests.py | raco/myrial/type_tests.py | """Various tests of type safety."""
import unittest
from raco.fakedb import FakeDatabase
from raco.scheme import Scheme
from raco.myrial.myrial_test import MyrialTestCase
from collections import Counter
class TypeTests(MyrialTestCase):
schema = Scheme(
[("clong", "LONG_TYPE"),
("cint", "INT_TYPE... | """Various tests of type safety."""
import unittest
from raco.fakedb import FakeDatabase
from raco.scheme import Scheme
from raco.myrial.myrial_test import MyrialTestCase
from raco.expression import TypeSafetyViolation
from collections import Counter
class TypeTests(MyrialTestCase):
schema = Scheme(
[("c... | Test of invalid equality test | Test of invalid equality test
| Python | bsd-3-clause | uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco | ---
+++
@@ -4,6 +4,7 @@
from raco.fakedb import FakeDatabase
from raco.scheme import Scheme
from raco.myrial.myrial_test import MyrialTestCase
+from raco.expression import TypeSafetyViolation
from collections import Counter
@@ -25,3 +26,11 @@
"""
self.check_scheme(query, TypeTests.schema)
... |
2048045b9b77d8cab88c0cab8e90cf72cb88b2a4 | station.py | station.py | """Creates the station class"""
class Station:
"""
Each train station is an instance of the Station class.
Methods:
__init__: creates a new stations
total_station_pop: calculates total station population
"""
def __init__(self):
self.capacity = capacity
self.escalators = es... | """Creates the station class"""
class Station:
"""
Each train station is an instance of the Station class.
Methods:
__init__: creates a new stations
total_station_pop: calculates total station population
"""
def __init__(self):
self.capacity = eval(input("Enter the max capacity of... | Add input parameters and test function | Add input parameters and test function
Added input parameters at time of instantiation.
Ref #23 | Python | mit | ForestPride/rail-problem | ---
+++
@@ -10,10 +10,13 @@
"""
def __init__(self):
- self.capacity = capacity
- self.escalators = escalators
- self.train_wait = train_wait
- #self.arrivalrate = arrivalrate
- #self.departurerate = departurerate
- self.travelors_arriving = travelors_arriving
- ... |
0bcbd9656723726f1098899d61140a3f1a11c7ea | scripts/1d-load-images.py | scripts/1d-load-images.py | #!/usr/bin/python
import sys
sys.path.insert(0, "/usr/local/opencv-2.4.11/lib/python2.7/site-packages/")
import argparse
import commands
import cv2
import fnmatch
import os.path
sys.path.append('../lib')
import ProjectMgr
# for all the images in the project image_dir, load the image meta data
# this script produce... | #!/usr/bin/python
import sys
sys.path.insert(0, "/usr/local/opencv-2.4.11/lib/python2.7/site-packages/")
import argparse
import commands
import cv2
import fnmatch
import os.path
sys.path.append('../lib')
import ProjectMgr
# for all the images in the project image_dir, load the image meta data
# this script produce... | Add an option to force recomputing of image dimensions. | Add an option to force recomputing of image dimensions.
| Python | mit | UASLab/ImageAnalysis | ---
+++
@@ -18,8 +18,9 @@
parser = argparse.ArgumentParser(description='Load the project\'s images.')
parser.add_argument('--project', required=True, help='project directory')
+parser.add_argument('--recompute-sizes', action='store_true', help='recompute image sizes')
args = parser.parse_args()
proj = Proje... |
f93f11f0369a5c263be5b8f078e188e7af630fba | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google Inc. 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 required by applicable law or a... | # Copyright 2017 Google Inc. 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 required by applicable law or a... | Update dsub version to 0.4.1. | Update dsub version to 0.4.1.
PiperOrigin-RevId: 328637531
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.4.1.dev0'
+DSUB_VERSION = '0.4.1' |
fe397dccf389e31e6b39d5eaa77aedd266cef72d | Practice.py | Practice.py | print 2**3
print pow(2,3)
print abs(-10)
print round(1.536,2)
print 1/2
print 1.0//2.0
print 0xAF
print 010
| print 2**3
print pow(2,3)
print abs(-10)
print round(1.536,2)
print 1/2
print 1.0//2.0
print 0xAF
print 010
import cmath
print cmath.sqrt(-1)
import math
print math.floor(32.8)
| Test math and cmath module. | Test math and cmath module.
| Python | apache-2.0 | Vayne-Lover/Python | ---
+++
@@ -6,3 +6,7 @@
print 1.0//2.0
print 0xAF
print 010
+import cmath
+print cmath.sqrt(-1)
+import math
+print math.floor(32.8) |
e4964832cf330f57c4ef6dc7be942d2533c840a7 | breakpad.py | breakpad.py | # Copyright (c) 2009 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.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
impor... | # Copyright (c) 2009 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.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
impor... | Fix KeyboardInterrupt exception filtering. Add exception information and not just the stack trace. Make the url easier to change at runtime. | Fix KeyboardInterrupt exception filtering.
Add exception information and not just the stack trace.
Make the url easier to change at runtime.
Review URL: http://codereview.chromium.org/2109001
git-svn-id: bd64dd6fa6f3f0ed0c0666d1018379882b742947@47179 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
| Python | bsd-3-clause | svn2github/chromium-depot-tools,svn2github/chromium-depot-tools,svn2github/chromium-depot-tools | ---
+++
@@ -13,14 +13,19 @@
import socket
import sys
+# Configure these values.
+DEFAULT_URL = 'http://chromium-status.appspot.com/breakpad'
-def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'):
+def SendStack(last_tb, stack, url=None):
+ if not url:
+ url = DEFAULT_URL
print 'Sending... |
ad97fa93ad50bfb73c29798f9f1f24465c6a3683 | _lua_paths.py | _lua_paths.py | import os
import re
_findBackslash = re.compile("/")
# http://rosettacode.org/wiki/Find_common_directory_path#Python
def __commonprefix(*args, sep='/'):
return os.path.commonprefix(*args).rpartition(sep)[0]
def __getProjectPaths(view):
project_data=view.window().project_data()
if project_data is None:
re... | import os
import re
_findBackslash = re.compile("/")
# http://rosettacode.org/wiki/Find_common_directory_path#Python
def __commonprefix(*args, sep='/'):
return os.path.commonprefix(*args).rpartition(sep)[0]
def __getProjectPaths(view):
project_data=view.window().project_data()
if project_data is None:
re... | Fix crash if view returns no valid path | Fix crash if view returns no valid path
| Python | mit | coronalabs/CoronaSDK-SublimeText,coronalabs/CoronaSDK-SublimeText | ---
+++
@@ -31,8 +31,10 @@
def getLuaFilesAndPaths(view,followlinks):
luaPaths=[]
paths=__getProjectPaths(view)
- paths.append(__getViewPath(view))
-
+ viewPath=__getViewPath(view)
+ if viewPath is not None:
+ paths.append(viewPath)
+
for path in paths:
for root, dirs, files in os.walk(path... |
a46d2de6bb0a9605944b44971cc29126023e0623 | commands.py | commands.py | from runcommands.commands import show_config # noqa: F401
from arctasks.base import lint # noqa: F401
from arctasks.python import show_upgraded_packages # noqa: F401
from arctasks.release import * # noqa: F401,F403
| from runcommands.commands import show_config # noqa: F401
from arctasks.base import install, lint # noqa: F401
from arctasks.python import show_upgraded_packages # noqa: F401
from arctasks.release import * # noqa: F401,F403
| Add install command (import from ARCTasks) | Add install command (import from ARCTasks)
Because `run install -u` is so much easier to type than
`pip install -U -r requirements.txt`.
| Python | mit | wylee/django-arcutils,PSU-OIT-ARC/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils | ---
+++
@@ -1,5 +1,5 @@
from runcommands.commands import show_config # noqa: F401
-from arctasks.base import lint # noqa: F401
+from arctasks.base import install, lint # noqa: F401
from arctasks.python import show_upgraded_packages # noqa: F401
from arctasks.release import * # noqa: F401,F403 |
d18919060fde86baaa1bd6fed561872dfe4cc37f | oam_base/urls.py | oam_base/urls.py | from django.conf.urls import patterns, include, url
from django.core.urlresolvers import reverse_lazy
from MyInfo import views as my_info_views
from django_cas import views as cas_views
from oam_base import views as base_views
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.... | from django.conf.urls import patterns, include, url
from django.core.urlresolvers import reverse_lazy
from MyInfo import views as my_info_views
from django_cas import views as cas_views
from oam_base import views as base_views
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.... | Make the ratelimited error URL follow established conventions. | Make the ratelimited error URL follow established conventions.
| Python | mit | hhauer/myinfo,hhauer/myinfo,hhauer/myinfo,hhauer/myinfo | ---
+++
@@ -18,7 +18,7 @@
url(r'^accounts/login/$', cas_views.login, {'next_page': reverse_lazy('AccountPickup:next_step')}, name='CASLogin'),
url(r'^accounts/logout/$', cas_views.logout, name='CASLogout'),
- url(r'^error/denied$', base_views.rate_limited, name='rate_limited'),
+ url(r'^error/denied... |
a0151bb7934beac7f5db3c79c60d7335a594d29a | alg_minmax.py | alg_minmax.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def find_min_max_naive(a_ls):
"""Find mix & max in a list by naive method."""
_min = a_ls[0]
_max = a_ls[0]
for i in range(1, len(a_ls)):
_min = min(_min, a_ls[i])
_max = max(_ma... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def find_min_max_naive(a_ls):
"""Find mix & max in a list by naive method."""
_min = a_ls[0]
_max = a_ls[0]
for i in range(1, len(a_ls)):
_min = min(_min, a_ls[i])
_max = max(_ma... | Complete find_min_max_dc() with divide and conquer method | Complete find_min_max_dc() with divide and conquer method
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -12,6 +12,21 @@
return [_min, _max]
+def find_min_max_dc(a_ls):
+ """Find mix & max in a list by divide and conquer method."""
+ if len(a_ls) == 1:
+ return [a_ls[0], a_ls[0]]
+ elif 1 < len(a_ls) < 3:
+ if a_ls[0] < a_ls[1]:
+ return [a_ls[0], a_ls[1]]
+ e... |
85bba7e080100ed7154330c8b0d1476bc3718e28 | one_time_eval.py | one_time_eval.py | # usage: python one_time_eval.py as8sqdtc
# usage: python one_time_eval.py as8sqdtc 2skskd
from convenience import find_pcts, pr, str2cards
import sys
## argv to strings
hole_cards_str = sys.argv[1]
board_str = ''
if len(sys.argv) > 2:
board_str = sys.argv[2]
## strings to lists of Card objects
hole_cards = str2... | # usage: python one_time_eval.py hole_cards [board_cards]
# examples:
# python one_time_eval.py as8sqdtc
# python one_time_eval.py as8sqdtc 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd3h5s
from convenience import find_pcts_multi, pr,... | Add support for multi-way pots. | Add support for multi-way pots.
| Python | mit | zimolzak/poker-experiments,zimolzak/poker-experiments,zimolzak/poker-experiments | ---
+++
@@ -1,7 +1,11 @@
-# usage: python one_time_eval.py as8sqdtc
-# usage: python one_time_eval.py as8sqdtc 2skskd
+# usage: python one_time_eval.py hole_cards [board_cards]
+# examples:
+# python one_time_eval.py as8sqdtc
+# python one_time_eval.py as8sqdtc 2skskd
+# python one_time_eval.... |
c5e319363727f332b04ac863e494cb04c52c91b5 | drupal/Revert.py | drupal/Revert.py | from fabric.api import *
from fabric.contrib.files import sed
import random
import string
import time
# Custom Code Enigma modules
import Drupal
import common.MySQL
# Small function to revert db
@task
@roles('app_primary')
def _revert_db(repo, branch, build, buildtype, site):
print "===> Reverting the database..."
... | from fabric.api import *
from fabric.contrib.files import sed
import random
import string
import time
# Custom Code Enigma modules
import Drupal
import common.MySQL
# Small function to revert db
@task
@roles('app_primary')
def _revert_db(repo, branch, build, buildtype, site):
print "===> Reverting the database..."
... | Add back the stable_build variable which is needed in the _revert_settings() function. Woops. | Add back the stable_build variable which is needed in the _revert_settings() function. Woops.
| Python | mit | codeenigma/deployments,codeenigma/deployments,codeenigma/deployments,codeenigma/deployments | ---
+++
@@ -24,6 +24,7 @@
def _revert_settings(repo, branch, build, buildtype, site, alias):
print "===> Reverting the settings..."
with settings(warn_only=True):
+ stable_build = run("readlink /var/www/live.%s.%s" % (repo, branch))
if sudo('sed -i.bak "s:/var/www/.*\.settings\.php:%s/www/sites/%s/%s.s... |
d600fc56127f234a7a14b4a89be14b5c31b072e7 | examples/edge_test.py | examples/edge_test.py | """
This test is only for Microsoft Edge (Chromium)!
"""
from seleniumbase import BaseCase
class EdgeTests(BaseCase):
def test_edge(self):
if self.browser != "edge":
print("\n This test is only for Microsoft Edge (Chromium)!")
print(' (Run this test using "--edge" or "--browser=... | """
This test is only for Microsoft Edge (Chromium)!
(Tested on Edge Version 89.0.774.54)
"""
from seleniumbase import BaseCase
class EdgeTests(BaseCase):
def test_edge(self):
if self.browser != "edge":
print("\n This test is only for Microsoft Edge (Chromium)!")
print(' (Run th... | Update the Edge example test | Update the Edge example test
| Python | mit | mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase | ---
+++
@@ -1,5 +1,6 @@
"""
This test is only for Microsoft Edge (Chromium)!
+(Tested on Edge Version 89.0.774.54)
"""
from seleniumbase import BaseCase
@@ -12,10 +13,10 @@
print(' (Run this test using "--edge" or "--browser=edge")')
self.skip('Use "--edge" or "--browser=edge"')
... |
166fd73f5ac4501b9357d0263e6b68888836588a | tests/test_cookiecutter_invocation.py | tests/test_cookiecutter_invocation.py | # -*- coding: utf-8 -*-
"""
test_cookiecutter_invocation
----------------------------
Tests to make sure that cookiecutter can be called from the cli without
using the entry point set up for the package.
"""
import os
import pytest
import subprocess
import sys
from cookiecutter import utils
def test_should_raise_... | # -*- coding: utf-8 -*-
"""
test_cookiecutter_invocation
----------------------------
Tests to make sure that cookiecutter can be called from the cli without
using the entry point set up for the package.
"""
import os
import pytest
import subprocess
import sys
from cookiecutter import utils
def test_should_raise_... | Use sys.executable when invoking python interpreter from tests | Use sys.executable when invoking python interpreter from tests
When we only have python3 installed, the test for missing argument is
failing because there is no "python" executable. Use `sys.executable`
instead. Also set environment correctly, like done in 7024d3b36176.
| Python | bsd-3-clause | audreyr/cookiecutter,hackebrot/cookiecutter,pjbull/cookiecutter,michaeljoseph/cookiecutter,michaeljoseph/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,audreyr/cookiecutter,pjbull/cookiecutter,luzfcb/cookiecutter | ---
+++
@@ -16,9 +16,11 @@
from cookiecutter import utils
-def test_should_raise_error_without_template_arg(capfd):
+def test_should_raise_error_without_template_arg(monkeypatch, capfd):
+ monkeypatch.setenv('PYTHONPATH', '.')
+
with pytest.raises(subprocess.CalledProcessError):
- subprocess.check... |
5eef9eaf6fabe00281c480fd5886917596066a50 | buildcert.py | buildcert.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from subprocess import call
from ca import app, db, mail
from ca.models import Request
from flask import Flask, render_template
from flask_mail import Message
def mail_certificate(id, email):
msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from subprocess import call
from ca import app, db, mail
from ca.models import Request
from flask import Flask, render_template
from flask_mail import Message
def mail_certificate(id, email):
msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca... | Fix spelling mistake in path for certificates | Fix spelling mistake in path for certificates
| Python | mit | freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net | ---
+++
@@ -14,7 +14,7 @@
def mail_certificate(id, email):
msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email])
msg.body = render_template('mail.txt')
- with app.open_resource("/etc/openvpn/client/freifunk_{}.tgz".format(id)) as fp:
+ with app.open_res... |
f48344f8b961971eb0946bcb4066df021f3eef8a | tinysrt.py | tinysrt.py | #!/usr/bin/env python
import re
import datetime
from collections import namedtuple
SUBTITLE_REGEX = re.compile(r'''\
(\d+)
(\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+)
(.+)
''')
Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'content'])
def parse_time(time):
hours, minutes, seconds, milliseconds = map(... | #!/usr/bin/env python
import re
import datetime
from collections import namedtuple
SUBTITLE_REGEX = re.compile(r'''\
(\d+)
(\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+)
(.+)
''')
Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'content'])
def parse_time(time):
hours, minutes, seconds, milliseconds = map(... | Allow passing a string since we're just going to .read() the FH | parse(): Allow passing a string since we're just going to .read() the FH
| Python | mit | cdown/srt | ---
+++
@@ -23,8 +23,8 @@
)
-def parse(srt_file_handle):
- for match in SUBTITLE_REGEX.finditer(srt_file_handle.read()):
+def parse(srt):
+ for match in SUBTITLE_REGEX.finditer(srt):
raw_index, raw_start, raw_end, content = match.groups()
yield Subtitle(
index=int(raw_ind... |
19a96cb5b687e580bd3bda348a47255394da7826 | tools/telemetry/telemetry/core/platform/power_monitor/ippet_power_monitor_unittest.py | tools/telemetry/telemetry/core/platform/power_monitor/ippet_power_monitor_unittest.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import unittest
from telemetry import decorators
from telemetry.core.platform import win_platform_backend
from telemetry.core.platform.power_... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import unittest
from telemetry import decorators
from telemetry.core.platform import win_platform_backend
from telemetry.core.platform.power_... | Disable IppetPowerMonitorTest.testFindOrInstallIppet which is failing on new trybots. | Disable IppetPowerMonitorTest.testFindOrInstallIppet which is failing on new trybots.
BUG=424027
TBR=dtu@chromium.org
Review URL: https://codereview.chromium.org/643763005
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#299833}
| Python | bsd-3-clause | dushu1203/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,dednal/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,jaruba/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,... | ---
+++
@@ -11,7 +11,7 @@
class IppetPowerMonitorTest(unittest.TestCase):
- @decorators.Enabled('win')
+ @decorators.Disabled
def testFindOrInstallIppet(self):
self.assertTrue(ippet_power_monitor.IppetPath())
|
cc09da295d61965af1552b35b7ece0caf4e5a399 | accountant/interface/forms.py | accountant/interface/forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from django.utils.translation import ugettext_lazy as _
from core import models
DUPLICATE_PLAYER_ERROR = \
_('There is already a player with this name in your game')
class CreateGameForm(forms.Form):
bank_cash... | # -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from django.utils.translation import ugettext_lazy as _
from core import models
DUPLICATE_PLAYER_ERROR = \
_('There is already a player with this name in your game')
class CreateGameForm(forms.Form):
bank_cash... | Hide Game ID input since it is automatically set | Hide Game ID input since it is automatically set
| Python | mit | XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant | ---
+++
@@ -25,3 +25,6 @@
error_messages = {
NON_FIELD_ERRORS: {'unique_together': DUPLICATE_PLAYER_ERROR},
}
+ widgets = {
+ 'game': forms.HiddenInput(),
+ } |
c9ca9ae51ebc976bc60b982b9e98f68325301aea | corehq/util/es/interface.py | corehq/util/es/interface.py | class ElasticsearchInterface(object):
def __init__(self, es):
self.es = es
def update_index_settings(self, index, settings_dict):
return self.es.indices.put_settings(settings_dict, index=index)
| import abc
from django.conf import settings
class AbstractElasticsearchInterface(metaclass=abc.ABCMeta):
def __init__(self, es):
self.es = es
def update_index_settings(self, index, settings_dict):
return self.es.indices.put_settings(settings_dict, index=index)
class ElasticsearchInterface1... | Split ElasticsearchInterface into ElasticsearchInterface1 and ElasticsearchInterface2 | Split ElasticsearchInterface into ElasticsearchInterface1 and ElasticsearchInterface2
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,6 +1,37 @@
-class ElasticsearchInterface(object):
+import abc
+
+from django.conf import settings
+
+
+class AbstractElasticsearchInterface(metaclass=abc.ABCMeta):
def __init__(self, es):
self.es = es
def update_index_settings(self, index, settings_dict):
return self.es.ind... |
22988dad36645bb5b1f6023579757d5a0fca3a9e | dvox/app.py | dvox/app.py | config = {
"CREATE_RETRIES": 5,
"CHUNK_LOCK_TIMEOUT_SECONDS": 30
}
| config = {
"CREATE_RETRIES": 5,
"CHUNK_LOCK_TIMEOUT_SECONDS": 10
}
| Reduce chunk lock timeout for testing | Reduce chunk lock timeout for testing
| Python | mit | numberoverzero/dvox | ---
+++
@@ -1,4 +1,4 @@
config = {
"CREATE_RETRIES": 5,
- "CHUNK_LOCK_TIMEOUT_SECONDS": 30
+ "CHUNK_LOCK_TIMEOUT_SECONDS": 10
} |
3380091215ef3918449f1a49210cb23de39603ea | docs/conf.py | docs/conf.py | project = 'django-bcrypt'
version = ''
release = ''
copyright = '2010, 2011 UUMC Ltd.'
html_logo = 'playfire.png'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
html_title = "%s documentation" % project
master_doc = 'index'
exclude_trees = ['_build']
templates_path = ['_templates']
latex_documents = [
... | project = 'django-bcrypt'
version = ''
release = ''
copyright = '2010, 2011 UUMC Ltd.'
html_logo = 'playfire.png'
html_theme = 'nature'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
html_title = "%s documentation" % project
master_doc = 'index'
exclude_trees = ['_build']
templates_path = ['_templates']... | Use the nature theme as it's nicer on our logo | Use the nature theme as it's nicer on our logo
| Python | bsd-3-clause | playfire/django-bcrypt | ---
+++
@@ -4,6 +4,7 @@
copyright = '2010, 2011 UUMC Ltd.'
html_logo = 'playfire.png'
+html_theme = 'nature'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
html_title = "%s documentation" % project
master_doc = 'index' |
a97f3948c0f9c2b7e446c70a2f158b38a6c9365b | modules/play/play.py | modules/play/play.py | from flask import Blueprint, request, url_for, render_template
from flask.ext.security import current_user
play = Blueprint('play', __name__, template_folder='templates')
@play.route('/')
def index():
api_token = current_user.api_token
return render_template('play/index.html', api_token=api_token)
| from flask import Blueprint, request, url_for, render_template
from flask import redirect
from flask.ext.security import current_user, AnonymousUser
play = Blueprint('play', __name__, template_folder='templates')
@play.route('/')
def index():
if hasattr(current_user, 'api_token'):
api_token = current_use... | Fix error if anonymous user is logged in, instead redirect to login page | Fix error if anonymous user is logged in, instead redirect to login page
| Python | mit | KanColleTool/kcsrv,KanColleTool/kcsrv,KanColleTool/kcsrv | ---
+++
@@ -1,10 +1,14 @@
from flask import Blueprint, request, url_for, render_template
-from flask.ext.security import current_user
+from flask import redirect
+from flask.ext.security import current_user, AnonymousUser
play = Blueprint('play', __name__, template_folder='templates')
@play.route('/')
def i... |
764a6387ddd117c5dc55b5345fcf7ebab5a01190 | addons/zotero/serializer.py | addons/zotero/serializer.py | from addons.base.serializer import CitationsAddonSerializer
class ZoteroSerializer(CitationsAddonSerializer):
addon_short_name = 'zotero'
@property
def serialized_node_settings(self):
result = super(ZoteroSerializer, self).serialized_node_settings
result['library'] = {
'name': ... | from addons.base.serializer import CitationsAddonSerializer
class ZoteroSerializer(CitationsAddonSerializer):
addon_short_name = 'zotero'
@property
def serialized_node_settings(self):
result = super(ZoteroSerializer, self).serialized_node_settings
result['library'] = {
'name': ... | Add groups key in response to zotero/settings. | Add groups key in response to zotero/settings.
| Python | apache-2.0 | brianjgeiger/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,mfraezz/osf.io,chennan47/osf.io,cslzchen/osf.io,adlius/osf.io,aaxelb/osf.io,caseyrollins/osf.io,erinspace/osf.io,aaxelb/osf.io,mattclark/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,saradbowman/osf.io,binoculars/osf.io,chennan47/osf.io,mfraezz/... | ---
+++
@@ -9,4 +9,5 @@
result['library'] = {
'name': self.node_settings.fetch_library_name
}
+ result['groups'] = self.node_settings.fetch_groups
return result |
da619869c8d321863a1cc081189ebda79e1b5dbc | djclick/test/test_params.py | djclick/test/test_params.py | from click.exceptions import BadParameter
import pytest
from djclick import params
@pytest.mark.django_db
def test_modelinstance_init():
from testapp.models import DummyModel
from django.db.models.query import QuerySet
param = params.ModelInstance(DummyModel)
assert isinstance(param.qs, QuerySet)
... | from click.exceptions import BadParameter
import pytest
from djclick import params
@pytest.mark.django_db
def test_modelinstance_init():
from testapp.models import DummyModel
from django.db.models.query import QuerySet
param = params.ModelInstance(DummyModel)
assert isinstance(param.qs, QuerySet)
... | Fix a check for specific formatting of an error message | tests: Fix a check for specific formatting of an error message
Instead of checking for the specific formatting of pytest's wrapper
around an exception, check the error message with `ExceptionInfo.match`.
This improves compatibility with different versions of pytest.
| Python | mit | GaretJax/django-click | ---
+++
@@ -46,7 +46,5 @@
def test_convert_fail(call_command, args, error_message):
with pytest.raises(BadParameter) as e:
call_command('modelcmd', *args)
- # Use `.endswith()` because of differences between CPython and pypy
- assert str(e).endswith(
- 'BadParameter: could not find testapp... |
6c870e242914d40601bf7ad24e48af2b0d28559e | notification/urls.py | notification/urls.py | from django.conf.urls.defaults import *
from notification.views import notices, mark_all_seen, feed_for_user, single, notice_settings
urlpatterns = patterns("",
url(r"^$", notices, name="notification_notices"),
url(r"^settings/$", notice_settings, name="notification_notice_settings"),
url(r"^(\d+)/$", si... | try:
from django.conf.urls.defaults import *
except ImportError:
from django.conf.urls import *
from notification.views import notices, mark_all_seen, feed_for_user, single, notice_settings
urlpatterns = patterns("",
url(r"^$", notices, name="notification_notices"),
url(r"^settings/$", notice_setting... | Change to work with django 1.7 | Change to work with django 1.7
| Python | mit | daniell/django-notification,daniell/django-notification | ---
+++
@@ -1,4 +1,7 @@
-from django.conf.urls.defaults import *
+try:
+ from django.conf.urls.defaults import *
+except ImportError:
+ from django.conf.urls import *
from notification.views import notices, mark_all_seen, feed_for_user, single, notice_settings
|
07ae4af01043887d584e3024d7d7e0aa093c85f4 | intercom.py | intercom.py | import configparser
import time
import RPi.GPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
self.sen... | import configparser
import time
import RPi.GPIO as GPIO
from client import MumbleClient
class InterCom:
def __init__(self):
config = configparser.ConfigParser()
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
if conf... | Add clearing if not recording and remove useless member | Add clearing if not recording and remove useless member
| Python | mit | pkronstrom/intercom | ---
+++
@@ -11,8 +11,6 @@
config.read('intercom.ini')
self.mumble_client = MumbleClient(config['mumbleclient'])
self.exit = False
- self.send_input = False
-
if config['general']['gpiotype'] == 'BCM':
GPIO.setmode(GPIO.BCM)
@@ -20,10 +18,13 @@
self.bu... |
094380f4e30608713de549389adc1657f55b97b6 | UCP/login/serializers.py | UCP/login/serializers.py | from rest_framework import serializers
from django.contrib.auth.models import User
from login.models import UserProfile
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
write_only_fields = ('password',)
read... | from rest_framework import serializers
from django.contrib.auth.models import User
from login.models import UserProfile
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
write_only_fields = ('password',)
read... | Fix saving passwords in Register API | Fix saving passwords in Register API
override the create method in UserSerializer and set password there
| Python | bsd-3-clause | BuildmLearn/University-Campus-Portal-UCP,BuildmLearn/University-Campus-Portal-UCP,BuildmLearn/University-Campus-Portal-UCP | ---
+++
@@ -8,6 +8,12 @@
fields = ('id', 'username', 'email', 'password')
write_only_fields = ('password',)
read_only_fields = ('id',)
+
+ def create(self, validated_data):
+ user = User(email=validated_data['email'], username=validated_data['username'])
+ user.set_pass... |
8db1207cc8564fff8fb739b627932ea3ce4785fc | app/gbi_server/forms/wfs.py | app/gbi_server/forms/wfs.py | # This file is part of the GBI project.
# Copyright (C) 2013 Omniscale GmbH & Co. KG <http://omniscale.com>
#
# 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/licens... | # This file is part of the GBI project.
# Copyright (C) 2013 Omniscale GmbH & Co. KG <http://omniscale.com>
#
# 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/licens... | Allow all characters for layer title | Allow all characters for layer title
| Python | apache-2.0 | omniscale/gbi-server,omniscale/gbi-server,omniscale/gbi-server | ---
+++
@@ -30,7 +30,5 @@
def is_submitted(self):
return request and request.method in ("PUT", "POST") and request.form.get('add_form')
- new_layer = TextField(_l('wfs_new_layer_name'), validators=[
- validators.Regexp(regex='^[\w\- ]+$', message=_l('Only alphanummeric lowercase characters a... |
382d304a3f8a4a1d2a396074836ed6e951245800 | cropList.py | cropList.py | #!/usr/bin/python
import os
if __name__ == '__main__':
js_file = open('cropList.js', 'w')
js_file.write('imageNames = [\n')
js_file.write(',\n'.join(['\t"%s"' % name for name in os.listdir('originals')
if name[-4:] in ('.JPG', '.jpg', '.PNG', '.png')]))
js_file.write('\n\t];\n')
js_file.close()
| #!/usr/bin/python
import os
if __name__ == '__main__':
js_file = open('cropList.js', 'w')
js_file.write('var imageNames = [\n')
js_file.write(',\n'.join(['\t"{}"'.format(name) for name in os.listdir('originals')
if name[-4:] in ('.JPG', '.jpg', '.PNG', '.png')]))
js_file.write('\n];\n')
js_file.close()
| Declare imageNames with var, use .format() instead of %, remove tab before closing bracket | Declare imageNames with var, use .format() instead of %, remove tab before closing bracket
| Python | mit | nightjuggler/pig,nightjuggler/pig,nightjuggler/pig | ---
+++
@@ -3,8 +3,8 @@
if __name__ == '__main__':
js_file = open('cropList.js', 'w')
- js_file.write('imageNames = [\n')
- js_file.write(',\n'.join(['\t"%s"' % name for name in os.listdir('originals')
+ js_file.write('var imageNames = [\n')
+ js_file.write(',\n'.join(['\t"{}"'.format(name) for name in os.listdi... |
abe30517c0a16cb54977979ab4a90c3fd841f801 | modules/tools.py | modules/tools.py | inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.paused = False
def register(self, callback):
self.callbacks.append(callback)
def unregister(self, ... | inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
def register(self, callback):
self.callbacks.append(callbac... | Add a has_expired() method to the Timer class. | Add a has_expired() method to the Timer class.
| Python | mit | kxgames/kxg | ---
+++
@@ -7,6 +7,7 @@
self.callbacks = list(callbacks)
self.elapsed = 0
+ self.expired = False
self.paused = False
def register(self, callback):
@@ -22,13 +23,19 @@
self.pause = False
def update(self, time):
+ if self.expired:
+ return
+
... |
e5b879a9b56f6a03a9ccec8eb5a2496de3ffe4ac | pairwise/pairwise_theano.py | pairwise/pairwise_theano.py | # Authors: James Bergstra
# License: MIT
import theano
import theano.tensor as TT
def pairwise_theano_tensor_prepare(dtype):
X = TT.matrix(dtype=str(dtype))
dists = TT.sqrt(
TT.sum(
TT.sqr(X[:, None, :] - X),
axis=2))
rval = theano.function([X],
t... | # Authors: James Bergstra
# License: MIT
import theano
import theano.tensor as TT
def pairwise_theano_tensor_prepare(dtype):
X = TT.matrix(dtype=str(dtype))
dists = TT.sqrt(
TT.sum(
TT.sqr(X[:, None, :] - X),
axis=2))
rval = theano.function([X],
t... | Set the Theano case name closer to the numpy test name. | Set the Theano case name closer to the numpy test name.
| Python | mit | numfocus/python-benchmarks,numfocus/python-benchmarks | ---
+++
@@ -13,7 +13,7 @@
rval = theano.function([X],
theano.Out(dists, borrow=True),
allow_input_downcast=True)
- rval.__name__ = 'pairwise_theano_tensor_' + dtype
+ rval.__name__ = 'pairwise_theano_broadcast_' + dtype
return rval
|
661299275942813a0c45aa90db64c9603d287839 | lib_common/src/d1_common/iter/string.py | lib_common/src/d1_common/iter/string.py | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 ... | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 ... | Improve StringIterator to allow for more general usage | Improve StringIterator to allow for more general usage
| Python | apache-2.0 | DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python | ---
+++
@@ -40,3 +40,10 @@
if not chunk_str:
break
yield chunk_str
+
+ def __len__(self):
+ return len(self._string)
+
+ @property
+ def size(self):
+ return len(self._string) |
0b6b90a91390551fffebacea55e9cccb4fa3d277 | capmetrics_etl/cli.py | capmetrics_etl/cli.py | import click
from . import etl
@click.command()
@click.option('--test', default=False)
def run(test):
if not test:
etl.run_excel_etl()
else:
click.echo('Capmetrics test.')
# Call run function when module deployed as script. This is approach is common
# within the python community
if __name__ ... | import click
import configparser
import json
from . import etl
def parse_capmetrics_configuration(config_parser):
worksheet_names = json.loads(config_parser['capmetrics']['worksheet_names'])
capmetrics_configuration = {
'timezone': 'America/Chicago',
'engine': config_parser['capmetrics']['e... | Add configuration parsing to CLI. | Add configuration parsing to CLI.
| Python | mit | jga/capmetrics-etl,jga/capmetrics-etl | ---
+++
@@ -1,14 +1,36 @@
import click
+import configparser
+
+import json
from . import etl
+
+
+def parse_capmetrics_configuration(config_parser):
+ worksheet_names = json.loads(config_parser['capmetrics']['worksheet_names'])
+ capmetrics_configuration = {
+ 'timezone': 'America/Chicago',
+ ... |
3d1774aeb21b38e7cbb677228aed25e36374d560 | basics/candidate.py | basics/candidate.py |
import numpy as np
class Candidate(object):
"""
Class for candidate bubble portions from 2D planes.
"""
def __init__(self, mask, img_coords):
super(Candidate, self).__init__()
self.mask = mask
self.img_coords = img_coords
self._parent = None
self._child = None... |
import numpy as np
class Bubble2D(object):
"""
Class for candidate bubble portions from 2D planes.
"""
def __init__(self, props):
super(Bubble2D, self).__init__()
self._channel = props[0]
self._y = props[1]
self._x = props[2]
self._major = props[3]
sel... | Update class for 2D bubbles | Update class for 2D bubbles
| Python | mit | e-koch/BaSiCs | ---
+++
@@ -2,32 +2,28 @@
import numpy as np
-class Candidate(object):
+class Bubble2D(object):
"""
Class for candidate bubble portions from 2D planes.
"""
- def __init__(self, mask, img_coords):
- super(Candidate, self).__init__()
- self.mask = mask
- self.img_coords = img... |
c9d8833d59ae4858cfba69e44c1e8aaa5dd07df9 | tests/test_create_template.py | tests/test_create_template.py | # -*- coding: utf-8 -*-
"""
test_create_template
--------------------
"""
import os
import pip
import pytest
import shutil
import subprocess
TEMPLATE = os.path.realpath('.')
@pytest.fixture(autouse=True)
def clean_tmp_dir(tmpdir, request):
"""
Remove the project directory that is created by cookiecutter d... | # -*- coding: utf-8 -*-
"""
test_create_template
--------------------
"""
import os
import pip
import pytest
import shutil
import subprocess
from cookiecutter.main import cookiecutter
TEMPLATE = os.path.realpath('.')
@pytest.fixture(autouse=True)
def clean_tmp_dir(tmpdir, request):
"""
Remove the projec... | Add a test that uses the cookiecutter python API | Add a test that uses the cookiecutter python API
| Python | mit | luzfcb/cookiecutter-pytest-plugin,pytest-dev/cookiecutter-pytest-plugin,s0undt3ch/cookiecutter-pytest-plugin | ---
+++
@@ -11,6 +11,9 @@
import pytest
import shutil
import subprocess
+
+from cookiecutter.main import cookiecutter
+
TEMPLATE = os.path.realpath('.')
@@ -30,7 +33,7 @@
request.addfinalizer(remove_project_dir)
-def test_run_cookiecutter_and_plugin_tests(testdir):
+def test_run_cookiecutter_cli_and_... |
cf05e02a1efc1bf680904df5f34eb783131b37bb | db/sql_server/pyodbc.py | db/sql_server/pyodbc.py | from django.db import connection
from django.db.models.fields import *
from south.db import generic
class DatabaseOperations(generic.DatabaseOperations):
"""
django-pyodbc (sql_server.pyodbc) implementation of database operations.
"""
def create_table(self, table_name, fields):
# Tweak stuff a... | from django.db import connection
from django.db.models.fields import *
from south.db import generic
class DatabaseOperations(generic.DatabaseOperations):
"""
django-pyodbc (sql_server.pyodbc) implementation of database operations.
"""
add_column_string = 'ALTER TABLE %s ADD %s;'
def create_ta... | Add column support for sql server | Add column support for sql server
--HG--
extra : convert_revision : svn%3A69d324d9-c39d-4fdc-8679-7745eae9e2c8/trunk%40111
| Python | apache-2.0 | philipn/django-south,RaD/django-south,RaD/django-south,philipn/django-south,RaD/django-south,nimnull/django-south,nimnull/django-south | ---
+++
@@ -6,6 +6,8 @@
"""
django-pyodbc (sql_server.pyodbc) implementation of database operations.
"""
+
+ add_column_string = 'ALTER TABLE %s ADD %s;'
def create_table(self, table_name, fields):
# Tweak stuff as needed |
0213bbb8f8075b2dc36a33380a66932c9d541f63 | src/sphobjinv/__init__.py | src/sphobjinv/__init__.py | r"""``sphobjinv`` *package definition module*.
``sphobjinv`` is a toolkit for manipulation and inspection of
Sphinx |objects.inv| files.
**Author**
Brian Skinn (bskinn@alum.mit.edu)
**File Created**
17 May 2016
**Copyright**
\(c) Brian Skinn 2016-2022
**Source Repository**
https://github.com/bskinn... | r"""``sphobjinv`` *package definition module*.
``sphobjinv`` is a toolkit for manipulation and inspection of
Sphinx |objects.inv| files.
**Author**
Brian Skinn (bskinn@alum.mit.edu)
**File Created**
17 May 2016
**Copyright**
\(c) Brian Skinn 2016-2022
**Source Repository**
https://github.com/bskinn... | Clean up the error imports | Clean up the error imports
The new errors that had been added for _intersphinx.py had left
the sphobjinv.error import line split. No need, when it all fits on
one line.
| Python | mit | bskinn/sphobjinv | ---
+++
@@ -28,10 +28,7 @@
from sphobjinv.data import DataFields, DataObjBytes, DataObjStr
from sphobjinv.enum import HeaderFields, SourceTypes
-from sphobjinv.error import (
- SphobjinvError,
- VersionError,
-)
+from sphobjinv.error import SphobjinvError, VersionError
from sphobjinv.fileops import readbyt... |
63b3184aeae800795775928a67bf7567b487cba3 | tools/windows/eclipse_make.py | tools/windows/eclipse_make.py | #!/usr/bin/env python
#
# Wrapper to run make and preprocess any paths in the output from MSYS Unix-style paths
# to Windows paths, for Eclipse
from __future__ import division, print_function
import os.path
import re
import subprocess
import sys
UNIX_PATH_RE = re.compile(r'(/[^ \'"]+)+')
paths = {}
def check_path(... | #!/usr/bin/env python
#
# Wrapper to run make and preprocess any paths in the output from MSYS Unix-style paths
# to Windows paths, for Eclipse
from __future__ import division, print_function
import os.path
import re
import subprocess
import sys
UNIX_PATH_RE = re.compile(r'(/[^ \'"]+)+')
paths = {}
def check_path(... | Fix eclipse build: “UnicodeDecodeError: 'ascii' codec can't decode byte” | Fix eclipse build: “UnicodeDecodeError: 'ascii' codec can't decode byte”
Closes https://github.com/espressif/esp-idf/pull/6505
| Python | apache-2.0 | espressif/esp-idf,espressif/esp-idf,espressif/esp-idf,espressif/esp-idf | ---
+++
@@ -21,7 +21,7 @@
pass
paths[path] = path # cache as failed, replace with success if it works
try:
- winpath = subprocess.check_output(['cygpath', '-w', path]).decode().strip()
+ winpath = subprocess.check_output(['cygpath', '-w', path]).decode('utf-8').strip()
except su... |
a3e5f553fdf8dffa894d7ba3b89fefd0019653fe | oscar/apps/customer/alerts/receivers.py | oscar/apps/customer/alerts/receivers.py | from django.conf import settings
from django.db.models import get_model
from django.db.models.signals import post_save
from django.contrib.auth.models import User
def send_product_alerts(sender, instance, created, **kwargs):
from oscar.apps.customer.alerts import utils
utils.send_product_alerts(instance.produ... | from django.conf import settings
from django.db.models import get_model
from django.db.models.signals import post_save
from django.db import connection
from django.contrib.auth.models import User
def send_product_alerts(sender, instance, created, **kwargs):
from oscar.apps.customer.alerts import utils
utils.s... | Adjust post-user-create receiver to check database state | Adjust post-user-create receiver to check database state
Need to avoid situation where this signal gets raised by syncdb and the
database isn't in the correct state.
Fixes #475
| Python | bsd-3-clause | rocopartners/django-oscar,marcoantoniooliveira/labweb,Idematica/django-oscar,rocopartners/django-oscar,adamend/django-oscar,makielab/django-oscar,michaelkuty/django-oscar,django-oscar/django-oscar,amirrpp/django-oscar,adamend/django-oscar,jinnykoo/wuyisj.com,jinnykoo/christmas,binarydud/django-oscar,jinnykoo/wuyisj.com... | ---
+++
@@ -1,6 +1,7 @@
from django.conf import settings
from django.db.models import get_model
from django.db.models.signals import post_save
+from django.db import connection
from django.contrib.auth.models import User
@@ -14,9 +15,17 @@
Transfer any active alerts linked to a user's email address to th... |
a565235303e1f2572ed34490e25c7e0f31aba74c | turngeneration/serializers.py | turngeneration/serializers.py | from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from . import models
class ContentTypeField(serializers.Field):
def to_representation(self, obj):
ct = ContentType.objects.get_for_model(obj)
return u'{ct.app_label}.{ct.model}'.format(ct=ct)
de... | from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from . import models
class ContentTypeField(serializers.Field):
def to_representation(self, value):
return u'{value.app_label}.{value.model}'.format(value=value)
def to_internal_value(self, data):
... | Support nested generator inside the realm. | Support nested generator inside the realm.
| Python | mit | jbradberry/django-turn-generation,jbradberry/django-turn-generation | ---
+++
@@ -5,15 +5,55 @@
class ContentTypeField(serializers.Field):
- def to_representation(self, obj):
+ def to_representation(self, value):
+ return u'{value.app_label}.{value.model}'.format(value=value)
+
+ def to_internal_value(self, data):
+ app_label, model = data.split('.')
+ ... |
1f75d6b1d13814207c5585da166e59f3d67af4c1 | stickord/commands/xkcd.py | stickord/commands/xkcd.py | '''
Provides commands to the xkcd system
'''
from stickord.helpers.xkcd_api import get_random, get_by_id, print_comic, get_recent
from stickord.registry import Command
@Command('xkcd', category='xkcd')
async def get_comic(cont, _mesg):
''' Search for a comic by id, if no id is provided it will post a random comic.... | '''
Provides commands to the xkcd system
'''
from stickord.helpers.xkcd_api import get_random, get_by_id, print_comic, get_recent
from stickord.registry import Command
@Command('xkcd', category='xkcd')
async def get_comic(cont, _mesg):
''' Search for a comic by id, if no id is provided it will post a random comic.... | Fix crash on invalid int | Fix crash on invalid int
| Python | mit | RobinSikkens/Sticky-discord | ---
+++
@@ -8,9 +8,12 @@
async def get_comic(cont, _mesg):
''' Search for a comic by id, if no id is provided it will post a random comic. '''
if cont:
- comic_id = int(cont[0])
- comic = await get_by_id(comic_id)
- return await print_comic(comic)
+ try:
+ comic_id = ... |
936a8b77625f881f39f2433fad126f1b5d73fa3f | commands.py | commands.py | from runcommands import command
from runcommands.commands import local as _local
@command
def format_code(check=False):
_local(f"black . {'--check' if check else ''}")
@command
def lint():
_local("flake8 .")
@command
def test(with_coverage=True, check=True):
if with_coverage:
_local(
... | from runcommands import command
from runcommands.commands import local as _local
@command
def format_code(check=False):
_local(f"black . {'--check' if check else ''}")
@command
def lint():
_local("flake8 .")
@command
def test(with_coverage=True, check=True):
if with_coverage:
_local(
... | Fix test command, esp. wrt. coverage | Fix test command, esp. wrt. coverage
| Python | mit | wylee/django-local-settings | ---
+++
@@ -16,11 +16,14 @@
def test(with_coverage=True, check=True):
if with_coverage:
_local(
- "coverage run --source local_settings -m unittest discover "
+ "coverage run "
+ "--source src/local_settings "
+ "-m unittest discover "
+ "-t . -s t... |
4d915a5a9056c17fe66f41a839a4ad8e3c0bffaa | test/conftest.py | test/conftest.py | import pytest
import station
@pytest.fixture(scope='module', params=['local', 'spark'])
def eng(request):
if request.param == 'local':
return None
if request.param == 'spark':
station.setup(spark=True)
return station.engine()
@pytest.fixture(scope='module')
def engspark():
station.... | import pytest
import station
@pytest.fixture(scope='module', params=['local', 'spark'])
def eng(request):
if request.param == 'local':
return None
if request.param == 'spark':
station.start(spark=True)
return station.engine()
@pytest.fixture(scope='module')
def engspark():
station.... | Fix for new version of station | Fix for new version of station
| Python | apache-2.0 | j-friedrich/thunder,j-friedrich/thunder,thunder-project/thunder,jwittenbach/thunder | ---
+++
@@ -6,10 +6,10 @@
if request.param == 'local':
return None
if request.param == 'spark':
- station.setup(spark=True)
+ station.start(spark=True)
return station.engine()
@pytest.fixture(scope='module')
def engspark():
- station.setup(spark=True)
+ station.star... |
a91ae078952471377505ffc09b58e8391d3b7713 | extensions/ExtGameController.py | extensions/ExtGameController.py | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
GameMode(mode="hexTough", priority=5, digits=3, guesses_al... | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
GameMode(mode="hexTough", priority=5, digits=3, guesses_al... | Update extensions and GameController subclass | Update extensions and GameController subclass
| Python | apache-2.0 | dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server | ---
+++
@@ -12,5 +12,5 @@
super(ExtGameController, self).__init__(
game_json=game_json,
mode=mode,
- game_modes=self.additional_modes + game_modes
+ game_modes=self.additional_modes + (game_modes or [])
) |
d1be59a87fce8e20d698c4d1f6a272c21834a1c3 | providers/popularity/kickasstorrents.py | providers/popularity/kickasstorrents.py | from providers.popularity.provider import PopularityProvider
from utils.torrent_util import torrent_to_movie, remove_bad_torrent_matches
IDENTIFIER = "kickasstorrents"
class Provider(PopularityProvider):
PAGES_TO_FETCH = 1
def get_popular(self):
names = []
for page in range(Provider.PAGES_TO_... | from providers.popularity.provider import PopularityProvider
from utils.torrent_util import torrent_to_movie, remove_bad_torrent_matches
IDENTIFIER = "kickasstorrents"
class Provider(PopularityProvider):
PAGES_TO_FETCH = 3
def get_popular(self):
names = []
base = "https://kickasstorrents.to/h... | Fix Kickasstorrents by using one of many mirrors. | Fix Kickasstorrents by using one of many mirrors.
| Python | mit | EmilStenstrom/nephele | ---
+++
@@ -4,12 +4,19 @@
IDENTIFIER = "kickasstorrents"
class Provider(PopularityProvider):
- PAGES_TO_FETCH = 1
+ PAGES_TO_FETCH = 3
def get_popular(self):
names = []
+ base = "https://kickasstorrents.to/highres-movies/"
+ # New mirrors can be found at https://thekickasstorre... |
aff229797b3914b6708920fd247861d7777ccc22 | framework/tasks/__init__.py | framework/tasks/__init__.py | # -*- coding: utf-8 -*-
"""Asynchronous task queue module."""
from celery import Celery
from celery.utils.log import get_task_logger
from kombu import Exchange, Queue
from raven import Client
from raven.contrib.celery import register_signal
from website import settings
app = Celery()
# TODO: Hardcoded settings mod... | # -*- coding: utf-8 -*-
"""Asynchronous task queue module."""
from celery import Celery
from celery.utils.log import get_task_logger
from raven import Client
from raven.contrib.celery import register_signal
from website import settings
app = Celery()
# TODO: Hardcoded settings module. Should be set using framework... | Use auto generated celery queues | Use auto generated celery queues
| Python | apache-2.0 | jmcarp/osf.io,MerlinZhang/osf.io,Nesiehr/osf.io,leb2dg/osf.io,emetsger/osf.io,GageGaskins/osf.io,ticklemepierce/osf.io,jinluyuan/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,caseyrygt/osf.io,kch8qx/osf.io,KAsante95/osf.io,crcresearch/osf.io,aaxelb/osf.io,zamattiac/osf.io,zamattiac/osf.io,cwisecarver/osf.io,fabia... | ---
+++
@@ -3,7 +3,6 @@
from celery import Celery
from celery.utils.log import get_task_logger
-from kombu import Exchange, Queue
from raven import Client
from raven.contrib.celery import register_signal
@@ -14,13 +13,6 @@
# TODO: Hardcoded settings module. Should be set using framework's config handler
a... |
4f903a6b974fafba7c4a17b41e0a75b6b62209b3 | ghtools/command/__init__.py | ghtools/command/__init__.py | import logging
from os import environ as env
__all__ = []
_log_level_default = logging.WARN
_log_level = getattr(logging, env.get('GHTOOLS_LOGLEVEL', '').upper(), _log_level_default)
logging.basicConfig(format='%(levelname)s: %(message)s', level=_log_level)
| import logging
from os import environ as env
__all__ = []
_log_level_default = logging.INFO
_log_level = getattr(logging, env.get('GHTOOLS_LOGLEVEL', '').upper(), _log_level_default)
logging.basicConfig(format='%(levelname)s: %(message)s', level=_log_level)
| Change default loglevel to INFO | Change default loglevel to INFO
| Python | mit | alphagov/ghtools | ---
+++
@@ -3,7 +3,7 @@
__all__ = []
-_log_level_default = logging.WARN
+_log_level_default = logging.INFO
_log_level = getattr(logging, env.get('GHTOOLS_LOGLEVEL', '').upper(), _log_level_default)
logging.basicConfig(format='%(levelname)s: %(message)s', level=_log_level) |
f919aa183d1a82ba745df6a5640e8a7a83f8e87e | stix/indicator/valid_time.py | stix/indicator/valid_time.py | # Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
class ValidTime(stix.Entity):
_namespace = "http://stix.mitre.org/Indicato... | # Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
from mixbox.entities import Entity
class ValidTime(Entity):
_namespace = "... | Change ValidTime to a mixbox Entity | Change ValidTime to a mixbox Entity
| Python | bsd-3-clause | STIXProject/python-stix | ---
+++
@@ -5,8 +5,9 @@
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
+from mixbox.entities import Entity
-class ValidTime(stix.Entity):
+class ValidTime(Entity):
_namespace = "http://stix.mitre.org/Indicator-2"
_binding = indicator_bindin... |
bc6e6f0faec8405849c896b0661c181e9853359d | match/management/commands/import-users.py | match/management/commands/import-users.py | from django.core.management.base import BaseCommand, CommandError
from match.models import User
import csv
import sys
class Command(BaseCommand):
help = 'Import a list of users from stdin'
def handle(self, *args, **options):
# read a file and copy its contents as test users
tsvin = csv.reade... | from django.core.management.base import BaseCommand, CommandError
from match.models import User
import csv
import sys
class Command(BaseCommand):
help = 'Import a list of users from stdin'
def handle(self, *args, **options):
# read a file and copy its contents as test users
User.objects.all(... | Delete users before importing them | Delete users before importing them
| Python | mit | maxf/address-matcher,maxf/address-matcher,maxf/address-matcher,maxf/address-matcher | ---
+++
@@ -10,6 +10,8 @@
def handle(self, *args, **options):
# read a file and copy its contents as test users
+ User.objects.all().delete()
+
tsvin = csv.reader(sys.stdin, delimiter='\t')
for row in tsvin: |
d656c0117e8487b8b56b4ee3caceb2dcb38ec198 | sympy/concrete/tests/test_gosper.py | sympy/concrete/tests/test_gosper.py | def test_normal():
pass
def test_gosper():
pass
| from sympy import Symbol, normal
from sympy.abc import n
def test_normal():
assert normal(4*n+5, 2*(4*n+1)*(2*n+3), n)
def test_gosper():
pass
| Add test for part of gosper's algorithm. | Add test for part of gosper's algorithm.
| Python | bsd-3-clause | abhiii5459/sympy,mafiya69/sympy,atreyv/sympy,wanglongqi/sympy,pandeyadarsh/sympy,liangjiaxing/sympy,srjoglekar246/sympy,Sumith1896/sympy,bukzor/sympy,atsao72/sympy,sunny94/temp,moble/sympy,cccfran/sympy,yashsharan/sympy,drufat/sympy,maniteja123/sympy,AunShiLord/sympy,shikil/sympy,pandeyadarsh/sympy,Davidjohnwilson/symp... | ---
+++
@@ -1,5 +1,8 @@
+from sympy import Symbol, normal
+from sympy.abc import n
+
def test_normal():
- pass
+ assert normal(4*n+5, 2*(4*n+1)*(2*n+3), n)
def test_gosper():
pass |
bcb84a5b85259644ec0949f820ac1ed8f03d1676 | scripts/reactions.py | scripts/reactions.py | import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
def run(self):
s = System.parse(self.kwargs['system'], **self.kwargs)
for line in TerminalView(s).lines(**self.kwargs):
... | import argparse
from lenrmc.nubase import System
from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
if 'studies' == self.kwargs.get('view'):
self.view_cls = StudiesTerminalView
else:
... | Add ability to print out studies view from command line. | Add ability to print out studies view from command line.
| Python | mit | emwalker/lenrmc | ---
+++
@@ -1,17 +1,21 @@
import argparse
from lenrmc.nubase import System
-from lenrmc.terminal import TerminalView
+from lenrmc.terminal import TerminalView, StudiesTerminalView
class App(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
+ if 'studies' == self.kwargs.get('v... |
00103355232a0efb76f401dbec3ab4f8be32526a | qual/calendar.py | qual/calendar.py | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar... | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar... | Handle julian leap days separately. | Handle julian leap days separately.
| Python | apache-2.0 | jwg4/calexicon,jwg4/qual | ---
+++
@@ -21,8 +21,16 @@
return self.from_date(d)
class JulianCalendar(Calendar):
+ @staticmethod
+ def is_julian_leap_year(y):
+ return (y % 4) == 0
+
def date(self, year, month, day):
- d = date(year, month, day)
- d = d + timedelta(days=10)
+ if day == 29 and mo... |
c4cd02672c81a486f6397ea099b9ed1e95b05df6 | docs/tests.py | docs/tests.py | import os
from django.test import Client, TestCase
from django.core.urlresolvers import reverse
from django.core.management import call_command
import views
class DocsTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_index(self):
response = self.client.get(reverse(views.... | import os
from django.test import Client, TestCase
from django.core.urlresolvers import reverse
from django.core.management import call_command
import views
class DocsTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_index(self):
response = self.client.get(reverse(views.... | Add test case for 404 on docs pages | Add test case for 404 on docs pages
| Python | mit | crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp | ---
+++
@@ -25,5 +25,9 @@
response = self.client.get(reverse(views.docs_pages, args=(page, )))
self.assertEqual(response.status_code, 200)
+ def test_doc_pages_404(self):
+ response = self.client.get(reverse(views.docs_pages, args=("notarealpage", )))
+ self.assertEqual(re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.