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 |
|---|---|---|---|---|---|---|---|---|---|
b7d8daf8377fff86662bb8721b1008667e8a4767 | gstorage/__init__.py | gstorage/__init__.py | # -*- coding: utf-8 -*-
"""
"""
__version__ = "0.0.1.1"
__author__ = "Fyndiq"
__license__ = "MIT"
__copyright__ = "Copyright 2016 Fyndiq AB"
| # -*- coding: utf-8 -*-
"""
django-gstorage
~~~~~~~~~~~~~~~
A plug-and-play replacement for FileSystemStorage but
using Google storage for persistence
"""
__version__ = '0.0.1.1'
__author__ = 'Fyndiq'
__license__ = 'MIT'
__copyright__ = 'Copyright 2016 Fyndiq AB'
| Add a one-liner about module functionality and tidy double quotes | Add a one-liner about module functionality and tidy double quotes
| Python | mit | fyndiq/django-gstorage |
cd67e3d2419fd84fd11e469d17562bba19131099 | looknsay.py | looknsay.py | #!/usr/bin/env python3
from argparse import ArgumentParser
from itertools import groupby
def iterate(n):
result = 0
digits = [int(i) for i in str(n)]
for k, g in groupby(digits):
result = result * 100 + len(tuple(g)) * 10 + k
return result
def compute(n, i=20):
yield n
x = n
for... | #!/usr/bin/env python3
from argparse import ArgumentParser
from itertools import groupby
def iterate(n):
result = 0
digits = [int(i) for i in str(n)]
for k, g in groupby(digits):
result = result * 100 + len(tuple(g)) * 10 + k
return result
def compute(n, i=20):
yield n
x = n
for... | Add option to print only last step of iteration. | Add option to print only last step of iteration.
| Python | unlicense | jajakobyly/looknsay |
e0055226a9d10d726fcde948ea72ac2e84f8109a | falafel/__init__.py | falafel/__init__.py | import os
from .core import LogFileOutput, Mapper, IniConfigFile, LegacyItemAccess # noqa: F401
from .core.plugins import mapper, reducer, make_response, make_metadata # noqa: F401
from .mappers import get_active_lines # noqa: F401
from .util import defaults, parse_table # noqa: F401
__here__ = os.path.dirname(os.... | import os
from .core import LogFileOutput, Mapper, IniConfigFile, LegacyItemAccess # noqa: F401
from .core import FileListing # noqa: F401
from .core.plugins import mapper, reducer, make_response, make_metadata # noqa: F401
from .mappers import get_active_lines # noqa: F401
from .util import defaults, parse_table ... | Add FileListing to objects we export | Add FileListing to objects we export
| Python | apache-2.0 | RedHatInsights/insights-core,RedHatInsights/insights-core |
25f2692d5865a76533f8087c2f566299ae777c8e | conman/redirects/views.py | conman/redirects/views.py | from django.views.generic import RedirectView
class RouteRedirectView(RedirectView):
"""Redirect to the target Route."""
def get_redirect_url(self, *args, **kwargs):
"""
Return the route's target url.
Save the route's redirect type for use by RedirectView.
"""
redirect... | from django.views.generic import RedirectView
class RouteRedirectView(RedirectView):
"""Redirect to the target Route."""
permanent = True # Set to django 1.9's default to avoid RemovedInDjango19Warning
def get_redirect_url(self, *args, **kwargs):
"""
Return the route's target url.
... | Set variable to future default | Set variable to future default
Deprecation warning was:
RemovedInDjango19Warning: Default value of 'RedirectView.permanent' will
change from True to False in Django 1.9. Set an explicit value to
silence this warning.
| Python | bsd-2-clause | meshy/django-conman,meshy/django-conman,Ian-Foote/django-conman |
38e25c5219476f51ca391fcea5e629177f4dde84 | daisyproducer/documents/storage.py | daisyproducer/documents/storage.py | """
A storage implementation that overwrites exiting files in the storage
See "Writing a custom storage system"
(https://docs.djangoproject.com/en/1.3/howto/custom-file-storage/) and
the discussion on stackoverflow on "ImageField overwrite image file"
(http://stackoverflow.com/questions/9522759/imagefield-overwrite-im... | """
A storage implementation that overwrites exiting files in the storage
See "Writing a custom storage system"
(https://docs.djangoproject.com/en/1.3/howto/custom-file-storage/) and
the discussion on stackoverflow on "ImageField overwrite image file"
(http://stackoverflow.com/questions/9522759/imagefield-overwrite-im... | Migrate to new Storage API | Migrate to new Storage API
for Django 1.8
| Python | agpl-3.0 | sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer |
7cc1a78d4fefcb216a6c8d5128d05ba9e70f5246 | jazzband/hooks.py | jazzband/hooks.py | from flask.ext.hookserver import Hooks
from .models import db, User
hooks = Hooks()
@hooks.hook('ping')
def ping(data, guid):
return 'pong'
@hooks.hook('membership')
def membership(data, guid):
if data['scope'] != 'team':
return
member = User.query.filter_by(id=data['member']['id']).first()
... | from flask.ext.hookserver import Hooks
from .models import db, User
hooks = Hooks()
@hooks.hook('ping')
def ping(data, guid):
return 'pong'
@hooks.hook('membership')
def membership(data, guid):
if data['scope'] != 'team':
return
member = User.query.filter_by(id=data['member']['id']).first()
... | Return a response for the membership webhook. | Return a response for the membership webhook.
| Python | mit | jazzband/website,jazzband/website,jazzband/website,jazzband/site,jazzband/jazzband-site,jazzband/site,jazzband/jazzband-site,jazzband/website |
7ce8e8e217e80098ce2b6371dd6c117009843602 | pyxform/tests_v1/test_whitespace.py | pyxform/tests_v1/test_whitespace.py | from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class WhitespaceTest(PyxformTestCase):
def test_over_trim(self):
self.assertPyxformXform(
name='issue96',
md="""
| survey | | | |
| | type | l... | from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class WhitespaceTest(PyxformTestCase):
def test_over_trim(self):
self.assertPyxformXform(
name='issue96',
md="""
| survey | | | |
| | type | l... | Remove test that can't be fulfilled | Remove test that can't be fulfilled
| Python | bsd-2-clause | XLSForm/pyxform,XLSForm/pyxform |
f00e8bcadd3d71ed8ab797073a744f5d3d9648ea | wrapper.py | wrapper.py | #!/usr/bin/env python
#
# Copyright (C) 2014 The Android Open Source Project
#
# 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 req... | #!/usr/bin/env python
#
# Copyright (C) 2014 The Android Open Source Project
#
# 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 req... | Remove redundant 'repo' in WrapperPath() | Remove redundant 'repo' in WrapperPath()
| Python | apache-2.0 | jcfrank/myrepo,jcfrank/myrepo |
20d766de4d20355303b5b423dd30bf0cd4c8ee8e | createGlyphsPDF.py | createGlyphsPDF.py | from fontTools.pens.cocoaPen import CocoaPen
# Some configuration
page_format = 'A4' # See http://drawbot.readthedocs.org/content/canvas/pages.html#size for other size-values
my_selection = CurrentFont() # May also be CurrentFont.selection or else
class RegisterGlyph(object):
def __init__(self, glyph):
... | from fontTools.pens.cocoaPen import CocoaPen
# Some configuration
page_format = 'A4' # See http://drawbot.readthedocs.org/content/canvas/pages.html#size for other size-values
margins = (50,50,50,50) # left, top, right, bottom
my_selection = CurrentFont() # May also be CurrentFont.selection or else
# Init
size(page_fo... | Set size nonce at the beginning of the script | Set size nonce at the beginning of the script
| Python | mit | AlphabetType/DrawBot-Scripts |
46e20cb4ac6571b922968674f2127318eef68821 | common/utilities/throttling.py | common/utilities/throttling.py | from rest_framework import throttling
class ThrottlingBySession(throttling.SimpleRateThrottle):
"""
Limits the rating of facility service to only 10 per day per IP.
This rate is configurable at the DRF settings.DEFAULT_THROTTLE_RATES.
The rate will apply to both the publc user and other authenticated... | from rest_framework import throttling
class ThrottlingBySession(throttling.SimpleRateThrottle):
"""
Limits the rating of facility service to only 10 per day per IP.
This rate is configurable at the DRF settings.DEFAULT_THROTTLE_RATES.
The rate will apply to both the publc user and other authenticated... | Remove is_autheticated check as by default all the endpoints are authenticated | Remove is_autheticated check as by default all the endpoints are authenticated
| Python | mit | MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api |
7125760a5d824ebe4bab81d688113a877f1c78c3 | csvkit/__init__.py | csvkit/__init__.py | #!/usr/bin/env python
from csvkit.unicsv import UnicodeCSVReader, UnicodeCSVWriter
class CSVKitReader(UnicodeCSVReader):
"""
A unicode-aware CSV reader with some additional features.
"""
pass
class CSVKitWriter(UnicodeCSVWriter):
"""
A unicode-aware CSV writer with some additional features.
... | #!/usr/bin/env python
from csvkit.unicsv import UnicodeCSVReader, UnicodeCSVWriter
class CSVKitReader(UnicodeCSVReader):
"""
A unicode-aware CSV reader with some additional features.
"""
pass
class CSVKitWriter(UnicodeCSVWriter):
"""
A unicode-aware CSV writer with some additional features.
... | Fix serialization bug in CSVKitWriter that was breaking 4 tests. | Fix serialization bug in CSVKitWriter that was breaking 4 tests.
| Python | mit | archaeogeek/csvkit,Tabea-K/csvkit,Jobava/csvkit,kyeoh/csvkit,moradology/csvkit,tlevine/csvkit,doganmeh/csvkit,bmispelon/csvkit,reubano/csvkit,wireservice/csvkit,wjr1985/csvkit,aequitas/csvkit,barentsen/csvkit,dannguyen/csvkit,arowla/csvkit,themiurgo/csvkit,KarrieK/csvkit,haginara/csvkit,onyxfish/csvkit,metasoarous/csvk... |
3be0c6c18a61f35ae5804464cc0da867fd0065f5 | tests/test_ez_setup.py | tests/test_ez_setup.py | import sys
import os
import tempfile
import unittest
import shutil
import copy
CURDIR = os.path.abspath(os.path.dirname(__file__))
TOPDIR = os.path.split(CURDIR)[0]
sys.path.insert(0, TOPDIR)
from ez_setup import (use_setuptools, _python_cmd, _install)
import ez_setup
class TestSetup(unittest.TestCase):
def url... | import sys
import os
import tempfile
import unittest
import shutil
import copy
CURDIR = os.path.abspath(os.path.dirname(__file__))
TOPDIR = os.path.split(CURDIR)[0]
sys.path.insert(0, TOPDIR)
from ez_setup import _python_cmd, _install
import ez_setup
class TestSetup(unittest.TestCase):
def urlopen(self, url):
... | Remove test for use_setuptools, as it fails when running under pytest because the installed version of setuptools is already present. | Remove test for use_setuptools, as it fails when running under pytest because the installed version of setuptools is already present.
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
d9ffd877f646b3a5c020ed823d3541135af74fef | tests/test_question.py | tests/test_question.py | from pywatson.question.question import Question
class TestQuestion:
def test___init___basic(self, questions):
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
def test_ask_question_basic(self, watson):
answer = watson.ask_... | from pywatson.question.evidence_request import EvidenceRequest
from pywatson.question.filter import Filter
from pywatson.question.question import Question
class TestQuestion(object):
"""Unit tests for the Question class"""
def test___init___basic(self, questions):
"""Question is constructed properly ... | Add complete question constructor test | Add complete question constructor test
| Python | mit | sherlocke/pywatson |
4ade8ef1f53340a9efd053eeae1694724187c4be | scripts/poweron/DRAC.py | scripts/poweron/DRAC.py | import subprocess, sys, os.path
class DRAC_NO_SUPP_PACK(Exception):
"""Base Exception class for all transfer plugin errors."""
def __init__(self, *args):
Exception.__init__(self, *args)
class DRAC_POWERON_FAILED(Exception):
"""Base Exception class for all transfer plugin errors."""
def... | import subprocess, sys, os.path
class DRAC_NO_SUPP_PACK(Exception):
"""Base Exception class for all transfer plugin errors."""
def __init__(self, *args):
Exception.__init__(self, *args)
class DRAC_POWERON_FAILED(Exception):
"""Base Exception class for all transfer plugin errors."""
def... | Change path to the supplemental pack | CA-40618: Change path to the supplemental pack
Signed-off-by: Javier Alvarez-Valle <cf4c8668a0b4c5e013f594a6940d05b3d4d9ddcf@citrix.com>
| Python | lgpl-2.1 | srowe/xen-api,koushikcgit/xen-api,koushikcgit/xen-api,agimofcarmen/xen-api,anoobs/xen-api,euanh/xen-api,Frezzle/xen-api,agimofcarmen/xen-api,simonjbeaumont/xen-api,srowe/xen-api,cheng-z/xen-api,djs55/xen-api,agimofcarmen/xen-api,thomassa/xen-api,rafalmiel/xen-api,ravippandey/xen-api,rafalmiel/xen-api,vasilenkomike/xen-... |
f8d3477dc4a496d648ac6bfd8d26eeacd853200f | src/masterfile/formatters.py | src/masterfile/formatters.py | # -*- coding: utf-8 -*-
# Part of the masterfile package: https://github.com/njvack/masterfile
# Copyright (c) 2017 Board of Regents of the University of Wisconsin System
# Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds
# at the University of Wisconsin-Madison.
# Released under MIT licence; see... | # -*- coding: utf-8 -*-
# Part of the masterfile package: https://github.com/njvack/masterfile
# Copyright (c) 2017 Board of Regents of the University of Wisconsin System
# Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds
# at the University of Wisconsin-Madison.
# Released under MIT licence; see... | Replace index_to_column_id with iterative fx | Replace index_to_column_id with iterative fx
The recursive one was neat but a bit too clever. | Python | mit | njvack/masterfile |
5e25577d067f891474c722000327026744068e88 | src/unittest/python/permission_lambda_tests.py | src/unittest/python/permission_lambda_tests.py | from unittest2 import TestCase
import simplejson as json
import boto3
from moto import mock_s3
import permission_lambda
class PermissionLambdaTests(TestCase):
def _get_permission_statements(self, client, queue_url):
""" Return a list of policy statements for given queue"""
policy_response = client... | from unittest2 import TestCase
import simplejson as json
import boto3
from moto import mock_s3
import permission_lambda
class PermissionLambdaTests(TestCase):
@mock_s3
def test_get_usofa_accountlist_from_bucket(self):
bucketname = "testbucket"
usofa_data = {
"account1": {
... | Remove Unittests done as integrationtests, due to NotImplementedErrors from moto | PIO-129: Remove Unittests done as integrationtests, due to NotImplementedErrors from moto
| Python | apache-2.0 | ImmobilienScout24/aws-set-sqs-permission-lambda |
5fd04a337dd6fec1afc9bf53b437cce01e4fef9e | myDevices/os/threadpool.py | myDevices/os/threadpool.py | from concurrent.futures import ThreadPoolExecutor
from myDevices.utils.singleton import Singleton
import inspect
executor = ThreadPoolExecutor(max_workers=4)
class ThreadPool(Singleton):
def Submit(something):
future = executor.submit(something)
def SubmitParam(*arg):
executor.submit(*arg)
def Shutdown():
ex... | """
This module provides a singleton thread pool class
"""
from concurrent.futures import ThreadPoolExecutor
from myDevices.utils.singleton import Singleton
executor = ThreadPoolExecutor(max_workers=4)
class ThreadPool(Singleton):
"""Singleton thread pool class"""
@staticmethod
def Submit(func):
"... | Clean up thread pool code. | Clean up thread pool code.
| Python | mit | myDevicesIoT/Cayenne-Agent,myDevicesIoT/Cayenne-Agent |
43776062a15640c62d94d8a9c19edadb21a773be | lab/trace_sample.py | lab/trace_sample.py | import os, sys
global nest
nest = 0
def trace(frame, event, arg):
#if event == 'line':
global nest
print "%s%s %s %d (%r)" % (
" " * nest,
event,
os.path.basename(frame.f_code.co_filename),
frame.f_lineno,
arg
)
if event == '... | import os, sys
global nest
nest = 0
def trace(frame, event, arg):
#if event == 'line':
global nest
print "%s%s %s %d" % (
" " * nest,
event,
os.path.basename(frame.f_code.co_filename),
frame.f_lineno,
)
if event == 'call':
ne... | Remove a little noise from this lab tool | Remove a little noise from this lab tool
| Python | apache-2.0 | hugovk/coveragepy,jayhetee/coveragepy,larsbutler/coveragepy,7WebPages/coveragepy,hugovk/coveragepy,nedbat/coveragepy,7WebPages/coveragepy,nedbat/coveragepy,nedbat/coveragepy,hugovk/coveragepy,blueyed/coveragepy,jayhetee/coveragepy,blueyed/coveragepy,blueyed/coveragepy,7WebPages/coveragepy,nedbat/coveragepy,blueyed/cove... |
1028e1a6e15af5a20caedd5598cebc49c5486f64 | scripts/iepy_runner.py | scripts/iepy_runner.py | """
Run IEPY core loop
Usage:
iepy_runner.py <dbname> <seeds_file>
iepy_runner.py -h | --help | --version
Options:
-h --help Show this screen
--version Version number
"""
import pprint
from docopt import docopt
from iepy.core import BootstrappedIEPipeline
from iepy import db
from... | """
Run IEPY core loop
Usage:
iepy_runner.py <dbname> <seeds_file> <output_file>
iepy_runner.py -h | --help | --version
Options:
-h --help Show this screen
--version Version number
"""
import pprint
from docopt import docopt
from iepy.core import BootstrappedIEPipeline
from iepy ... | Add <output_file> parameter to the IEPY runner script. | Add <output_file> parameter to the IEPY runner script.
| Python | bsd-3-clause | mrshu/iepy,machinalis/iepy,machinalis/iepy,mrshu/iepy,machinalis/iepy,mrshu/iepy |
a79bb92e976eee795cb3118b3a03f5f0df11e14d | deepchem/feat/__init__.py | deepchem/feat/__init__.py | """
Making it easy to import in classes.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
__author__ = "Bharath Ramsundar"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "GPL"
from deepchem.feat.base_classes import Featurizer
from d... | """
Making it easy to import in classes.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
__author__ = "Bharath Ramsundar"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "GPL"
from deepchem.feat.base_classes import Featurizer
from d... | Add CoulombMatrix to dc.feat import | Add CoulombMatrix to dc.feat import
| Python | mit | ktaneishi/deepchem,ktaneishi/deepchem,ktaneishi/deepchem,miaecle/deepchem,joegomes/deepchem,peastman/deepchem,miaecle/deepchem,rbharath/deepchem,miaecle/deepchem,Agent007/deepchem,rbharath/deepchem,peastman/deepchem,deepchem/deepchem,lilleswing/deepchem,joegomes/deepchem,Agent007/deepchem,deepchem/deepchem,Agent007/dee... |
a65eea671a605bdeef70160e2d967a59888fcd1b | molml/features.py | molml/features.py | from .atom import * # NOQA
from .molecule import * # NOQA
| from .atom import * # NOQA
from .molecule import * # NOQA
from .crystal import * # NOQA
from .kernel import * # NOQA
| Add default import for crystal and kernel | Add default import for crystal and kernel
| Python | mit | crcollins/molml |
84bf7bd05b683890e817efb6d26f7176cf555f04 | rapydo/do/__main__.py | rapydo/do/__main__.py | # -*- coding: utf-8 -*-
"""
Command line script main
"""
from rapydo.do.app import Application
import better_exceptions as be
def main():
be # activate better exceptions
Application()
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
"""
Command line script: main function
"""
import better_exceptions as be
from rapydo.do.app import Application
from rapydo.utils.logs import get_logger
log = get_logger(__name__)
def main():
be # activate better exceptions
try:
Application()
except KeyboardInterrup... | Handle nicely keyboard interruption (ctrl+c) | Handle nicely keyboard interruption (ctrl+c)
| Python | mit | rapydo/do |
fe974197217eff350f1dc0bc5687c83066d6dd34 | kaggle_tools/features_engineering/dates_engineering.py | kaggle_tools/features_engineering/dates_engineering.py | import pandas as pd
def date_features(input_df, datetime_column='tms_gmt'):
"""
Given a datetime column, extracts useful date information
(minute, hour, dow...)
"""
df = input_df.copy()
return (df.set_index(time_column)
.assign(minute=lambda df: df.index.minute,
... | import pandas as pd
import pytz
def date_features(input_df, datetime_column='tms_gmt'):
"""
Given a datetime column, extracts useful date information
(minute, hour, dow...)
"""
df = input_df.copy()
return (df.set_index(time_column)
.assign(minute=lambda df: df.index.minute,
... | Add a datetime localization function | Add a datetime localization function
| Python | mit | yassineAlouini/kaggle-tools,yassineAlouini/kaggle-tools |
cdb10489382144f77dbe720f230ae92020ffb66c | messaging/test/test_message.py | messaging/test/test_message.py | """Tests the message framework."""
import threading
import time
import unittest
from messaging.message_consumer import consume_messages
from messaging.message_producer import MessageProducer
class TestMessage(unittest.TestCase):
"""Tests the message framework."""
EXCHANGE = 'test'
def setUp(self):
... | """Tests the message framework."""
import threading
import time
import unittest
from messaging.message_consumer import consume_messages
from messaging.message_producer import MessageProducer
class TestMessage(unittest.TestCase):
"""Tests the message framework."""
EXCHANGE = 'test'
def setUp(self):
... | Make messaging test more reliable | Make messaging test more reliable
| Python | mit | bskari/sparkfun-avc,bskari/sparkfun-avc,bskari/sparkfun-avc,bskari/sparkfun-avc,bskari/sparkfun-avc,bskari/sparkfun-avc |
8b7d8919afa12f33bed096f49780914f8878163f | brew/__init__.py | brew/__init__.py | from flask import Flask
from flask.ext.pymongo import PyMongo
from flask.ext.babel import Babel
from flask.ext.cache import Cache
from brew.io import TemperatureController
from brew.state import Machine
app = Flask(__name__)
app.config.from_object('brew.settings')
babel = Babel(app)
cache = Cache(app)
mongo = PyMong... | from flask import Flask
from flask.ext.pymongo import PyMongo
from flask.ext.babel import Babel
from flask.ext.cache import Cache
from brew.io import TemperatureController
from brew.state import Machine
app = Flask(__name__)
app.config.from_object('brew.settings')
app.config.from_pyfile('brewmeister.cfg', silent=True... | Allow loading settings from brewmeister.cfg | Allow loading settings from brewmeister.cfg
| Python | mit | brewpeople/brewmeister,brewpeople/brewmeister,brewpeople/brewmeister |
e64acbdf756839adf28320641124ee696d38be54 | crispy_forms/tests/runtests.py | crispy_forms/tests/runtests.py | #!/usr/bin/env python
import os
import sys
cmds = [
'python runtests_bootstrap.py',
'python runtests_bootstrap3.py',
'python runtests_uniform.py',
]
for cmd in cmds:
retval = os.system(cmd)
if retval:
sys.exit(1)
| #!/usr/bin/env python
import os
import sys
import django
if django.VERSION < (1,6):
cmds = [
'python runtests_bootstrap_legacy.py',
'python runtests_bootstrap3_legacy.py',
'python runtests_uniform_legacy.py',
]
else:
cmds = [
'python runtests_bootstrap.py',
'python ... | Use old legacy runtest files for Django 1.4 | Use old legacy runtest files for Django 1.4
| Python | mit | ngenovictor/django-crispy-forms,jtyoung/django-crispy-forms,VishvajitP/django-crispy-forms,davidszotten/django-crispy-forms,jtyoung/django-crispy-forms,schrd/django-crispy-forms,django-crispy-forms/django-crispy-forms,dzhuang/django-crispy-forms,davidszotten/django-crispy-forms,ngenovictor/django-crispy-forms,RamezIssa... |
ca6d0c5f0fc61ce7d939e49f276c36c5cb12a589 | backend/globaleaks/tests/utils/test_zipstream.py | backend/globaleaks/tests/utils/test_zipstream.py | # -*- encoding: utf-8 -*-
import os
from zipfile import ZipFile
from twisted.internet.defer import inlineCallbacks
from globaleaks.db.datainit import load_appdata
from globaleaks.settings import GLSettings
from globaleaks.tests import helpers
from globaleaks.utils.zipstream import ZipStream, get_compression_opts
cl... | # -*- encoding: utf-8 -*-
import os
from zipfile import ZipFile
from twisted.internet.defer import inlineCallbacks
from globaleaks.db.datainit import load_appdata
from globaleaks.settings import GLSettings
from globaleaks.tests import helpers
from globaleaks.utils.zipstream import ZipStream
class TestCollection(hel... | Simplify zipstream following the simplification of the zip routines implemented | Simplify zipstream following the simplification of the zip routines implemented
| Python | agpl-3.0 | vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks |
cdb66acf92dae34d1b17c2a429738c73fb06caad | scoring/checks/ldap.py | scoring/checks/ldap.py | from __future__ import absolute_import
from config import config
import ldap
# DEFAULTS
ldap_config = {
'timeout': 5
}
# /DEFAULTS
# CONFIG
if "ldap" in config:
ldap_config.update(config["ldap"])
# /CONFIG
def check_ldap_lookup(check, data):
check.addOutput("ScoreEngine: %s Check\n" % (check.getServiceName()))
c... | from __future__ import absolute_import
from config import config
import ldap
# DEFAULTS
ldap_config = {
'timeout': 5
}
# /DEFAULTS
# CONFIG
if "ldap" in config:
ldap_config.update(config["ldap"])
# /CONFIG
def check_ldap_lookup(check, data):
check.addOutput("ScoreEngine: %s Check\n" % (check.getServiceName()))
c... | Make LDAP check even better | Make LDAP check even better
| Python | mit | ubnetdef/scoreengine,ubnetdef/scoreengine |
7576d63bc2061074a41685c69546a4a5d57bc3fb | unihan_db/__about__.py | unihan_db/__about__.py | __title__ = 'unihan-db'
__package_name__ = 'unihan_db'
__description__ = 'SQLAlchemy models for UNIHAN database'
__version__ = '0.1.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/cihai/unihan-db'
__pypi__ = 'https://pypi.org/project/unihan-db/'
__email__ = 'cihai@git-pull.com'
__license__ = 'MIT'
__cop... | __title__ = 'unihan-db'
__package_name__ = 'unihan_db'
__description__ = 'SQLAlchemy models for UNIHAN database'
__version__ = '0.1.0'
__author__ = 'Tony Narlock'
__github__ = 'https://github.com/cihai/unihan-db'
__docs__ = 'https://unihan-db.git-pull.com'
__tracker__ = 'https://github.com/cihai/unihan-db/issues'
__pyp... | Add docs and tracker to metadata | Add docs and tracker to metadata
| Python | mit | cihai/unihan-db |
6b97c1bdcb7d7152c7c0a14833caadbf3aa5ad04 | lms/djangoapps/coursewarehistoryextended/fields.py | lms/djangoapps/coursewarehistoryextended/fields.py | """
Custom fields for use in the coursewarehistoryextended django app.
"""
from django.db.models.fields import AutoField
class UnsignedBigIntAutoField(AutoField):
"""
An unsigned 8-byte integer for auto-incrementing primary keys.
"""
def db_type(self, connection):
if connection.settings_dict[... | """
Custom fields for use in the coursewarehistoryextended django app.
"""
from django.db.models.fields import AutoField
class UnsignedBigIntAutoField(AutoField):
"""
An unsigned 8-byte integer for auto-incrementing primary keys.
"""
def db_type(self, connection):
if connection.settings_dict[... | Add a rel_db_type to UnsignedBigIntAutoField | Add a rel_db_type to UnsignedBigIntAutoField
| Python | agpl-3.0 | proversity-org/edx-platform,angelapper/edx-platform,gymnasium/edx-platform,kmoocdev2/edx-platform,jolyonb/edx-platform,TeachAtTUM/edx-platform,cpennington/edx-platform,kmoocdev2/edx-platform,edx/edx-platform,eduNEXT/edunext-platform,angelapper/edx-platform,ahmedaljazzar/edx-platform,kmoocdev2/edx-platform,hastexo/edx-p... |
7ed3ba20aae568d0c12ec361210d1189ecd534cf | lazysignup/backends.py | lazysignup/backends.py | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
class LazySignupBackend(ModelBackend):
def authenticate(self, username=None):
users = [u for u in User.objects.filter(username=username)
if not u.has_usable_password()]
if len(users) ... | from django.contrib.auth.backends import ModelBackend
from lazysignup.models import LazyUser
class LazySignupBackend(ModelBackend):
def authenticate(self, username=None):
lazy_users = LazyUser.objects.filter(
user__username=username
).select_related('user')
try:
ret... | Remove the lazy signup backend's hard dependency on django.contrib.auth.user (and remove the inconsistency in checking for whether a user is lazy or not). | Remove the lazy signup backend's hard dependency on django.contrib.auth.user (and remove the inconsistency in checking for whether a user is lazy or not). | Python | bsd-3-clause | stefanklug/django-lazysignup,rwillmer/django-lazysignup,rwillmer/django-lazysignup,danfairs/django-lazysignup,stefanklug/django-lazysignup,danfairs/django-lazysignup |
501bcb9aab561f9155857e1601a303374ae5698c | byceps/typing.py | byceps/typing.py | """
byceps.typing
~~~~~~~~~~~~~
BYCEPS-specific type aliases for PEP 484 type hints
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from uuid import UUID
UserID = UUID
BrandID = str
PartyID = str
| """
byceps.typing
~~~~~~~~~~~~~
BYCEPS-specific type aliases for PEP 484 type hints
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import NewType
from uuid import UUID
UserID = NewType('UserID', UUID)
BrandID = NewType('BrandID', str)
PartyID = NewType... | Make BYCEPS-specific types actual lightweight types | Make BYCEPS-specific types actual lightweight types
This makes mypy report the custom type names in error messages instead of the existing types the alias.
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps |
b66171d0b3d8cdf361f4341976d7eb0830fb38ce | dribdat/boxout/dribdat.py | dribdat/boxout/dribdat.py | """Boxout module for Dribdat projects."""
import pystache
TEMPLATE_PROJECT = r"""
<div class="onebox honeycomb">
<a href="{{link}}"
class="hexagon
{{#is_challenge}}challenge{{/is_challenge}}
{{^is_challenge}}project stage-{{progress}}{{/is_challenge}}">
<div class="hexagontent">
... | """Boxout module for Dribdat projects."""
import pystache
TEMPLATE_PROJECT = r"""
<div class="onebox honeycomb">
<a href="{{link}}"
class="hexagon
{{#is_challenge}}challenge{{/is_challenge}}
{{^is_challenge}}project stage-{{progress}}{{/is_challenge}}">
<div class="hexagontent">
... | Fix project links broken by anchor | Fix project links broken by anchor
| Python | mit | loleg/dribdat,loleg/dribdat,loleg/dribdat,loleg/dribdat |
a7058352df6cd8c0e411df5e1b0948729f8ffe60 | dezede/__init__.py | dezede/__init__.py | # coding: utf-8
from __future__ import unicode_literals
__version__ = 1, 8, 3
get_version = lambda: '.'.join(str(i) for i in __version__)
__verbose_name__ = 'Dezède'
| # coding: utf-8
from __future__ import unicode_literals
__version__ = 2, 0, 0, 'pre'
get_version = lambda: '.'.join(str(i) for i in __version__)
__verbose_name__ = 'Dezède'
| Change le numéro de version pour 2.0.0.pre | Change le numéro de version pour 2.0.0.pre
| Python | bsd-3-clause | dezede/dezede,dezede/dezede,dezede/dezede,dezede/dezede |
8f04b56a842fa1a84e704af3c5b724c14006315e | server/models/user.py | server/models/user.py | from app_factory import db
from models.session import Session
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column('name', db.String(50))
username = db.Column('username', db.String(50))
password = db.Column('password', db.String(50))
email... | from app_factory import db
from models.session import Session
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column('name', db.String(50))
username = db.Column('username', db.String(50))
password = db.Column('password', db.String(50))
email... | Implement properties and methods for the User model class to enable the Flask-Login module | Implement properties and methods for the User model class to enable the Flask-Login module
| Python | mit | ganemone/ontheside,ganemone/ontheside,ganemone/ontheside |
fe772c380c48eb14fc47bbd0a0c95888b9ea700a | jsonschema/__init__.py | jsonschema/__init__.py | """
An implementation of JSON Schema for Python
The main functionality is provided by the validator classes for each of the
supported JSON Schema versions.
Most commonly, `validate` is the quickest way to simply validate a given
instance under a schema, and will create a validator for you.
"""
from jsonschema.except... | """
An implementation of JSON Schema for Python
The main functionality is provided by the validator classes for each of the
supported JSON Schema versions.
Most commonly, `validate` is the quickest way to simply validate a given
instance under a schema, and will create a validator for you.
"""
from jsonschema.except... | Use importlib from std (if possible) | Use importlib from std (if possible) | Python | mit | Julian/jsonschema,Julian/jsonschema,python-jsonschema/jsonschema |
dfc885784a869dc3f3ef200557be4303aa2752e9 | ldap_sync/callbacks.py | ldap_sync/callbacks.py | def removed_user_deactivate(user):
if user.is_active:
user.is_active = False
user.save()
def removed_user_delete(user):
user.delete()
| def user_active_directory_deactivate(user, attributes, created, updated):
"""
Deactivate user accounts based on Active Directory's
userAccountControl flags. Requires 'userAccountControl'
to be included in LDAP_SYNC_USER_EXTRA_ATTRIBUTES.
"""
try:
user_account_control = int(attributes['us... | Add callback to disable users by AD userAccountControl flags | Add callback to disable users by AD userAccountControl flags
| Python | bsd-3-clause | jbittel/django-ldap-sync,alexsilva/django-ldap-sync,alexsilva/django-ldap-sync |
47b346404f29c89ddc7e85cd3833564593823449 | zou/app/utils/query.py | zou/app/utils/query.py | def get_query_criterions_from_request(request):
"""
Turn request parameters into a dict where keys are attributes to filter and
values are values to filter.
"""
criterions = {}
for key, value in request.args.items():
if key not in ["page"]:
criterions[key] = value
return ... | import math
from zou.app import app
from zou.app.utils import fields
def get_query_criterions_from_request(request):
"""
Turn request parameters into a dict where keys are attributes to filter and
values are values to filter.
"""
criterions = {}
for key, value in request.args.items():
... | Add helper to paginate results | Add helper to paginate results
| Python | agpl-3.0 | cgwire/zou |
c688a587d49d6186462737ab00c429a30c0a4d4c | src/puzzle/problems/crossword/crossword_problem.py | src/puzzle/problems/crossword/crossword_problem.py | import collections
import re
from data import crossword, warehouse
from puzzle.problems.crossword import _base_crossword_problem
_CROSSWORD_REGEX = re.compile(r'^.*\(([\d\s,|]+)\)$')
_INTS = re.compile(r'(\d+)')
class CrosswordProblem(_base_crossword_problem._BaseCrosswordProblem):
@staticmethod
def score(lines... | import collections
from data import crossword, warehouse
from puzzle.problems.crossword import _base_crossword_problem
class CrosswordProblem(_base_crossword_problem._BaseCrosswordProblem):
@staticmethod
def score(lines):
return _base_crossword_problem.score(lines)
def _solve(self):
clue = ''.join(sel... | Delete unused module local constants. | Delete unused module local constants.
| Python | mit | PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge |
d478082c93125212f07a7b73e2d9d04d1b2c1058 | libthumbor/__init__.py | libthumbor/__init__.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# libthumbor - python extension to thumbor
# http://github.com/heynemann/libthumbor
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 Bernardo Heynemann heynemann@gmail.com
'''libthumbor is the library used to access thum... | #!/usr/bin/python
# -*- coding: utf-8 -*-
# libthumbor - python extension to thumbor
# http://github.com/heynemann/libthumbor
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 Bernardo Heynemann heynemann@gmail.com
'''libthumbor is the library used to access thum... | Fix verson number in tests | Fix verson number in tests
| Python | mit | APSL/libthumbor,thumbor/libthumbor,DomainGroupOSS/libthumbor |
727f221767c662e95585f54e06c0c8b4e4a77d88 | smartfile/exceptions.py | smartfile/exceptions.py | from requests.exceptions import ConnectionError
class SmartFileException(Exception):
pass
class SmartFileConnException(SmartFileException):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
if isinstance(exc, ConnectionError):
... | from requests.exceptions import ConnectionError
class SmartFileException(Exception):
pass
class SmartFileConnException(SmartFileException):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
if isinstance(exc, ConnectionError):
... | Handle responses without JSON or detail field | Handle responses without JSON or detail field
Check the response for JSON and a detail field before trying to access
them within SmartFileResponseException. This could occur if the server
returns a 500.
| Python | mit | smartfile/client-python |
1364470725a55232556d8856be7eb910f3376fb3 | permuta/misc/union_find.py | permuta/misc/union_find.py |
class UnionFind(object):
"""A collection of distjoint sets."""
def __init__(self, n = 0):
"""Creates a collection of n disjoint unit sets."""
self.p = [-1]*n
self.leaders = set( i for i in range(n) )
def find(self, x):
"""Return the identifier of a representative element f... |
class UnionFind(object):
"""A collection of distjoint sets."""
def __init__(self, n = 0):
"""Creates a collection of n disjoint unit sets."""
self.p = [-1]*n
self.leaders = set( i for i in range(n) )
def find(self, x):
"""Return the identifier of a representative element f... | Make UnionFind.unite return whether the operation was successful | Make UnionFind.unite return whether the operation was successful
| Python | bsd-3-clause | PermutaTriangle/Permuta |
c90e9798881630c2f956e08901f5bd35d948df6d | salt_observer/management/commands/fetchpackages.py | salt_observer/management/commands/fetchpackages.py | from django.core.management.base import BaseCommand
from django.utils import timezone
from salt_observer.models import Minion
from . import ApiCommand
import json
class Command(ApiCommand, BaseCommand):
help = 'Fetch and save new data from all servers'
def save_packages(self, api):
print('Fetching ... | from django.core.management.base import BaseCommand
from django.utils import timezone
from salt_observer.models import Minion
from . import ApiCommand
import json
class Command(ApiCommand, BaseCommand):
help = 'Fetch and save new data from all servers'
def save_packages(self, api):
packages = api.g... | Remove unwanted prints in management command | Remove unwanted prints in management command
| Python | mit | hs-hannover/salt-observer,hs-hannover/salt-observer,hs-hannover/salt-observer |
a39a91b406be3965addc613021f0c94007c42cf6 | matchzoo/__init__.py | matchzoo/__init__.py | from pathlib import Path
USER_DIR = Path.expanduser(Path('~')).joinpath('.matchzoo')
if not USER_DIR.exists():
USER_DIR.mkdir()
USER_DATA_DIR = USER_DIR.joinpath('datasets')
if not USER_DATA_DIR.exists():
USER_DATA_DIR.mkdir()
from .logger import logger
from .version import __version__
from .utils import *
f... | from pathlib import Path
USER_DIR = Path.expanduser(Path('~')).joinpath('.matchzoo')
if not USER_DIR.exists():
USER_DIR.mkdir()
USER_DATA_DIR = USER_DIR.joinpath('datasets')
if not USER_DATA_DIR.exists():
USER_DATA_DIR.mkdir()
from .logger import logger
from .version import __version__
from .utils import *
f... | Add callbacks to matchzoo root scope. | Add callbacks to matchzoo root scope.
| Python | apache-2.0 | faneshion/MatchZoo,faneshion/MatchZoo |
67c58e3941491d276318daf568354f1e17ef3892 | omics/gsa/__init__.py | omics/gsa/__init__.py | """Gene Set Analysis Module
"""
from GeneSetCollection import GeneSetCollection
| """Gene Set Analysis Module
"""
from GeneSetCollection import GeneSetCollect
def enrichment(gene_list, gene_set, background, alternative="two-sided", verbose=True):
"""Gene set enrichment analysis by Fisher Exact Test.
gene_list : query gene list
gene_set : predefined gene set
background : back... | Add enrichment function in gsa module | Add enrichment function in gsa module
| Python | mit | choyichen/omics |
7818f9aa2d66ab0f4a99f731ecfb03e711e9ad6c | utils/send_messages.py | utils/send_messages.py | from django.conf import settings
import requests
def send_message_android(destination, title, message):
headers = {
'Authorization': 'key=' + settings.FIREBASE_SERVER_KEY,
'Content - Type': 'application/json'
}
payload = {
"to": destination,
"notification": {"title": title,... | """Push notification service
send_message_android and send_message_ios are the same, but this is intentional, in order
to support any future different conditions for both platforms, different keys or addtional parameters
shit happens sometimes ROFL!
"""
from django.conf import settings
from constance import config
i... | Add send_push_notification function and separate android and ios functions | Add send_push_notification function and separate android and ios functions
| Python | apache-2.0 | belatrix/BackendAllStars |
fc6b3df720ac05b715ae6478367f79e834c47c26 | pi_broadcast_service/rabbit.py | pi_broadcast_service/rabbit.py | import json
import pika
class Publisher(object):
def __init__(self, rabbit_url, exchange):
self._rabbit_url = rabbit_url
self._exchange = exchange
self._connection = pika.BlockingConnection(pika.URLParameters(self._rabbit_url))
self._channel = self._connection.channel()
def s... | import json
import pika
class Publisher(object):
def __init__(self, rabbit_url, exchange):
self._rabbit_url = rabbit_url
self._exchange = exchange
self._connection = pika.BlockingConnection(pika.URLParameters(self._rabbit_url))
self._channel = self._connection.channel()
se... | Make sure the exchange is there first | Make sure the exchange is there first
| Python | mit | projectweekend/Pi-Broadcast-Service |
02c74c5235b8ad821786213a3bcf5f824162454d | flax/linen/combinators.py | flax/linen/combinators.py | """Combinators of modules, such as a Sequential."""
from typing import Callable, Sequence
from flax.linen.module import Module
class Sequential(Module):
"""Applies a linear chain of Modules.
Meant to be used only for the simple case of fusing together callables where
the input of a particular module/op is the... | """Combinators of modules, such as a Sequential."""
from typing import Callable, Sequence
from flax.linen.module import Module
class Sequential(Module):
"""Applies a linear chain of Modules.
Meant to be used only for the simple case of fusing together callables where
the input of a particular module/op is the... | Include activations in Sequential example. | Include activations in Sequential example.
| Python | apache-2.0 | google/flax,google/flax |
0e6de6bc5890d6028a7115a62289bf26b0dd043b | hydra_agent/actions/server_conf.py | hydra_agent/actions/server_conf.py | # ==============================
# Copyright 2011 Whamcloud, Inc.
# ==============================
from hydra_agent.plugins import AgentPlugin
def set_server_conf(args = None):
import simplejson as json
data = json.loads(args.args)
from hydra_agent.store import AgentStore
AgentStore.set_server_conf(d... | # ==============================
# Copyright 2011 Whamcloud, Inc.
# ==============================
from hydra_agent.plugins import AgentPlugin
def _validate_conf(server_conf):
from hydra_agent.main_loop import MainLoop
result = MainLoop()._send_update(server_conf['url'], server_conf['token'], None, {})
if... | Test HTTP access to server before saving server config | Test HTTP access to server before saving server config
| Python | mit | intel-hpdd/intel-manager-for-lustre,intel-hpdd/intel-manager-for-lustre,intel-hpdd/intel-manager-for-lustre |
60edf2f1534e02a6da9aa715662a0e4ea8922191 | mk/get_config_dir.py | mk/get_config_dir.py | #!/usr/bin/env python
import os
component = os.getenv("COMPONENT")
if component == "ocaml":
print "/repos/xen-dist-ocaml.hg"
if component == "api-libs":
print "/repos/xen-api-libs-rpm-buildroot"
| #!/usr/bin/env python
import os
component = os.getenv("COMPONENT")
if component == "ocaml":
print "/repos/xen-dist-ocaml.hg"
if component == "api-libs":
print "/repos/xen-api-libs-specs"
| Change name of config repo for api-libs component | Change name of config repo for api-libs component
Signed-off-by: Jon Ludlam <e7e3380887a8f95cc9dc4f0d51dedc7e849a287a@eu.citrix.com>
| Python | lgpl-2.1 | simonjbeaumont/planex,jonludlam/planex,euanh/planex-cleanhistory,jonludlam/planex,djs55/planex,djs55/planex,djs55/planex,simonjbeaumont/planex,jonludlam/planex,euanh/planex-cleanhistory,euanh/planex-cleanhistory,simonjbeaumont/planex |
0043fe9c8de4d8341afbcea388f472a50017de2c | jiradoc/__main__.py | jiradoc/__main__.py | # ------------------------------------------------------------
# __main__.py
#
# The main program which expects a jiradoc formatted file to
# be passed in as a cmdline option. It reads the file and
# parses its content to Story objects.
# ------------------------------------------------------------
import argparse
impo... | # ------------------------------------------------------------
# __main__.py
#
# The main program
# ------------------------------------------------------------
import argparse
import os
import pkg_resources
import sys
from jiradoc.parser.parser import parser as jiradoc_parser
def main(args=None):
parser = argpa... | Validate that the input file ends with .jiradoc | Validate that the input file ends with .jiradoc
| Python | mit | lucianovdveekens/jiradoc |
af2c9647e64ad0e0575b191e35e38f8bf23ed6f8 | config.py | config.py | ###
# Copyright (c) 2012-2013, spline
# All rights reserved.
#
#
###
import supybot.conf as conf
import supybot.registry as registry
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('NFL')
def configure(advanced):
# This will be called by supybot to co... | ###
# Copyright (c) 2012-2013, spline
# All rights reserved.
#
#
###
import supybot.conf as conf
import supybot.registry as registry
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified himself as an advanced
#... | Remove internationalization because its not needed. | Remove internationalization because its not needed.
| Python | mit | cottongin/NFL,fasteddie2/NFL,reticulatingspline/NFL |
91c35078c7a8aad153d9aabe0b02fc3c48cfc76a | hesiod.py | hesiod.py | #!/usr/bin/env python
from _hesiod import bind, resolve
| #!/usr/bin/env python
"""
Present both functional and object-oriented interfaces for executing
lookups in Hesiod, Project Athena's service name resolution protocol.
"""
from _hesiod import bind, resolve
from pwd import struct_passwd
class HesiodParseError(Exception):
pass
class Lookup(object):
"""
A Ge... | Add object-oriented-style lookups for filsys, passwd, and uid lookups | Add object-oriented-style lookups for filsys, passwd, and uid lookups
The filsys entry parsing code is taken from pyHesiodFS and was explicitly
relicensed under the MIT license by Quentin Smith <quentin@mit.edu>
| Python | mit | ebroder/python-hesiod |
637c19a54c6bee656ba3effd9316ad3d5587a963 | src/dynmen/__init__.py | src/dynmen/__init__.py | # -*- coding: utf-8 -*-
"""
dynmen - A simple python interface to dynamic menus like dmenu or rofi
import dynmen
menu = dynmen.Menu(['dmenu', '-fn', 'Sans-30'])
output = menu({'a': 1, 'b': 2, 'c': 3})
You can make the menu non-blocking by setting:
menu.process_mode = 'futures'
Please see the repository for more e... | # -*- coding: utf-8 -*-
"""
dynmen - A simple python interface to dynamic menus like dmenu or rofi
import dynmen
menu = dynmen.Menu(['dmenu', '-fn', 'Sans-30'])
output = menu({'a': 1, 'b': 2, 'c': 3})
You can make the menu non-blocking by setting:
menu.process_mode = 'futures'
Please see the repository for more e... | Add docstrings to dynmen.new_dmenu and dynmen.new_rofi | Add docstrings to dynmen.new_dmenu and dynmen.new_rofi
| Python | mit | frostidaho/dynmen |
968ef4bfb57743328587f9f693a7c531e20cbce0 | go_cli/tests/test_main.py | go_cli/tests/test_main.py | """ Tests for go_cli.main. """
from unittest import TestCase
from click.testing import CliRunner
from go_cli.main import cli
class TestCli(TestCase):
def test_help(self):
runner = CliRunner()
result = runner.invoke(cli, ['--help'])
self.assertEqual(result.exit_code, 0)
self.asse... | """ Tests for go_cli.main. """
from unittest import TestCase
from click.testing import CliRunner
from go_cli.main import cli
class TestCli(TestCase):
def test_help(self):
runner = CliRunner()
result = runner.invoke(cli, ['--help'])
self.assertEqual(result.exit_code, 0)
self.asse... | Check that export-contacts is included in the top-level command. | Check that export-contacts is included in the top-level command.
| Python | bsd-3-clause | praekelt/go-cli,praekelt/go-cli |
ea9273ba54dc502327bcca8b233e8d338aaa0d43 | pombola/south_africa/management/commands/south_africa_create_new_parties_for_election_2019.py | pombola/south_africa/management/commands/south_africa_create_new_parties_for_election_2019.py | import unicodecsv
from django.core.management.base import BaseCommand, CommandError
from pombola.core.models import Organisation, OrganisationKind
parties_csv = "pombola/south_africa/data/elections/2019/parties.csv"
class Command(BaseCommand):
help = "Creates new parties for the 2019 elections"
def handl... | import unicodecsv
from django.core.management.base import BaseCommand, CommandError
from pombola.core.models import Organisation, OrganisationKind
parties_csv = "pombola/south_africa/data/elections/2019/parties.csv"
class Command(BaseCommand):
help = "Creates new parties for the 2019 elections"
def handl... | Move party name to defaults argument | [ZA] Move party name to defaults argument
Some party names have changed, but the slug remains the same, so to
avoid errors move the name to the defaults sections so it's not checked
for existing parties.
| Python | agpl-3.0 | mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola |
d51fcb604f9e4a0f9b7d4178d4c85209594afbde | dataset/types.py | dataset/types.py | from datetime import datetime, date
from sqlalchemy import Integer, UnicodeText, Float, BigInteger
from sqlalchemy import Boolean, Date, DateTime, Unicode
from sqlalchemy.types import TypeEngine
class Types(object):
"""A holder class for easy access to SQLAlchemy type names."""
integer = Integer
string =... | from datetime import datetime, date
from sqlalchemy import Integer, UnicodeText, Float, BigInteger
from sqlalchemy import Boolean, Date, DateTime, Unicode
from sqlalchemy.types import TypeEngine
class Types(object):
"""A holder class for easy access to SQLAlchemy type names."""
integer = Integer
string =... | Replace `cls` argument with `self` Not sure if this was originally intended to be a `@classmethod` but it's now written and called as a method bound to an instance of the class. | Replace `cls` argument with `self`
Not sure if this was originally intended to be a `@classmethod` but it's now written and called as a method bound to an instance of the class.
| Python | mit | pudo/dataset |
4e63db0d699eeb7a313708f82c129637222e1014 | src/penn_chime/utils.py | src/penn_chime/utils.py | """Utils."""
from base64 import b64encode
import pandas as pd
def dataframe_to_base64(df: pd.DataFrame) -> str:
"""Converts a dataframe to a base64-encoded CSV representation of that data.
This is useful for building datauris for use to download the data in the browser.
Arguments:
df: The data... | """Utils."""
from base64 import b64encode
import pandas as pd
def dataframe_to_base64(df: pd.DataFrame) -> str:
"""Converts a dataframe into csv base64-encoded data.
This is useful for building datauris for use to download the data in the browser.
Arguments:
df: The dataframe to convert
""... | Update excel_to_base64 to always close file handles | Update excel_to_base64 to always close file handles
| Python | mit | CodeForPhilly/chime,CodeForPhilly/chime,CodeForPhilly/chime |
e14ca7e0a71e558ae9d8327248012d8109f9e0c5 | needlestack/base.py | needlestack/base.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
class SearchBackend(object):
pass
class Field(object):
"""
Base class for any field.
"""
name = None
def __init__(self, **kwargs)
self.options = kwargs
def set_name(self, name):
self.name... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
class SearchBackend(object):
pass
class Field(object):
"""
Base class for any field.
"""
name = None
def __init__(self, **kwargs)
for name, value in kwargs.items():
setattr(self, name, val... | Add type addaptation methods for generic field class. | Add type addaptation methods for generic field class.
| Python | bsd-3-clause | niwinz/needlestack |
6f6d1a7146020121a98ba6bb6cfa718686fc2a8d | ffflash/lib/api.py | ffflash/lib/api.py | from datetime import datetime
from pprint import pformat
from re import search as re_search
from re import sub as re_sub
class FFApi:
def __init__(self, content):
self.c = content
def pull(self, *fields):
c = self.c
for f in fields:
if isinstance(c,... | from datetime import datetime
from pprint import pformat
from re import search as re_search
from re import sub as re_sub
class FFApi:
def __init__(self, content):
self.c = content
def pull(self, *fields):
c = self.c
for f in fields:
if isinstance(c, dict) and f in c.keys()... | Fix double indentation error in FFApi class | Fix double indentation error in FFApi class
| Python | bsd-3-clause | spookey/ffflash,spookey/ffflash |
786d1ee8f58c95ab3d27d06bda2ec593cadef48e | apps/videos/tests/__init__.py | apps/videos/tests/__init__.py | from apps.videos.tests.celery_tasks import *
from apps.videos.tests.downloads import *
from apps.videos.tests.feeds import *
from apps.videos.tests.following import *
from apps.videos.tests.forms import *
from apps.videos.tests.metadata import *
from apps.videos.tests.models import *
from apps.videos.tests.rpc import *... | from apps.videos.tests.celery_tasks import *
from apps.videos.tests.downloads import *
from apps.videos.tests.feeds import *
from apps.videos.tests.following import *
from apps.videos.tests.forms import *
from apps.videos.tests.metadata import *
from apps.videos.tests.models import *
from apps.videos.tests.rpc import *... | Remove the syncing tests from the list. | Remove the syncing tests from the list.
| Python | agpl-3.0 | ReachingOut/unisubs,ofer43211/unisubs,ofer43211/unisubs,ReachingOut/unisubs,ujdhesa/unisubs,norayr/unisubs,wevoice/wesub,norayr/unisubs,eloquence/unisubs,wevoice/wesub,pculture/unisubs,ofer43211/unisubs,eloquence/unisubs,wevoice/wesub,norayr/unisubs,ujdhesa/unisubs,pculture/unisubs,eloquence/unisubs,ujdhesa/unisubs,wev... |
980aaa340a03353742d03be2844d4ceb829715c0 | numpy/core/__init__.py | numpy/core/__init__.py |
from info import __doc__
from numpy.version import version as __version__
import multiarray
import umath
import numerictypes as nt
multiarray.set_typeDict(nt.sctypeDict)
import _sort
from numeric import *
from fromnumeric import *
from defmatrix import *
import ma
import defchararray as char
import records as rec
fro... |
from info import __doc__
from numpy.version import version as __version__
import multiarray
import umath
import _internal # for freeze programs
import numerictypes as nt
multiarray.set_typeDict(nt.sctypeDict)
import _sort
from numeric import *
from fromnumeric import *
from defmatrix import *
import ma
import defchar... | Add an dummy import statement so that freeze programs pick up _internal.p | Add an dummy import statement so that freeze programs pick up _internal.p
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@3807 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,illume/numpy3k,teoliphant/numpy-refactor,illume/numpy3k,efiring/numpy-work,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,Ademan/NumPy-GSoC,chadnetzer/numpy-gaurdro,efiring/numpy-work,teoliphant/numpy-refactor,Ademan/NumPy-GSoC,Ademan/NumPy-GSoC,jasonm... |
4aa979273bfe698459d9a8066ee41741c3a68e3d | megamix/__init__.py | megamix/__init__.py | # Module of Gaussian Mixture models for python
__all__ = ['batch','online'] | # Module of Gaussian Mixture models for python
import megamix.batch
import megamix.online
__all__ = ['batch','online'] | Solve minor import problems with submodules | Solve minor import problems with submodules
| Python | apache-2.0 | 14thibea/megamix |
525441540306cb2ac385b0f633681e24587117dc | gdx2py/__init__.py | gdx2py/__init__.py | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 24 11:01:10 2016
@author: ererkka
"""
__version__ = '1.2.2'
| # -*- coding: utf-8 -*-
"""
Created on Wed Feb 24 11:01:10 2016
@author: ererkka
"""
__version__ = '1.2.2'
from .gdxfile import GdxFile | Revert "Fixed bug with imports" | Revert "Fixed bug with imports"
This reverts commit 7b63b268a002a0ceb0b7bb2c6c57237bf6d5f25b.
| Python | mit | ererkka/GDX2py |
b63ee83574605e79075ee834d2418cd58b722bc6 | docs/tests.py | docs/tests.py | from django.test import Client, TestCase
from django.core.urlresolvers import reverse
import views
class DocsTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_index(self):
response = self.client.get(reverse(views.index))
self.assertEqual(response.status_code, 200)
... | from django.test import Client, TestCase
from django.core.urlresolvers import reverse
import views
class DocsTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_index(self):
response = self.client.get(reverse(views.index))
self.assertEqual(response.status_code, 200)
... | Add test case for resources docs page | Add test case for resources docs page
| Python | mit | crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp |
1ac385de638854cad1095a3f81a63ecf45fa60ae | organizer/models.py | organizer/models.py | from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(
max_length=31, unique=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config... | from django.db import models
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Tag(models.Model):
name = models.CharField(
max_length=31, unique=True)
slug = models.SlugField(
max_length=31,
unique=True,
help_text='A label for URL config... | Declare Meta class in NewsLink model. | Ch03: Declare Meta class in NewsLink model. [skip ci]
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 |
f317f946f9f17cbaf162b12c8770908abba5bbeb | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by NotSqrt
# Copyright (c) 2013 NotSqrt
#
# License: MIT
#
"""This module exports the Cppcheck plugin class."""
from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
"""Provides an interface to cpp... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by NotSqrt
# Copyright (c) 2013 NotSqrt
#
# License: MIT
#
"""This module exports the Cppcheck plugin class."""
from SublimeLinter.lint import Linter, util
class Cppcheck(Linter):
"""Provides an interface to cpp... | Change on the regex variable such that it distinguish warnings from errors. | Change on the regex variable such that it distinguish warnings from errors.
| Python | mit | SublimeLinter/SublimeLinter-cppcheck,ftoulemon/SublimeLinter-cppcheck |
a521c4a4a55437452a4a7d006ec8faea0521ea05 | capstone/rl/learners/sarsa.py | capstone/rl/learners/sarsa.py | from ..learner import Learner
from ..policies import RandomPolicy
from ..value_functions import TabularQ
from ...utils import check_random_state
class Sarsa(Learner):
def __init__(self, env, policy=None, learning_rate=0.1, discount_factor=0.99,
n_episodes=1000, verbose=True, random_state=None):
... | from ..learner import Learner
from ..policies import RandomPolicy
from ..value_functions import TabularQ
from ...utils import check_random_state
class Sarsa(Learner):
def __init__(self, env, policy=None, learning_rate=0.1, discount_factor=0.99,
n_episodes=1000, verbose=True, random_state=None):
... | Create tabular q-function with kwarg random_state | Create tabular q-function with kwarg random_state
| Python | mit | davidrobles/mlnd-capstone-code |
b388722fcc70d2787b91b5a4492cb9659cea7a42 | parsl/providers/torque/template.py | parsl/providers/torque/template.py | template_string = '''#!/bin/bash
#PBS -S /bin/bash
#PBS -N ${jobname}
#PBS -m n
#PBS -k eo
#PBS -l walltime=$walltime
#PBS -l nodes=${nodes_per_block}:ppn=${tasks_per_node}
#PBS -o ${submit_script_dir}/${jobname}.submit.stdout
#PBS -e ${submit_script_dir}/${jobname}.submit.stderr
${scheduler_options}
${worker_init}
... | template_string = '''#!/bin/bash
#PBS -S /bin/bash
#PBS -N ${jobname}
#PBS -m n
#PBS -l walltime=$walltime
#PBS -l nodes=${nodes_per_block}:ppn=${tasks_per_node}
#PBS -o ${submit_script_dir}/${jobname}.submit.stdout
#PBS -e ${submit_script_dir}/${jobname}.submit.stderr
${scheduler_options}
${worker_init}
export JOBN... | Remove line which was preventing stdout redirect | Remove line which was preventing stdout redirect
I think this line tries to send stdout and stderr to the same file. I'm
not really sure why removing it causes the later specification of the
stdout and stderr lines to be respected, but we don't want them in the
same file in any case. Fixes #647.
| Python | apache-2.0 | Parsl/parsl,Parsl/parsl,Parsl/parsl,swift-lang/swift-e-lab,swift-lang/swift-e-lab,Parsl/parsl |
3b83e983f1e7cd3a0866109c66dd91903db87fa1 | goodtablesio/integrations/github/tasks/repos.py | goodtablesio/integrations/github/tasks/repos.py | import datetime
from goodtablesio.models.user import User
from goodtablesio.models.source import Source
from goodtablesio.services import database
from goodtablesio.celery_app import celery_app
from goodtablesio.integrations.github.utils.repos import iter_repos_by_token
@celery_app.task(name='goodtablesio.github.sync... | import datetime
from goodtablesio.models.user import User
from goodtablesio.services import database
from goodtablesio.celery_app import celery_app
from goodtablesio.integrations.github.models.repo import GithubRepo
from goodtablesio.integrations.github.utils.repos import iter_repos_by_token
@celery_app.task(name='go... | Use own model class on github task | Use own model class on github task
| Python | agpl-3.0 | frictionlessdata/goodtables.io,frictionlessdata/goodtables.io,frictionlessdata/goodtables.io,frictionlessdata/goodtables.io |
274a1b43a57f838f078d11ef71803d46f8fd34bf | perfect-numbers/perfect_numbers.py | perfect-numbers/perfect_numbers.py | def divisor_generator(n):
big_factors = {1}
for i in range(2, n):
if i in big_factors:
break
if n % i == 0:
big_factors.add(n // i)
yield i
yield from big_factors
def is_perfect(n):
return n == sum(divisor_generator(n))
| from math import sqrt, ceil
def divisor_generator(n):
yield 1
for i in range(2, ceil(sqrt(n))):
if n % i == 0:
yield i
yield n // i
def is_perfect(n):
return n == sum(divisor_generator(n))
| Refactor to give faster solution | Refactor to give faster solution
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
9fe93f19c38ea1e41ce7bfe5aca8ec9327b195b5 | test/test_reqmodules.py | test/test_reqmodules.py |
import tserver, sys, md5, math
from disco import Disco, result_iterator
def data_gen(path):
return path[1:] + "\n"
def fun_map(e, params):
k = str(int(math.ceil(float(e))) ** 2)
return [(md5.new(k).hexdigest(), "")]
tserver.run_server(data_gen)
disco = Disco(sys.argv[1])
inputs = [1, 485, 3... |
import tserver, sys, base64, math
from disco import Disco, result_iterator
def data_gen(path):
return path[1:] + "\n"
def fun_map(e, params):
k = str(int(math.ceil(float(e))) ** 2)
return [(base64.encodestring(k), "")]
tserver.run_server(data_gen)
disco = Disco(sys.argv[1])
inputs = [1, 485... | Use the base64 module for testing rather than md5 which is deprecated in python2.6 | Use the base64 module for testing rather than md5 which is deprecated in python2.6
| Python | bsd-3-clause | ErikDubbelboer/disco,beni55/disco,ErikDubbelboer/disco,beni55/disco,pombredanne/disco,scrapinghub/disco,scrapinghub/disco,pombredanne/disco,ErikDubbelboer/disco,seabirdzh/disco,pooya/disco,ErikDubbelboer/disco,discoproject/disco,pombredanne/disco,mwilliams3/disco,simudream/disco,discoproject/disco,mwilliams3/disco,ktkt... |
49a2502043e1d7ad5f3907779be7815a39ad85c7 | awx/main/models/activity_stream.py | awx/main/models/activity_stream.py | # Copyright (c) 2013 AnsibleWorks, Inc.
# All Rights Reserved.
from django.db import models
class ActivityStream(models.Model):
'''
Model used to describe activity stream (audit) events
'''
OPERATION_CHOICES = [
('create', _('Entity Created')),
('update', _("Entity Updated")),
... | # Copyright (c) 2013 AnsibleWorks, Inc.
# All Rights Reserved.
from django.db import models
from django.utils.translation import ugettext_lazy as _
class ActivityStream(models.Model):
'''
Model used to describe activity stream (audit) events
'''
class Meta:
app_label = 'main'
OPERATION_... | Fix up some issues with supporting schema migration | Fix up some issues with supporting schema migration
| Python | apache-2.0 | wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx |
5fe73f508d87018db1d6f574cd22d76b46cbe862 | events/api.py | events/api.py | '''
Api for the events app
'''
import datetime
from models import Event
from tastypie.utils import trailing_slash
from apis.resources.base import BaseResource
from django.conf.urls.defaults import url
class EventResource(BaseResource):
class Meta:
queryset = Event.objects.all()
allowed_methods = ['... | '''
Api for the events app
'''
import datetime
from models import Event
from tastypie.utils import trailing_slash
from apis.resources.base import BaseResource
from django.conf.urls.defaults import url
class EventResource(BaseResource):
class Meta:
queryset = Event.objects.all()
allowed_methods = ['... | Fix the event APIv2 to account for retrieval of a single event. | Fix the event APIv2 to account for retrieval of a single event.
| Python | bsd-3-clause | alonisser/Open-Knesset,OriHoch/Open-Knesset,habeanf/Open-Knesset,daonb/Open-Knesset,otadmor/Open-Knesset,navotsil/Open-Knesset,MeirKriheli/Open-Knesset,DanaOshri/Open-Knesset,Shrulik/Open-Knesset,daonb/Open-Knesset,otadmor/Open-Knesset,habeanf/Open-Knesset,DanaOshri/Open-Knesset,Shrulik/Open-Knesset,daonb/Open-Knesset,... |
2d7c7872bb030a280de6047a609d14560ff7e29f | 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):
... | Patch mnist example to specify theano for keras. | Patch mnist example to specify theano for keras.
| Python | mit | spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc |
81cd919f4f85f2d26d89006234d608aebe8a8047 | plugins/clue/clue.py | plugins/clue/clue.py | from __future__ import unicode_literals
# don't convert to ascii in py2.7 when creating string to return
crontable = []
outputs = []
state = {}
def process_message(data):
channel = data['channel']
if channel not in state.keys():
state[channel] = {'count': 0, 'clue': ''}
st = state[channel]
... | from __future__ import unicode_literals
# don't convert to ascii in py2.7 when creating string to return
crontable = []
outputs = []
state = {}
class ClueState:
def __init__(self):
self.count = 0
self.clue = ''
def process_message(data):
channel = data['channel']
if channel not in sta... | Switch to a ClueState class instead of just a dictionary | Switch to a ClueState class instead of just a dictionary
This makes the syntax a little easier to read, (such as "st.count"
instead of "st['count']").
| Python | mit | cworth-gh/stony |
2f968509be6ae8e3bcd15d0f46ebc3ba290ca086 | astroplan/exceptions.py | astroplan/exceptions.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from astropy.utils.exceptions import AstropyWarning
__all__ = ["TargetAlwaysUpWarning", "TargetNeverUpWarning",
"OldEarthOrientationDa... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from astropy.utils.exceptions import AstropyWarning
__all__ = ["TargetAlwaysUpWarning", "TargetNeverUpWarning",
"OldEarthOrientationDa... | Make all astroplan warnings decend from an AstroplanWarning | Make all astroplan warnings decend from an AstroplanWarning
| Python | bsd-3-clause | StuartLittlefair/astroplan |
5b00b6cd392a1f5f317cc18893198bb5d62c565d | pystache/parsed.py | pystache/parsed.py | # coding: utf-8
"""
Exposes a class that represents a parsed (or compiled) template.
"""
class ParsedTemplate(object):
"""
Represents a parsed or compiled template.
An instance wraps a list of unicode strings and node objects. A node
object must have a `render(engine, stack)` method that accepts ... | # coding: utf-8
"""
Exposes a class that represents a parsed (or compiled) template.
"""
class ParsedTemplate(object):
"""
Represents a parsed or compiled template.
An instance wraps a list of unicode strings and node objects. A node
object must have a `render(engine, stack)` method that accepts ... | Rename variable name from "val" to "node". | Rename variable name from "val" to "node".
| Python | mit | charbeljc/pystache,nitish116/pystache,defunkt/pystache,harsh00008/pystache,rismalrv/pystache,nitish116/pystache,arlenesr28/pystache,nitish116/pystache,rismalrv/pystache,charbeljc/pystache,arlenesr28/pystache,harsh00008/pystache,beni55/pystache,harsh00008/pystache,jrnold/pystache,rismalrv/pystache,jrnold/pystache,arlene... |
336edeebe5ac04df719569efa40e2fef01a2dccc | testproject/__init__.py | testproject/__init__.py | #!/usr/bin/env python
import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.testproject.settings")
from django.test.utils import get_runner
from django.conf import settings
def runtests():
# Stolen from django/core/management/commands/test.py
TestRunner = get_runner(settings)
t... | #!/usr/bin/env python
import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.testproject.settings")
import django
from django.test.utils import get_runner
from django.conf import settings
def runtests():
if hasattr(django, 'setup'):
# django >= 1.7
django.setup()
# S... | Set up the app registry when running tests on django 1.7 | Set up the app registry when running tests on django 1.7
(cherry picked from commit 7b3c994758254f16e8f47bf0f13b363d98082f20)
Signed-off-by: Antoine Catton <4589f2e060cef08c47d868a06754605a848a1006@fusionbox.com>
| Python | bsd-2-clause | fusionbox/django-argonauts |
80958236edd4390b3f2f9fe4848de68fdda60513 | hurdles/tools.py | hurdles/tools.py | from functools import wraps
def extra_setup(setup_code):
"""Allows to setup some extra context to it's decorated function.
As a convention, the bench decorated function should always handle
*args and **kwargs. Kwargs will be updated with the extra context
set by the decorator.
Example:
@... | from functools import wraps
def extra_setup(setup_code):
"""Allows to setup some extra context to it's decorated function.
As a convention, the bench decorated function should always handle
*args and **kwargs. Kwargs will be updated with the extra context
set by the decorator.
Example:
@... | Update : extra_setup compiles code, and runs it into custom global context | Update : extra_setup compiles code, and runs it into custom global context
| Python | mit | oleiade/Hurdles |
918c30a22bf6dc6e0c69037ba21759710c5e7602 | glance_registry_local_check.py | glance_registry_local_check.py | #!/usr/bin/env python
from maas_common import (status_ok, status_err, metric, metric_bool,
get_auth_ref)
from requests import Session
from requests import exceptions as exc
def check(auth_ref):
registry_endpoint = 'http://127.0.0.1:9191'
api_status = 1
milliseconds = 0
s = Se... | #!/usr/bin/env python
from maas_common import (status_ok, status_err, metric, get_keystone_client,
get_auth_ref)
from requests import Session
from requests import exceptions as exc
def check(auth_ref):
keystone = get_keystone_client(auth_ref)
tenant_id = keystone.tenant_id
auth_t... | Revert "Use new metric_bool function" | Revert "Use new metric_bool function"
This reverts commit e186b59c83f187900ce4bfd8b02b735d068434bb.
| Python | apache-2.0 | sigmavirus24/rpc-openstack,stevelle/rpc-openstack,cfarquhar/rpc-maas,jacobwagner/rpc-openstack,andymcc/rpc-openstack,cfarquhar/rpc-maas,briancurtin/rpc-maas,darrenchan/rpc-openstack,cfarquhar/rpc-openstack,stevelle/rpc-openstack,claco/rpc-openstack,major/rpc-openstack,sigmavirus24/rpc-openstack,miguelgrinberg/rpc-opens... |
3ec825c5ad8f1b4bacbbe9921d7caa46ad5ccd55 | comrade/core/context_processors.py | comrade/core/context_processors.py | from django.conf import settings
from django.contrib.sites.models import Site
from settings import DeploymentType
def default(request):
context = {}
context['DEPLOYMENT'] = settings.DEPLOYMENT
context['site'] = Site.objects.get_current()
if settings.DEPLOYMENT != DeploymentType.PRODUCTION:
cont... | from django.conf import settings
from django.contrib.sites.models import Site
from settings import DeploymentType
def default(request):
context = {}
context['DEPLOYMENT'] = settings.DEPLOYMENT
context['site'] = Site.objects.get_current()
if settings.DEPLOYMENT != DeploymentType.PRODUCTION:
cont... | Add contact email to context. | Add contact email to context.
| Python | mit | bueda/django-comrade |
cfbe762a0e752dcb58edbbd0835371ecc300d3f4 | nosewatch/plugin.py | nosewatch/plugin.py | import sys
from nose.plugins import Plugin
from subprocess import Popen
class WatchPlugin(Plugin):
"""
Plugin that use watchdog for continuous tests run.
"""
name = 'watch'
is_watching = False
sys = sys
def call(self, args):
Popen(args).wait()
def finalize(self, result):
... | import sys
from nose.plugins import Plugin
from subprocess import Popen
class WatchPlugin(Plugin):
"""
Plugin that use watchdog for continuous tests run.
"""
name = 'watch'
is_watching = False
sys = sys
def call(self, args):
Popen(args).wait()
def finalize(self, result):
... | Add try block to argv remove statement | Add try block to argv remove statement
When running nose-watch withing an environment like django-nose argv doesn't contain any arguments to remove.
| Python | bsd-2-clause | lukaszb/nose-watch,lukaszb/nose-watch |
c3762443859ada75687e5a62d576fe8140a42a7c | tests/test_csv2iati.py | tests/test_csv2iati.py | import pytest
from web_test_base import *
class TestCSV2IATI(WebTestBase):
requests_to_load = {
'CSV2IATI Homepage': {
'url': 'http://csv2iati.iatistandard.org/'
}
}
def test_contains_links(self, loaded_request):
"""
Test that each page contains links to the def... | import pytest
from web_test_base import *
class TestCSV2IATI(WebTestBase):
requests_to_load = {
'CSV2IATI Homepage': {
'url': 'http://csv2iati.iatistandard.org/'
}
}
| Remove redundant csv2iati test now site has been decommissioned | Remove redundant csv2iati test now site has been decommissioned
| Python | mit | IATI/IATI-Website-Tests |
6c3b5a314c9ba25fba2b0a605215d2fdad97e8dc | tests/test_evaluate.py | tests/test_evaluate.py | import numpy as np
from numpy.testing import assert_equal
from gala import evaluate as ev
def test_contingency_table():
seg = np.array([0, 1, 1, 1, 2, 2, 2, 3])
gt = np.array([1, 1, 1, 2, 2, 2, 2, 0])
ct = ev.contingency_table(seg, gt, ignore_seg=[], ignore_gt=[])
ct0 = ev.contingency_table(seg, gt, ig... | import numpy as np
from numpy.testing import assert_equal
from gala import evaluate as ev
def test_contingency_table():
seg = np.array([0, 1, 1, 1, 2, 2, 2, 3])
gt = np.array([1, 1, 1, 2, 2, 2, 2, 0])
ct = ev.contingency_table(seg, gt, ignore_seg=[], ignore_gt=[])
ct0 = ev.contingency_table(seg, gt, ig... | Add basic test to assert same shape of seg and gt | Add basic test to assert same shape of seg and gt
| Python | bsd-3-clause | jni/gala,janelia-flyem/gala |
96755c5e3ccf0573e7190da2a4a9264fdf409710 | linter.py | linter.py | #
# linter.py
# Markdown Linter for SublimeLinter, a code checking framework
# for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2018 Jon LaBelle
#
# License: MIT
#
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class MarkdownLint(NodeLinter):
... | #
# linter.py
# Markdown Linter for SublimeLinter, a code checking framework
# for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2018 Jon LaBelle
#
# License: MIT
#
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class MarkdownLint(NodeLinter):
... | Remove deprecated SL 'syntax' property override | Remove deprecated SL 'syntax' property override
Replaced by 'defaults/selector':
http://www.sublimelinter.com/en/stable/linter_settings.html#selector
| Python | mit | jonlabelle/SublimeLinter-contrib-markdownlint,jonlabelle/SublimeLinter-contrib-markdownlint |
9b2ee2e4a956f8409047b289ee5c35ad4fcb4310 | insanity/layers.py | insanity/layers.py | import numpy as np
import theano
import theano.tensor as T
from theano.tensor.nnet import conv
from theano.tensor.nnet import softmax
from theano.tensor import shared_randomstreams
from theano.tensor.signal import downsample
class NeuralNetworkLayer(object):
def __init__(self, numInputs, input, inputDropout, numNe... | import numpy as np
import theano
import theano.tensor as T
from theano.tensor.nnet import conv
from theano.tensor.nnet import softmax
from theano.tensor import shared_randomstreams
from theano.tensor.signal import downsample
class Layer(object):
def __init__(self, numInputs, numNeurons, activation):
self.numInpu... | Add @property for network layer inputs | Add @property for network layer inputs
| Python | cc0-1.0 | cn04/insanity |
f707f0daec148ae16604a8fb1326fe10155d4453 | tunobase/corporate/company_info/contact/tasks.py | tunobase/corporate/company_info/contact/tasks.py | """
CONTACT APP
This module provides a variety of tasks to be queued by Celery.
Classes:
n/a
Functions:
email_contact_message
Created on 21 Oct 2013
@author: michael
"""
from celery.decorators import task
from django.conf import settings
from tunobase.mailer import utils as mailer_utils
@task(defau... | """
CONTACT APP
This module provides a variety of tasks to be queued by Celery.
Classes:
n/a
Functions:
email_contact_message
Created on 21 Oct 2013
@author: michael
"""
from celery.decorators import task
from django.conf import settings
from tunobase.mailer import utils as mailer_utils
@task(defau... | Send contact us message from the email the user inputted on the site or use the default setting | Send contact us message from the email the user inputted on the site or use the default setting
| Python | bsd-3-clause | unomena/tunobase,unomena/tunobase |
d410c30ba779ac0b32fdac7bf15733b1edacafe7 | src/weitersager/util.py | src/weitersager/util.py | """
weitersager.util
~~~~~~~~~~~~~~~~
Utilities
:Copyright: 2007-2021 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
import logging
from logging import Formatter, StreamHandler
from threading import Thread
from typing import Callable
def configure_logging(level: str) -> None:
"""Configure app... | """
weitersager.util
~~~~~~~~~~~~~~~~
Utilities
:Copyright: 2007-2021 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
import logging
from logging import Formatter, StreamHandler
from threading import Thread
from typing import Callable, Optional
def configure_logging(level: str) -> None:
"""Con... | Make thread name argument optional | Make thread name argument optional
| Python | mit | homeworkprod/weitersager |
530549f7fe2c6bbf45996e17b2b125150ad031ae | manage.py | manage.py | #!/usr/bin/env python
"""
Run the Varda REST server.
To reset the database:
from varda import db
db.drop_all()
db.create_all()
"""
from flaskext.script import Manager
from flaskext.celery import install_commands as install_celery_commands
from varda import app, db
manager = Manager(app)
install_cele... | #!/usr/bin/env python
"""
Run the Varda REST server.
To setup the database:
create database varda;
create database vardacelery;
create database vardaresults;
grant all privileges on varda.* to varda@localhost identified by 'varda';
grant all privileges on vardacelery.* to varda@localhost identifie... | Add some notes on database setup | Add some notes on database setup
| Python | mit | varda/varda,sndrtj/varda |
830e1a23559b82af37f52657484edd20641318c5 | teamsupport/__init__.py | teamsupport/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from teamsupport.services import TeamSupportService
__author__ = 'Yola Engineers'
__email__ = 'engineers@yola.com'
__version__ = '0.1.0'
__all__ = (TeamSupportService,)
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
from teamsupport.models import Action, Ticket
from teamsupport.services import TeamSupportService
__author__ = 'Yola Engineers'
__email__ = 'engineers@yola.com'
__version__ = '0.1.0'
__all__ = (Action, TeamSupportService, Ticket,)
| Add convenience imports for models | Add convenience imports for models
| Python | mit | zoidbergwill/teamsupport-python,yola/teamsupport-python |
404d499877c050f706ca0f713d1c8ef0e5a88889 | ooni/tests/bases.py | ooni/tests/bases.py | from twisted.trial import unittest
from ooni.settings import config
class ConfigTestCase(unittest.TestCase):
def setUp(self):
config.initialize_ooni_home("ooni_home")
def tearDown(self):
config.read_config_file() | import os
from twisted.trial import unittest
from ooni.settings import config
class ConfigTestCase(unittest.TestCase):
def setUp(self):
config.global_options['datadir'] = os.path.join(__file__, '..', '..', '..', 'data')
config.global_options['datadir'] = os.path.abspath(config.global_options['da... | Set the datadirectory to be that of the repo. | Set the datadirectory to be that of the repo.
| Python | bsd-2-clause | kdmurray91/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-pro... |
eacc1f88f7e34e26c3a4d29ec009b4984c10a345 | SimPEG/Mesh/__init__.py | SimPEG/Mesh/__init__.py | from TensorMesh import TensorMesh
from CylMesh import CylMesh
from Cyl1DMesh import Cyl1DMesh
from LogicallyRectMesh import LogicallyRectMesh
from TreeMesh import TreeMesh
from BaseMesh import BaseMesh
| from TensorMesh import TensorMesh
from CylMesh import CylMesh
from LogicallyRectMesh import LogicallyRectMesh
from TreeMesh import TreeMesh
from BaseMesh import BaseMesh
| Remove Cyl1DMesh from init file... | Remove Cyl1DMesh from init file...
| Python | mit | simpeg/discretize,simpeg/simpeg,simpeg/discretize,simpeg/discretize |
26330025ccdeab7febd69c7f9053a99ac46d421b | cactus/static/external/manager.py | cactus/static/external/manager.py | class ExternalManager(object):
"""
Manager the active externals
"""
def __init__(self, processors=None, optimizers=None):
self.processors = processors if processors is not None else []
self.optimizers = optimizers if optimizers is not None else []
def _register(self, external, exter... | class ExternalManager(object):
"""
Manager the active externals
"""
def __init__(self, processors=None, optimizers=None):
self.processors = processors if processors is not None else []
self.optimizers = optimizers if optimizers is not None else []
def _register(self, external, exter... | Add option to unregister externals | Add option to unregister externals
| Python | bsd-3-clause | page-io/Cactus,juvham/Cactus,ibarria0/Cactus,gone/Cactus,Knownly/Cactus,ibarria0/Cactus,dreadatour/Cactus,danielmorosan/Cactus,PegasusWang/Cactus,dreadatour/Cactus,andyzsf/Cactus-,Bluetide/Cactus,koenbok/Cactus,Knownly/Cactus,PegasusWang/Cactus,koobs/Cactus,ibarria0/Cactus,eudicots/Cactus,page-io/Cactus,chaudum/Cactus,... |
962ae8a53c95e8ade1e0fd5804062b807837781e | pycalc.py | pycalc.py | # vim: set fileencoding=utf-8
import sys
try:
import readline
# No idea if this is a license violation. Hope it isn't.
except ImportError:
print("Could not find readline, you will likely get no line editing functionality")
if sys.version_info.major < 3:
print("This program is for python version 3 onl... | # vim: set fileencoding=utf-8
import sys
try:
import readline # noqa: this is used simply by being imported.
# No idea if this is a license violation. Hope it isn't.
except ImportError:
print("Could not find readline, you will likely get no line editing functionality")
if sys.version_info.major < 3:
... | Add lines to shut flake8 up. | Add lines to shut flake8 up.
| Python | mit | 5225225/pycalc,5225225/pycalc |
2f03aa69f55d4d899af968e57a59a58d27ef82c8 | url_shortener/forms.py | url_shortener/forms.py | # -*- coding: utf-8 -*-
from flask_wtf import Form
from flask_wtf.recaptcha import RecaptchaField, Recaptcha
from wtforms import StringField, validators
from .validation import not_blacklisted_nor_spam
class ShortenedURLForm(Form):
url = StringField(
validators=[
validators.DataRequired(),
... | # -*- coding: utf-8 -*-
from flask_wtf import Form
from flask_wtf.recaptcha import RecaptchaField, Recaptcha
from wtforms import StringField, validators
from .validation import not_blacklisted_nor_spam
class ShortenedURLForm(Form):
url = StringField(
validators=[
validators.DataRequired(),
... | Add placeholder text to URL form field | Add placeholder text to URL form field
| Python | mit | piotr-rusin/url-shortener,piotr-rusin/url-shortener |
43e4d71a193f78e83f26e9d1c5fe69cee1b289b5 | raffle.py | raffle.py | # -*- coding: utf-8 -*-
import random
import webbrowser
from pythonkc_meetups import PythonKCMeetups
from optparse import OptionParser
def raffle_time(api_key=None, event_id=None):
client = PythonKCMeetups(api_key=api_key)
attendees = client.get_event_attendees(event_id)
random.shuffle(attendees)
win... | # -*- coding: utf-8 -*-
import random
import webbrowser
from pythonkc_meetups import PythonKCMeetups
from optparse import OptionParser
def raffle_time(api_key=None, event_id=None):
client = PythonKCMeetups(api_key=api_key)
attendees = client.get_event_attendees(event_id)
random.seed()
random.shuffle(... | Add call to random.seed() and change print statement to print function. | Add call to random.seed() and change print statement to print function.
| Python | bsd-3-clause | pythonkc/pythonkc-raffler |
c7b40736b6e59a654652afaab7fb643e00c1f186 | clients/cron/call_uw_course_alerter.py | clients/cron/call_uw_course_alerter.py | import subprocess
import urllib
def main():
api_url = 'https://uw-alert.herokuapp.com/check_availability'
courses = [{'level': 'under',
'session': 1151,
'subject': 'CS',
'number': 341,
'email': 'youremail@example.com'}]
for course in courses:
... | #!/usr/bin/env python
import subprocess
import urllib
def main():
api_url = 'https://uw-alert.herokuapp.com/check_availability'
courses = [{'level': 'under',
'session': 1151,
'subject': 'CS',
'number': 341,
'email': 'youremail@example.com'}]
... | Add shebang for Python to sample script | Add shebang for Python to sample script
| Python | mit | tuzhucheng/uw-course-alerter,tuzhucheng/uw-course-alerter,tuzhucheng/uw-course-alerter,tuzhucheng/uw-course-alerter |
9b524fa97d1d1c8c132d1a880103a5ab4d0dabfc | models.py | models.py | from google.appengine.ext import ndb
class Photo(ndb.Model):
name = ndb.StringProperty()
blob_info_key = ndb.BlobKeyProperty()
date_created = ndb.DateTimeProperty(auto_now_add=True)
class Album(ndb.Model):
name = ndb.StringProperty()
description = ndb.StringProperty()
date_created = ndb.Date... | from google.appengine.ext import ndb
class Photo(ndb.Model):
name = ndb.StringProperty()
blob_info_key = ndb.BlobKeyProperty()
date_created = ndb.DateTimeProperty(auto_now_add=True)
class Album(ndb.Model):
name = ndb.StringProperty()
description = ndb.StringProperty()
date_created = ndb.Date... | Add Comment Model for Photo and Album | Add Comment Model for Photo and Album
| Python | mit | MichaelAquilina/Photo-Nebula,MichaelAquilina/Photo-Nebula |
34274289f0cbfafbb1d762cad38a7225873d6850 | matches/admin.py | matches/admin.py | from django.contrib import admin
from .models import Match
from .models import Tip
def delete_tips(modeladmin, request, queryset):
for match in queryset:
tips = Tip.object.filter(match = match)
for tip in tips:
tip.score = 0
tip.scoring_field = ""
tip.is_score_ca... | from django.contrib import admin
from .models import Match
from .models import Tip
def delete_tips(modeladmin, request, queryset):
for match in queryset:
tips = Tip.object.filter(match = match)
for tip in tips:
tip.score = 0
tip.scoring_field = ""
tip.is_score_ca... | Add action to zero out tips for given match | Add action to zero out tips for given match
| Python | mit | leventebakos/football-ech,leventebakos/football-ech |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.