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 |
|---|---|---|---|---|---|---|---|---|---|
660fc35a1bb25e728ad86d2b0ce8d3af46645a99 | base/apps/storage.py | base/apps/storage.py | import urlparse
from django.conf import settings
from ecstatic.storage import CachedStaticFilesMixin, StaticManifestMixin
from s3_folder_storage.s3 import DefaultStorage, StaticStorage
def domain(url):
return urlparse.urlparse(url).hostname
class MediaFilesStorage(DefaultStorage):
def __init__(self, *args... | import urlparse
from django.conf import settings
from django.contrib.staticfiles.storage import ManifestFilesMixin
from s3_folder_storage.s3 import DefaultStorage, StaticStorage
def domain(url):
return urlparse.urlparse(url).hostname
class MediaFilesStorage(DefaultStorage):
def __init__(self, *args, **kwa... | Switch out django-ecstatic for ManifestFilesMixin. | Switch out django-ecstatic for ManifestFilesMixin.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web |
e23ba33c3a57cb384b93bf51a074a83711f0dea0 | backend/breach/tests/base.py | backend/breach/tests/base.py | from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
... | from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
... | Add balance checking test victim | Add balance checking test victim
| Python | mit | dionyziz/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,dimkarakostas/ruptur... |
5d0a29a908a4019e7d7cf1edc17ca1e002e19c14 | vumi/application/__init__.py | vumi/application/__init__.py | """The vumi.application API."""
__all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager",
"MessageStore"]
from vumi.application.base import ApplicationWorker
from vumi.application.session import SessionManager
from vumi.application.tagpool import TagpoolManager
from vumi.application.message_store... | """The vumi.application API."""
__all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager",
"MessageStore", "HTTPRelayApplication"]
from vumi.application.base import ApplicationWorker
from vumi.application.session import SessionManager
from vumi.application.tagpool import TagpoolManager
from vumi.a... | Add HTTPRelayApplication to vumi.application package API. | Add HTTPRelayApplication to vumi.application package API.
| Python | bsd-3-clause | TouK/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,harrissoerja/vumi |
6381204585c64ed70bf23237731bdb92db445c05 | cycy/parser/ast.py | cycy/parser/ast.py | class Node(object):
def __eq__(self, other):
return (
self.__class__ == other.__class__ and
self.__dict__ == other.__dict__
)
def __ne__(self, other):
return not self == other
| class Node(object):
def __eq__(self, other):
return (
self.__class__ == other.__class__ and
self.__dict__ == other.__dict__
)
def __ne__(self, other):
return not self == other
class BinaryOperation(Node):
def __init__(self, operand, left, right):
ass... | Add the basic AST nodes. | Add the basic AST nodes.
| Python | mit | Magnetic/cycy,Magnetic/cycy,Magnetic/cycy |
294b1c4d398c5f6a01323e18e53d9ab1d1e1a732 | web/mooctracker/api/views.py | web/mooctracker/api/views.py | from django.http import HttpResponse
from django.core.context_processors import csrf
import json
from students.models import Student
STATUS_OK = {
'success' : 'API is running'
}
# status view
def status(request):
return HttpResponse(
json.dumps(STATUS_OK),
content_type = 'application/json'
)
# stud... | from django.http import HttpResponse
from django.core.context_processors import csrf
import json
from students.models import Student
STATUS_OK = {
'success' : 'API is running'
}
# status view
def status(request):
return HttpResponse(
json.dumps(STATUS_OK),
content_type = 'application/json'
)
# stud... | DELETE method added to api | DELETE method added to api
| Python | mit | Jaaga/mooc-tracker,Jaaga/mooc-tracker,Jaaga/mooc-tracker,Jaaga/mooc-tracker,Jaaga/mooc-tracker,Jaaga/mooc-tracker |
0cdb7a0baa6e4f00b3b54cb49701175cdb3c8a05 | entities/filters.py | entities/filters.py | from . import forms
import django_filters as filters
class Group(filters.FilterSet):
name = filters.CharFilter(lookup_expr='icontains')
class Meta:
form = forms.GroupFilter
| from . import forms
import django_filters as filters
from features.groups import models
class Group(filters.FilterSet):
name = filters.CharFilter(label='Name', lookup_expr='icontains')
class Meta:
model = models.Group
fields = ['name']
form = forms.GroupFilter
| Fix filter for django-filter 1.0 | Fix filter for django-filter 1.0
| Python | agpl-3.0 | stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten |
911ae13f760d221f5477cb5d518d4a9719386b81 | demo/demo_esutils/mappings.py | demo/demo_esutils/mappings.py | # -*- coding: utf-8 -*-
from django.db.models.signals import post_save
from django.db.models.signals import post_delete
from django_esutils.mappings import SearchMappingType
from demo_esutils.models import Article
ARTICLE_MAPPING = {
# author
'author__username': {
'type': 'string',
},
'autho... | # -*- coding: utf-8 -*-
from django.db.models.signals import post_save
from django.db.models.signals import post_delete
from django_esutils.mappings import SearchMappingType
from django_esutils.models import post_update
from demo_esutils.models import Article
ARTICLE_MAPPING = {
# author
'author__username':... | Update signals methods to call and connects Article to post_update signal. | Update signals methods to call and connects Article to post_update signal.
| Python | mit | novafloss/django-esutils,novafloss/django-esutils |
b4578d34adaa641dab5082f9d2bffe14c69649c5 | detour/__init__.py | detour/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
__version_info__ = '0.1.0'
__version__ = '0.1.0'
version = '0.1.0'
VERSION = '0.1.0'
def get_version():
return version # pragma: no cover
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
__version_info__ = '0.1.0'
__version__ = '0.1.0'
version = '0.1.0'
VERSION = '0.1.0'
def get_version():
return version # pragma: no cover
class DetourException(NotImplementedError):
pass
| Add a root exception for use if necessary. | Add a root exception for use if necessary.
| Python | bsd-2-clause | kezabelle/wsgi-detour |
a135e5a0919f64984b1348c3956bd95dc183e874 | scripts/test_deployment.py | scripts/test_deployment.py | import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == ... | import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == ... | Add test for custom images | Add test for custom images
| Python | mit | jacebrowning/memegen,jacebrowning/memegen |
ffb1dcff764b7494e0990f85f3af5f2354de0657 | zou/app/models/serializer.py | zou/app/models/serializer.py | from sqlalchemy.inspection import inspect
from zou.app.utils.fields import serialize_value
class SerializerMixin(object):
def serialize(self):
attrs = inspect(self).attrs.keys()
return {
attr: serialize_value(getattr(self, attr)) for attr in attrs
}
@staticmethod
def ... | from sqlalchemy.inspection import inspect
from zou.app.utils.fields import serialize_value
class SerializerMixin(object):
def serialize(self, obj_type=None):
attrs = inspect(self).attrs.keys()
obj_dict = {
attr: serialize_value(getattr(self, attr)) for attr in attrs
}
... | Add object type to dict serialization | Add object type to dict serialization
| Python | agpl-3.0 | cgwire/zou |
9ef3e6d884566b514be50dd468665cd65e939a9f | akhet/urlgenerator.py | akhet/urlgenerator.py | """
Contributed by Michael Mericikel.
"""
from pyramid.decorator import reify
import pyramid.url as url
class URLGenerator(object):
def __init__(self, context, request):
self.context = context
self.request = request
@reify
def context(self):
return url.resource_url(self.context, s... | """
Contributed by Michael Mericikel.
"""
from pyramid.decorator import reify
import pyramid.url as url
class URLGenerator(object):
def __init__(self, context, request):
self.context = context
self.request = request
@reify
def context(self):
return url.resource_url(self.context, s... | Comment out 'static' and 'deform' methods; disagreements on long-term API. | Comment out 'static' and 'deform' methods; disagreements on long-term API.
| Python | mit | koansys/akhet,koansys/akhet |
369f607df1efa7cd715a1d5ed4d86b972f44d23b | project/home/views.py | project/home/views.py |
# imports
from flask import render_template, Blueprint
from project import db # pragma: no cover
from project.models import Person # pragma: no cover
# config
home_blueprint = Blueprint(
'home', __name__,
template_folder='templates'
) # pragma: no cover
# routes
# use decorators to link the function... |
# imports
from flask import render_template, Blueprint
from project import db # pragma: no cover
from project.models import Person # pragma: no cover
import random
# config
home_blueprint = Blueprint(
'home', __name__,
template_folder='templates'
) # pragma: no cover
MAX_GRID_SIZE_HOMEPAGE_PEOPLE = 6... | Select MAX people randomly, else all. | Select MAX people randomly, else all.
| Python | isc | dhmncivichacks/timewebsite,mikeputnam/timewebsite,mikeputnam/timewebsite,dhmncivichacks/timewebsite,dhmncivichacks/timewebsite,mikeputnam/timewebsite |
42869823b4af024906606c5caf50e5dc5de69a57 | api/mcapi/user/projects.py | api/mcapi/user/projects.py | from ..mcapp import app
from ..decorators import apikey, jsonp
from flask import g
import rethinkdb as r
#from .. import dmutil
from .. import args
from ..utils import error_response
@app.route('/v1.0/user/<user>/projects', methods=['GET'])
@apikey
@jsonp
def get_all_projects(user):
rr = r.table('projects').filter... | from ..mcapp import app
from ..decorators import apikey, jsonp
from flask import g
import rethinkdb as r
#from .. import dmutil
from .. import args
from ..utils import error_response
@app.route('/v1.0/user/<user>/projects', methods=['GET'])
@apikey
@jsonp
def get_all_projects(user):
rr = r.table('projects').filter... | Add call to get datadirs for a project. | Add call to get datadirs for a project.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org |
2c999f4a6bea1da70bf35f06283428ea0e196087 | python/getmonotime.py | python/getmonotime.py | import getopt, sys
if __name__ == '__main__':
sippy_path = None
try:
opts, args = getopt.getopt(sys.argv[1:], 's:S:i:o:b')
except getopt.GetoptError:
usage()
for o, a in opts:
if o == '-S':
sippy_path = a.strip()
continue
if sippy_path != None:
... | import getopt, sys
if __name__ == '__main__':
sippy_path = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'rS:')
except getopt.GetoptError:
usage()
out_realtime = False
for o, a in opts:
if o == '-S':
sippy_path = a.strip()
continue
if o... | Add an option to also output realtime along with monotime. | Add an option to also output realtime along with monotime.
| Python | bsd-2-clause | sippy/b2bua,sippy/b2bua |
fa22d91e053f301498d9d09a950558758bf9b40f | patroni/exceptions.py | patroni/exceptions.py | class PatroniException(Exception):
pass
class DCSError(PatroniException):
"""Parent class for all kind of exceptions related to selected distributed configuration store"""
def __init__(self, value):
self.value = value
def __str__(self):
"""
>>> str(DCSError('foo'))
"... | class PatroniException(Exception):
"""Parent class for all kind of exceptions related to selected distributed configuration store"""
def __init__(self, value):
self.value = value
def __str__(self):
"""
>>> str(DCSError('foo'))
"'foo'"
"""
return repr(self.v... | Move some basic methods implementation into parent exception class | Move some basic methods implementation into parent exception class
| Python | mit | sean-/patroni,pgexperts/patroni,zalando/patroni,sean-/patroni,jinty/patroni,jinty/patroni,zalando/patroni,pgexperts/patroni |
f0ede3d2c32d4d3adce98cd3b762b672f7af91a9 | relay_api/__main__.py | relay_api/__main__.py | from relay_api.api.server import server
from relay_api.core.relay import relay
from relay_api.conf.config import relays
import relay_api.api.server as api
for r in relays:
relays[r]["instance"] = relay(relays[r]["gpio"],
relays[r]["NC"])
@server.route("/relay-api/relays", metho... | from relay_api.api.server import server
from relay_api.core.relay import relay
from relay_api.conf.config import relays
import relay_api.api.server as api
relays_dict = {}
for r in relays:
relays_dict[r] = relay(relays[r]["gpio"], relays[r]["NC"])
@server.route("/relay-api/relays", methods=["GET"])
def get_rela... | Update to generate a dict with the relay instances | Update to generate a dict with the relay instances
| Python | mit | pahumadad/raspi-relay-api |
a406334f0fcc26f235141e1d453c4aa5b632fdaf | nbconvert/utils/exceptions.py | nbconvert/utils/exceptions.py | """Contains all of the exceptions used in NBConvert explicitly"""
#-----------------------------------------------------------------------------
# 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 w... | """NbConvert specific exceptions"""
#-----------------------------------------------------------------------------
# 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.
#----------... | Comment & Refactor, utils and nbconvert main. | Comment & Refactor, utils and nbconvert main.
| Python | bsd-3-clause | jupyter-widgets/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywi... |
bc0193a3a32521512b77e6149e91eab805836f8d | django_dbq/management/commands/queue_depth.py | django_dbq/management/commands/queue_depth.py | from django.core.management.base import BaseCommand
from django_dbq.models import Job
class Command(BaseCommand):
help = "Print the current depth of the given queue"
def add_arguments(self, parser):
parser.add_argument("queue_name", nargs="*", default=["default"], type=str)
def handle(self, *ar... | from django.core.management.base import BaseCommand
from django_dbq.models import Job
class Command(BaseCommand):
help = "Print the current depth of the given queue"
def add_arguments(self, parser):
parser.add_argument("queue_name", nargs="*", default=["default"], type=str)
def handle(self, *ar... | Convert f-string to .format call | Convert f-string to .format call
| Python | bsd-2-clause | dabapps/django-db-queue |
b493073ec6978b6291cc66491bb3406179013d3d | create_variants_databases.py | create_variants_databases.py | #!/usr/bin/env python
import argparse
import getpass
from cassandra import query
from cassandra.cqlengine.management import sync_table
from cassandra.cqlengine.management import create_keyspace_simple
from cassandra.cluster import Cluster
from cassandra.cqlengine import connection
from cassandra.auth import PlainTextA... | #!/usr/bin/env python
import argparse
import getpass
from cassandra import query
from cassandra.cqlengine.management import sync_table
from cassandra.cqlengine.management import create_keyspace_simple
from cassandra.cluster import Cluster
from cassandra.cqlengine import connection
from cassandra.auth import PlainTextA... | Add additional table to cassandra variant store | Add additional table to cassandra variant store
| Python | mit | dgaston/ddb-datastore,dgaston/ddb-variantstore,dgaston/ddbio-variantstore,GastonLab/ddb-datastore |
d46d896b63ac24759a21c49e30ff9b3dc5c81595 | TS/Utils.py | TS/Utils.py | # Copyright (C) 2016 Antoine Carme <Antoine.Carme@Laposte.net>
# All rights reserved.
# This file is part of the Python Automatic Forecasting (PyAF) library and is made available under
# the terms of the 3 Clause BSD license
import sys, os
def createDirIfNeeded(dirname):
try:
os.mkdir(dirname);
excep... | # Copyright (C) 2016 Antoine Carme <Antoine.Carme@Laposte.net>
# All rights reserved.
# This file is part of the Python Automatic Forecasting (PyAF) library and is made available under
# the terms of the 3 Clause BSD license
import sys, os
def createDirIfNeeded(dirname):
try:
os.mkdir(dirname);
excep... | Enable default logging (not sure if this is OK) | Enable default logging (not sure if this is OK)
| Python | bsd-3-clause | antoinecarme/pyaf,antoinecarme/pyaf,antoinecarme/pyaf |
4407fcb950f42d080ca7e6477cddd507c87e4619 | tests/unit/cloudsearch/test_exceptions.py | tests/unit/cloudsearch/test_exceptions.py | import mock
from boto.compat import json
from tests.unit import unittest
from .test_search import HOSTNAME, CloudSearchSearchBaseTest
from boto.cloudsearch.search import SearchConnection, SearchServiceException
def fake_loads_value_error(content, *args, **kwargs):
"""Callable to generate a fake ValueError"""
... | import mock
from boto.compat import json
from tests.unit import unittest
from .test_search import HOSTNAME, CloudSearchSearchBaseTest
from boto.cloudsearch.search import SearchConnection, SearchServiceException
def fake_loads_value_error(content, *args, **kwargs):
"""Callable to generate a fake ValueError"""
... | Use assertRaises instead of try/except blocks for unit tests | Use assertRaises instead of try/except blocks for unit tests
| Python | mit | ekalosak/boto,kouk/boto,revmischa/boto,Asana/boto,TiVoMaker/boto,rjschwei/boto,tpodowd/boto,Timus1712/boto,drbild/boto,awatts/boto,yangchaogit/boto,campenberger/boto,podhmo/boto,israelbenatar/boto,alex/boto,khagler/boto,abridgett/boto,FATruden/boto,janslow/boto,appneta/boto,j-carl/boto,clouddocx/boto,jindongh/boto,bryx... |
c80a0e14b0fc7a61accddd488f096f363fc85f2f | iss.py | iss.py | import requests
from datetime import datetime
def get_next_pass(lat, lon):
iss_url = 'http://api.open-notify.org/iss-pass.json'
location = {'lat': lat, 'lon': lon}
response = requests.get(iss_url, params=location).json()
next_pass = response['response'][0]['risetime']
return datetime.fromtimestam... | import requests
from redis import Redis
from rq_scheduler import Scheduler
from twilio.rest import TwilioRestClient
from datetime import datetime
redis_server = Redis()
scheduler = Scheduler(connection=Redis())
client = TwilioRestClient()
def get_next_pass(lat, lon):
iss_url = 'http://api.open-notify.org/iss-p... | Add functions for scheduling messages and adding numbers to Redis | Add functions for scheduling messages and adding numbers to Redis
| Python | mit | sagnew/ISSNotifications,sagnew/ISSNotifications,sagnew/ISSNotifications |
567aa141546c905b842949799474742bf171a445 | codegolf/__init__.py | codegolf/__init__.py | from flask import Flask
from .models import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
from codegolf import views
| from flask import Flask
import sqlalchemy as sa
from .models import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
engine = sa.create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
Session = sa.sessionmaker(bind=engine)
# instantiate Session to do things.
# I might write some ... | Update app decl to use sqlalchemy rather than flask_sqlalchemy properly | Update app decl to use sqlalchemy rather than flask_sqlalchemy properly
| Python | mit | UQComputingSociety/codegolf,UQComputingSociety/codegolf,UQComputingSociety/codegolf |
c50051bd8699589c20acb32764b13bdb1473ff23 | itsy/utils.py | itsy/utils.py | from . import Task, client
from .document import Document
def test_handler(handler, url):
print "Testing handler: %s" % handler.__name__
t = Task(url=url, document_type=None, referer=None)
print " Fetching url: %s" % url
raw = client.get(url, None)
doc = Document(t, raw)
print " Applying han... | from datetime import datetime
from decimal import Decimal
from . import Task
from .client import Client
from .document import Document
def test_handler(handler, url):
print "Testing handler: %s" % handler.__name__
t = Task(url=url, document_type=None, referer=None)
print " Fetching url: %s" % url
cl... | Update test_handler() to use Client() class | Update test_handler() to use Client() class
| Python | mit | storborg/itsy |
acf7b76e098e70c77fbce95d03ec70911260ab58 | accloudtant/__main__.py | accloudtant/__main__.py | from accloudtant import load_data
if __name__ == "__main__":
usage = load_data("tests/fixtures/2021/03/S3.csv")
print("Simple Storage Service")
for area, concepts in usage.totals(omit=lambda x: x.is_data_transfer or x.type == "StorageObjectCount"):
print("\t", area)
for c, v, u in concept... | import argparse
from accloudtant import load_data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="AWS cost calculator")
parser.add_argument("csv_file", type=str, help='CSV file to read')
args = parser.parse_args()
usage = load_data(args.csv_file)
print("Simple Storage Se... | Add argument to specify different files to load | Add argument to specify different files to load
This will make implementing other services easier.
| Python | apache-2.0 | ifosch/accloudtant |
63f06cdea9a0471708ee633ff0546b22cdebb786 | pycolfin/cli.py | pycolfin/cli.py | # -*- coding: utf-8 -*-
import click
from .pycolfin import COLFin
from getpass import getpass
verbosity_help = """
1 = User ID, Last Login, Equity Value, Day Change
2 = Display all info from 1 and portfolio summary
3 = Display all info in 1 & 2 and detailed portfolio
"""
@click.command()
@click.option('-v', '--ve... | # -*- coding: utf-8 -*-
import click
from .pycolfin import COLFin
from getpass import getpass
verbosity_help = """
1 = User ID, Last Login, Equity Value, Day Change
2 = Display all info from 1 and portfolio summary
3 = Display all info in 1 & 2 and detailed portfolio
"""
@click.command()
@click.option('-v', '--ve... | Print message if exception encountered when trying to show detailed port/mutual funds | Print message if exception encountered when trying to show detailed port/mutual funds
Hopefully this handles the case when the user currently has no stocks and/or mutual funds. :fire:
| Python | mit | patpatpatpatpat/pycolfin |
a6adcc09bd1abe1d2538d499153a102cc37d5565 | reader/reader.py | reader/reader.py | import json
import pika
from twython import TwythonStreamer
class TwitterConfiguration:
def __init__(self):
with open('twitter_key.json') as jsonData:
data = json.load(jsonData)
self.consumer_key = data['consumer_key']
self.consumer_secret = data['consumer_secret']
self... | import json
import pika
import time
from twython import TwythonStreamer
class TwitterConfiguration:
def __init__(self):
with open('twitter_key.json') as jsonData:
data = json.load(jsonData)
self.consumer_key = data['consumer_key']
self.consumer_secret = data['consumer_secret']
... | Add retry for opening RabbitMQ connection (cluster start) | Add retry for opening RabbitMQ connection (cluster start)
| Python | mit | estiller/tweet-analyzer-demo,estiller/tweet-analyzer-demo,estiller/tweet-analyzer-demo,estiller/tweet-analyzer-demo,estiller/tweet-analyzer-demo |
575a73f7e1ba7d175fa406478e71fd05fd2cae2e | test/test_web_services.py | test/test_web_services.py | # -*- coding: utf-8 -*-
#
| # -*- coding: utf-8 -*-
#
import avalon.web.services
def test_intersection_with_empty_set():
set1 = set(['foo', 'bar'])
set2 = set(['foo'])
set3 = set()
res = avalon.web.services.intersection([set1, set2, set3])
assert 0 == len(res), 'Expected empty set of common results'
def test_intersectio... | Add tests for result set intersection method | Add tests for result set intersection method
| Python | mit | tshlabs/avalonms |
5d7c85d33f8e51947d8791bd597720f161a48f82 | game/views.py | game/views.py | from django.shortcuts import render
from django.http import HttpResponse
def index(request):
context = {'text': 'Welcome to our game'}
return render(request, 'game/index.html', context)
def users(request):
context = {'text': 'User list here'}
return render(request, 'game/users.html', context)
def user_deta... | from django.shortcuts import render
from django.http import HttpResponse
def index(request):
context = {'text': 'Welcome to our game'}
return render(request, 'game/index.html', context)
def register(request):
context = {'text': 'Register here'}
return render(request, 'registration/register.html', cont... | Fix merge conflict with master repo | Fix merge conflict with master repo
| Python | mit | shintouki/augmented-pandemic,shintouki/augmented-pandemic,shintouki/augmented-pandemic |
8c96f3211967c680ee26b673dc9fe0299180a1c4 | knights/dj.py | knights/dj.py | from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEn... | from collections import defaultdict
from django.template.base import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(B... | Update adapter to catch exception from loader | Update adapter to catch exception from loader
| Python | mit | funkybob/knights-templater,funkybob/knights-templater |
9f80145574cfad56e91df9a598c311894d12a675 | scratchpad/ncurses.py | scratchpad/ncurses.py | #!/usr/bin/env python3
from curses import wrapper
import platform
if platform.system() == "Darwin":
# create mock class for Pi Camera
class Camera:
def __init__(self):
self.brightness = 10
self.contrast = 24
else:
import picamera
properties = [
"brightness",
"contrast"
]
camera = Camera()
def main(std... | #!/usr/bin/env python3
from curses import wrapper
import platform
if platform.system() == "Darwin":
# create mock class for Pi Camera
class PiCamera:
def __init__(self):
self.brightness = 10
self.contrast = 24
else:
from picamera import PiCamera
properties = [
"brightness",
"contrast"
]
camera = PiCame... | Fix name of Camera class | Fix name of Camera class
| Python | mit | gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x |
75c1dedb6eddfcb540ee29de5ae31b99d9927d07 | reddit/admin.py | reddit/admin.py | from django.contrib import admin
from reddit.models import RedditAccount
from reddit.forms import RedditAccountForm
from datetime import date
class RedditAccountAdmin(admin.ModelAdmin):
list_display = ('username', 'user', 'date_created', 'link_karma', 'comment_karma', 'last_update', 'is_valid')
search_fields ... | from django.contrib import admin
from reddit.models import RedditAccount
from reddit.forms import RedditAccountForm
from datetime import date
class RedditAccountAdmin(admin.ModelAdmin):
list_display = ('username', 'user', 'date_created', 'link_karma', 'comment_karma', 'last_update', 'validated', 'is_valid')
s... | Add validation details to the Admin interface | Add validation details to the Admin interface
| Python | bsd-3-clause | nikdoof/test-auth |
ca09f3e4286be605e179f0b6ac742305d165b431 | monasca_setup/detection/plugins/http_check.py | monasca_setup/detection/plugins/http_check.py | import logging
import monasca_setup.agent_config
import monasca_setup.detection
log = logging.getLogger(__name__)
class HttpCheck(monasca_setup.detection.ArgsPlugin):
""" Setup an http_check according to the passed in args.
Despite being a detection plugin this plugin does no detection and will be a noo... | import ast
import logging
import monasca_setup.agent_config
import monasca_setup.detection
log = logging.getLogger(__name__)
class HttpCheck(monasca_setup.detection.ArgsPlugin):
""" Setup an http_check according to the passed in args.
Despite being a detection plugin this plugin does no detection and wi... | Allow additional customization of HttpCheck | Allow additional customization of HttpCheck
Documentation on HttpCheck detection plugin refers to things that do
not currently work in the plugin, like activating use_keystone. This
change fixes that, and adds the ability to customize other http_check
parameters which were missing.
Change-Id: I2309b25f83f395dcd56914... | Python | bsd-3-clause | sapcc/monasca-agent,sapcc/monasca-agent,sapcc/monasca-agent |
a61d50ff6f564112c04d3a9a8ac6e57d5b99da9d | heufybot/output.py | heufybot/output.py | class OutputHandler(object):
def __init__(self, connection):
self.connection = connection
def cmdJOIN(self, channels, keys=None):
chans = channels.split(",")
for i in range(len(chans)):
if chans[i][0] not in self.connection.supportHelper.chanTypes:
chans[i] =... | class OutputHandler(object):
def __init__(self, connection):
self.connection = connection
def cmdJOIN(self, channels, keys=[]):
for i in range(len(channels)):
if channels[i][0] not in self.connection.supportHelper.chanTypes:
channels[i] = "#{}".format(channels[i])
... | Use lists for the JOIN command and parse them before sending | Use lists for the JOIN command and parse them before sending
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot |
980492cb76d0d72a005269a4fb9c1ec9767c10de | symfit/api.py | symfit/api.py | # Overwrite behavior of sympy objects to make more sense for this project.
import symfit.core.operators
# Expose useful objects.
from symfit.core.fit import (
Fit, Model, Constraint, ODEModel, ModelError, CallableModel,
CallableNumericalModel, GradientModel
)
from symfit.core.fit_results import FitResults
from... | # Overwrite behavior of sympy objects to make more sense for this project.
import symfit.core.operators
# Expose useful objects.
from symfit.core.fit import (
Fit, Model, ODEModel, ModelError, CallableModel,
CallableNumericalModel, GradientModel
)
from symfit.core.fit_results import FitResults
from symfit.core... | Remove Constraint objects from the API | Remove Constraint objects from the API
| Python | mit | tBuLi/symfit |
81cd197e95e89dd37797c489774f34496ecea259 | server/pushlanding.py | server/pushlanding.py | import logging
import os
from django.http import HttpResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from twilio.rest import TwilioRestClient
logger = logging.getLogger('django')
@csrf_exempt
def handle(request):
if (request.method != 'POST'):
raise Http404
return HttpResponse("Hello, ... | import logging
import os
import json
from django.http import HttpResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from twilio.rest import TwilioRestClient
logger = logging.getLogger('django')
@csrf_exempt
def handle(request):
if (request.method != 'POST'):
raise Http404
logger.info("Rec... | Add debug logging for push landing | Add debug logging for push landing
| Python | mit | zackzachariah/scavenger,zackzachariah/scavenger |
9729a77b9b8cbfe8a6960ded4b5931e3ed64fe10 | discover/__init__.py | discover/__init__.py | import logging
LOG_FORMAT = '%(asctime)s [%(name)s] %(levelname)s %(message)s'
LOG_DATE = '%Y-%m-%d %I:%M:%S %p'
logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE, level=logging.WARN)
logger = logging.getLogger('yoda-discover')
logger.level = logging.INFO
| import logging
LOG_FORMAT = '[%(name)s] %(levelname)s %(message)s'
logging.basicConfig(format=LOG_FORMAT, level=logging.WARN)
logger = logging.getLogger('yoda-discover')
logger.level = logging.INFO
| Remove date from log formatting (handled by syslog) | Remove date from log formatting (handled by syslog)
| Python | mit | totem/yoda-discover |
99b72ab4e40a4ffca901b36d870947ffb5103da8 | HadithHouseWebsite/textprocessing/regex.py | HadithHouseWebsite/textprocessing/regex.py | import re
class DocScanner(object):
"""
A class used to find certain tokens in a given document. The tokens can be
specified by regular expressions.
"""
def __init__(self, tokens_dict, callback):
"""
Initialize a new document scanner.
:param tokens_dict: A dictionary whose keys are the types of... | import re
class DocScanner(object):
"""
A class used to find certain tokens in a given document. The tokens can be
specified by regular expressions.
"""
def __init__(self, tokens_dict, callback):
"""
Initialize a new document scanner.
:param tokens_dict: A dictionary whose keys are the types of... | Support passing context to callback | feat(docscanner): Support passing context to callback
It might be useful to send some additional parameters to the callback
function. For example, you might want to write to a file in the
callback. This commit allows the user to pass an optional context to
the callback everytime it finds a match.
| Python | mit | hadithhouse/hadithhouse,rafidka/hadithhouse,rafidka/hadithhouse,hadithhouse/hadithhouse,hadithhouse/hadithhouse,hadithhouse/hadithhouse,rafidka/hadithhouse,rafidka/hadithhouse,rafidka/hadithhouse,hadithhouse/hadithhouse,rafidka/hadithhouse,hadithhouse/hadithhouse |
114382ff9b6dad3c9ba621014dd7cd63ad49bef6 | django/santropolFeast/meal/models.py | django/santropolFeast/meal/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Meal(models.Model):
class Meta:
verbose_name_plural = _('meals')
# Meal information
nom = models.CharField(max_length=50, verbose_name=_('name'))
description = models.TextField(verbose_name=_('descript... | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Meal(models.Model):
class Meta:
verbose_name_plural = _('meals')
# Meal information
nom = models.CharField(max_length=50, verbose_name=_('name'))
description = models.TextField(verbose_name=_('descript... | Use string representation for objects | Use string representation for objects
| Python | agpl-3.0 | savoirfairelinux/santropol-feast,savoirfairelinux/sous-chef,savoirfairelinux/santropol-feast,savoirfairelinux/sous-chef,madmath/sous-chef,savoirfairelinux/sous-chef,madmath/sous-chef,savoirfairelinux/santropol-feast,madmath/sous-chef |
31eadf6cdaf70621941a6c5d269ed33f46e27cd7 | check.py | check.py | """
This script can be used to check if TM1py can connect to your TM1 instance
"""
import getpass
from distutils.util import strtobool
from TM1py.Services import TM1Service
# Parameters for connection
user = input("TM1 User (leave empty if SSO): ")
password = getpass.getpass("Password (cmd doesn't show input, leave ... | """
This script can be used to check if TM1py can connect to your TM1 instance
"""
import getpass
from distutils.util import strtobool
from TM1py.Services import TM1Service
# Parameters for connection
user = input("TM1 User (leave empty if SSO): ")
password = getpass.getpass("Password (leave empty if SSO): ")
namesp... | Return error message instead of stack and add defaults to input | Return error message instead of stack and add defaults to input
| Python | mit | cubewise-code/TM1py-samples |
759e22f8d629f76d7fca0d0567603c9ae6835fa6 | api_v3/serializers/profile.py | api_v3/serializers/profile.py | from django.conf import settings
from rest_framework import fields
from rest_framework_json_api import serializers
from api_v3.models import Profile, Ticket
class ProfileSerializer(serializers.ModelSerializer):
tickets_count = fields.SerializerMethodField()
class Meta:
model = Profile
read_... | from django.conf import settings
from rest_framework import fields
from rest_framework_json_api import serializers
from api_v3.models import Profile, Ticket
class ProfileSerializer(serializers.ModelSerializer):
tickets_count = fields.SerializerMethodField()
class Meta:
model = Profile
read_... | Return sorted member centers and expense scopes. | Return sorted member centers and expense scopes.
| Python | mit | occrp/id-backend |
ecfa18b7f05a23bdc6beab705dc748559eef2873 | lockdown/decorators.py | lockdown/decorators.py | from django.utils.decorators import decorator_from_middleware_with_args
from lockdown.middleware import LockdownMiddleware
def lockdown(*args, **kwargs):
"""Define a decorator based on the LockdownMiddleware.
This decorator takes the same arguments as the middleware, but allows a
more granular locking t... | """Provide a decorator based on the LockdownMiddleware.
This module provides a decorator that takes the same arguments as the
middleware, but allows more granular locking than the middleware.
"""
from django.utils.decorators import decorator_from_middleware_with_args
from lockdown.middleware import LockdownMiddleware... | Remove wrapping of decorator in a func | Remove wrapping of decorator in a func
Growing older, growing wiser ...
This removes the unnecesary wrapping of the decorator in a function
introduced in e4a04c6, as it's not necessary and is less performant than
without.
| Python | bsd-3-clause | Dunedan/django-lockdown,Dunedan/django-lockdown |
23604efc203f62f1059c4bd18f233cccdaf045e6 | server/app_factory/create_app.py | server/app_factory/create_app.py | import wtforms_json
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
wtforms_json.init()
# Define the WSGI Application object
app = Flask(
__name__,
template_folder="../../",
static_folder="../../static"
)
# Configu... | import wtforms_json
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
# Create db object so it can be shared throughout the application
db = SQLAlchemy()
# Create the login manager to be shared throughout the application
login_manager = LoginManager()
def c... | Add login manager initialization to app creation method | Add login manager initialization to app creation method
| Python | mit | ganemone/ontheside,ganemone/ontheside,ganemone/ontheside |
2d35e48b68ff51fae09369b4a1a00d7599c454c1 | common/djangoapps/util/json_request.py | common/djangoapps/util/json_request.py | from functools import wraps
import copy
import json
def expect_json(view_function):
@wraps(view_function)
def expect_json_with_cloned_request(request, *args, **kwargs):
if request.META['CONTENT_TYPE'] == "application/json":
cloned_request = copy.copy(request)
cloned_request.POS... | from functools import wraps
import copy
import json
def expect_json(view_function):
@wraps(view_function)
def expect_json_with_cloned_request(request, *args, **kwargs):
# cdodge: fix postback errors in CMS. The POST 'content-type' header can include additional information
# e.g. 'charset', so ... | Fix JSON postback error where the content-type header line can contain more info than just the application/json descriptor. Now we just to a compare on the start of the header value. | Fix JSON postback error where the content-type header line can contain more info than just the application/json descriptor. Now we just to a compare on the start of the header value.
| Python | agpl-3.0 | 10clouds/edx-platform,chrisndodge/edx-platform,beacloudgenius/edx-platform,ahmadio/edx-platform,devs1991/test_edx_docmode,jzoldak/edx-platform,rismalrv/edx-platform,beacloudgenius/edx-platform,kmoocdev2/edx-platform,vismartltd/edx-platform,beni55/edx-platform,auferack08/edx-platform,adoosii/edx-platform,ferabra/edx-pla... |
ed271823e5a5f957b17f00fd4823b6ae0b973e83 | scripts/seam.py | scripts/seam.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Produces IPHAS Data Release 2 using an MPI computing cluster."""
from IPython import parallel
from astropy import log
__author__ = 'Geert Barentsen'
# Create the cluster view
client = parallel.Client('/home/gb/.config/ipython/profile_mpi/security/ipcontroller-seaming-c... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Produces IPHAS Data Release 2 using an MPI computing cluster."""
from IPython import parallel
from astropy import log
__author__ = 'Geert Barentsen'
# Create the cluster view
client = parallel.Client('/home/gb/.config/ipython/profile_mpi/security/ipcontroller-seaming-c... | Allow Glazebrook to be executed in a multi-pass fashion + parallelise | Allow Glazebrook to be executed in a multi-pass fashion + parallelise
| Python | mit | barentsen/iphas-dr2,barentsen/iphas-dr2,barentsen/iphas-dr2 |
b51c8d107b6da5d6d6b0cc5a1db525bff856a1cf | AgileCLU/tests/__init__.py | AgileCLU/tests/__init__.py | #!/usr/bin/env python
import AgileCLU
import unittest
class AgileCLUTestCase(unittest.TestCase):
def setup(self):
self.agileclu = AgileCLU()
def test_epwbasekey(self):
return
def test_e_pw_hash(self):
return
def test_e_pw_dehash(self):
return
if __name__ == "__main__":
unittest.main()
| #!/usr/bin/env python
import unittest
import AgileCLU
class AgileCLUTestCase(unittest.TestCase):
def test_epwbasekey(self):
hash=AgileCLU.epwbasekey('test', 'test', 'test.example.com', '/')
self.assertEqual(hash, 'AbiDicIBaEuvafIuegJWVP8j')
def test_e_pw_hash(self):
hash=AgileCLU.e_pw_hash('teststr',... | Add basic asserts for hashing helper functions. | Add basic asserts for hashing helper functions.
| Python | bsd-2-clause | wylieswanson/AgileCLU |
52c5f4ddfde8db6179f11c3bec2bc8be69eed238 | flake8_docstrings.py | flake8_docstrings.py | # -*- coding: utf-8 -*-
"""pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import pep257
__version__ = '0.2.1.post1'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
version = __version__
def __in... | # -*- coding: utf-8 -*-
"""pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import io
import pep8
import pep257
__version__ = '0.2.1.post1'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
version = __... | Handle stdin in the plugin | Handle stdin in the plugin
Closes #2
| Python | mit | PyCQA/flake8-docstrings |
017ba0d18acb83a5135dd7a23c085b3c93d539b3 | linkatos/message.py | linkatos/message.py | import re
link_re = re.compile("https?://\S+(\s|$)")
def extract_url(message):
"""
Returns the first url in a message. If there aren't any returns None
"""
answer = link_re.search(message)
if answer is not None:
answer = answer.group(0).strip()
return answer
| import re
link_re = re.compile("(\s|^)<(https?://[\w./?+]+)>(\s|$)")
def extract_url(message):
"""
Returns the first url in a message. If there aren't any returns None
"""
answer = link_re.search(message)
if answer is not None:
answer = answer.group(2).strip()
return answer
| Change regex to adapt to the <url> format | fix: Change regex to adapt to the <url> format
| Python | mit | iwi/linkatos,iwi/linkatos |
4c4f4e3e5f1e92d0acdaf1598d4f9716bcd09727 | app/users/models.py | app/users/models.py | from datetime import datetime
from app import db, bcrypt
from app.utils.misc import make_code
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Co... | from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = d... | Put pw reset expiration date in future | Put pw reset expiration date in future
| Python | mit | projectweekend/Flask-PostgreSQL-API-Seed |
5f88686bdd089d67192f75eac9d3f46effad2983 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Sergey Margaritov
# Copyright (c) 2013 Sergey Margaritov
#
# License: MIT
#
"""This module exports the scss-lint plugin linter class."""
import os
from SublimeLinter.lint import RubyLinter, util
class Scss(RubyLin... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Sergey Margaritov
# Copyright (c) 2013 Sergey Margaritov
#
# License: MIT
#
"""This module exports the scss-lint plugin linter class."""
import os
from SublimeLinter.lint import RubyLinter, util
class Scss(RubyLin... | Fix regex for different output from scss-lint 0.49.0 | Fix regex for different output from scss-lint 0.49.0
| Python | mit | attenzione/SublimeLinter-scss-lint |
4f64f04a2fbbd2b25c38c9e0171be6eeaff070cf | main.py | main.py | #!/usr/bin/env python
from blinkenlights import setup, cleanup
from fourleds import light, clear
from time import sleep
pins = [32, 22, 18, 16]
# blu grn red yel
for p in pins:
setup(p)
for i in range(20):
for p in [32, 22, 18, 16, 18, 22, 32]:
clear(pins)
light(p)
sleep(0.07)
... | #!/usr/bin/env python
from blinkenlights import setup, cleanup
from fourleds import light, clear
from time import sleep
from random import randint
pins = [32, 22, 18, 16]
# blu grn red yel
for p in pins:
setup(p)
for i in range(20):
k1 = randint(5, 10) * 0.01
k2 = randint(5, 20) * 0.1
for p in... | Add pleasant surprises in timing | Add pleasant surprises in timing
| Python | mit | zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie |
1a150cb57171212358b84e351a0c073baa83d9fd | Home/xsOros.py | Home/xsOros.py | def checkio(array):
if array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]:
return array[0][0]
if array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0] == array[1][1] == array[... | def checkio(array):
if (array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]) and array[0][0] != '.':
return array[0][0]
if (array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0... | Fix the issue on Xs or Os problem. | Fix the issue on Xs or Os problem.
| Python | mit | edwardzhu/checkio-solution |
359cbd7b45289e364ad262f09dd3d3ef3932eb76 | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
from website.app import init_app
if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.base.settings')
from django.core.management import execute_from_command_line
init_app(set_backends=True, routes=False, mfr=False, attach_request_han... | #!/usr/bin/env python
import os
import sys
from website.app import init_app
if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.base.settings')
from django.core.management import execute_from_command_line
init_app(set_backends=True, routes=False, attach_request_handlers=False... | Remove mfr kwarg from app init so the API will run | Remove mfr kwarg from app init so the API will run
| Python | apache-2.0 | alexschiller/osf.io,Ghalko/osf.io,dplorimer/osf,mluo613/osf.io,CenterForOpenScience/osf.io,ZobairAlijan/osf.io,cldershem/osf.io,ticklemepierce/osf.io,chennan47/osf.io,aaxelb/osf.io,rdhyee/osf.io,abought/osf.io,crcresearch/osf.io,KAsante95/osf.io,mattclark/osf.io,lyndsysimon/osf.io,brianjgeiger/osf.io,amyshi188/osf.io,j... |
f1957185f0d93861a8ed319223f574df8f4e838f | src/graphql_relay/node/plural.py | src/graphql_relay/node/plural.py | from typing import Any, Callable
from graphql.type import (
GraphQLArgument,
GraphQLField,
GraphQLInputType,
GraphQLOutputType,
GraphQLList,
GraphQLNonNull,
GraphQLResolveInfo,
)
def plural_identifying_root_field(
arg_name: str,
input_type: GraphQLInputType,
output_type: Graph... | from typing import Any, Callable
from graphql.type import (
GraphQLArgument,
GraphQLField,
GraphQLInputType,
GraphQLOutputType,
GraphQLList,
GraphQLNonNull,
GraphQLResolveInfo,
is_non_null_type,
)
def plural_identifying_root_field(
arg_name: str,
input_type: GraphQLInputType,
... | Use graphql's predicate function instead of 'isinstance' | Use graphql's predicate function instead of 'isinstance'
Replicates graphql/graphql-relay-js@5b428507ef246be7ca3afb3589c410874a57f9bc
| Python | mit | graphql-python/graphql-relay-py |
6e2a484ac46279c6a077fb135d7e5f66605e9b88 | mox/app.py | mox/app.py | from flask import Flask
from flask.ext.mongoengine import MongoEngine
from views import mocks
import os
app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {
"db": "mox"
}
app.config["SECRET_KEY"] = "KeepThisS3cr3t"
if os.environ.get('PRODUCTION'):
app.config["MONGODB_SETTINGS"]["host"] = os.environ.get("PROD_MO... | from flask import Flask
from flask.ext.mongoengine import MongoEngine
from views import mocks
import os
app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {
"db": "mox"
}
app.config["SECRET_KEY"] = "KeepThisS3cr3t"
if os.environ.get('HEROKU') == 1:
app.config["MONGODB_SETTINGS"]["host"] = os.environ.get("MONGOD... | Fix up settings for Heroku | Fix up settings for Heroku
| Python | mit | abouzek/mox,abouzek/mox |
2198e43a3701351085ac186a9a8574b788148fcf | mysite/mysite/tests/test_middleware.py | mysite/mysite/tests/test_middleware.py | from django.contrib.auth.models import User
from django.test import TestCase
from DjangoLibrary.middleware import FactoryBoyMiddleware
from mock import Mock
class TestFactoryBoyMiddleware(TestCase):
def setUp(self):
self.cm = FactoryBoyMiddleware()
self.request = Mock()
self.request.sessi... | from django.contrib.auth.models import User
from django.test import TestCase
from DjangoLibrary.middleware import FactoryBoyMiddleware
from mock import Mock
import json
class TestFactoryBoyMiddleware(TestCase):
def setUp(self):
self.middleware = FactoryBoyMiddleware()
self.request = Mock()
... | Add unit test for factory boy middleware. | Add unit test for factory boy middleware.
| Python | apache-2.0 | kitconcept/robotframework-djangolibrary |
f176051094b5482f48781f0695835fed5727742c | src/webassets/filter/uglifyjs.py | src/webassets/filter/uglifyjs.py | """Minify Javascript using `UglifyJS <https://github.com/mishoo/UglifyJS/>`_.
UglifyJS is an external tool written for NodeJS; this filter assumes that
the ``uglifyjs`` executable is in the path. Otherwise, you may define
a ``UGLIFYJS_BIN`` setting.
"""
import subprocess
from webassets.exceptions import FilterError
f... | """Minify Javascript using `UglifyJS <https://github.com/mishoo/UglifyJS/>`_.
UglifyJS is an external tool written for NodeJS; this filter assumes that
the ``uglifyjs`` executable is in the path. Otherwise, you may define
a ``UGLIFYJS_BIN`` setting. Additional options may be passed to ``uglifyjs``
by setting ``UGLIFYJ... | Allow UglifyJS to accept additional command-line arguments | Allow UglifyJS to accept additional command-line arguments
| Python | bsd-2-clause | JDeuce/webassets,scorphus/webassets,heynemann/webassets,scorphus/webassets,aconrad/webassets,JDeuce/webassets,glorpen/webassets,wijerasa/webassets,john2x/webassets,heynemann/webassets,aconrad/webassets,heynemann/webassets,wijerasa/webassets,glorpen/webassets,aconrad/webassets,0x1997/webassets,florianjacob/webassets,joh... |
d97dd4a8f4c0581ce33ed5838dcc0329745041bf | pirate_add_shift_recurrence.py | pirate_add_shift_recurrence.py | #!/usr/bin/python
import sys
import os
from tasklib.task import TaskWarrior
time_attributes = ('wait', 'scheduled')
def is_new_local_recurrence_child_task(task):
# Do not affect tasks not spun by recurrence
if not task['parent']:
return False
# Newly created recurrence tasks actually have
# ... | #!/usr/bin/python
import sys
import os
from tasklib import TaskWarrior
time_attributes = ('wait', 'scheduled')
def is_new_local_recurrence_child_task(task):
# Do not affect tasks not spun by recurrence
if not task['parent']:
return False
# Newly created recurrence tasks actually have
# modif... | Fix old style import and config overrides | Fix old style import and config overrides
| Python | mit | tbabej/task.shift-recurrence |
c429abe7bee0461c8d2874ecb75093246565e58c | code/python/Gaussian.py | code/python/Gaussian.py | import numpy as np
class Gaussian:
"""
An object of this class is a 2D elliptical gaussian
"""
def __init__(self):
"""
Constructor sets up a standard gaussian
"""
self.xc, self.yc, self.mass, self.width, self.q, self.theta =\
0., 0., 1., 1., 1., 0.
self.cos_theta, self.sin_theta = np.cos(self.theta... | import numpy as np
class Gaussian:
"""
An object of this class is a 2D elliptical gaussian
"""
def __init__(self):
"""
Constructor sets up a standard gaussian
"""
self.xc, self.yc, self.mass, self.width, self.q, self.theta =\
0., 0., 1., 1., 1., 0.
def evaluate(self, x, y):
"""
Evaluate the den... | Make an image of a gaussian | Make an image of a gaussian
| Python | mit | eggplantbren/MogTrack |
bce7111c2b927290e054dffb765468c41b785947 | bonspy/tests/test_features.py | bonspy/tests/test_features.py | from bonspy.features import _apply_operations
def test_apply_operations_domain():
value = _apply_operations('domain', 'www.test.com')
assert value == 'test.com'
def test_apply_operations_segment():
value = _apply_operations('segment', 1)
assert value == 1
| from bonspy.features import _apply_operations
def test_apply_operations_domain():
value = _apply_operations('domain', 'www.test.com')
assert value == 'test.com'
def test_apply_operations_other_feature():
value = _apply_operations('other_feature', 'www.test.com')
assert value == 'www.test.com'
de... | Test that stripping leading www is specific to domain feature | Test that stripping leading www is specific to domain feature
| Python | bsd-3-clause | markovianhq/bonspy |
9340b43508c4203c81e3feb9607c8a7fe5972eb5 | tools/skp/page_sets/skia_intelwiki_desktop.py | tools/skp/page_sets/skia_intelwiki_desktop.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=W0401,W0614
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
clas... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=W0401,W0614
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
clas... | Remove anchor and increase wait time for desk_intelwiki.skp | Remove anchor and increase wait time for desk_intelwiki.skp
No-Try: true
Bug: skia:11804
Change-Id: Ib30df7f233bd3c2bcbfdf5c62e803be187a4ff01
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/389712
Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com>
Reviewed-by: Robert Phillips <9... | Python | bsd-3-clause | google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,goo... |
1c5b70610a973ff90dab4253cb525acb7504d239 | filer/tests/__init__.py | filer/tests/__init__.py | #-*- coding: utf-8 -*-
from filer.tests.admin import *
from filer.tests.fields import *
from filer.tests.models import *
from filer.tests.permissions import *
from filer.tests.server_backends import *
from filer.tests.tools import *
from filer.tests.utils import *
| #-*- coding: utf-8 -*-
from filer.tests.admin import *
from filer.tests.models import *
from filer.tests.permissions import *
from filer.tests.server_backends import *
from filer.tests.tools import *
from filer.tests.utils import *
| Remove field tests import as they no loger exists | Remove field tests import as they no loger exists
| Python | bsd-3-clause | SmithsonianEnterprises/django-filer,jrief/django-filer,kriwil/django-filer,jakob-o/django-filer,samastur/django-filer,o-zander/django-filer,mkoistinen/django-filer,nimbis/django-filer,belimawr/django-filer,webu/django-filer,kriwil/django-filer,DylannCordel/django-filer,o-zander/django-filer,webu/django-filer,vechorko/d... |
018e76e5aa2a7ca8652af008a3b658017b3f178d | thefederation/tests/factories.py | thefederation/tests/factories.py | import factory
from django.utils.timezone import utc, now
from thefederation.models import Node, Platform, Protocol, Stat
class PlatformFactory(factory.DjangoModelFactory):
name = factory.Faker('word')
class Meta:
model = Platform
class ProtocolFactory(factory.DjangoModelFactory):
name = facto... | import factory
from django.utils.timezone import utc, now
from thefederation.models import Node, Platform, Protocol, Stat
class PlatformFactory(factory.DjangoModelFactory):
name = factory.Faker('pystr')
class Meta:
model = Platform
class ProtocolFactory(factory.DjangoModelFactory):
name = fact... | Make factory random names a bit more random to avoid clashes | Make factory random names a bit more random to avoid clashes
| Python | agpl-3.0 | jaywink/the-federation.info,jaywink/diaspora-hub,jaywink/diaspora-hub,jaywink/diaspora-hub,jaywink/the-federation.info,jaywink/the-federation.info |
524ee1cd2f56f6fe968f409d37cbd2af1621e7f3 | framework/guid/model.py | framework/guid/model.py | from framework import StoredObject, fields
class Guid(StoredObject):
_id = fields.StringField()
referent = fields.AbstractForeignField()
_meta = {
'optimistic': True,
}
class GuidStoredObject(StoredObject):
# Redirect to content using URL redirect by default
redirect_mode = 'redir... | from framework import StoredObject, fields
class Guid(StoredObject):
_id = fields.StringField()
referent = fields.AbstractForeignField()
_meta = {
'optimistic': True,
}
class GuidStoredObject(StoredObject):
# Redirect to content using URL redirect by default
redirect_mode = 'redir... | Fix last commit: Must ensure GUID before saving so that PK is defined | Fix last commit: Must ensure GUID before saving so that PK is defined
| Python | apache-2.0 | zkraime/osf.io,emetsger/osf.io,RomanZWang/osf.io,chennan47/osf.io,TomHeatwole/osf.io,adlius/osf.io,cwisecarver/osf.io,petermalcolm/osf.io,mfraezz/osf.io,wearpants/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,samanehsan/osf.io,CenterForOpenScience/osf.io,caseyrollins/osf.io,felliott/osf.io,monikagrabowska/osf.io,Johneto... |
3992e424169a9ac6eb0d13c03045139403dc27cf | main.py | main.py | import hashlib
import models
import os
import os.path
import peewee
def init():
models.db.connect()
models.db.create_tables([models.Entry])
def digest(file_path):
h = hashlib.sha1()
file = open(file_path, 'rb')
buf = file.read(8192)
while len(buf) > 0:
h.update(buf)
buf = file.... | import hashlib
import models
import os
import os.path
def init():
models.db.connect()
models.db.create_tables([models.Entry])
def digest(file_path):
h = hashlib.sha1()
file = open(file_path, 'rb')
buf = file.read(8192)
while len(buf) > 0:
h.update(buf)
buf = file.read(8192)
... | Fix import and indent issue | Fix import and indent issue
| Python | mit | rschiang/pineapple.py |
2567e56c7c17754e18346b21bcad6eab713276ea | googlebot/middleware.py | googlebot/middleware.py | import socket
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.models import User
class GooglebotMiddleware(object):
"""
Middleware to automatically log in the Googlebot with the user account 'googlebot'
"""
def process_request(self, request):
request.is_googlebot... | import socket
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.models import User
class GooglebotMiddleware(object):
"""
Middleware to automatically log in the Googlebot with the user account 'googlebot'
"""
def process_request(self, request):
request.is_googlebot... | Check to see if request.META contains HTTP_USER_AGENT | Check to see if request.META contains HTTP_USER_AGENT
| Python | bsd-3-clause | macropin/django-googlebot |
a270b7ea7636cd70b38f7e3534871a76ea2cdae1 | rejected/example.py | rejected/example.py | """Example Rejected Consumer"""
from rejected import consumer
import random
from tornado import gen
from tornado import httpclient
__version__ = '1.0.0'
class ExampleConsumer(consumer.SmartConsumer):
def process(self):
self.logger.info('Message: %r', self.body)
"""
action = random.rand... | """Example Rejected Consumer"""
from rejected import consumer
import random
from tornado import gen
from tornado import httpclient
__version__ = '1.0.0'
class ExampleConsumer(consumer.SmartConsumer):
def process(self):
self.logger.info('Message: %r', self.body)
action = random.randint(0, 100)
... | Remove the commented out block | Remove the commented out block
| Python | bsd-3-clause | gmr/rejected,gmr/rejected |
35f59e256224b82c82b2be3af4cd22e43443bc9f | mgsv_names.py | mgsv_names.py | from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select = 'select {} from {} order by random() limit 1'
_uncommon_select = 'select value from uncommons where key=?'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
cursor = conn... | from __future__ import unicode_literals, print_function
import sqlite3, os, random
_select = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_uncommon_select = 'select value from uncommons where key=?;'
def generate_name():
conn = sqlite3.connect(os.path.join(os.path.dirname(__f... | Update SQL for efficiency and semicolons. | Update SQL for efficiency and semicolons.
| Python | unlicense | rotated8/mgsv_names |
1a5a5268cea83a7d29346a677e9d10ec9e5411e8 | cuteshop/downloaders/git.py | cuteshop/downloaders/git.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from ..utils import DEVNULL, change_working_directory
from .base import DOWNLOAD_CONTAINER
def _checkout(name):
with change_working_directory(DOWNLOAD_CONTAINER):
subprocess.call(
('git', 'checkout', name),
stdout=DEV... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from ..utils import DEVNULL, change_working_directory
from .base import DOWNLOAD_CONTAINER
def _checkout(name):
with change_working_directory(DOWNLOAD_CONTAINER):
subprocess.call(
('git', 'checkout', name),
stdout=DEV... | Allow submodules in lib repo | Allow submodules in lib repo
| Python | mit | uranusjr/cuteshop |
6a9407d7cc4ac5555180a2ee331ff95eef131902 | mitmproxy/platform/osx.py | mitmproxy/platform/osx.py | import subprocess
from . import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing ... | import subprocess
from . import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing ... | Make sudo pfctl error check Python 3 compatible | Make sudo pfctl error check Python 3 compatible
In Python 3, subprocess.check_output() returns a sequence of bytes. This change ensures that it will be converted to a string, so the substring test for the sudo error message does not raise a TypeError. This fixes the code in Python 3 while remaining compatible with Pyt... | Python | mit | mitmproxy/mitmproxy,cortesi/mitmproxy,MatthewShao/mitmproxy,MatthewShao/mitmproxy,laurmurclar/mitmproxy,mosajjal/mitmproxy,cortesi/mitmproxy,vhaupert/mitmproxy,mhils/mitmproxy,dwfreed/mitmproxy,ddworken/mitmproxy,gzzhanghao/mitmproxy,StevenVanAcker/mitmproxy,ujjwal96/mitmproxy,StevenVanAcker/mitmproxy,xaxa89/mitmproxy,... |
f7f6a8a1b1f019b45b9f3c3c9c6124469a335798 | phildb_client/__init__.py | phildb_client/__init__.py | from client import PhilDBClient
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
| from phildb_client.client import PhilDBClient
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
| Make import of client module explicit | Make import of client module explicit
| Python | bsd-3-clause | amacd31/phildb_client |
9f17fc03a79434b3d92e4dea00ea33567c806280 | runner/update_manifest.py | runner/update_manifest.py | import json
import os
import sys
here = os.path.abspath(os.path.split(__file__)[0])
root = os.path.abspath(os.path.join(here, "..", ".."))
sys.path.insert(0, os.path.abspath(os.path.join(here, "..", "scripts")))
import manifest
def main(request, response):
manifest_path = os.path.join(root, "MANIFEST.json")
... | import json
import os
import sys
here = os.path.abspath(os.path.split(__file__)[0])
root = os.path.abspath(os.path.join(here, "..", ".."))
sys.path.insert(0, os.path.abspath(os.path.join(here, "..", "scripts")))
import manifest
def main(request, response):
path = os.path.join(root, "MANIFEST.json")
manifest... | Update test runner for changes in the manifest API. | Update test runner for changes in the manifest API.
| Python | bsd-3-clause | frewsxcv/wpt-tools,wpt-on-tv-tf/wpt-tools,wpt-on-tv-tf/wpt-tools,frewsxcv/wpt-tools,kaixinjxq/wpt-tools,UprootStaging/wpt-tools,UprootStaging/wpt-tools,wpt-on-tv-tf/wpt-tools,kaixinjxq/wpt-tools,vivliostyle/wpt-tools,UprootStaging/wpt-tools,frewsxcv/wpt-tools,vivliostyle/wpt-tools,kaixinjxq/wpt-tools,vivliostyle/wpt-to... |
6fab7a8170cbd993400b097478f328024c3f9247 | ezdaemon/__init__.py | ezdaemon/__init__.py | """Daemonize makes Unix-y daemons real easy. Just import daemonize.daemonize
and call the function before whatever you want the daemon to be. A couple
gotchas:
1) It will disconnect your python process from stdin and stdout, so any
print calls will not show up. This is because daemons are disconnected
from... | """ezdaemon makes Unix-y daemons real easy. Just import ezdaemon.daemonize
and call it before whatever you want the daemon to be. A couple gotchas:
1. It will disconnect your python process from stdin and stdout, so any
print calls will not show up. This is because daemons are disconnected
from any controlling t... | Make init docstring reflect README | Make init docstring reflect README
| Python | mit | cjeffers/ezdaemon |
b262d53e8347ea666cb5cd46bc9e19b7944cf7e6 | core/data/DataWriter.py | core/data/DataWriter.py | """
DataWriter.py
"""
from DataController import DataController
from DataReader import DataReader
from vtk import vtkMetaImageWriter
from vtk import vtkXMLImageDataWriter
class DataWriter(DataController):
"""
DataWriter writes an image data object to
disk using the provided format.
"""
def __init__(self):
sup... | """
DataWriter.py
"""
from DataController import DataController
from DataReader import DataReader
from vtk import vtkMetaImageWriter
from vtk import vtkXMLImageDataWriter
class DataWriter(DataController):
"""
DataWriter writes an image data object to
disk using the provided format.
"""
def __init__(self):
sup... | Build in support for writing mha files. | Build in support for writing mha files.
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop |
a806d55b7cb2c554357895ca441f30c906aa1fc1 | application.py | application.py | from canis import siriusxm, spotify, oauth
def main():
try:
current = siriusxm.get_currently_playing('siriusxmu')
spotify_id = spotify.id_for_song(current)
print(current, spotify_id)
except Exception, e:
print "Error {}".format(e)
if __name__ == "__main__":
oauth.app.run()
... | from time import sleep
from datetime import datetime
from canis import siriusxm, spotify, oauth
def main():
channels = ['siriusxmu', 'altnation']
while True:
if oauth.expiration > datetime.utcnow():
oauth.refresh()
for channel in channels:
try:
current = ... | Restructure error handling a bit | Restructure error handling a bit
| Python | mit | maxgoedjen/canis |
cae43a00c1a9421194721601c0bebc3468f134e4 | sekh/utils.py | sekh/utils.py | """Utils for django-sekh"""
import re
from itertools import izip
def remove_duplicates(items):
"""
Remove duplicates elements in a list preserving the order.
"""
seen = {}
result = []
for item in items:
item = item.strip()
if not item or item in seen:
continue
... | """Utils for django-sekh"""
from future_builtins import zip
import re
def remove_duplicates(items):
"""
Remove duplicates elements in a list preserving the order.
"""
seen = {}
result = []
for item in items:
item = item.strip()
if not item or item in seen:
continue... | Use zip from future_builtins for Python 2 and 3 compatibility | Use zip from future_builtins for Python 2 and 3 compatibility
| Python | bsd-3-clause | Fantomas42/django-sekh |
fc6acce0667d23c0f0b51d67c5899cf979d37516 | kindred/pycorenlp.py | kindred/pycorenlp.py | # Temporary inclusion of pycorenlp code for easier edits
# https://github.com/smilli/py-corenlp
import json, requests
import six
class StanfordCoreNLP:
useSessions = False
sessions = {}
def __init__(self, server_url):
self.server_url = server_url
if StanfordCoreNLP.useSessions:
if not server_url in Stanfo... | # Temporary inclusion of pycorenlp code for easier edits
# https://github.com/smilli/py-corenlp
import json, requests
import six
class StanfordCoreNLP:
def __init__(self, server_url):
self.server_url = server_url
def annotate(self, text, properties={}):
assert isinstance(text, six.string_types),"text must be ... | Remove experimental CoreNLP session code | Remove experimental CoreNLP session code
| Python | mit | jakelever/kindred,jakelever/kindred |
d04a0000d231b1a597992bd28ab4ab8de27667e2 | cron/updateGameCache.py | cron/updateGameCache.py | import urllib2
urllib2.urlopen('http://www.gamingwithlemons.com/cron/update') | import urllib.request
urllib.request.urlopen('http://www.gamingwithlemons.com/cron/update') | Update cron job to use python3 | Update cron job to use python3
| Python | mit | rewphus/tidbitsdev,Clidus/gwl,rewphus/tidbitsdev,Clidus/gwl,rewphus/tidbitsdev,rewphus/tidbitsdev,Clidus/gwl,Clidus/gwl |
8e8545c024e307a4878cdb93a79b854afc84fad5 | nyucal/cli.py | nyucal/cli.py | # -*- coding: utf-8 -*-
"""Console script for nyucal."""
import io
import click
from lxml import html
from nyucal import nyucal
import requests
@click.group()
def main(args=None):
"""Console script for nyucal."""
click.echo("Replace this message by putting your code into "
"nyucal.cli.main")... | # -*- coding: utf-8 -*-
"""Console script for nyucal.
See click documentation at http://click.pocoo.org/
"""
import io
import click
from nyucal import nyucal
import requests
@click.group()
def main(args=None):
"""Console script for nyucal."""
click.echo("cli for nyucal")
@main.command()
def list(source... | Use the module variable for source URL | Use the module variable for source URL
| Python | mit | nyumathclinic/nyucal,nyumathclinic/nyucal |
a94aa2d9aa58a7c2df289588eb4f16d83725ce8f | numba/exttypes/tests/test_vtables.py | numba/exttypes/tests/test_vtables.py | __author__ = 'mark'
| # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import numba as nb
from numba import *
from numba.minivect.minitypes import FunctionType
from numba.exttypes import virtual
from numba.exttypes import ordering
from numba.exttypes import methodtable
from numba.exttypes.signatures ... | Add test for hash-based vtable creation | Add test for hash-based vtable creation
| Python | bsd-2-clause | cpcloud/numba,ssarangi/numba,jriehl/numba,stuartarchibald/numba,pombredanne/numba,stefanseefeld/numba,stuartarchibald/numba,pitrou/numba,seibert/numba,cpcloud/numba,ssarangi/numba,IntelLabs/numba,IntelLabs/numba,sklam/numba,cpcloud/numba,seibert/numba,GaZ3ll3/numba,stonebig/numba,GaZ3ll3/numba,stonebig/numba,cpcloud/nu... |
8e9de7c0df2f37c40d40b32612aae8e351c748b4 | class4/exercise1.py | class4/exercise1.py | #!/usr/bin/python
from getpass import getpass
import time
import paramiko
def main():
ip_addr = '50.76.53.27'
username = 'pyclass'
password = getpass()
ssh_port = 8022
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_con... | # Use Paramiko to retrieve the entire 'show version' output from pynet-rtr2.
#!/usr/bin/python
from getpass import getpass
import time
import paramiko
def main():
ip_addr = '50.76.53.27'
username = 'pyclass'
password = getpass()
ssh_port = 8022
remote_conn_pre = paramiko.SSHClient()
remote_... | Use Paramiko to retrieve the entire 'show version' output from pynet-rtr2. | Use Paramiko to retrieve the entire 'show version' output from pynet-rtr2.
| Python | apache-2.0 | linkdebian/pynet_course |
81ca54adbfdb605cd63674134144e058c46bab5f | nalaf/features/embeddings.py | nalaf/features/embeddings.py | from nalaf.features import FeatureGenerator
from gensim.models import Word2Vec
class WordEmbeddingsFeatureGenerator(FeatureGenerator):
"""
DOCSTRING
"""
def __init__(self, model_file, weight=1):
self.model = Word2Vec.load(model_file)
self.weight = weight
def generate(self, datase... | from nalaf.features import FeatureGenerator
from gensim.models import Word2Vec
class WordEmbeddingsFeatureGenerator(FeatureGenerator):
"""
DOCSTRING
"""
def __init__(self, model_file, additive=0, multiplicative=1):
self.model = Word2Vec.load(model_file)
self.additive = additive
... | Make WE use additive and multiplicative constants | Make WE use additive and multiplicative constants
| Python | apache-2.0 | Rostlab/nalaf |
984d8626a146770fe93d54ae107cd33dc3d2f481 | dbmigrator/commands/init_schema_migrations.py | dbmigrator/commands/init_schema_migrations.py | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_d... | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_d... | Add "applied" timestamp to schema migrations table | Add "applied" timestamp to schema migrations table
| Python | agpl-3.0 | karenc/db-migrator |
8dbea15b789227d55972512307feb8f40f5d11a1 | git_upstream_diff.py | git_upstream_diff.py | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import sys
import subprocess2
from git_common import current_branch, get_or_create_merge_base, config_list
from git_c... | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import sys
import subprocess2
import git_common as git
def main(args):
default_args = git.config_list('depot-tools... | Make udiff print reasonable errors while not on a branch. | Make udiff print reasonable errors while not on a branch.
R=agable@chromium.org
BUG=
Review URL: https://codereview.chromium.org/212493002
git-svn-id: bd64dd6fa6f3f0ed0c0666d1018379882b742947@259647 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
| Python | bsd-3-clause | svn2github/chromium-depot-tools,svn2github/chromium-depot-tools,svn2github/chromium-depot-tools |
2a285104807b07eba3682796536903254a175170 | images_of/connect.py | images_of/connect.py | import praw
from images_of import settings
class Reddit(praw.Reddit):
def oauth(self, **kwargs):
self.set_oauth_app_info(
client_id = kwargs.get('client_id') or settings.CLIENT_ID,
client_secret = kwargs.get('client_secret') or settings.CLIENT_SECRET,
redirect_uri = kwa... | import praw
from images_of import settings
class Reddit(praw.Reddit):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.config.api_request_delay = 1.0
def oauth(self, **kwargs):
self.set_oauth_app_info(
client_id = kwargs.get('client_id') or setti... | Reduce oauth api-delay to 1s. | Reduce oauth api-delay to 1s.
| Python | mit | amici-ursi/ImagesOfNetwork,scowcron/ImagesOfNetwork |
cab3289827c859085dff9d492362d6648b52d23f | karma.py | karma.py |
from brutal.core.plugin import cmd, match
import collections
karmas = collections.Counter()
@match(regex=r'^([a-zA-Z0-9_]+)((:?\+)+)$')
def karma_inc(event, name, pluses, *args):
if name == event.meta['nick']:
return 'Not in this universe, maggot!'
else:
karmas[name] += len(pluses)//2
... |
from brutal.core.plugin import cmd, match
import collections
karmas = collections.Counter()
@match(regex=r'^([a-zA-Z0-9_]+)((:?\+)+)$')
def karma_inc(event, name, pluses, *args):
if name == event.meta['nick']:
return 'Not in this universe, maggot!'
else:
karmas[name] += len(pluses)//2
... | Split long line to make it more readable. | Karma: Split long line to make it more readable.
Signed-off-by: Jakub Novak <3db738bfafc513cdba5d3154e6b5319945461327@gmail.com>
| Python | apache-2.0 | mrshu/brutal-plugins,Adman/brutal-plugins |
51060b1def98a98bee0a401205116e2cac056299 | test_core.py | test_core.py | #!/usr/bin/env python
from ookoobah import core
from ookoobah import utils
grid = utils.make_grid_from_string("""
# # # # # #
# > . . \ #
# . # . | #
# . / | o #
# . \ . / #
# # # # # #
""")
game = core.Game(grid=grid)
game.start()
print "hit <enter> to render next; ^C to abort"
status = co... | #!/usr/bin/env python
from ookoobah import core
from ookoobah import session
from ookoobah import utils
grid = utils.make_grid_from_string("""
# # # # # #
# > . . \ #
# . # . | #
# . / | o #
# . \ . / #
# # # # # #
""")
sess = session.Session(grid=grid)
sess.start()
print "<enter> to render ... | Switch to Session from a bare Game | test: Switch to Session from a bare Game
| Python | mit | vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah |
2c7464e8428359bec607623bffa3418e58ec8f1d | funbox/itertools_compat.py | funbox/itertools_compat.py |
"""itertools compatibility for Python 2 and 3, for imap, izip and ifilter.
Just use:
from funbox.itertools_compat import imap, izip, ifilter
instead of:
from itertools import imap, izip, ifilter, ifilterfalse
>>> list(imap(int, ['1', '2', '3']))
[1, 2, 3]
>>> is_even = lambda x: (x % 2 == 0)
>>> list(ifil... |
"""itertools compatibility for Python 2 and 3, for imap, izip and ifilter.
Just use:
from funbox.itertools_compat import imap, izip, ifilter, ifilterfalse
instead of:
from itertools import imap, izip, ifilter, ifilterfalse
>>> list(imap(int, ['1', '2', '3']))
[1, 2, 3]
>>> is_even = lambda x: (x % 2 == 0)
... | Fix small incompleteness in documentation. | Fix small incompleteness in documentation.
| Python | mit | nmbooker/python-funbox,nmbooker/python-funbox |
da4c39696a71077b34d4ab9347f7d7b4c5ef1601 | scripts/create_test_data_file_from_bt.py | scripts/create_test_data_file_from_bt.py |
import serial
import time
import platform
import csv
import zephyr.protocol
def main():
serial_port_dict = {"Darwin": "/dev/cu.BHBHT001931-iSerialPort1",
"Windows": 23}
serial_port = serial_port_dict[platform.system()]
ser = serial.Serial(serial_port)
... |
import serial
import time
import platform
import csv
import threading
import zephyr.protocol
import zephyr.message
def callback(x):
print x
def reading_thread(protocol):
start_time = time.time()
while time.time() < start_time + 120:
protocol.read_and_handle_bytes(1)
... | Refactor to support multiple devices for test data generation | Refactor to support multiple devices for test data generation | Python | bsd-2-clause | jpaalasm/zephyr-bt |
a49cc6d6ca1ce22358292c00d847cb424306b229 | wordsaladflask.py | wordsaladflask.py | import wordsalad
from flask import Flask
App = Flask(__name__)
@App.route("salad/<int:n>/<string:corpus>")
def _get(self, n, corpus="default"):
"""Generate n word salads from the given (optional) corpus."""
pass
@App.route("salad/corpuses")
def _get_corpuses(self):
"""Fetch a list of "corpus:es" we can u... | import wordsalad
from flask import Flask
App = Flask(__name__)
@App.route("salad/<int:n>/<string:corpus>")
def _get(self, n, corpus="default"):
"""Generate n word salads from the given (optional) corpus."""
pass
@App.route("salad/corpuses")
def _get_corpora(self):
"""Fetch a list of "corpora" we can use ... | Use the proper words ;) | Use the proper words ;)
| Python | mit | skurmedel/wordsalad |
fa4be57f00827ea452e0d7bc1c0b5b17f20a6d2d | test.py | test.py | import nltk
import xml.dom.minidom as dom
import codecs
file = open("tweets.xml")
tree = dom.parse(file)
i = 0
e = 0
for tweet in tree.firstChild.childNodes:
try:
textNodes = tweet.getElementsByTagName("text")
x = tree.createElement("foo")
for textNode in textNodes:
textValu... | import nltk
import xml.dom.minidom as dom
import codecs
import nltk.data
sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
file = open("tweets.xml")
tree = dom.parse(file)
i = 0
e = 0
for tweet in tree.firstChild.childNodes:
try:
textNodes = tweet.getElementsByTagName("text")
... | Test implementation of xml.minidom / nltk | Test implementation of xml.minidom / nltk
| Python | apache-2.0 | markusmichel/Tworpus-Client,markusmichel/Tworpus-Client,markusmichel/Tworpus-Client |
70929aa10fb59ed25c8fc4e76ce60bd6d2934c3f | rcamp/rcamp/settings/auth.py | rcamp/rcamp/settings/auth.py | AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'lib.pam_backend.PamBackend',
)
AUTH_USER_MODEL = 'accounts.User'
LOGIN_URL = '/login'
PAM_SERVICES = {
'default': 'login',
'csu': 'csu'
}
| AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'lib.pam_backend.PamBackend',
)
AUTH_USER_MODEL = 'accounts.User'
LOGIN_URL = '/login'
PAM_SERVICES = {
'default': 'curc-twofactor-duo',
'csu': 'csu'
}
| Change the default pam login service | Change the default pam login service
| Python | mit | ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP |
db3cadcf3baa22efe65495aca2efe5352d5a89a5 | nhs/gunicorn_conf.py | nhs/gunicorn_conf.py | bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
workers = 3
| bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
workers = 3
timeout = 60
| Extend Gunicorn worker timeout for long-running API calls. | Extend Gunicorn worker timeout for long-running API calls.
| Python | agpl-3.0 | openhealthcare/open-prescribing,openhealthcare/open-prescribing,openhealthcare/open-prescribing |
b786ae0b845374ca42db42ac64322d6aa9e894c5 | setup.py | setup.py | from distutils.core import setup
setup(name='TOPKAPI',
version='0.2dev',
description='SAHG TOPKAPI model implementation',
author='Theo Vischel & Scott Sinclair',
author_email='theo.vischel@hmg.inpg.fr; sinclaird@ukzn.ac.za',
packages=['TOPKAPI', 'TOPKAPI.parameter_utils', 'TOPKAPI.results... | from distutils.core import setup
setup(name='TOPKAPI',
version='0.2dev',
description='SAHG TOPKAPI model implementation',
author='Theo Vischel & Scott Sinclair',
author_email='theo.vischel@hmg.inpg.fr; sinclaird@ukzn.ac.za',
packages=['TOPKAPI',
'TOPKAPI.parameter_utils',
... | Reformat to be more pleasing on the eye | STY: Reformat to be more pleasing on the eye
| Python | bsd-3-clause | sahg/PyTOPKAPI,scottza/PyTOPKAPI |
51f32076e8708c55420989b660323cdfd9fc6650 | cycy/interpreter.py | cycy/interpreter.py | from cycy import compiler
from cycy.parser.sourceparser import parse
class CyCy(object):
"""
The main CyCy interpreter.
"""
def run(self, bytecode):
pass
def interpret(source):
print "Hello, world!"
return
bytecode = compiler.Context.to_bytecode(parse(source.getContent()))
... | from cycy import compiler
from cycy.parser.sourceparser import parse
class CyCy(object):
"""
The main CyCy interpreter.
"""
def run(self, bytecode):
pass
def interpret(source):
bytecode = compiler.Context.to_bytecode(parse(source))
CyCy().run(bytecode)
| Break the tests to show us we're not writing RPython. | Break the tests to show us we're not writing RPython.
| Python | mit | Magnetic/cycy,Magnetic/cycy,Magnetic/cycy |
a22d36688995ec798628238f716dd7852b7af0a2 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup, Extension
import numpy
import re
with open('README.rst') as f:
readme = f.read()
with open('tifffile.py') as f:
text = f.read()
version = re.search("__version__ = '(.*?)'", text).groups()[0]
setup(
name='tifffile',
ve... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup, Extension
import numpy
import re
with open('README.rst') as f:
readme = f.read()
with open('tifffile.py') as f:
text = f.read()
version = re.search("__version__ = '(.*?)'", text).groups()[0]
setup(
name='tifffile',
ve... | Make sure the tifffile.py is installed. | Make sure the tifffile.py is installed.
| Python | bsd-3-clause | blink1073/vidsrc,blink1073/vidsrc |
8cdf631d8f3c817e75c2c02218ae60635b49951c | setup.py | setup.py | from distutils.core import setup
# Load in babel support, if available.
try:
from babel.messages import frontend as babel
cmdclass = {"compile_catalog": babel.compile_catalog,
"extract_messages": babel.extract_messages,
"init_catalog": babel.init_catalog,
"updat... | from distutils.core import setup
# Load in babel support, if available.
try:
from babel.messages import frontend as babel
cmdclass = {"compile_catalog": babel.compile_catalog,
"extract_messages": babel.extract_messages,
"init_catalog": babel.init_catalog,
"updat... | Increase version and switch location to new upstream. | Increase version and switch location to new upstream.
| Python | bsd-3-clause | pjdelport/django-money,AlexRiina/django-money,tsouvarev/django-money,iXioN/django-money,rescale/django-money,recklessromeo/django-money,iXioN/django-money,tsouvarev/django-money,recklessromeo/django-money |
a134bdbe2677fdc5a9c7d6408ea021b8e981098b | qtawesome/tests/test_qtawesome.py | qtawesome/tests/test_qtawesome.py | r"""
Tests for QtAwesome.
"""
# Standard library imports
import sys
import subprocess
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
from PyQt5.QtWidgets import QApplication
def test_segfault_import():
output_number = subprocess.call('py... | r"""
Tests for QtAwesome.
"""
# Standard library imports
import sys
import subprocess
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
from PyQt5.QtWidgets import QApplication
def test_segfault_import():
output_number = subprocess.call('py... | Add more details in the test docstring. | Add more details in the test docstring.
| Python | mit | spyder-ide/qtawesome |
5982e5a4f0bb7f47e604aea2c851ba50bcbe07e1 | hexify.py | hexify.py | import uflash
import argparse
import sys
import os
_HELP_TEXT = """
A simple utility script intended for creating hexified versions of MicroPython
scripts on the local filesystem _NOT_ the microbit. Does not autodetect a
microbit. Accepts multiple input scripts and optionally one output directory.
"""
def main(arg... | import uflash
import argparse
import sys
import os
_HELP_TEXT = """
A simple utility script intended for creating hexified versions of MicroPython
scripts on the local filesystem _NOT_ the microbit. Does not autodetect a
microbit. Accepts multiple input scripts and optionally one output directory.
"""
def main(arg... | Add runtime and minify support | Add runtime and minify support
Added command line arguments for runtime and minify.
| Python | mit | ntoll/uflash |
ee2bd9191bb10a31c0eb688cbddaaa8fedba68a7 | IPython/html/terminal/handlers.py | IPython/html/terminal/handlers.py | """Tornado handlers for the terminal emulator."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from tornado import web
import terminado
from ..base.handlers import IPythonHandler
class TerminalHandler(IPythonHandler):
"""Render the terminal interface."""
... | """Tornado handlers for the terminal emulator."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from tornado import web
import terminado
from ..base.handlers import IPythonHandler
class TerminalHandler(IPythonHandler):
"""Render the terminal interface."""
... | Add authentication for terminal websockets | Add authentication for terminal websockets
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.