commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
fea4ef7bc124da42c00989d8e4d69ff463854f02 | bot.py | bot.py | #! /usr/bin/env python
from time import gmtime, strftime
from foaas import foaas
from diaspy_client import Client
import re
import urllib2
client = Client()
notify = client.notifications()
for n in notify:
if not n.unread: continue
idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html'])
if hasattr(i... | #! /usr/bin/env python
from time import gmtime, strftime
from foaas import foaas
from diaspy_client import Client
import re
import urllib2
client = Client()
notify = client.notifications()
for n in notify:
if not n.unread: continue
idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html'])
if hasattr(i... | Add helper on not-well-formed commands | Add helper on not-well-formed commands
| Python | mit | Zauberstuhl/foaasBot |
4c2c0e9da70459063c6f1f682a181e4d350e853c | do_the_tests.py | do_the_tests.py | # pop the current directory from search path
# python interpreter adds this to a top level script
# but we will likely have a name conflict (runtests.py .vs runtests package)
import sys; sys.path.pop(0)
from runtests import Tester
import os.path
tester = Tester(os.path.abspath(__file__), "fake_spectra")
tester.main(s... | from runtests import Tester
import os.path
tester = Tester(os.path.abspath(__file__), "fake_spectra")
tester.main(sys.argv[1:])
| Remove now not needed path munging | Remove now not needed path munging
| Python | mit | sbird/fake_spectra,sbird/fake_spectra,sbird/fake_spectra |
eb8862c6048dea7612bdb808156b42792669d61a | apps/bplan/models.py | apps/bplan/models.py | from django.contrib.auth.models import AnonymousUser
from django.db import models
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(ExternalProject):
office_worker_email = models.EmailField()
... | from django.contrib.auth.models import AnonymousUser
from django.db import models
from django.utils.translation import ugettext_lazy as _
from adhocracy4.models.base import TimeStampedModel
from adhocracy4.modules import models as module_models
from apps.extprojects.models import ExternalProject
class Bplan(External... | Add bplan model field verbose names | Add bplan model field verbose names
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin |
563eb0c209a0cc75742d8acbae5dd6053e60636c | apps/welcome/urls.py | apps/welcome/urls.py | from django.conf.urls.defaults import *
from django.core.urlresolvers import reverse
# Smrtr
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^1$', 'welcome.views.profile', name='welcome-1' ),
url(r'^2$', 'network.view... | from django.conf.urls.defaults import *
from django.core.urlresolvers import reverse
# Smrtr
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^1$', 'welcome.views.profile', name='welcome-1' ),
#url(r'^2$', 'network.vie... | Remove networks from welcome activation, replace with challenges | Remove networks from welcome activation, replace with challenges
| Python | bsd-3-clause | mfitzp/smrtr,mfitzp/smrtr |
11f7c1ecadbbc68aa0a7d87570d25b24efb71fe6 | tests/run/ass2global.py | tests/run/ass2global.py | """
>>> getg()
5
>>> setg(42)
>>> getg()
42
"""
g = 5
def setg(a):
global g
g = a
def getg():
return g
class Test(object):
"""
>>> global_in_class
9
>>> Test.global_in_class
Traceback (most recent call last):
AttributeError: type object 'Test' has no attrib... | # mode: run
# tag: pyglobal
"""
>>> getg()
5
>>> getg()
5
>>> getg()
5
>>> setg(42)
>>> getg()
42
>>> getg()
42
>>> getg()
42
"""
g = 5
def setg(a):
global g
g = a
def getg():
return g
class Test(object):
"""
>>> global_in_class
9
>>> Test.global_in_class
Traceback (most recent c... | Extend test to see if global name caching actually works. | Extend test to see if global name caching actually works.
| Python | apache-2.0 | cython/cython,cython/cython,da-woods/cython,da-woods/cython,da-woods/cython,cython/cython,cython/cython,scoder/cython,scoder/cython,da-woods/cython,scoder/cython,scoder/cython |
98550946e8bc0da9a1ecdec8f0e53490f8fd5e91 | conftest.py | conftest.py | import shutil
import pytest
try:
import six
except ImportError:
from django.utils import six
from django.conf import settings
def teardown_assets_directory():
# Removing the temporary TEMP_DIR. Ensure we pass in unicode
# so that it will successfully remove temp trees containing
# non-ASCII filen... | import shutil
import pytest
try:
import six
except ImportError:
from django.utils import six
from django.conf import settings
def teardown_assets_directory():
# Removing the temporary TEMP_DIR. Ensure we pass in unicode
# so that it will successfully remove temp trees containing
# non-ASCII filen... | Make pytest autodiscover tests depending on the INSTALLED_APPS | Make pytest autodiscover tests depending on the INSTALLED_APPS
| Python | apache-2.0 | j00bar/django-widgy,j00bar/django-widgy,j00bar/django-widgy |
7de22e999bb63cd83f8af6065638a97eeb3ba2d6 | bongo/settings/travis.py | bongo/settings/travis.py | from prod import *
# The same settings as production, but no database password.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bongo_test',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '5432',
},
}
IN... | from prod import *
# The same settings as production, but no database password.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bongo_test',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '5432',
},
}
IN... | Throw this Raven DSN from the docs at Travis to make it shut up | Throw this Raven DSN from the docs at Travis to make it shut up
| Python | mit | BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo |
9b4f83ec89c76d8a5b5d0502e2903e2821078271 | logger.py | logger.py | #! /usr/bin/env python
# logger.py
"""Log the serial output from the Arduino to a text file.
"""
import sys
import serial
def log_serial(filename, device='/dev/ttyACM0', baud=9600):
ser = serial.Serial(device, baud)
outfile = open(filename, 'w')
while True:
line = ser.readline()
outfile.w... | #! /usr/bin/env python
# logger.py
"""Log the serial output from the Arduino to a text file.
"""
import sys
import serial
def log_serial(filename, device='/dev/ttyACM0', baud=9600):
ser = serial.Serial(device, baud)
outfile = open(filename, 'w')
while True:
line = ser.readline()
print(lin... | Print lines that are logged | Print lines that are logged
| Python | mit | wapcaplet/ardiff |
5238fed5b5557b8a282a9120380eee01abb49bc5 | fuzzers/038-cfg/add_constant_bits.py | fuzzers/038-cfg/add_constant_bits.py | import sys
constant_bits = {
"CFG_CENTER_MID.ALWAYS_ON_PROP1": "26_2206",
"CFG_CENTER_MID.ALWAYS_ON_PROP2": "26_2207",
"CFG_CENTER_MID.ALWAYS_ON_PROP3": "27_2205"
}
with open(sys.argv[1], "a") as f:
for bit_name, bit_value in constant_bits.items():
f.write(bit_name + " " + bit_value + "\n")
| """
Add bits that are considered always on to the db file.
This script is Zynq specific.
There are three bits that are present in all Zynq bitstreams.
The investigation that was done to reach this conclusion is captured on GH
(https://github.com/SymbiFlow/prjxray/issues/746)
In brief, these bits seem to be bitstream ... | Add background to script's purpose | Add background to script's purpose
Signed-off-by: Tomasz Michalak <a2fdaa543b4cc5e3d6cd8672ec412c0eb393b86e@antmicro.com>
| Python | isc | SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray |
9e67babf85a46128b96dd6818fa860447b4052e7 | tests/integration/ssh/test_mine.py | tests/integration/ssh/test_mine.py | # -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.case import SSHCase
from tests.support.unit import skipIf
# Import Salt Libs
import salt.utils
@skipIf(salt.utils.is_windows(), 'salt-ssh not available on Windows')
class SSHMineTest(SS... | # -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
import os
import shutil
# Import Salt Testing Libs
from tests.support.case import SSHCase
from tests.support.unit import skipIf
# Import Salt Libs
import salt.utils
@skipIf(salt.utils.is_windows(), 'salt-ssh not available on Window... | Add teardown to remove ssh dir | Add teardown to remove ssh dir
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
13e4d867e724f408b5d2dd21888b2f8a28d8fbc6 | fabfile.py | fabfile.py | # -*- coding: utf-8 -*
"""
Simple fabric file to test oinspect output
"""
from __future__ import print_function
import webbrowser
import oinspect.sphinxify as oi
def test_basic():
"""Test with an empty context"""
docstring = 'A test'
content = oi.sphinxify(docstring, oi.generate_context())
page_nam... | # -*- coding: utf-8 -*
"""
Simple fabric file to test oinspect output
"""
from __future__ import print_function
import webbrowser
import oinspect.sphinxify as oi
def _show_page(content, fname):
with open(fname, 'w') as f:
f.write(content)
webbrowser.open_new_tab(fname)
def test_basic():
"""Tes... | Add a test for math | Add a test for math
| Python | bsd-3-clause | techtonik/docrepr,spyder-ide/docrepr,techtonik/docrepr,techtonik/docrepr,spyder-ide/docrepr,spyder-ide/docrepr |
c7ee6f0094535aa0ea37becfc4e9403a3d511304 | tests/src/core/views/test_index.py | tests/src/core/views/test_index.py | #/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2012 Cidadania S. Coop. Galega
#
# This file is part of e-cidadania.
#
# e-cidadania is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either v... | #/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2012 Cidadania S. Coop. Galega
#
# This file is part of e-cidadania.
#
# e-cidadania is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either v... | Add tests for core.views.index.py. The tests presently test only if the corresponding urls can be accessed. | Add tests for core.views.index.py. The tests presently test only if the corresponding urls can be accessed.
| Python | apache-2.0 | cidadania/e-cidadania,cidadania/e-cidadania |
a04a5a80057e86af2c5df0e87a7d2c3c221123ae | rpc_server/CouchDBViewDefinitions.py | rpc_server/CouchDBViewDefinitions.py | definitions = (
{ "doc": "basicStats", "view": "addCar",
"map": """
function(doc) {
// car creations
for (var id in doc.cars){
if (doc.cars[id].state && doc.cars[id].state === 'add') {
emit(id, {'time': doc.time});
}
... | definitions = (
{ "doc": "basicStats", "view": "addCar",
"map": """
function(doc) {
// car creations
for (var id in doc.cars){
if (doc.cars[id].state && doc.cars[id].state === 'add') {
emit(id, {'time': doc.time});
}
... | Add view to get project jobs. | Add view to get project jobs.
| Python | apache-2.0 | anthony-kolesov/kts46,anthony-kolesov/kts46,anthony-kolesov/kts46,anthony-kolesov/kts46 |
b7ce3042c67c17a203590dd78014590626abbc48 | fragdev/urls.py | fragdev/urls.py | from django.conf import settings
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Blog URLs
url(r'^blog/(?P<path>.*)', include('wiblog.urls', namespace='wiblog')),
# Handl... | from django.conf import settings
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Blog URLs
#url(r'^blog/(?P<path>.*)', include('wiblog.urls', namespace='wiblog')),
# Hand... | Remove Debugging Paths, Comment Out Unfinished Portions | Remove Debugging Paths, Comment Out Unfinished Portions
| Python | agpl-3.0 | lo-windigo/fragdev,lo-windigo/fragdev |
07c9b76d63714c431a983f0506ff71f19face3bd | astroquery/alma/tests/setup_package.py | astroquery/alma/tests/setup_package.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
def get_package_data():
paths = [os.path.join('data', '*.txt')]
return {'astroquery.alma.tests': paths}
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
def get_package_data():
paths = [os.path.join('data', '*.txt'), os.path.join('data', '*.xml')]
return {'astroquery.alma.tests': paths}
| Include xml datafile for alma tests | Include xml datafile for alma tests
| Python | bsd-3-clause | imbasimba/astroquery,imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery |
c0ee0f27b21ed7c6eb97ad6b1fc1c7d72127c772 | audio_pipeline/tb_ui/util/Resources.py | audio_pipeline/tb_ui/util/Resources.py | import uuid
import os
from audio_pipeline.util.AudioFileFactory import AudioFileFactory
from audio_pipeline.util import Exceptions
mbid_directory = "Ready To Filewalk"
picard_directory = "Picard Me!"
cache_limit = 30
cancel = -1
checked = 1
unchecked = 0
def has_mbid(track):
"""
Check whether or not the gi... | import uuid
import os
from audio_pipeline.util.AudioFileFactory import AudioFileFactory
from audio_pipeline.util import Exceptions
mbid_directory = "Ready To Filewalk"
picard_directory = "Picard Me!"
cache_limit = 30
cancel = -1
checked = 1
unchecked = 0
def has_mbid(track):
"""
Check whether or not the gi... | Remove os.scandir usage (not in python 3.4) | Remove os.scandir usage (not in python 3.4)
| Python | mit | hidat/audio_pipeline |
dd55baacdda9e0a88ec6924bbe29ad3f4bb30d21 | ghost.py | ghost.py | # creating file
| # ghost.py
# globals
g_words = dict()
_END = "_END"
def addWord(word):
# check if subset is already in the dictionary
cur = g_words
for char in word:
if char in cur:
cur = cur[char]
elif _END in cur:
return
else
break
# add word to d... | Set up framework, need to work on strategy | Set up framework, need to work on strategy
| Python | cc0-1.0 | tobiaselder/ghost |
e751cb4f4805aed079fc025b9b1655f30cf5e69a | watson/html/entities.py | watson/html/entities.py | # -*- coding: utf-8 -*-
import re
from html import _escape_map_full
from html.entities import codepoint2name
html_entities = {_ord: '&{0};'.format(value)
for _ord, value in codepoint2name.items()}
html_entities.update(_escape_map_full)
entities_html = {value: _ord for _ord, value in html_entities.item... | # -*- coding: utf-8 -*-
import re
from html.entities import codepoint2name
try:
from html import _escape_map_full
except:
# taken from the 3.3 standard lib, as it's removed in 3.4
_escape_map_full = {ord('&'): '&', ord('<'): '<', ord('>'): '>',
ord('"'): '"', ord('\''... | Fix for Python 3.4 html module not containing _escape_map_full | Fix for Python 3.4 html module not containing _escape_map_full
| Python | bsd-3-clause | watsonpy/watson-html |
9a003165301e60ee4486b0a8bdde79e84eef65d8 | rparse.py | rparse.py | #!/usr/bin/env python
# Copyright 2015, Dmitry Veselov
from plyplus import Grammar, ParseError
try:
# Python 2.x and pypy
from itertools import imap as map
except ImportError:
# Python 3.x already have lazy map
pass
__all__ = [
"parse"
]
grammar = Grammar(r"""
start : package ;
package: name ... | #!/usr/bin/env python
# Copyright 2015, Dmitry Veselov
from plyplus import Grammar, STransformer, ParseError
try:
# Python 2.x and pypy
from itertools import imap as map
except ImportError:
# Python 3.x already have lazy map
pass
__all__ = [
"parse"
]
grammar = Grammar(r"""
@start : package ;
... | Transform AST to python objects | Transform AST to python objects
| Python | mit | dveselov/rparse |
82316ec166b4ab64f1890f33e8b9b75bd6733e53 | fabfile/eg.py | fabfile/eg.py | from fabric.api import task, local, run, lcd, cd, env
from os.path import exists as file_exists
from fabtools.python import virtualenv
from os import path
PWD = path.join(path.dirname(__file__), '..')
VENV_DIR = path.join(PWD, '.env')
@task
def mnist():
with virtualenv(VENV_DIR):
with lcd(PWD):
... | from fabric.api import task, local, run, lcd, cd, env
from os.path import exists as file_exists
from fabtools.python import virtualenv
from os import path
PWD = path.join(path.dirname(__file__), '..')
VENV_DIR = path.join(PWD, '.env')
@task
def mnist():
with virtualenv(VENV_DIR):
with lcd(PWD):
... | Remove dataset installation from fabfile | Remove dataset installation from fabfile
| Python | mit | spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc |
551335ba6cd219cd90bf7419bb73804bb5851c64 | typescript/commands/build.py | typescript/commands/build.py | import sublime_plugin
import sublime
import os
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
file_name = self.window.active_view().file_name()
directory = os.path.dirname(file_name)
if "tsconfig.json" in os.listdir(directory):
self.window.run_comman... | import sublime_plugin
import sublime
import os
from ..libs.global_vars import IS_ST2
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
file_name = self.window.active_view().file_name()
directory = os.path.dirname(file_name)
if "tsconfig.json" in os.listdir(director... | Add support for sublime 2 | Add support for sublime 2
| Python | apache-2.0 | RyanCavanaugh/TypeScript-Sublime-Plugin,kungfusheep/TypeScript-Sublime-Plugin,Microsoft/TypeScript-Sublime-Plugin,zhengbli/TypeScript-Sublime-Plugin,fongandrew/TypeScript-Sublime-JSX-Plugin,Microsoft/TypeScript-Sublime-Plugin,zhengbli/TypeScript-Sublime-Plugin,hoanhtien/TypeScript-Sublime-Plugin,zhengbli/TypeScript-Sub... |
e2b77a2c98cbd51c5c0546e4146dd60af0a64c86 | comics/accounts/admin.py | comics/accounts/admin.py | from django.contrib import admin
from comics.accounts import models
class SubscriptionInline(admin.StackedInline):
model = models.Subscription
extra = 1
def email(obj):
return obj.user.email
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', email, 'secret_key')
inlines = [Subs... | from django.contrib import admin
from comics.accounts import models
class SubscriptionInline(admin.StackedInline):
model = models.Subscription
extra = 1
def email(obj):
return obj.user.email
def subscription_count(obj):
return obj.comics.count()
class UserProfileAdmin(admin.ModelAdmin):
lis... | Add subscription count to comics profile list | Add subscription count to comics profile list
| Python | agpl-3.0 | datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics |
1d5442aa70d2ed2569cc062d476129840d08a610 | oscar/apps/shipping/repository.py | oscar/apps/shipping/repository.py | from django.core.exceptions import ImproperlyConfigured
from oscar.apps.shipping.methods import Free, NoShippingRequired
class Repository(object):
"""
Repository class responsible for returning ShippingMethod
objects for a given user, basket etc
"""
def get_shipping_methods(self, user, basket... | from django.core.exceptions import ImproperlyConfigured
from oscar.apps.shipping.methods import Free, NoShippingRequired
class Repository(object):
"""
Repository class responsible for returning ShippingMethod
objects for a given user, basket etc
"""
def get_shipping_methods(self, user, basket, sh... | Make the cheapest shipping method the default one | Make the cheapest shipping method the default one
| Python | bsd-3-clause | mexeniz/django-oscar,kapari/django-oscar,makielab/django-oscar,eddiep1101/django-oscar,Jannes123/django-oscar,thechampanurag/django-oscar,rocopartners/django-oscar,john-parton/django-oscar,elliotthill/django-oscar,itbabu/django-oscar,mexeniz/django-oscar,jinnykoo/wuyisj.com,marcoantoniooliveira/labweb,sonofatailor/djan... |
e337dc55aa5420506c1351d7000e903afdb4d4ef | account_analytic_invoice_line_menu/__openerp__.py | account_analytic_invoice_line_menu/__openerp__.py | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Account Analytic Invoice Line Menu",
"version": "8.0.1.0.0",
"license": "AGPL-3",
"author": "AvanzOSC",
"website": "http://www.avanzosc.es",
"contributor... | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Account Analytic Invoice Line Menu",
"version": "8.0.1.0.0",
"license": "AGPL-3",
"author": "AvanzOSC",
"website": "http://www.avanzosc.es",
"contributor... | Put dependency to "account_analytic_analysis" module. | [FIX] account_analytic_invoice_line_menu: Put dependency to "account_analytic_analysis" module.
| Python | agpl-3.0 | esthermm/odoo-addons,Daniel-CA/odoo-addons,mikelarre/hr-addons,Daniel-CA/odoo-addons,esthermm/odoo-addons,Daniel-CA/odoo-addons,esthermm/odoo-addons |
477364a4d2895fc79af2a57ace35ededf0281911 | mistral/db/sqlalchemy/migration/alembic_migrations/versions/003_cron_trigger_constraints.py | mistral/db/sqlalchemy/migration/alembic_migrations/versions/003_cron_trigger_constraints.py | # Copyright 2015 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | # Copyright 2015 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | Fix database upgrade from a new database | Fix database upgrade from a new database
This fixes the problem where running "mistral-db-manage upgrade heads" on a
new database result in error with workflow_input_hash index does not exist.
Change-Id: I560b2b78d11cd3fd4ae9c8606e4336e87b22ef27
Closes-Bug: #1519929
| Python | apache-2.0 | openstack/mistral,StackStorm/mistral,openstack/mistral,StackStorm/mistral |
9f1d4788c5f3751b978da97434b5f6c2e22105b5 | django_inbound_email/__init__.py | django_inbound_email/__init__.py | """An inbound email handler for Django."""
__title__ = 'django-inbound-email'
__version__ = '0.3.3'
__author__ = 'YunoJuno Ltd'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 YunoJuno'
__description__ = (
"A Django app to make it easy to receive inbound emails from "
"a hosted transactional email service ... | """An inbound email handler for Django."""
__title__ = 'django-inbound-email'
__version__ = '0.3.3'
__author__ = 'YunoJuno Ltd'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 YunoJuno'
__description__ = 'A Django app for receiving inbound emails.'
| Update package description so it displays correctly on PyPI. | Update package description so it displays correctly on PyPI.
The description was wrapping, so it appeared with a single '(' character
on PyPI. I've updated it so that it's now all on a single line.
| Python | mit | yunojuno/django-inbound-email |
f4014dea504293f3630205092d71ac272763c3b3 | blist/__init__.py | blist/__init__.py | from blist._blist import *
import collections
if hasattr(collections, 'MutableSet'): # Only supported in Python 2.6+
from blist._sortedlist import sortedlist, sortedset, weaksortedlist, weaksortedset
from blist._sorteddict import sorteddict
from blist._btuple import btuple
collections.MutableSequence.re... | from blist._blist import *
import collections
if hasattr(collections, 'MutableSet'): # Only supported in Python 2.6+
from blist._sortedlist import sortedlist, sortedset, weaksortedlist, weaksortedset
from blist._sorteddict import sorteddict
from blist._btuple import btuple
collections.MutableSequence.re... | Clean up the blist namespace. | Clean up the blist namespace.
| Python | bsd-3-clause | DanielStutzbach/blist,DanielStutzbach/blist,pfmoore/blist,pfmoore/blist |
8c3e3ec6076d8b9ee858fca00d92717d77c67ade | time_lapse.py | time_lapse.py | #!/usr/bin/env python
import sys
import time
import picamera
import settings
from settings import IMAGE, SNAP
import uploader
def main():
with picamera.PiCamera() as camera:
camera.resolution = (IMAGE.resolution_x, IMAGE.resolution_y)
time.sleep(2)
output_file = settings.IMAGES_DIRECTORY ... | #!/usr/bin/env python
import time
import picamera
from settings import Job, IMAGES_DIRECTORY
def main():
job = Job()
if job.exists():
resolution_x = job.image_settings.resolution_x
resolution_y = job.image_settings.resolution_y
image_quality = job.image_settings.quality
snap_i... | Check for job in main loop | Check for job in main loop
| Python | mit | projectweekend/Pi-Camera-Time-Lapse,projectweekend/Pi-Camera-Time-Lapse |
7f1a58f9faacb0bb0e95c2527a348195742eb866 | tornado/test/autoreload_test.py | tornado/test/autoreload_test.py | from __future__ import absolute_import, division, print_function
import os
import subprocess
from subprocess import Popen
import sys
from tempfile import mkdtemp
from tornado.test.util import unittest
MAIN = """\
import os
import sys
from tornado import autoreload
# This import will fail if path is not set up corr... | from __future__ import absolute_import, division, print_function
import os
import subprocess
from subprocess import Popen
import sys
from tempfile import mkdtemp
from tornado.test.util import unittest
MAIN = """\
import os
import sys
from tornado import autoreload
# This import will fail if path is not set up corr... | Fix newline handling in autoreload test | Fix newline handling in autoreload test
| Python | apache-2.0 | SuminAndrew/tornado,mivade/tornado,legnaleurc/tornado,tornadoweb/tornado,ifduyue/tornado,bdarnell/tornado,NoyaInRain/tornado,bdarnell/tornado,ajdavis/tornado,NoyaInRain/tornado,bdarnell/tornado,eklitzke/tornado,wujuguang/tornado,allenl203/tornado,SuminAndrew/tornado,Lancher/tornado,Lancher/tornado,NoyaInRain/tornado,No... |
ace1997f5d1cab297ab68886501b45602b2d8e2d | cards/models.py | cards/models.py | from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from time import time
def card_image_filename(instance, filename):
timestamp = int(time())
return 'cards/%s%d.jpg' % (instance, timest... | from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from time import time
def card_image_filename(instance):
timestamp = int(time())
return 'cards/%s%d.jpg' % (instance, timestamp)
@py... | Remove unused filename parameter from card image filename function | Remove unused filename parameter from card image filename function
| Python | mit | neosergio/WisdomBox |
1261777b6aaaea6947a32477e340ef1597045866 | nested_admin/urls.py | nested_admin/urls.py | try:
from django.conf.urls.defaults import patterns, url
except ImportError:
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^server-data\.js$', 'nested_admin.views.server_data_js',
name="nesting_server_data"),
)
| from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^server-data\.js$', 'nested_admin.views.server_data_js',
name="nesting_server_data"),
)
| Fix DeprecationWarning in Django 1.5 | Fix DeprecationWarning in Django 1.5
| Python | bsd-2-clause | sbussetti/django-nested-admin,sbussetti/django-nested-admin,olivierdalang/django-nested-admin,sbussetti/django-nested-admin,olivierdalang/django-nested-admin,olivierdalang/django-nested-admin |
1cb01d48246baf0ca84a23bd8718d46471b8105f | bin/mpy-tool-wrapper.py | bin/mpy-tool-wrapper.py | #!/usr/bin/env python
#
# Wrapper for mpy-cross.py.
#
from __future__ import print_function
import sys
import os
import subprocess
def main():
command = sys.argv[3:]
env = dict(os.environ, PYTHONPATH=sys.argv[2])
with open(sys.argv[1], 'w') as f:
f.write(subprocess.check_output(command, env=env)... | #!/usr/bin/env python
#
# Wrapper for mpy-cross.py.
#
from __future__ import print_function
import sys
import os
import subprocess
def main():
command = sys.argv[3:]
env = dict(os.environ, PYTHONPATH=sys.argv[2])
with open(sys.argv[1], 'w') as f:
f.write(subprocess.check_output(command, env=env)... | Add support for Python 3 | Add support for Python 3 | Python | mit | eerimoq/pumba,eerimoq/pumbaa,eerimoq/pumbaa,eerimoq/pumbaa,eerimoq/pumbaa,eerimoq/pumba,eerimoq/pumba |
108a05b050383bca218cd02be499f1fad58065dc | test/test_refmanage.py | test/test_refmanage.py | # -*- coding: utf-8 -*-
import unittest
import pathlib2 as pathlib
import refmanage
class NoSpecifiedFunctionality(unittest.TestCase):
"""
Tests when no functionality has been specified on cli
"""
def test_no_args(self):
"""
`ref` without arguments should print the help text
"""... | # -*- coding: utf-8 -*-
import unittest
import pathlib2 as pathlib
import refmanage
class NoSpecifiedFunctionality(unittest.TestCase):
"""
Tests when no functionality has been specified on cli
"""
def test_no_args(self):
"""
`ref` without arguments should print the help text
"""... | Replace "pass" with "self.fail()" in tests | Replace "pass" with "self.fail()" in tests
In this way, tests that haven't been written will run noisily instead of
silently, encouraging completion of writing tests.
| Python | mit | jrsmith3/refmanage |
5156af5576d5663555bc04f5960e7e4cdd861166 | objectrocket/util.py | objectrocket/util.py | """Utility code for the objectrocket package."""
import types
def register_extension_class(ext, base, *args, **kwargs):
"""Instantiate the given extension class and register as a public attribute of the given base.
README: The expected protocol here to instantiate the given extension and pass the base object... | """Utility code for the objectrocket package."""
import types
def register_extension_class(ext, base, *args, **kwargs):
"""Instantiate the given extension class and register as a public attribute of the given base.
README: The expected protocol here is to instantiate the given extension and pass the base
... | Clean up docs on extension protocols. | Clean up docs on extension protocols.
| Python | mit | objectrocket/python-client,objectrocket/python-client |
1a8419c6b91276cf578f4c354e34d17551ac2403 | metakernel/__init__.py | metakernel/__init__.py | from ._metakernel import MetaKernel
from . import pexpect
from . import replwrap
from .process_metakernel import ProcessMetaKernel
from .magic import Magic, option
from .parser import Parser
__all__ = ['Magic', 'MetaKernel', 'option']
__version__ = '0.3'
del magic, _metakernel, parser, process_metakernel
| from ._metakernel import MetaKernel
from . import pexpect
from .replwrap import REPLWrapper, u
from .process_metakernel import ProcessMetaKernel
from .magic import Magic, option
from .parser import Parser
__all__ = ['Magic', 'MetaKernel', 'option']
__version__ = '0.3'
del magic, _metakernel, parser, process_metakern... | Move REPLWrapper and u() function to pkg level | Move REPLWrapper and u() function to pkg level
| Python | bsd-3-clause | Calysto/metakernel |
e30b8b60de491721f635300840b08b481250fea6 | microbower/__init__.py | microbower/__init__.py |
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
if not (os.path.isfile('.bowerrc') and os.path.isfile('bower.json')):
return
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(... |
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
if not (os.path.isfile('.bowerrc') and os.path.isfile('bower.json')):
return
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(... | Check if the git repo already exists before cloning it again | Check if the git repo already exists before cloning it again
| Python | isc | zenhack/microbower |
4c0cc07edc566b2feebefbcc301a6e16033c613a | bin/register_jsonl.py | bin/register_jsonl.py | #!/usr/bin/env python
# create a single jsonl file from individual register entries
import sys
import os
from openregister import Item
from openregister.representations.jsonl import Writer
register = sys.argv[1] or "register"
dirname = "data/" + register + "/"
writer = Writer(sys.stdout)
for file in os.listdir(dir... | #!/usr/bin/env python
# create a single jsonl file from individual register entries
import sys
import os
from openregister import Item
from openregister.representations.jsonl import Writer
register = sys.argv[1] or "register"
dirname = os.path.join("data", register)
writer = Writer(sys.stdout)
for file in os.listd... | Use os.path.join to build prod | Use os.path.join to build prod
| Python | mit | openregister/registry-data |
8f698f862e1ea4e2c17e8ddd14052c83bf87ea4c | adzone/views.py | adzone/views.py | # -*- coding: utf-8 -*-
# © Copyright 2009 Andre Engelbrecht. All Rights Reserved.
# This script is licensed under the BSD Open Source Licence
# Please see the text file LICENCE for more information
# If this script is distributed, it must be accompanied by the Licence
from datetime import datetime
from django.short... | # -*- coding: utf-8 -*-
# © Copyright 2009 Andre Engelbrecht. All Rights Reserved.
# This script is licensed under the BSD Open Source Licence
# Please see the text file LICENCE for more information
# If this script is distributed, it must be accompanied by the Licence
import re
from datetime import datetime
from d... | Improve http check to allow https as well | Improve http check to allow https as well
We switch from 'startswith' to a regex check which allows both as we
tested with https facebook urls and it failed to handle them properly.
| Python | bsd-3-clause | michaeljones/django-adzone,michaeljones/django-adzone |
f29477416729df9cc198f679a2478f6a077ce365 | app/util.py | app/util.py | # Various utility functions
import os
from typing import Any, Callable
SHOULD_CACHE = os.environ.get('ENV', 'development') == 'production'
def cached_function(func: Callable[..., Any]) -> Callable[..., Any]:
data = {}
def wrapper(*args: Any) -> Any:
if not SHOULD_CACHE:
return func(*arg... | # Various utility functions
import inspect
import os
from typing import Any, Callable
SHOULD_CACHE = os.environ.get('ENV', 'development') == 'production'
def cached_function(func: Callable[..., Any]) -> Callable[..., Any]:
data = {}
def wrapper(*args: Any) -> Any:
if not SHOULD_CACHE:
r... | Make cached_function not overwrite signature of wrapped function | Make cached_function not overwrite signature of wrapped function
| Python | mit | albertyw/albertyw.com,albertyw/albertyw.com,albertyw/albertyw.com,albertyw/albertyw.com,albertyw/albertyw.com |
8f66d41be2ffc8dd42392a30e6eefcbb6da9b667 | sheared/web/entwine.py | sheared/web/entwine.py | import warnings
from dtml import tal, metal, tales, context
from sheared.python import io
from sheared.python import benchmark
class Entwiner:
def __init__(self):
self.builtins = context.BuiltIns({})
#self.context = context.Context()
#self.context.setDefaults(self.builtins)
def handl... | import warnings
from dtml import tal, metal, tales, context
from sheared.python import io
class Entwiner:
def __init__(self):
self.builtins = context.BuiltIns({})
#self.context = context.Context()
#self.context.setDefaults(self.builtins)
def handle(self, request, reply, subpath):
... | Remove import of n/a benchmark module. | Remove import of n/a benchmark module.
git-svn-id: 8b0eea19d26e20ec80f5c0ea247ec202fbcc1090@75 5646265b-94b7-0310-9681-9501d24b2df7
| Python | mit | kirkeby/sheared |
27ff37e0b0f87d112ea98ff9c3674abed4a3e413 | fontcrunch/__init__.py | fontcrunch/__init__.py | from __future__ import print_function
from fontTools import ttLib
from multiprocessing import Pool
from .fontcrunch import optimize_glyph, plot_glyph
def _optimize(args):
font, name, pdf, penalty, quiet = args
if not quiet:
print('optimizing', name)
glyph = font['glyf'][name]
plot_glyph(font,... | from __future__ import print_function
from fontTools import ttLib
from multiprocessing import Pool
from .fontcrunch import optimize_glyph, plot_glyph
def _optimize(args):
font, name, pdf, penalty, quiet = args
if not quiet:
print('optimizing', name)
glyph = font['glyf'][name]
plot_glyph(font,... | Make this code actually do something! | Make this code actually do something!
| Python | apache-2.0 | googlefonts/fontcrunch,googlefonts/quadopt,googlefonts/quadopt,googlefonts/fontcrunch |
a28fe5793c6bcfc7482f840821eb6d7b779a78dd | slackelot/slackelot.py | slackelot/slackelot.py | import time
import requests
class SlackNotificationError(Exception):
pass
def send_slack_message(message, webhook_url, pretext=None, title=None):
""" Send slack message using webhooks
Args:
message (string)
webhook_url (string), 'https://hooks.slack.com/services/{team id}/{bot or channe... | import time
import requests
class SlackNotificationError(Exception):
pass
def send_slack_message(message, webhook_url, pretext=None, title=None):
""" Send slack message using webhooks
Args:
message (string)
webhook_url (string), 'https://hooks.slack.com/services/{team id}/{bot or channe... | Add initial check for arg webhook_url | Add initial check for arg webhook_url
| Python | mit | Chris-Graffagnino/slackelot |
9b3203bae4d72dab90e15dc1b60fb0518a4a0f40 | run_patch.py | run_patch.py | from patch_headers import patch_headers, add_object_info
import sys
for currentDir in sys.argv[1:]:
print "working on directory: %s" % currentDir
patch_headers(currentDir, new_file_ext='', overwrite=True)
add_object_info(currentDir, new_file_ext='', overwrite=True)
#add_overscan(currentDir, new_file_ex... | """
SYNOPSIS
python run_patch.py dir1 [dir2 dir3 ...]
DESCRIPTION
For each directory dir1, dir2, ... provided on the command line the
headers all of the FITS files in that directory are modified
to add information like LST, apparent object position, and more.
See the full documentation for a list... | Change to script and add significant documentation | Change to script and add significant documentation
| Python | bsd-3-clause | mwcraig/msumastro |
c4009fdedc1625fe3692c689242d9f32a1c89f97 | tests/services/conftest.py | tests/services/conftest.py | import pytest
from responses import RequestsMock
from netvisor import Netvisor
@pytest.fixture
def netvisor():
kwargs = dict(
sender='Test client',
partner_id='xxx_yyy',
partner_key='E2CEBB1966C7016730C70CA92CBB93DD',
customer_id='xx_yyyy_zz',
customer_key='7767899D6F5FB33... | import pytest
from responses import RequestsMock
from netvisor import Netvisor
@pytest.fixture
def netvisor():
kwargs = dict(
sender='Test client',
partner_id='xxx_yyy',
partner_key='E2CEBB1966C7016730C70CA92CBB93DD',
customer_id='xx_yyyy_zz',
customer_key='7767899D6F5FB33... | Fix tests to work with responses 0.3.0 | Fix tests to work with responses 0.3.0
| Python | mit | fastmonkeys/netvisor.py |
e946f239695f74d83fcb1b4929ed2281846add4c | avalon/fusion/pipeline.py | avalon/fusion/pipeline.py |
def imprint_container(tool,
name,
namespace,
context,
loader=None):
"""Imprint a Loader with metadata
Containerisation enables a tracking of version, author and origin
for loaded assets.
Arguments:
tool (... |
def imprint_container(tool,
name,
namespace,
context,
loader=None):
"""Imprint a Loader with metadata
Containerisation enables a tracking of version, author and origin
for loaded assets.
Arguments:
tool (... | Store tool's name when parsing container | Store tool's name when parsing container
| Python | mit | MoonShineVFX/core,MoonShineVFX/core,getavalon/core,getavalon/core,mindbender-studio/core,mindbender-studio/core |
6b3dd31b1a795a92a00c7dba636a88636018655c | tests/blueprints/admin/conftest.py | tests/blueprints/admin/conftest.py | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
Fixtures specific to admin blueprints
"""
import pytest
from tests.base import create_admin_app
from tests.conftest import database_recreated
@pytest.fixture(scope='session')
def admin_app_without_db(db):
app = crea... | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
Fixtures specific to admin blueprints
"""
import pytest
from tests.conftest import database_recreated
@pytest.fixture(scope='module')
def app(admin_app, db):
app = admin_app
with app.app_context():
with ... | Use existing `admin_app` fixture for admin tests | Use existing `admin_app` fixture for admin tests
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
ed8add36f605def54e53c34627a1eedeefb145e5 | project/api/forms.py | project/api/forms.py | # Django
from django import forms
# Local
from .models import User
class UserCreationForm(forms.ModelForm):
class Meta:
model = User
fields = '__all__'
def save(self, commit=True):
user = super().save(commit=False)
user.email = self.cleaned_data['person'].email.lower()
... | # Django
from django import forms
# Local
from .models import User
class UserCreationForm(forms.ModelForm):
class Meta:
model = User
fields = '__all__'
def save(self, commit=True):
user = super().save(commit=False)
user.email = self.cleaned_data['person'].email.lower()
... | Create user name on Admin form create | Create user name on Admin form create
| Python | bsd-2-clause | dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api |
ed88d9b598b3bd360a6575d83ffd3d4044846a96 | traits/tests/test_array.py | traits/tests/test_array.py | #------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in /LICENSE.txt and may be redistributed only
# under the conditions described in the ... | #------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in /LICENSE.txt and may be redistributed only
# under the conditions described in the ... | Make definition of conditional on NumPy being installed; update skip message to match that used elsewhere | Make definition of conditional on NumPy being installed; update skip message to match that used elsewhere
| Python | bsd-3-clause | burnpanck/traits,burnpanck/traits |
ce39e4a5573e7b3a882ee4a327b3c9eb088d1d07 | senlin/profiles/container/docker.py | senlin/profiles/container/docker.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... | Add 'host_node' and 'host_cluster' properties to container profile | Add 'host_node' and 'host_cluster' properties to container profile
Add 'host_node' and 'host_cluster' properties to container profile,
in a container profile, either 'host_node' or 'host_cluster' will
be assigned a value for a container node creation or a container
cluster creation.
blueprint container-profile-suppor... | Python | apache-2.0 | stackforge/senlin,openstack/senlin,stackforge/senlin,openstack/senlin,openstack/senlin |
d357136075bce9d8582759a525536daf7489becb | unitypack/engine/object.py | unitypack/engine/object.py | def field(f, cast=None):
def _inner(self):
ret = self._obj[f]
if cast:
ret = cast(ret)
return ret
return property(_inner)
class Object:
def __init__(self, data=None):
if data is None:
data = {}
self._obj = data
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, self.name)
def __... | def field(f, cast=None, **kwargs):
def _inner(self):
if "default" in kwargs:
ret = self._obj.get(f, kwargs["default"])
else:
ret = self._obj[f]
if cast:
ret = cast(ret)
return ret
return property(_inner)
class Object:
def __init__(self, data=None):
if data is None:
data = {}
self._obj = dat... | Allow default values in field() | Allow default values in field()
| Python | mit | andburn/python-unitypack |
be30b8220900eaf549fbe1bff7a1e7c3a9be8529 | settings_test.py | settings_test.py | # The test system uses this to override settings in settings.py and
# settings_local.py with settings appropriate for testing.
# Make sure Celery is EAGER.
CELERY_ALWAYS_EAGER = True
# Make sure the doctypes (the keys) match the doctypes in ES_INDEXES
# in settings.py and settings_local.py.
ES_INDEXES = {'default': '... | from django.conf import settings
# The test system uses this to override settings in settings.py and
# settings_local.py with settings appropriate for testing.
# Make sure Celery is EAGER.
CELERY_ALWAYS_EAGER = True
# Make sure the doctypes (the keys) match the doctypes in ES_INDEXES
# in settings.py and settings_loc... | Make settings test respect ES_INDEX_PREFIX. | Make settings test respect ES_INDEX_PREFIX.
| Python | bsd-3-clause | chirilo/kitsune,H1ghT0p/kitsune,feer56/Kitsune1,NewPresident1/kitsune,safwanrahman/kitsune,asdofindia/kitsune,brittanystoroz/kitsune,MikkCZ/kitsune,H1ghT0p/kitsune,philipp-sumo/kitsune,mozilla/kitsune,safwanrahman/kitsune,Osmose/kitsune,YOTOV-LIMITED/kitsune,philipp-sumo/kitsune,feer56/Kitsune1,dbbhattacharya/kitsune,a... |
9af78701228df0decee22854eae1fbb306d90068 | cactusbot/handlers/spam.py | cactusbot/handlers/spam.py | """Handle incoming spam messages."""
from ..handler import Handler
import logging
import json
class SpamHandler(Handler):
"""Spam handler."""
MAX_SCORE = 16
MAX_EMOTES = 6
ALLOW_LINKS = False
def __init__(self):
self.logger = logging.getLogger(__name__)
def on_message(self, packet)... | """Handle incoming spam messages."""
from ..handler import Handler
import logging
class SpamHandler(Handler):
"""Spam handler."""
MAX_SCORE = 16
MAX_EMOTES = 6
ALLOW_LINKS = False
def __init__(self):
self.logger = logging.getLogger(__name__)
def on_message(self, packet):
""... | Fix json loading, fix capital checker | Fix json loading, fix capital checker
| Python | mit | CactusDev/CactusBot |
9127e56a26e836c7e2a66359a9f9b67e6c7f8474 | ovp_users/tests/test_filters.py | ovp_users/tests/test_filters.py | from django.test import TestCase
from ovp_users.recover_password import RecoveryTokenFilter
from ovp_users.recover_password import RecoverPasswordFilter
def test_filter(c):
obj = c()
obj.filter_queryset('a', 'b', 'c')
obj.get_fields('a')
def TestPasswordRecoveryFilters(TestCase):
def test_filters():
"""A... | from django.test import TestCase
from ovp_users.recover_password import RecoveryTokenFilter
from ovp_users.recover_password import RecoverPasswordFilter
def test_filter(c):
obj = c()
obj.filter_queryset('a', 'b', 'c')
obj.get_fields('a')
def PasswordRecoveryFiltersTestCase(TestCase):
def test_filters():
... | Fix PasswordRecovery test case name | Fix PasswordRecovery test case name
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users |
1b502cdf399b5b9cd4593aea82750b77114fe858 | examples/flask_hello.py | examples/flask_hello.py | from pyinstrument import Profiler
try:
from flask import Flask, g, make_response, request
except ImportError:
print('This example requires Flask.')
print('Install using `pip install flask`.')
exit(1)
app = Flask(__name__)
@app.before_request
def before_request():
if "profile" in request.args:
... | import time
from pyinstrument import Profiler
try:
from flask import Flask, g, make_response, request
except ImportError:
print('This example requires Flask.')
print('Install using `pip install flask`.')
exit(1)
app = Flask(__name__)
@app.before_request
def before_request():
if "profile" in reque... | Add some more endpoints to the flask example | Add some more endpoints to the flask example
| Python | bsd-3-clause | joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument |
c8c186e46990797e1faa07c71fb57920a89a2dcc | webquills/core/commands.py | webquills/core/commands.py | """
Business logic in this app is implemented using a CQRS style. Commands should
be implemented as functions here. Queries should be implemented as methods on
Django model managers. Commands can then be called from a management command
(i.e. the CLI), a view, a signal, etc.
"""
from django.conf import settings
from dj... | """
Business logic in this app is implemented using a CQRS style. Commands should
be implemented as functions here. Queries should be implemented as methods on
Django model managers. Commands can then be called from a management command
(i.e. the CLI), a view, a signal, etc.
"""
from django.conf import settings
from dj... | Create SiteMeta for default site | Create SiteMeta for default site
| Python | apache-2.0 | veselosky/webquills,veselosky/webquills,veselosky/webquills |
e24ee559a607172f0072ac9f28c90f09765ddc62 | examples/print_gcode.py | examples/print_gcode.py | import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import s3g
import serial
import optparse
parser = optparse.OptionParser()
parser.add_option("-p", "--serialport", dest="serialportname",
help="serial port (ex: /dev/ttyUSB0)", default="/dev/ttyACM0")
parser.add_option("... | import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import s3g
import serial
import optparse
parser = optparse.OptionParser()
parser.add_option("-p", "--serialport", dest="serialportname",
help="serial port (ex: /dev/ttyUSB0)", default="/dev/ttyACM0")
parser.add_option("... | Update print_gcide example to work with latest api changes. | Update print_gcide example to work with latest api changes.
| Python | agpl-3.0 | Jnesselr/s3g,makerbot/s3g,makerbot/s3g,Jnesselr/s3g,makerbot/s3g,makerbot/s3g |
560ff8d533a2247e7b194755fb13941ffbc1f544 | IPython/nbconvert/exporters/python.py | IPython/nbconvert/exporters/python.py | """Python script Exporter class"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#----------... | """Python script Exporter class"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#----------... | Remove magic for loading templates from module names | Remove magic for loading templates from module names
| Python | bsd-3-clause | SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidg... |
188e4e6d3419793ae8811eb66d94e31849af3461 | conf_site/core/forms.py | conf_site/core/forms.py | from django import forms
class CsvUploadForm(forms.Form):
"""Form for uploading a CSV file."""
csv_file = forms.FileField(label="Please upload a CSV file.")
| from django import forms
class CsvUploadForm(forms.Form):
"""Form for uploading a CSV file."""
csv_file = forms.FileField(label="Please upload a CSV file.")
def _is_csv_file(self, file_data):
"""
Test whether an uploaded file is a CSV file.
Returns a list of a boolean of the res... | Test whether uploaded CSV has correct mime type. | Test whether uploaded CSV has correct mime type.
Add cleaning method to CsvUploadForm to ensure that uploaded file has
either the mime type for a CSV file or no mime type. Return error if
user uploads a different mime type.
| Python | mit | pydata/conf_site,pydata/conf_site,pydata/conf_site |
6995c7ca63f26a6c350fbdad5e5d194c4c1a60b0 | irco/graphs/country.py | irco/graphs/country.py | import sys
import itertools
import collections
import networkx as nx
from irco import logging
log = logging.get_logger()
def get_countries(publication):
publication_countries = set()
for affiliation in publication.affiliations:
country = affiliation.institution.country
if country is None:... | import sys
import itertools
import collections
import networkx as nx
from irco import logging
log = logging.get_logger()
def get_countries(publication):
publication_countries = set()
for affiliation in publication.affiliations:
country = affiliation.institution.country
if country is None:... | Sort countries before generating combinations. | Sort countries before generating combinations.
| Python | mit | GaretJax/irco,GaretJax/irco,GaretJax/irco,GaretJax/irco |
c0d8b7f13a74fd4da7b36d30a61224b76367acbe | scraper.py | scraper.py | import urllib, datetime, os
def fetch():
url = 'http://loadmeter.egyptera.org/ClockToolTip.aspx'
output = datetime.datetime.now().strftime('egyptera.%Y-%m-%d-%H-%M-%S.html')
output = os.path.join(os.path.dirname(__file__), output)
content = urllib.urlretrieve(url, output)
if __name__ == '__main__':
... | import urllib, datetime, os
def fetch():
# Instead of doing all the parsing later, I get the status from Mosab's site & store it
url = 'http://power-grid-status.mos3abof.com/status'
output = datetime.datetime.now().strftime('egyptera.%Y-%m-%d-%H-%M-%S.json')
output = os.path.join(os.path.dirname(__file... | Use Mosab's site to get the status | Use Mosab's site to get the status
| Python | apache-2.0 | mtayseer/power-grid-scraper |
4a7b0fb482011400da0b3e760cde2d6f294d168f | sysrev/models.py | sysrev/models.py | from django.db import models
from django.contrib.auth.models import User
class Review(models.Model):
user = models.ForeignKey(User, default=None)
title = models.CharField(max_length=128)
description = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
last_modified = models.... | from django.db import models
from django.contrib.auth.models import User
class Review(models.Model):
user = models.ForeignKey(User, default=None)
title = models.CharField(max_length=128)
description = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
last_modified = models.... | Add completed field to review | Add completed field to review
| Python | mit | iliawnek/SystematicReview,iliawnek/SystematicReview,iliawnek/SystematicReview,iliawnek/SystematicReview |
0337f32a493690f5a0be3893c43b7af3644f964d | tests/runtests.py | tests/runtests.py | #!/usr/bin/env python
from __future__ import print_function, unicode_literals
import sys
import pytest
if __name__ == '__main__':
sys.exit(pytest.main(sys.argv[1:]))
| #!/usr/bin/env python
from __future__ import print_function, unicode_literals
import sys
import pytest
if __name__ == '__main__':
if len(sys.argv) >= 2 and sys.argv[1] != '--':
args = ['--db', sys.argv[1]] + sys.argv[2:]
else:
args = sys.argv[1:]
sys.exit(pytest.main(args))
| Fix running unit tests through the old test runner. | Fix running unit tests through the old test runner.
The old test runner (currently used in CI) had a regression when moving
to pytest. It failed to convert the first argument (the database name to
run everything against) to the new `pytest --db=` argument.
This change adds this back to the test runner. If an argument... | Python | bsd-3-clause | beanbaginc/django-evolution |
9c1907d1b431281632da187617e857c4911c1ee1 | fmsgame_project/urls.py | fmsgame_project/urls.py | from django.conf.urls.defaults import patterns, url, include
from django.views.generic.simple import direct_to_template
import django.views.static
import settings
import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
... | from django.conf.urls.defaults import patterns, url, include
from django.views.generic.simple import direct_to_template
import django.views.static
import settings
import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
... | Add back in geolocate url name. | Add back in geolocate url name.
| Python | agpl-3.0 | mysociety/fmsgame,mysociety/fmsgame,mysociety/fmsgame |
8dd3457b20b5ce96cf7e0f5029e3541d57ca116d | wqflask/wqflask/decorators.py | wqflask/wqflask/decorators.py | """This module contains gn2 decorators"""
from flask import g
from typing import Dict
from functools import wraps
from utility.hmac import hmac_creation
from utility.tools import GN_PROXY_URL
import json
import requests
def edit_access_required(f):
"""Use this for endpoints where admins are required"""
@wrap... | """This module contains gn2 decorators"""
import hashlib
import hmac
from flask import current_app, g
from typing import Dict
from functools import wraps
import json
import requests
def create_hmac(data: str, secret: str) -> str:
return hmac.new(bytearray(secret, "latin-1"),
bytearray(data, "... | Remove "utility.hmac.hmac_creation" which causes circular imports | Remove "utility.hmac.hmac_creation" which causes circular imports
Hacky but re-implement `hmac_creation` as `create_hmac`
| Python | agpl-3.0 | pjotrp/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2 |
fb1cfd15c646cc076a152acbd823b736f2a46724 | studygroups/migrations/0028_auto_20150806_0039.py | studygroups/migrations/0028_auto_20150806_0039.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('studygroups', '0027_auto_20150513_2005'),
]
operations = [
migrations.CreateModel(
name='Location',
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('studygroups', '0027_auto_20150513_2005'),
]
operations = [
migrations.CreateModel(
name='Location',
... | Fix migration that fails on postgres | Fix migration that fails on postgres
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles |
e78b8704a68b49593b43ac5b9690be36fca2e274 | default_config.py | default_config.py | class DefaultConfig():
secret_key = "LONG_AND_RANDOM"
tmdb_api_key = "THEMOVIEDB.ORG_API_KEY"
| class DefaultConfig():
secret_key = None # Django secret key used for sessions. Make this a long random string and keep it a secret
tmdb_api_key = None # API key for The Movie Database (themoviedb.org).
| Set default config values to none so user is forced to set them. | Set default config values to none so user is forced to set them.
Also document fields in the default config
| Python | mit | simon-andrews/movieman2,simon-andrews/movieman2 |
bc5abf988956235b48aeb1234d9944fe70be619a | pytest_hidecaptured.py | pytest_hidecaptured.py | # -*- coding: utf-8 -*-
def pytest_runtest_logreport(report):
"""Overwrite report by removing any captured stderr."""
# print("PLUGIN SAYS -> report -> {0}".format(report))
# print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections))
# print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(rep... | # -*- coding: utf-8 -*-
import pytest
@pytest.mark.tryfirst
def pytest_runtest_logreport(report):
"""Overwrite report by removing any captured stderr."""
# print("PLUGIN SAYS -> report -> {0}".format(report))
# print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections))
# print("PLUGIN SAYS ... | Fix interop issues with pytest-instafail | Fix interop issues with pytest-instafail
| Python | mit | hamzasheikh/pytest-hidecaptured |
74db127246b7111a35c64079eec91d46f88ebd55 | src/test/stresstest.py | src/test/stresstest.py | #!/usr/bin/env python
# Copyright 2007 Albert Strasheim <fullung@gmail.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/licenses/LICENSE-2.0
#
# Unless requ... | #!/usr/bin/env python
# Copyright 2007 Albert Strasheim <fullung@gmail.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/licenses/LICENSE-2.0
#
# Unless requ... | Test everything with stress test. | Test everything with stress test.
| Python | apache-2.0 | tabish121/pyActiveMQ,tabish121/pyActiveMQ,tabish121/pyActiveMQ |
e422f77898853fc759d3828c4053b799cd2b1fa3 | plumeria/plugins/bot_control.py | plumeria/plugins/bot_control.py | from plumeria.command import commands, CommandError
from plumeria.message.lists import build_list
from plumeria.perms import owners_only
from plumeria.transport import transports
@commands.register('accept invite', category='Discord')
@owners_only
async def accept_invite(message):
"""
Accept an invite to join... | from plumeria.command import commands, CommandError
from plumeria.message.lists import build_list
from plumeria.perms import owners_only
from plumeria.transport import transports
@commands.register('join', category='Discord')
@owners_only
async def join(message):
"""
Accept an invite to join a server.
Ex... | Use /join instead of /accept invite. | Use /join instead of /accept invite.
| Python | mit | sk89q/Plumeria,sk89q/Plumeria,sk89q/Plumeria |
d8da4526375946551fd3963b42f2bb13035abb2d | hijack_admin/tests/test_hijack_admin.py | hijack_admin/tests/test_hijack_admin.py | # -*- coding: utf-8 -*-
from hijack.tests.test_hijack import BaseHijackTests
from hijack.tests.utils import SettingsOverride
from hijack_admin import settings as hijack_admin_settings
from hijack_admin.tests.test_app.models import RelatedModel
class HijackAdminTests(BaseHijackTests):
def setUp(self):
s... | # -*- coding: utf-8 -*-
from hijack.tests.test_hijack import BaseHijackTests
from hijack_admin import settings as hijack_admin_settings
from hijack_admin.tests.test_app.models import RelatedModel
class HijackAdminTests(BaseHijackTests):
def setUp(self):
super(HijackAdminTests, self).setUp()
def tea... | Remove unused import in tests | Remove unused import in tests
| Python | mit | arteria/django-hijack-admin,arteria/django-hijack-admin,arteria/django-hijack-admin |
d69b41307b94db7e8658fd209fdae0e0240bc62a | Monstr/Core/Config.py | Monstr/Core/Config.py | import ConfigParser
Config = ConfigParser.ConfigParser()
import os
print os.getcwd()
try:
Config.read('/opt/monstr/current.cfg')
except Exception as e:
print 'WARNING! Configuration is missing. Using test_conf.cfg'
Config.read('test.cfg')
def get_section(section):
result = {}
if section in Con... | import ConfigParser
Config = ConfigParser.ConfigParser()
import os
print os.getcwd()
try:
Config.read('/opt/monstr/current.cfg')
except Exception as e:
print 'WARNING! Configuration is missing. Using test_conf.cfg'
Config.read('test.cfg')
def get_section(section):
result = {}
if section in Con... | Raise Exception instead of plain string | FIX: Raise Exception instead of plain string
| Python | apache-2.0 | tier-one-monitoring/monstr,tier-one-monitoring/monstr |
ded0d2ced823deeabf860abd9ec5120165ed7fde | djoser/utils.py | djoser/utils.py | from django.contrib.auth import user_logged_in, user_logged_out, login, logout
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from djoser.conf import settings
def encode_uid(pk):
return urlsafe_base64_encode(force_bytes(pk)).de... | from django.contrib.auth import user_logged_in, user_logged_out, login, logout
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from djoser.conf import settings
def encode_uid(pk):
return urlsafe_base64_encode(force_bytes(pk)).de... | Add **kwargs to ActionViewmixin.post() handler | Add **kwargs to ActionViewmixin.post() handler
Details: #359
| Python | mit | sunscrapers/djoser,sunscrapers/djoser,sunscrapers/djoser |
9fefa30f51f1a3c0e4586bc21c36324c6dfbbc87 | test/tst_filepath.py | test/tst_filepath.py | import os
import unittest
import netCDF4
class test_filepath(unittest.TestCase):
def setUp(self):
self.netcdf_file = os.path.join(os.getcwd(), "netcdf_dummy_file.nc")
self.nc = netCDF4.Dataset(self.netcdf_file)
def test_filepath(self):
assert self.nc.filepath() == str(self.netcdf_file... | import os
import unittest
import tempfile
import netCDF4
class test_filepath(unittest.TestCase):
def setUp(self):
self.netcdf_file = os.path.join(os.getcwd(), "netcdf_dummy_file.nc")
self.nc = netCDF4.Dataset(self.netcdf_file)
def test_filepath(self):
assert self.nc.filepath() == str(... | Add test for filepath with non-ascii-chars | Add test for filepath with non-ascii-chars | Python | mit | Unidata/netcdf4-python,Unidata/netcdf4-python,Unidata/netcdf4-python |
42abaca67b742ff343c4f6c5553b9eb9dad28d43 | skeleton/__init__.py | skeleton/__init__.py | """
Basic Template system for project skeleton.
skeleton is similar to the template part of PasteScript but
without any dependencies; it should also be compatible with Python 3.
However in this early phase of development, it only target python 2.5+,
and tests require Mock.
"""
from skeleton.core import Skeleton, Va... | """
Basic Template system for project skeleton.
skeleton is similar to the template part of PasteScript but
without any dependencies.
"""
from skeleton.core import Skeleton, Var
from skeleton.utils import insert_into_file
| Add insert_into_file to skeleton module | Add insert_into_file to skeleton module | Python | bsd-2-clause | dinoboff/skeleton |
15eae70c91cd08f9028944f8b6a3990d3170aa28 | snippet_parser/fr.py | snippet_parser/fr.py | #-*- encoding: utf-8 -*-
import base
def handle_date(template):
year = None
if len(template.params) >= 3:
try:
year = int(unicode(template.params[2]))
except ValueError:
pass
if isinstance(year, int):
# assume {{date|d|m|y|...}}
return ' '.join(map(u... | #-*- encoding: utf-8 -*-
import base
def handle_date(template):
year = None
if len(template.params) >= 3:
try:
year = int(unicode(template.params[2]))
except ValueError:
pass
if isinstance(year, int):
# assume {{date|d|m|y|...}}
return ' '.join(map(u... | Fix params handling in {{s}}. | Fix params handling in {{s}}.
| Python | mit | Stryn/citationhunt,Stryn/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt |
665af108d44e5aa91483bc70c0c76dab9b297d41 | tests/test_api_info.py | tests/test_api_info.py | from tests.types import string
def test_get(test):
def handle_connect(handler):
info = handler.api.get_info()
assert isinstance(info['api_version'], string)
assert isinstance(info['server_timestamp'], string)
if info.get('rest_server_url'):
assert info['websocket_serve... | from tests.types import string
from tests.conftest import not_implemented_skip
def test_get(test):
def handle_connect(handler):
info = handler.api.get_info()
assert isinstance(info['api_version'], string)
assert isinstance(info['server_timestamp'], string)
if info.get('rest_server... | Add not implemeted get cluster | Add not implemeted get cluster
| Python | apache-2.0 | devicehive/devicehive-python |
11103afa4a46cc1835f1479651bcd7c808d6a33c | sdks/python/apache_beam/runners/api/__init__.py | sdks/python/apache_beam/runners/api/__init__.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | Add instructions to regenerate Python proto wrappers. | Add instructions to regenerate Python proto wrappers.
| Python | apache-2.0 | apache/beam,staslev/incubator-beam,jbonofre/beam,iemejia/incubator-beam,lukecwik/incubator-beam,rangadi/beam,wtanaka/beam,rangadi/beam,markflyhigh/incubator-beam,chamikaramj/beam,manuzhang/beam,tgroh/incubator-beam,wangyum/beam,charlesccychen/beam,RyanSkraba/beam,manuzhang/beam,eljefe6a/incubator-beam,apache/beam,charl... |
7176ec5d4abe678d8f0d01baeacf4dc78204b18f | tests/integration/modules/grains.py | tests/integration/modules/grains.py | '''
Test the grains module
'''
import integration
class TestModulesGrains(integration.ModuleCase):
'''
Test the grains module
'''
def test_items(self):
'''
grains.items
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.items')['... | '''
Test the grains module
'''
import integration
class TestModulesGrains(integration.ModuleCase):
'''
Test the grains module
'''
def test_items(self):
'''
grains.items
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.items')['... | Add test to test if os_family grain is provided. | Add test to test if os_family grain is provided.
Corey Quinn reported a issue where __grains__['os_family'] returned a
KeyError. This commits adds a check to the grains module test to ensure
os_family is present.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
892393458612ea78319cceeb98957c34ccb91d2d | django_react_templatetags/encoders.py | django_react_templatetags/encoders.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.serializers.json import DjangoJSONEncoder
from django_react_templatetags.mixins import RepresentationMixin
def json_encoder_cls_factory(context):
class ReqReactRepresentationJSONEncoder(ReactRepresentationJSONEncoder):
conte... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.serializers.json import DjangoJSONEncoder
from django_react_templatetags.mixins import RepresentationMixin
def json_encoder_cls_factory(context):
class ReqReactRepresentationJSONEncoder(ReactRepresentationJSONEncoder):
conte... | Drop support for reacct_representation property | Drop support for reacct_representation property
| Python | mit | Frojd/django-react-templatetags,Frojd/django-react-templatetags,Frojd/django-react-templatetags |
cfe78dabea226e24928d26183f4b135c52b64663 | feder/cases/forms.py | feder/cases/forms.py | # -*- coding: utf-8 -*-
from atom.ext.crispy_forms.forms import SingleButtonMixin
from braces.forms import UserKwargModelFormMixin
from django import forms
from .models import Case
class CaseForm(SingleButtonMixin, UserKwargModelFormMixin, forms.ModelForm):
def __init__(self, *args, **kwargs):
self.moni... | # -*- coding: utf-8 -*-
from atom.ext.crispy_forms.forms import SingleButtonMixin
from braces.forms import UserKwargModelFormMixin
from django import forms
from .models import Case
class CaseForm(SingleButtonMixin, UserKwargModelFormMixin, forms.ModelForm):
def __init__(self, *args, **kwargs):
self.moni... | Clean up form in CaseForm | Clean up form in CaseForm
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder |
06ec0a7f0a6a53fddfb2038b0ae8cc1bad2c8511 | blankspot/node_registration/models.py | blankspot/node_registration/models.py | from django.db import models
class Contact(models.Model):
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
nick = models.CharField(max_length=128)
email = models.EmailField(max_length=254)
def __unicode__(self):
return (self.... | from django.db import models
class Position(models.Model):
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
nick = models.CharField(max_length=128)
email = models.EmailField(max_length=254)
street = models.CharField(max_length=2... | Revert splitting of model as its adding to much complexitiy for the timebeing to later logics IIt's just not adding enought value for having a more complicated implementation. | Revert splitting of model as its adding to much complexitiy for the timebeing to later logics
IIt's just not adding enought value for having a more complicated implementation.
| Python | agpl-3.0 | frlan/blankspot |
b86d88a10839ba642f992dcaf3e69de3a244f984 | golingo/urls.py | golingo/urls.py | """golingo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | """golingo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | Add initial url to question | Add initial url to question
| Python | bsd-3-clause | jesuejunior/golingo,jesuejunior/golingo,jesuejunior/golingo |
4a330e190dcb727cb7483b826f2927b94b081e8a | yardcam.py | yardcam.py | import capture
from picamera import PiCamera
import time
import delay
def image_cap_loop(camera, status=None):
"""Set image parameters, capture image, set wait time, repeat"""
resolution = (1640, 1232)
wait = delay.next_capture() # Delay time in seconds from delay.py
waithours = wait / 60 / 60 # Co... | import capture
from picamera import PiCamera
import time
import delay
def image_cap_loop(camera, status=None):
"""Set image parameters, capture image, set wait time, repeat"""
resolution = (1640, 1232)
# wait = delay.next_capture() # Delay time in seconds from delay.py
wait = 60
waithours = wait... | Remove delay from loop for testing | Remove delay from loop for testing
| Python | mit | gnfrazier/YardCam |
3f6b18304a3f947cc165201a507a672a56af851f | warehouse/cli.py | warehouse/cli.py | # Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | # Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | Remove a useless function call | Remove a useless function call
| Python | apache-2.0 | robhudson/warehouse,mattrobenolt/warehouse,techtonik/warehouse,mattrobenolt/warehouse,mattrobenolt/warehouse,robhudson/warehouse,techtonik/warehouse |
aff8cebfd168493a4a9dff77cf9722507429d570 | contrib/examples/actions/pythonactions/isprime.py | contrib/examples/actions/pythonactions/isprime.py | import math
class PrimeChecker(object):
def run(self, **kwargs):
return self._is_prime(**kwargs)
def _is_prime(self, value=0):
if math.floor(value) != value:
raise ValueError('%s should be an integer.' % value)
if value < 2:
return False
for test in ra... | import math
class PrimeChecker(object):
def run(self, value=0):
if math.floor(value) != value:
raise ValueError('%s should be an integer.' % value)
if value < 2:
return False
for test in range(2, int(math.floor(math.sqrt(value)))+1):
if value % test == ... | Update pythonaction sample for simpler run. | Update pythonaction sample for simpler run.
| Python | apache-2.0 | peak6/st2,lakshmi-kannan/st2,pixelrebel/st2,StackStorm/st2,jtopjian/st2,pinterb/st2,Plexxi/st2,punalpatel/st2,armab/st2,grengojbo/st2,grengojbo/st2,punalpatel/st2,pixelrebel/st2,Itxaka/st2,lakshmi-kannan/st2,emedvedev/st2,lakshmi-kannan/st2,pixelrebel/st2,nzlosh/st2,peak6/st2,dennybaa/st2,pinterb/st2,Plexxi/st2,nzlosh/... |
035ae3b2acf5c29304a1c2ec327feb5cc7160559 | django_vend/core/forms.py | django_vend/core/forms.py | import re
from django import forms
from django.utils.dateparse import parse_datetime
from django.core.exceptions import ValidationError
def valid_date(date):
regex = ("^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13"
"-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[... | import re
from django import forms
from django.utils.dateparse import parse_datetime
from django.core.exceptions import ValidationError
def valid_date(date):
regex = ("^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13"
"-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[... | Allow VendDateTimeField to accept null dates (if required is set to False) | Allow VendDateTimeField to accept null dates (if required is set to False)
| Python | bsd-3-clause | remarkablerocket/django-vend,remarkablerocket/django-vend |
080637c99898082d38b306ef73983552b263e628 | inbox/ignition.py | inbox/ignition.py | from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[Fo... | from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[Fo... | Set pool_recycle to deal with MySQL closing idle connections. | Set pool_recycle to deal with MySQL closing idle connections.
See http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#connection-timeouts
Cherry-picking this onto master so it definitely gets deployed.
| Python | agpl-3.0 | Eagles2F/sync-engine,Eagles2F/sync-engine,ErinCall/sync-engine,ErinCall/sync-engine,ErinCall/sync-engine,PriviPK/privipk-sync-engine,closeio/nylas,Eagles2F/sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,wakermahmud/sync-engine,jobscore/sync-engine,jobscore/sync-engine,Eagles2F/sync-engine,wakermahmud/sync-eng... |
1513532e473866438ac9dabbfb462e9348a5895e | hug/output_format.py | hug/output_format.py | import json as json_converter
from datetime import date, datetime
from hug.format import content_type
def _json_converter(item):
if isinstance(item, (date, datetime)):
return item.isoformat()
elif isinstance(item, bytes):
return item.decode('utf8')
raise TypeError("Type not serializable")... | import json as json_converter
from datetime import date, datetime
from hug.format import content_type
def _json_converter(item):
if isinstance(item, (date, datetime)):
return item.isoformat()
elif isinstance(item, bytes):
return item.decode('utf8')
elif getattr(item, '__json__', None):
... | Add the ability for individual objects to define how they would like there data to be outputed for json | Add the ability for individual objects to define how they would like there data to be outputed for json
| Python | mit | janusnic/hug,yasoob/hug,janusnic/hug,shaunstanislaus/hug,timothycrosley/hug,alisaifee/hug,gbn972/hug,MuhammadAlkarouri/hug,philiptzou/hug,giserh/hug,timothycrosley/hug,STANAPO/hug,shaunstanislaus/hug,STANAPO/hug,origingod/hug,MuhammadAlkarouri/hug,MuhammadAlkarouri/hug,alisaifee/hug,giserh/hug,yasoob/hug,gbn972/hug,phi... |
e507461dba5020726c9505fef187098ad234a68a | kazoo/tests/__init__.py | kazoo/tests/__init__.py | import os
import unittest
import time
import uuid
from kazoo.client import KazooClient, KazooState
# if this env variable is set, ZK client integration tests are run
# against the specified host list
ENV_TEST_HOSTS = "KAZOO_TEST_HOSTS"
def get_hosts_or_skip():
if ENV_TEST_HOSTS in os.environ:
return os.... | import os
import unittest
import time
import uuid
from nose import SkipTest
from kazoo.client import KazooClient, KazooState
# if this env variable is set, ZK client integration tests are run
# against the specified host list
ENV_TEST_HOSTS = "KAZOO_TEST_HOSTS"
def get_hosts_or_skip():
if ENV_TEST_HOSTS in os.... | Use SkipTest that works on Py2.6 | Use SkipTest that works on Py2.6
| Python | apache-2.0 | kormat/kazoo,rackerlabs/kazoo,tempbottle/kazoo,max0d41/kazoo,rgs1/kazoo,rockerbox/kazoo,harlowja/kazoo,kormat/kazoo,rgs1/kazoo,harlowja/kazoo,pombredanne/kazoo,python-zk/kazoo,python-zk/kazoo,pombredanne/kazoo,rockerbox/kazoo,tempbottle/kazoo,AlexanderplUs/kazoo,jacksontj/kazoo,max0d41/kazoo,Asana/kazoo,jacksontj/kazoo... |
f55af10f1767d39fdba65fb4c17beee526f96748 | lib/__init__.py | lib/__init__.py | """retriever.lib contains the core EcoData Retriever modules."""
|
"""retriever.lib contains the core EcoData Retriever modules."""
import os
def set_proxy():
proxies = ["https_proxy", "http_proxy", "ftp_proxy", "HTTP_PROXY", "HTTPS_PROXY", "FTP_PROXY"]
for proxy in proxies:
if os.getenv(proxy):
if len(os.environ[proxy]) != 0:
for i in proxies:
os.env... | Check for and use system proxies for downloading files | Check for and use system proxies for downloading files
In some cases when the user is using a proxy urlib.urlopen() will fail to successfully open https files. This prevents the retriever from accessing the scripts stored on GitHub and causes the installation to fail (see #268). This change checks for the existence of... | Python | mit | embaldridge/retriever,davharris/retriever,davharris/retriever,davharris/retriever,embaldridge/retriever,goelakash/retriever,henrykironde/deletedret,goelakash/retriever,henrykironde/deletedret,embaldridge/retriever |
0867054258e231b2ce9b028c5ce2bc3a26bca7be | gamernews/apps/threadedcomments/views.py | gamernews/apps/threadedcomments/views.py | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from core.models import Account as User
from django_c... | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from core.models import Account as User
from django_c... | Remove name, url and email from comment form | Remove name, url and email from comment form
| Python | mit | underlost/GamerNews,underlost/GamerNews |
8cd11782d4b3558d204f438accdc15b3b702839b | unn/cli.py | unn/cli.py | import sys
commands = {}
args = []
kwargs = {}
def EXIT(msg, code=1):
print(msg)
sys.exit(code)
def command(fn):
commands[fn.__name__] = fn
return fn
def run():
if len(sys.argv) < 2:
EXIT('No command provided')
cmd = sys.argv[1]
if cmd not in commands:
EXIT('Unkown co... | import sys
commands = {}
args = []
kwargs = {}
def EXIT(msg, code=1):
print(msg)
sys.exit(code)
def command(fn):
commands[fn.__name__] = fn
return fn
def run():
if len(sys.argv) < 2:
EXIT('Valid commands are:\n ' + '\n '.join(commands))
cmd = sys.argv[1]
if cmd not in command... | Add a helpful message if no command given | Add a helpful message if no command given
| Python | mit | runningskull/unn |
ab6526b14f5bdc544367bcaa281a861d2314330b | gi2fasta.py | gi2fasta.py | import sys
from Bio import Entrez
from Bio import SeqIO
Entrez.email = "davidsshin@lbl.gov"
infilename = sys.argv[1]
outfilename = sys.argv[2]
with open(infilename) as f:
gi_numbers=', '.join(line.rstrip() for line in f)
handle = Entrez.efetch(db="protein", rettype="fasta", retmode="text", id=gi_numbers)
records... | import sys
#from Bio import Entrez
#from Bio import SeqIO
user_email = "" # User must supply email here to access NCBI api
# Add error message in the event no email address is supplied
if user_email == "":
sys.exit("Error: Please supply your email address to line 5 of gi2fasta.py")
Entrez.email = user_email
inf... | Add error message if User does not enter email address | Add error message if User does not enter email address
| Python | bsd-2-clause | datadaveshin/bioinformatics,datadaveshin/bioinformatics |
10c6112dd343901b502c31655a001e612ed6e441 | api/logs/permissions.py | api/logs/permissions.py | # -*- coding: utf-8 -*-
from rest_framework import permissions
from website.models import Node, NodeLog
from api.nodes.permissions import ContributorOrPublic
from api.base.utils import get_object_or_error
class ContributorOrPublicForLogs(permissions.BasePermission):
def has_object_permission(self, request, vie... | # -*- coding: utf-8 -*-
from rest_framework import permissions
from website.models import Node, NodeLog
from api.nodes.permissions import ContributorOrPublic
from api.base.utils import get_object_or_error
class ContributorOrPublicForLogs(permissions.BasePermission):
def has_object_permission(self, request, vie... | Add case for when there are no node backrefs on logs. Again, this whole method will change when eliminating backrefs from nodelogs is merged. | Add case for when there are no node backrefs on logs. Again, this whole method will change when eliminating backrefs from nodelogs is merged.
| Python | apache-2.0 | doublebits/osf.io,mluo613/osf.io,cwisecarver/osf.io,billyhunt/osf.io,baylee-d/osf.io,caneruguz/osf.io,mattclark/osf.io,Johnetordoff/osf.io,kwierman/osf.io,kwierman/osf.io,amyshi188/osf.io,acshi/osf.io,mfraezz/osf.io,zamattiac/osf.io,pattisdr/osf.io,samchrisinger/osf.io,RomanZWang/osf.io,hmoco/osf.io,alexschiller/osf.io... |
acec4dd403201dec5d22623c37ce1aff3324bc67 | drivnal/remote_snapshot.py | drivnal/remote_snapshot.py | from constants import *
from core_snapshot import CoreSnapshot
import logging
logger = logging.getLogger(APP_NAME)
class RemoteSnapshot(CoreSnapshot):
def _get_path(self):
return ''
def _get_log_path(self):
return ''
def _setup_snapshot(self, last_snapshot):
pass
def set_sta... | from constants import *
from core_snapshot import CoreSnapshot
import logging
logger = logging.getLogger(APP_NAME)
class RemoteSnapshot(CoreSnapshot):
def _get_path(self):
dir_name = str(self.id)
if self.state != COMPLETE:
dir_name = '%s.%s' % (dir_name, self.state)
return '%s@... | Add get path for remote snapshot | Add get path for remote snapshot
| Python | agpl-3.0 | drivnal/drivnal,drivnal/drivnal,drivnal/drivnal |
5b1ab860a0706831b8abc77a060d6ba89cf8946a | interface/subprocess/001.backticks.py | interface/subprocess/001.backticks.py | import subprocess
# --- replacing shell backticks ---
# https://docs.python.org/2/library/subprocess.html#replacing-bin-sh-shell-backquote
# output=`mycmd myarg`
# output = check_output(["mycmd", "myarg"])
# not true, because mycmd is not passed to shell
try:
output = subprocess.check_output(["mycmd", "myarg"]... | import subprocess
# --- replacing shell backticks ---
# https://docs.python.org/2/library/subprocess.html#replacing-bin-sh-shell-backquote
# output=`mycmd myarg`
# output = check_output(["mycmd", "myarg"])
# not true, because mycmd is not passed to shell
try:
output = subprocess.check_output(["mycmd", "myarg"]... | Add docs to backtics function | interface.subprocess: Add docs to backtics function
| Python | unlicense | techtonik/discovery,techtonik/discovery,techtonik/discovery |
91bb9574ec760efd8aba2d9ae8fe67fe2e69d0a2 | jacquard/buckets/tests/test_bucket.py | jacquard/buckets/tests/test_bucket.py | import pytest
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_three_buckets_per_percent():
assert NUM_BUCKETS / 100 >= 3
| import pytest
from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_thr... | Add a test for getting an empty bucket | Add a test for getting an empty bucket
| Python | mit | prophile/jacquard,prophile/jacquard |
6c4e94f1133c9c9cd18b97a386f04f56b229f9a8 | las_reader/las2excel.py | las_reader/las2excel.py | try:
import argparse
except ImportError:
argparse = None
import sys
import core
def main():
if argparse:
args = get_parser().parse_args(sys.argv[1:])
lasfn = args.las_filename
xlsfn = args.xls_filename
else:
if len(sys.argv >= 3):
lasfn = sys.argv[1]
... | try:
import argparse
except ImportError:
argparse = None
import sys
import core
def main():
if argparse:
args = get_parser().parse_args(sys.argv[1:])
print args.__dict__.keys()
lasfn = args.las_filename
xlsfn = args.xls_filename
else:
if len(sys.argv >= 3):... | Fix Namespace for cmd line args | Fix Namespace for cmd line args
| Python | mit | kinverarity1/las-reader,Kramer477/lasio,kinverarity1/lasio,VelizarVESSELINOV/las-reader,kwinkunks/lasio |
ccb774b58ab7dbe704abfb7df3fa29915fad8f8f | examples/memnn/download.py | examples/memnn/download.py | #!/usr/bin/env python
from six.moves.urllib import request
def main():
opener = request.FancyURLopener()
opener.addheaders = [('User-Agent', '')]
opener.retrieve(
'http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz',
'tasks_1-20_v1-2.tar.gz')
if __name__ == '__main__':
... | #!/usr/bin/env python
from six.moves.urllib import request
def main():
request.urlretrieve(
'http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz',
'tasks_1-20_v1-2.tar.gz')
if __name__ == '__main__':
main()
| Replace deprecated URLopener in `donwload.py` | Replace deprecated URLopener in `donwload.py`
| Python | mit | niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,wkentaro/chainer,pfnet/chainer,keisuke-umezawa/chainer,wkentaro/chainer,niboshi/chainer,niboshi/chainer,okuta/chainer,okuta/chainer,chainer/chainer,hvy/chainer,chainer/chainer,keisuke-umezawa/chainer,wkentaro/chainer,okuta/chainer,keisuke-umezawa/chainer,hvy/chai... |
361ebc774fba5489c1911ac40dde4828f6cbd374 | flysight_manager/report.py | flysight_manager/report.py | #!/usr/bin/env python
import log
from jinja2 import Template
import traceback
class Report(object):
def __init__(self):
self.logs = log.LogAggregator.new()
def format_exception_as_reason(exc):
return traceback.format_exc(exc)
@log.make_loggable
class UploadReport(Report):
TEMPLATE_FILENAME = '... | #!/usr/bin/env python
import log
import time
from jinja2 import Template
import traceback
class Report(object):
TIME_FMT = ": %y/%m/%d %H:%M %z (%Z)"
def __init__(self):
self.logs = log.LogAggregator.new()
self.started = time.strftime(TIME_FMT)
def format_exception_as_reason(exc):
return ... | Include the time in the email | Include the time in the email
| Python | mit | richo/flysight-manager,richo/flysight-manager |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.