Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Update time service to simulate gradually increasing slow response times. | """ service_time.py """
from datetime import datetime
from flask import Flask, jsonify
app = Flask(__name__)
count = 0
@app.route("/time", methods=['GET'])
def get_datetime():
global count
count += 1
return jsonify(count=count,
datetime=datetime.now().isoformat())
if __name__ == "... | """ service_time.py """
from datetime import datetime
from time import sleep
from flask import Flask, jsonify
app = Flask(__name__)
count = 0
@app.route("/time", methods=['GET'])
def get_datetime():
global count
# sleep to simulate the service response time degrading
sleep(count)
count += 1
re... |
Update openfisca-core requirement from <32.0,>=27.0 to >=27.0,<33.0 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.9.4",
author = "OpenFisca Team",
author_email = "contact@openfisca.org",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approve... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.9.4",
author = "OpenFisca Team",
author_email = "contact@openfisca.org",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approve... |
Add README.rst contents to PyPI page | from setuptools import setup
REPO_URL = 'http://github.com/okfn-brasil/serenata-toolbox'
setup(
author='Serenata de Amor',
author_email='contato@serenata.ai',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT L... | from setuptools import setup
REPO_URL = 'http://github.com/okfn-brasil/serenata-toolbox'
with open('README.rst') as fobj:
long_description = fobj.read()
setup(
author='Serenata de Amor',
author_email='contato@serenata.ai',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audi... |
Add more requirements that are needed for this module | from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read... | from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read... |
Add what the example should output. | """
Compute the force of gravity between the Earth and Sun.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
# Import the gravitational constant and the Quantity class
from dimensionful import G, Quantity
# Supply the mass of Earth, mass of Sun, and the distance between.
mass_earth = Quant... | """
Compute the force of gravity between the Earth and Sun.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
# Import the gravitational constant and the Quantity class
from dimensionful import G, Quantity
# Supply the mass of Earth, mass of Sun, and the distance between.
mass_earth = Quant... |
Add a named tuple PriceEvent sub class and update methods accordingly. | class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price_history = []
@property
def price(self):
return self.price_history[-1] if self.price_history else None
def update(self, timestamp, price):
if price < 0:
raise ValueError("price should no... | import bisect
import collections
PriceEvent = collections.namedtuple("PriceEvent", ["timestamp", "price"])
class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price_history = []
@property
def price(self):
return self.price_history[-1].price if self.price_history el... |
Add an exception based version | DNA = {"A", "C", "T", "G"}
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
# Check validity - `difference` returns elements in dna not in DNA
if set(dna).difference(DNA):
return ""
return "".join([TRANS[n] for n in dna])
| TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
try:
return "".join([TRANS[n] for n in dna])
except KeyError:
return ""
# Old version: it's slightly slower for valid DNA, but slightly faster for invalid DNA
DNA = {"A", "C", "T", "G"}
TRANS = {"G": "C", "C":"G", "T":"A", "A":"... |
Add preprints to the sidebar | from django.conf.urls import include, url
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(
base_pattern,
include([
url(r'^$', views.home, name='home'),
url(r... | from django.conf.urls import include, url
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(
base_pattern,
include([
url(r'^$', views.home, name='home'),
url(r... |
Make the hello protocol example more user-friendly | import os
import avro.protocol
import tornado.web
import tornado.ioloop
import tornavro.server
import tornavro.responder
class HelloResponder(tornavro.responder.Responder):
def hello(self, name):
return 'Hello, %s' % name
proto = open(os.path.join(os.path.dirname(__file__), 'hello.avpr')).read()
proto... | import os
import avro.protocol
import tornado.web
import tornado.ioloop
from tornado.options import define, options
import tornavro.server
import tornavro.responder
define('port', default=8888, help='Listen on this port')
class HelloResponder(tornavro.responder.Responder):
def hello(self, name):
retur... |
Use InaSAFE in the email subject line rather | # noinspection PyUnresolvedReferences
from .prod import * # noqa
import os
print os.environ
ALLOWED_HOSTS = ['*']
ADMINS = (
('Tim Sutton', 'tim@kartoza.com'),
('Ismail Sunni', 'ismail@kartoza.com'),
('Christian Christellis', 'christian@kartoza.com'),
('Akbar Gumbira', 'akbargumbira@gmail.com'),)
DA... | # noinspection PyUnresolvedReferences
from .prod import * # noqa
import os
print os.environ
ALLOWED_HOSTS = ['*']
ADMINS = (
('Tim Sutton', 'tim@kartoza.com'),
('Ismail Sunni', 'ismail@kartoza.com'),
('Christian Christellis', 'christian@kartoza.com'),
('Akbar Gumbira', 'akbargumbira@gmail.com'),)
DA... |
Fix for faulty trace files | import numpy as np
import os
from FeatureExtractorAbstract import FeatureExtractorAbstract
from helpers.config import PathConfig
class Gait(FeatureExtractorAbstract):
def getCSVheader(self):
return ["gaitPeriod"]
def extract(self, experiment, type, indiv):
filepath = experiment[2] + os.path.... | import numpy as np
import os
from FeatureExtractorAbstract import FeatureExtractorAbstract
from helpers.config import PathConfig
class Gait(FeatureExtractorAbstract):
def getCSVheader(self):
return ["gaitPeriod"]
# isValidLine and sameAsFloat have been copied from distanceCalc.py
def isValidLin... |
Remove the now-defunct middleware from the test settings | # Settings to be used when running unit tests
# python manage.py test --settings=lazysignup.test_settings lazysignup
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '' # Or path to database file if using sqlite3.
DATABASE_USER = '... | # Settings to be used when running unit tests
# python manage.py test --settings=lazysignup.test_settings lazysignup
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '' # Or path to database file if using sqlite3.
DATABASE_USER = '... |
Replace database_uri method with a property | class Config(object):
"""
Base configuration class. Contains one method that defines the database URI.
This class is to be subclassed and its attributes defined therein.
"""
def __init__(self):
self.database_uri()
def database_uri(self):
if self.DIALECT == 'sqlite':
... | class Config(object):
"""
Base configuration class. Contains one property that defines the database URI.
This class is to be subclassed and its attributes defined therein.
"""
@property
def database_uri(self):
return r'sqlite://{name}'.format(name=self.DBNAME) if self.DIALECT == 'sqli... |
Allow key settings to be saved | from __future__ import absolute_import
from django import forms
from django.utils.translation import ugettext_lazy as _
from sentry.models import ApiKey, OrganizationMemberType
from sentry.web.forms.fields import OriginsField
from sentry.web.frontend.base import OrganizationView
class ApiKeyForm(forms.ModelForm):
... | from __future__ import absolute_import
from django import forms
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from sentry.models import ApiKey, OrganizationMemberType
from sentry.web.forms.fields import OriginsField
from sentry... |
Change number of cores for submit | """
Doc string here.
@author mje
@email: mads [] cnru.dk
"""
import sys
import subprocess
cmd = "/usr/local/common/meeg-cfin/configurations/bin/submit_to_isis"
subjects = ["0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011",
"0012", "0013", "0014", "0015", "0016", "0017", "0020", "0021",
... | """
Doc string here.
@author mje
@email: mads [] cnru.dk
"""
import sys
import subprocess
cmd = "/usr/local/common/meeg-cfin/configurations/bin/submit_to_isis"
subjects = ["0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011",
"0012", "0013", "0014", "0015", "0016", "0017", "0020", "0021",
... |
Allow version parsing code to use non-annotated tags | # -*- coding: utf-8 -*-
# ############# version ##################
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
import re
GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
__version__ = None
try:
_dist = get_d... | # -*- coding: utf-8 -*-
# ############# version ##################
from pkg_resources import get_distribution, DistributionNotFound
import os.path
import subprocess
import re
GIT_DESCRIBE_RE = re.compile('^(?P<version>v\d+\.\d+\.\d+)-(?P<git>\d+-g[a-fA-F0-9]+(?:-dirty)?)$')
__version__ = None
try:
_dist = get_d... |
Remove needless creation of MarshmallowConverter | import uplink
# Local imports
import github
BASE_URL = "https://api.github.com/"
if __name__ == "__main__":
# Create a client that uses the marshmallow converter
gh = github.GitHub(
base_url=BASE_URL, converter=uplink.MarshmallowConverter()
)
# Get all public repositories
repos = gh.get_... | # Standard library imports
from pprint import pformat
# Local imports
import github
BASE_URL = "https://api.github.com/"
if __name__ == "__main__":
# Create a GitHub API client
gh = github.GitHub(base_url=BASE_URL)
# Get all public repositories
repos = gh.get_repos()
# Shorten to first 10 res... |
Move rabbit vars to globals | import os
import sys
# Append .. to sys path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import multiscanner
from celery import Celery
app = Celery('celery_worker', broker='pyamqp://guest@localhost//')
@app.task
def multiscanner_celery(filelist, config=multiscanner.CONFIG):
'''
... | import os
import sys
# Append .. to sys path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import multiscanner
from celery import Celery
RABBIT_USER = 'guest'
RABBIT_HOST = 'localhost'
app = Celery('celery_worker', broker='pyamqp://%s@%s//' % (RABBIT_USER, RABBIT_HOST))
@app.task
def ... |
Make path variable working for server side | import feedparser
import pickle
import requests
hub = "http://feeds.feedburner.com/ampparit-politiikka" ## collect from ampparit all politics related sites
feed = feedparser.parse( hub )
stored = []
try:
stored = pickle.load( open( '.history' , 'r' ) )
except:
pass
stored = []
out = open( 'urls.txt' , 'a'... | import feedparser
import pickle
import requests
import sys
hub = "http://feeds.feedburner.com/ampparit-politiikka" ## collect from ampparit all politics related sites
feed = feedparser.parse( hub )
stored = []
path = sys.argv[0]
try:
stored = pickle.load( open( path + '/.history' , 'r' ) )
except:
pass
... |
Fix datetime usage in memorize model | from datetime import datetime, timedelta
import datetime
from django.utils.timezone import utc
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from .algorithm import interval
class Pra... | from datetime import datetime, timedelta
from django.utils.timezone import utc
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from .algorithm import interval
class Practice(models.Mo... |
Add more tests for ACF format | import pytest
from steamfiles import acf
@pytest.yield_fixture
def acf_data():
with open('tests/test_data/appmanifest_202970.acf', 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf_data)) == acf_data
| import io
import pytest
from steamfiles import acf
test_file_name = 'tests/test_data/appmanifest_202970.acf'
@pytest.yield_fixture
def acf_data():
with open(test_file_name, 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf... |
Fix app minification script on non-Windows systems | # Python 3
import glob
import os
uglifyjs = os.path.abspath("../lib/uglifyjs")
input_dir = os.path.abspath("./Resources/Tracker/scripts")
output_dir = os.path.abspath("./Resources/Tracker/scripts.min")
for file in glob.glob(input_dir + "/*.js"):
name = os.path.basename(file)
print("Minifying {0}...".format(n... | #!/usr/bin/env python3
import glob
import os
import shutil
import sys
if os.name == "nt":
uglifyjs = os.path.abspath("../lib/uglifyjs.cmd")
else:
uglifyjs = "uglifyjs"
if shutil.which(uglifyjs) is None:
print("Cannot find executable: {0}".format(uglifyjs))
sys.exit(1)
input_dir = os.path.abspath("./... |
Add signature and visibility status to addon feature | import json
from feature import Feature
from output import good, bad, info
from tabulate import tabulate
class Addons(Feature):
def run(self, args):
with open(self.profile_path('extensions.json')) as f:
addons = json.load(f)['addons']
info(('%d addons found. (%d active)\n' %
... | import json
from feature import Feature
from output import good, bad, info
from tabulate import tabulate
def signed_state(num):
# See constants defined in [1]
states = {
-2: 'broken',
-1: 'unknown',
0: 'missing',
1: 'preliminary',
2: 'signed',
3: 'system',
... |
Fix compatibility with new parser. | """Request handler of the module."""
from functools import partial
from ppp_datamodel import Sentence, TraceItem, Response
from ppp_datamodel.parsers import parse_triples, ParseError
def tree_to_response(measures, trace, tree):
trace = trace + [TraceItem('DatamodelNotationParser',
... | """Request handler of the module."""
from functools import partial
from ppp_datamodel import Sentence, TraceItem, Response
from ppp_datamodel.parsers import parse_triples, ParseError
def tree_to_response(tree, measures, trace):
trace = trace + [TraceItem('DatamodelNotationParser',
... |
Use f-strings in place of `str.format()` | from django.contrib import admin
from django.contrib.auth import get_user_model
from .models import InvitationStat, JoinInvitation
User = get_user_model()
class InvitationStatAdmin(admin.ModelAdmin):
raw_id_fields = ["user"]
readonly_fields = ["invites_sent", "invites_accepted"]
list_display = [
... | from django.contrib import admin
from django.contrib.auth import get_user_model
from .models import InvitationStat, JoinInvitation
User = get_user_model()
class InvitationStatAdmin(admin.ModelAdmin):
raw_id_fields = ["user"]
readonly_fields = ["invites_sent", "invites_accepted"]
list_display = [
... |
Fix indent and don't decode input command. | import os
import shlex
import sys
from canaryd_packages import six
from canaryd.log import logger
if os.name == 'posix' and sys.version_info[0] < 3:
from canaryd_packages.subprocess32 import * # noqa
else:
from subprocess import * # noqa
def get_command_output(command, *args, **kwargs):
logger.debug... | import os
import shlex
import sys
from canaryd_packages import six
from canaryd.log import logger
if os.name == 'posix' and sys.version_info[0] < 3:
from canaryd_packages.subprocess32 import * # noqa
else:
from subprocess import * # noqa
def get_command_output(command, *args, **kwargs):
logger.debug... |
Set the default sdl2 library locations. | from pract2d.game import gamemanager
if __name__ == '__main__':
game = gamemanager.GameManager()
game.run()
| from pract2d.game import gamemanager
from pract2d.core import files
from platform import system
import os
if __name__ == '__main__':
try:
if system() == 'Windows' or not os.environ["PYSDL2_DLL_PATH"]:
os.environ["PYSDL2_DLL_PATH"] = files.get_path()
except KeyError:
pass
game = ... |
Add path for laptop for fixtures | # Statement for enabling the development environment
DEBUG = True
TESTING = True
# Define the application directory
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
# Define the database - we are working with
# SQLite for this example
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/ont... | # Statement for enabling the development environment
DEBUG = True
TESTING = True
# Define the application directory
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
# Define the database - we are working with
# SQLite for this example
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/ont... |
Remove the preview prefix from the positions URL pattern | from django.conf.urls import patterns, include, url
from aspc.senate.views import DocumentList, AppointmentList
urlpatterns = patterns('',
url(r'^documents/$', DocumentList.as_view(), name="document_list"),
url(r'^documents/(?P<page>[0-9]+)/$', DocumentList.as_view(), name="document_list_page"),
url(r'^pre... | from django.conf.urls import patterns, include, url
from aspc.senate.views import DocumentList, AppointmentList
urlpatterns = patterns('',
url(r'^documents/$', DocumentList.as_view(), name="document_list"),
url(r'^documents/(?P<page>[0-9]+)/$', DocumentList.as_view(), name="document_list_page"),
url(r'^pos... |
Add HTTPRelayApplication to vumi.application package API. | """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... |
Fix html rendering after making it a RawDescriptor | import json
import logging
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
from lxml import etree
from pkg_resources import resource_string
log = logging.getLogger("mitx.courseware")
class HtmlModule(XModule):
def get_html(self):
return self.html
def __init__(self,... | import json
import logging
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
from lxml import etree
from pkg_resources import resource_string
log = logging.getLogger("mitx.courseware")
class HtmlModule(XModule):
def get_html(self):
return self.html
def __init__(self,... |
Stop using deprecated list_dir in the examples. | #!/usr/bin/python2
# This is a simple example program to show how to use PyCdlib to open up an
# existing ISO passed on the command-line, and print out all of the file names
# at the root of the ISO.
# Import standard python modules.
import sys
# Import pycdlib itself.
import pycdlib
# Check that there are enough c... | #!/usr/bin/python2
# This is a simple example program to show how to use PyCdlib to open up an
# existing ISO passed on the command-line, and print out all of the file names
# at the root of the ISO.
# Import standard python modules.
import sys
# Import pycdlib itself.
import pycdlib
# Check that there are enough c... |
Add retry for opening RabbitMQ connection (cluster start) | 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']
... |
Remove Constraint objects from the API | # 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... |
Support passing context to callback | 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... |
Put pw reset expiration date in future | 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... |
Reduce size of testings images by default to speed up tests | import StringIO
import PIL
import pytest
from django.core.files.uploadedfile import InMemoryUploadedFile
class Image:
def __init__(self):
self.dimensions = (100, 100)
self.color = 'blue'
self.name = 'image.jpg'
@property
def django_file(self):
# Create a new Django file-... | import StringIO
import PIL
import pytest
from django.core.files.uploadedfile import InMemoryUploadedFile
class Image:
def __init__(self):
self.dimensions = (10, 10)
self.color = 'blue'
self.name = 'image.jpg'
@property
def django_file(self):
# Create a new Django file-li... |
Allow submodules in lib repo | #!/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... |
Change playlist to a new. | # Load data for videos in Youtube playlist
# https://www.youtube.com/playlist?list=PLy7eek8wTbV9OtrbY3CJo5mRWnhuwTen0
## TODO handle videos for multiple months
# all_videos dict contains videos by day.
import pafy
from datetime import datetime
# TODO import app key
# pafy.set_api_key(key)
print("Loading Youtube vid... | # Load data for videos in Youtube playlist
# Uses video title as date, formatted as 20151230
## TODO handle videos for multiple months
# all_videos dict contains videos by day.
import pafy
from datetime import datetime
# TODO import app key
# pafy.set_api_key(key)
print("Loading Youtube video playlist")
playlist =... |
Restructure error handling a bit | 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 = ... |
Handle matches with no name | from common.log import logUtils as log
from constants import clientPackets
from constants import exceptions
from objects import glob
def handle(userToken, packetData):
try:
# get usertoken data
userID = userToken.userID
# Read packet data
packetData = clientPackets.createMatch(packetData)
# Create a matc... | from common.log import logUtils as log
from constants import clientPackets, serverPackets
from constants import exceptions
from objects import glob
def handle(userToken, packetData):
try:
# get usertoken data
userID = userToken.userID
# Read packet data
packetData = clientPackets.createMatch(packetData)
... |
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_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_... |
Switch to Session from a bare Game | #!/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 ... |
Correct the trove categorization to say License = BSD. | from setuptools import setup
import tamarin
DESCRIPTION = "A Django app for monitoring AWS usage in Django's admin."
LONG_DESCRIPTION = None
try:
LONG_DESCRIPTION = open('README.rst').read()
except:
pass
version_str = '%d.%d' % (tamarin.VERSION[0], tamarin.VERSION[1])
CLASSIFIERS = [
'Development Status... | from setuptools import setup
import tamarin
DESCRIPTION = "A Django app for monitoring AWS usage in Django's admin."
LONG_DESCRIPTION = None
try:
LONG_DESCRIPTION = open('README.rst').read()
except:
pass
version_str = '%d.%d' % (tamarin.VERSION[0], tamarin.VERSION[1])
CLASSIFIERS = [
'Development Status... |
Add Django version trove classifiers | from setuptools import setup
setup(
name='django-easymoney',
version='0.5',
author='Alexander Schepanovski',
author_email='suor.web@gmail.com',
description='An easy MoneyField for Django.',
long_description=open('README.rst').read(),
url='http://github.com/Suor/django-easymoney',
licen... | from setuptools import setup
setup(
name='django-easymoney',
version='0.5',
author='Alexander Schepanovski',
author_email='suor.web@gmail.com',
description='An easy MoneyField for Django.',
long_description=open('README.rst').read(),
url='http://github.com/Suor/django-easymoney',
licen... |
Update the version for 2.0.0~rc2 release. | __version__ = '2.0.0~rc1'
__license__ = '''
Copyright (c) 2009-2011, Cameron Dale <camrdale@gmail.com>
Copyright (c) 2005-2009, Bill McCloskey <bill.mccloskey@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following co... | __version__ = '2.0.0~rc2'
__license__ = '''
Copyright (c) 2009-2011, Cameron Dale <camrdale@gmail.com>
Copyright (c) 2005-2009, Bill McCloskey <bill.mccloskey@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following co... |
Use find_packages instead of listing them manually. | # coding: utf-8
from setuptools import setup
# lets prepare our initial setup
setup_dict = {'name': 'PYSCSI',
'version': '1.0',
'license': 'LGPLv2.1',
'author': 'Ronnie Sahlberg',
'author_email': 'ronniesahlberg@gmail.com',
'description': 'Module f... | # coding: utf-8
from setuptools import find_packages, setup
# lets prepare our initial setup
setup_dict = {'name': 'PYSCSI',
'version': '1.0',
'license': 'LGPLv2.1',
'author': 'Ronnie Sahlberg',
'author_email': 'ronniesahlberg@gmail.com',
'descript... |
Reformat to be more pleasing on the eye | 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',
... |
Fix a deprecation warning from python-fedora | from myfedora.widgets.resourceview import ToolWidget
from fedora.tg.client import BaseClient
from myfedora.lib.app_factory import AppFactory
class ProfileInfoToolApp(AppFactory):
entry_name = "tools.profileinfo"
class ProfileInfoToolWidget(ToolWidget):
template = 'genshi:myfedora.plugins.apps.tools.templates.... | from myfedora.widgets.resourceview import ToolWidget
from fedora.client import BaseClient
from myfedora.lib.app_factory import AppFactory
class ProfileInfoToolApp(AppFactory):
entry_name = "tools.profileinfo"
class ProfileInfoToolWidget(ToolWidget):
template = 'genshi:myfedora.plugins.apps.tools.templates.pro... |
Add default message to safe_print | #!/usr/bin/env
from __future__ import print_function, unicode_literals
import sys
def safe_print(msg, *args, **kwargs):
"""Safely print strings containing unicode characters."""
try:
print(msg, *args, **kwargs)
except:
print(msg.encode(sys.stdout.encoding or 'utf8', errors='replace'), *args, **kwargs)
| #!/usr/bin/env
from __future__ import print_function, unicode_literals
import sys
def safe_print(msg="", *args, **kwargs):
"""Safely print strings containing unicode characters."""
try:
print(msg, *args, **kwargs)
except:
print(msg.encode(sys.stdout.encoding or 'utf8', errors='replace'), *args, **kwargs)
|
Make Button plugin usable inside Text plugin | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
ge... | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
ge... |
Correct operation. Now to fix panda warnings | import pandas as pd
def fn(row):
if row['Type'] == 'DIRECT DEBIT':
return 'DD'
if row['Type'] == 'DIRECT CREDIT' or row['Spending Category'] == 'INCOME':
return 'BP'
if row['Amount (GBP)'] < 0:
return 'SO'
raise Exception('Unintended state')
df = pd.read_csv('statement.csv')
... | import json
import pandas as pd
def fn(row):
if row['Type'] == 'DIRECT DEBIT':
return 'DD'
if row['Type'] == 'DIRECT CREDIT' or row['Spending Category'] == 'INCOME':
return 'BP'
if row['Amount (GBP)'] < 0:
return 'SO'
raise Exception('Unintended state')
df = pd.read_csv('stat... |
Change package name because of conflict | from setuptools import setup, find_packages
__author__ = 'Michiaki Ariga'
setup(
name='tabula',
version='0.1',
description='Simple wrapper for tabula, read tables from PDF into DataFrame',
author=__author__,
author_email='chezou@gmail.com',
url='https://github.com/chezou/tabula-py',
classifiers=[
'D... | from setuptools import setup, find_packages
__author__ = 'Michiaki Ariga'
setup(
name='tabula-py',
version='0.1',
description='Simple wrapper for tabula, read tables from PDF into DataFrame',
author=__author__,
author_email='chezou@gmail.com',
url='https://github.com/chezou/tabula-py',
classifiers=[
... |
Increase minor version number + dev. | __author__ = "Shyue Ping Ong, Anubhav Jain, Michael Kocher, " + \
"Geoffroy Hautier, William Davidson Richard, Dan Gunter, " + \
"Shreyas Cholia, Vincent L Chevrier, Rickard Armiento"
__date__ = "Jul 27, 2012"
__version__ = "2.1.2"
"""
Useful aliases for commonly used objects and modules.
"""... | __author__ = "Shyue Ping Ong, Anubhav Jain, Michael Kocher, " + \
"Geoffroy Hautier, William Davidson Richard, Dan Gunter, " + \
"Shreyas Cholia, Vincent L Chevrier, Rickard Armiento"
__date__ = "Jul 27, 2012"
__version__ = "2.1.3dev"
"""
Useful aliases for commonly used objects and modules.
... |
Include cmt in installed packages. | from setuptools import setup, find_packages
import versioneer
def read_requirements():
import os
path = os.path.dirname(os.path.abspath(__file__))
requirements_file = os.path.join(path, 'requirements.txt')
try:
with open(requirements_file, 'r') as req_fp:
requires = req_fp.read(... | from setuptools import setup, find_packages
import versioneer
def read_requirements():
import os
path = os.path.dirname(os.path.abspath(__file__))
requirements_file = os.path.join(path, "requirements.txt")
try:
with open(requirements_file, "r") as req_fp:
requires = req_fp.read()... |
Add pubsub dependency for tests | from setuptools import setup, find_packages
import sys, os
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
except IOError:
README = ''
version = "0.0.1"
setup(name='tgext.socketio',
version=version,
description="SocketIO support for Tu... | from setuptools import setup, find_packages
import sys, os
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
except IOError:
README = ''
version = "0.0.1"
setup(name='tgext.socketio',
version=version,
description="SocketIO support for Tu... |
Change Python package version to 1.2.1 | __version__='1.1.0'
from .pylazperfapi import PyDecompressor as Decompressor
from .pylazperfapi import PyCompressor as Compressor
from .pylazperfapi import PyVLRDecompressor as VLRDecompressor
from .pylazperfapi import PyVLRCompressor as VLRCompressor
from .pylazperfapi import PyRecordSchema as RecordSchema
from .pylaz... | __version__='1.2.1'
from .pylazperfapi import PyDecompressor as Decompressor
from .pylazperfapi import PyCompressor as Compressor
from .pylazperfapi import PyVLRDecompressor as VLRDecompressor
from .pylazperfapi import PyVLRCompressor as VLRCompressor
from .pylazperfapi import PyRecordSchema as RecordSchema
from .pylaz... |
Enable backported ``int`` in future.builtins | """
A module that brings in equivalents of the new and modified Python 3
builtins into Py2. Has no effect on Py3.
See the docs for these modules for more information::
- future.builtins.iterators
- future.builtins.backports
- future.builtins.misc
- future.builtins.disabled
"""
from future.builtins.iterators import ... | """
A module that brings in equivalents of the new and modified Python 3
builtins into Py2. Has no effect on Py3.
See the docs for these modules for more information::
- future.builtins.iterators
- future.builtins.backports
- future.builtins.misc
- future.builtins.disabled
"""
from future.builtins.iterators import ... |
Change CaseInsensitiveComparator to support all operations. | from sqlalchemy import func
from sqlalchemy.ext.hybrid import Comparator
class CaseInsensitiveComparator(Comparator):
def __eq__(self, other):
return func.lower(self.__clause_element__()) == func.lower(other)
| from sqlalchemy import String
class CaseInsensitiveComparator(String.Comparator):
def __eq__(self, other):
return func.lower(self.__clause_element__()) == func.lower(other)
|
Choose the version of python at runtime (portable version) | #!/usr/bin/env python
# This file is only a "symlink" to bootstrap.py, all logic should go there.
import os
import sys
rust_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(rust_dir, "src", "bootstrap"))
import bootstrap
bootstrap.main()
| #!/usr/bin/env python
# This file is only a "symlink" to bootstrap.py, all logic should go there.
import os
import sys
# If this is python2, check if python3 is available and re-execute with that
# interpreter.
if sys.version_info.major < 3:
try:
# On Windows, `py -3` sometimes works.
# Try this ... |
Add django-keyedcache as a requirement | from setuptools import setup, find_packages
VERSION = (1, 4, 13)
# Dynamically calculate the version based on VERSION tuple
if len(VERSION)>2 and VERSION[2] is not None:
str_version = "%d.%d_%s" % VERSION[:3]
else:
str_version = "%d.%d" % VERSION[:2]
version= str_version
setup(
name = 'django-livesettin... | from setuptools import setup, find_packages
VERSION = (1, 6, 0)
# Dynamically calculate the version based on VERSION tuple
if len(VERSION)>2 and VERSION[2] is not None:
str_version = "%d.%d_%s" % VERSION[:3]
else:
str_version = "%d.%d" % VERSION[:2]
version= str_version
setup(
name = 'django-livesetting... |
Add pytz to required dependencies | from setuptools import setup
import mzgtfs
setup(
name='mzgtfs',
version=mzgtfs.__version__,
description='Mapzen GTFS',
author='Ian Rees',
author_email='ian@mapzen.com',
url='https://github.com/transitland/mapzen-gtfs',
license='License :: OSI Approved :: MIT License',
packages=['mzgtfs'],
install_r... | from setuptools import setup
import mzgtfs
setup(
name='mzgtfs',
version=mzgtfs.__version__,
description='Mapzen GTFS',
author='Ian Rees',
author_email='ian@mapzen.com',
url='https://github.com/transitland/mapzen-gtfs',
license='License :: OSI Approved :: MIT License',
packages=['mzgtfs'],
install_r... |
Add holidays module to packages list | #!/usr/bin/env python
"""How to release a new version: https://packaging.python.org/en/latest/distributing.html#uploading-your-project-to-pypi"""
from businesstime import __version__
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='businesstime',
ve... | #!/usr/bin/env python
"""How to release a new version: https://packaging.python.org/en/latest/distributing.html#uploading-your-project-to-pypi"""
from businesstime import __version__
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='businesstime',
ve... |
Implement autoloading and summary function | # -*- coding: utf-8 -*-
"""Processor for remote INDRA JSON files."""
import requests
from typing import List
from ..statements import Statement, stmts_from_json
__all__ = [
'RemoteProcessor',
]
class RemoteProcessor:
"""A processor for INDRA JSON file to be retrieved by URL.
Parameters
----------... | # -*- coding: utf-8 -*-
"""Processor for remote INDRA JSON files."""
from collections import Counter
import requests
from typing import List
from ..statements import Statement, stmts_from_json
__all__ = [
'RemoteProcessor',
]
class RemoteProcessor:
"""A processor for INDRA JSON file to be retrieved by UR... |
Modify gatekeeper config for master.chromium.chrome after switch to recipes | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from master import gatekeeper
from master import master_utils
# This is the list of the builder categories and the corresponding critical
# steps. If one cr... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from master import gatekeeper
from master import master_utils
# This is the list of the builder categories and the corresponding critical
# steps. If one cr... |
Test changing file path for nosetests | import unittest
import src
import resources.Constants as const
class TestAssignments(unittest.TestCase):
string_file = ''
int_file = ''
@classmethod
def setUpClass(cls):
cls.string_file = src.main("../resources/BasicStringAssignment.txt")
cls.int_file = src.main("../resources/BasicIn... | import unittest
import src
import resources.Constants as const
class TestAssignments(unittest.TestCase):
string_file = ''
int_file = ''
@classmethod
def setUpClass(cls):
cls.string_file = src.main("./resources/BasicStringAssignment.txt")
cls.int_file = src.main("./resources/BasicInte... |
Set the secure flag for both our cookies | from .base import *
DEBUG = False
ALLOWED_HOSTS = ['selling-online-overseas.export.great.gov.uk']
ADMINS = (('David Downes', 'david@downes.co.uk'),)
MIDDLEWARE_CLASSES += [
'core.middleware.IpRestrictionMiddleware',
]
INSTALLED_APPS += [
'raven.contrib.django.raven_compat'
]
RAVEN_CONFIG = {
'dsn': os.e... | from .base import *
DEBUG = False
ALLOWED_HOSTS = ['selling-online-overseas.export.great.gov.uk']
ADMINS = (('David Downes', 'david@downes.co.uk'),)
MIDDLEWARE_CLASSES += [
'core.middleware.IpRestrictionMiddleware',
]
INSTALLED_APPS += [
'raven.contrib.django.raven_compat'
]
RAVEN_CONFIG = {
'dsn': os.e... |
Enable native custom elements for Pica benchmark | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry import test
from telemetry.page import page_measurement
class PicaMeasurement(page_measurement.PageMeasurement):
def MeasurePage(self, _, t... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry import test
from telemetry.page import page_measurement
class PicaMeasurement(page_measurement.PageMeasurement):
def CustomizeBrowserOption... |
Use broker IP instead of domain name | BROKER_URL = 'amqp://couchbase:couchbase@ci.sc.couchbase.com:5672/broker'
CELERY_RESULT_BACKEND = 'amqp'
CELERY_RESULT_EXCHANGE = 'perf_results'
CELERY_RESULT_PERSISTENT = False
| BROKER_URL = 'amqp://couchbase:couchbase@172.23.97.73:5672/broker'
CELERY_RESULT_BACKEND = 'amqp'
CELERY_RESULT_EXCHANGE = 'perf_results'
CELERY_RESULT_PERSISTENT = False
|
Break out items pending deprecation, remove double underscores | from fabric import api as __api
# Setup some default values.
__api.env.deploy_user = 'webapps'
from denim.paths import (cd_deploy, cd_package, deploy_path, package_path)
from denim import (scm, service, system, virtualenv, webserver)
from denim.decorators import deploy_env
@__api.task(name="help")
def show_help():
... | from fabric import api as _api
# Setup some default values.
_api.env.deploy_user = 'webapps'
from denim.paths import (cd_deploy, cd_application, deploy_path, application_path)
from denim import (scm, service, system, virtualenv, webserver)
from denim.decorators import deploy_env
# Pending deprecation
from denim.path... |
Set DEBUG = False in production | from local_settings import *
ALLOWED_HOSTS = ['uchicagohvz.org']
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database fi... | from local_settings import *
settings.DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', ... |
Test compatibility with older Django versions. | from django.db import models
class TestModel(models.Model):
name = models.CharField(max_length=63, unique=True, verbose_name='Name')
image = models.ImageField(verbose_name='Image')
| from django.db import models
class TestModel(models.Model):
name = models.CharField(max_length=63, unique=True, verbose_name='Name')
image = models.ImageField(verbose_name='Image', upload_to='uploads/')
|
Add originally raised exception value to pytest error message | import re
import py.code
import pytest
def pytest_namespace():
return {'raises_regexp': raises_regexp}
class raises_regexp(object):
def __init__(self, expected_exception, regexp):
self.exception = expected_exception
self.regexp = regexp
self.excinfo = None
def __enter__(self):
... | import re
import py.code
import pytest
def pytest_namespace():
return {'raises_regexp': raises_regexp}
class raises_regexp(object):
def __init__(self, expected_exception, regexp):
self.exception = expected_exception
self.regexp = regexp
self.excinfo = None
def __enter__(self):
... |
Define subprocesses in the context of the root process. Maybe this is more readable? | from simpy import Simulation, InterruptedException
def test_simple_process():
def pem(ctx, result):
while True:
result.append(ctx.now)
yield ctx.wait(1)
result = []
Simulation(pem, result).simulate(until=4)
assert result == [0, 1, 2, 3]
def test_interrupt():
def p... | from simpy import Simulation, InterruptedException
def test_simple_process():
def pem(ctx, result):
while True:
result.append(ctx.now)
yield ctx.wait(1)
result = []
Simulation(pem, result).simulate(until=4)
assert result == [0, 1, 2, 3]
def test_interrupt():
def r... |
Fix unicode source code on py3 | import json
from . import _dukpy
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
try: # pragma: no cover
unicode
string_types = (str, unicode)
except NameError: # pragma: no cover
string_types = (bytes, str)
class JSInterpreter(object):
"""Jav... | import json
from . import _dukpy
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
try: # pragma: no cover
unicode
string_types = (str, unicode)
jscode_type = str
except NameError: # pragma: no cover
string_types = (bytes, str)
jscode_type = s... |
Delete unused value extractor attribute. | from webapp_health_monitor import errors
class Verificator(object):
verificator_name = None
def __init__(self, **kwargs):
pass
def run(self):
raise NotImplementedError()
def __str__(self):
if self.verificator_name:
return self.verificator_name
else:
... | from webapp_health_monitor import errors
class Verificator(object):
verificator_name = None
def __init__(self, **kwargs):
pass
def run(self):
raise NotImplementedError()
def __str__(self):
if self.verificator_name:
return self.verificator_name
else:
... |
Remove 'thunk' jargon from PythonExecutor | import itertools
from functools import partial
import math
from typing import Any, Callable, Iterable
from rechunker.types import CopySpec, StagedCopySpec, Executor
Thunk = Callable[[], None]
class PythonExecutor(Executor[Thunk]):
"""An execution engine based on Python loops.
Supports copying between any... | import itertools
from functools import partial
import math
from typing import Callable, Iterable
from rechunker.types import CopySpec, StagedCopySpec, Executor
# PythonExecutor represents delayed execution tasks as functions that require
# no arguments.
Task = Callable[[], None]
class PythonExecutor(Executor[Task... |
Add some nose.tools to testing imports. | """The testing directory contains a small set of imaging files to be used
for doctests only. More thorough tests and example data will be stored in
a nipy-data-suite to be created later and downloaded separately.
Examples
--------
>>> from neuroimaging.testing import funcfile
>>> from neuroimaging.core.image import ... | """The testing directory contains a small set of imaging files to be used
for doctests only. More thorough tests and example data will be stored in
a nipy-data-suite to be created later and downloaded separately.
Examples
--------
>>> from neuroimaging.testing import funcfile
>>> from neuroimaging.core.image import ... |
Fix email case issues when restoring user pointers. | from optparse import make_option
from django.core.management.base import BaseCommand
from zephyr.models import Realm, UserProfile
import simplejson
def dump():
pointers = []
for u in UserProfile.objects.select_related("user__email").all():
pointers.append((u.user.email, u.pointer))
file("dumped-poi... | from optparse import make_option
from django.core.management.base import BaseCommand
from zephyr.models import Realm, UserProfile
import simplejson
def dump():
pointers = []
for u in UserProfile.objects.select_related("user__email").all():
pointers.append((u.user.email, u.pointer))
file("dumped-poi... |
Change tilt series type to float in manual background sub. | def transform_scalars(dataset):
from tomviz import utils
import numpy as np
#----USER SPECIFIED VARIABLES-----#
###XRANGE###
###YRANGE###
###ZRANGE###
#---------------------------------#
data_bs = utils.get_array(dataset) #get data as numpy array
if data_bs is None: #Check if ... | def transform_scalars(dataset):
from tomviz import utils
import numpy as np
#----USER SPECIFIED VARIABLES-----#
###XRANGE###
###YRANGE###
###ZRANGE###
#---------------------------------#
data_bs = utils.get_array(dataset) #get data as numpy array
data_bs = data_bs.astype(np.float3... |
Update strategy (was wrong way around before) | import json
def navigate_maze_struct(strategy, f='input/MAZE.txt'):
rooms = json.load(open(f))
for row in rooms:
for room in row:
room['visited'] = False
queue = [(0, 0)]
while queue:
y, x = queue.pop()
room = rooms[y][x]
if room['visited']:
... | import json
def navigate_maze_struct(strategy, f='input/MAZE.txt'):
rooms = json.load(open(f))
for row in rooms:
for room in row:
room['visited'] = False
queue = [(0, 0)]
while queue:
y, x = queue.pop()
room = rooms[y][x]
if room['visited']:
... |
Change @bench to return a list, because there will never be more than 1 key in the dict | from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res... | from functools import wraps
from inspect import getcallargs
from timer import Timer
def bench(f):
"""Times a function given specific arguments."""
timer = Timer(tick_now=False)
@wraps(f)
def wrapped(*args, **kwargs):
timer.start()
f(*args, **kwargs)
timer.stop()
res... |
Remove python 3.6 only format strings | class SDP:
def __init__(self, local_addr, ptime):
self.local_addr = local_addr
self.ptime = ptime
local_addr_desc = f'IN IP4 {self.local_addr[0]}'
self.payload = '\r\n'.join([
'v=0',
f'o=user1 53655765 2353687637 {local_addr_desc}',
's=-',
... | class SDP:
def __init__(self, local_addr, ptime):
self.local_addr = local_addr
self.ptime = ptime
local_addr_desc = 'IN IP4 {}'.format(self.local_addr[0])
self.payload = '\r\n'.join([
'v=0',
'o=user1 53655765 2353687637 {local_addr_desc}',
's=-',
... |
Return 404 if package was not found instead of raising an exception | """Simple blueprint."""
import os
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['POST'])
def search_simple():
"""Handling pip search."""
re... | """Simple blueprint."""
import os
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['POST'])
def search_simple():
"""Handling pip search."""
re... |
Remove unused config on accounts tests | # coding: utf-8
from flask.ext.testing import TestCase
from quokka import create_app
from flask.ext.security.utils import encrypt_password
from ..models import User
class TestAuthModels(TestCase):
def setUp(self):
self.db = self.app.extensions.get('mongoengine')
self.user_dict = {
'na... | # coding: utf-8
from flask.ext.testing import TestCase
from quokka import create_app
from flask.ext.security.utils import encrypt_password
from ..models import User
class TestAuthModels(TestCase):
def setUp(self):
self.user_dict = {
'name': u'Guybrush Treepwood',
'email': u'guybru... |
Add missing import for sys | from gengine.app.tests import db as db
from gengine.metadata import init_declarative_base, init_session
import unittest
import os
import pkgutil
import testing.redis
import logging
log = logging.getLogger(__name__)
init_session()
init_declarative_base()
__path__ = [x[0] for x in os.walk(os.path.dirname(__file__))]
... | from gengine.app.tests import db as db
from gengine.metadata import init_declarative_base, init_session
import unittest
import os
import pkgutil
import testing.redis
import logging
import sys
log = logging.getLogger(__name__)
init_session()
init_declarative_base()
__path__ = [x[0] for x in os.walk(os.path.dirname(__... |
Add DispatchedState, add target, add id | class Dispatched(object):
def __init__(self, w=None, cb=None):
self.w = w
self.cb = cb
self.retval = None
self.output = None
class DispatchInquiry(object):
def __init__(self, msg=None, payload=None, resp=None):
self.msg = msg
self.resp = resp
self.payload = payload
| class Dispatched(object):
def __init__(self, w=None, _id=None):
self.w = w
self.id = _id if _id != None else id(self)
class DispatchedState(object):
def __init__(self, retval=None, output=None, exc=None, _id=None):
self.retval = retval
self.output = output
self.exc = exc
self.id = _id if ... |
Set cli tests to base test class | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `pyutrack` package."""
import unittest
from click.testing import CliRunner
from pyutrack import cli
class TestYoutrack_cli(unittest.TestCase):
def test_improt(self):
import pyutrack
def test_command_line_interface(self):
runner =... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `pyutrack` package."""
import unittest
from click.testing import CliRunner
from pyutrack import cli
from tests import PyutrackTest
class TestYoutrack_cli(PyutrackTest):
def test_improt(self):
import pyutrack
def test_command_line_interface(... |
Check if file is executable, before executing it | import os
import subprocess
import logbook
logger = logbook.Logger('connman-dispatcher')
def execute_scripts_in_dirs(paths, state):
for path in sorted(paths):
if os.path.exists(path) and os.path.isdir(path):
execute_scripts_in_dir(path, state)
def execute_scripts_in_dir(path, state):
for ... | import os
import subprocess
import logbook
logger = logbook.Logger('connman-dispatcher')
def is_executable(path):
return all([os.path.isfile(path), os.access(path, os.X_OK)])
def execute_scripts_in_dirs(paths, state):
for path in sorted(paths):
if os.path.exists(path) and os.path.isdir(path):
... |
Add test case: Post method for experiment | import unittest
import timevis
class TestAPIs(unittest.TestCase):
def setUp(self):
self.app = timevis.app.test_client()
def test_api(self):
resp = self.app.get('/api/v2/experiment')
self.assertIsNotNone(resp.data)
if __name__ == '__main__':
unittest.main()
| import unittest
import timevis
import os.path
import json
# The folder holding the test data
test_path = os.path.dirname(__file__)
class TestExperiment(unittest.TestCase):
def setUp(self):
self.app = timevis.app.test_client()
self.url = '/api/v2/experiment'
# TODO create test db
... |
Put in first proper tiny package class and unit test. | from unittest import TestCase
class TestBuildError(TestCase):
def test_push_message(self):
self.fail()
def test_format_as_single_string(self):
self.faildoo()
| from unittest import TestCase
from builderror import BuildError
class TestBuildError(TestCase):
def test_that_multiple_pushed_messages_are_formatted_properly_when_asked_for(self):
err = BuildError()
err.push_message('message about error details')
err.push_message('message about error cont... |
Remove the logging setup call. | import os
from ctypeslib.dynamic_module import include
from ctypes import *
import logging
logging.basicConfig(level=logging.INFO)
if os.name == "nt":
_libc = CDLL("msvcrt")
else:
_libc = CDLL(None)
include("""\
#include <stdio.h>
#ifdef _MSC_VER
# include <fcntl.h>
#else
# include <sys/fcntl.h>
#endif
"""... | import os
from ctypeslib.dynamic_module import include
from ctypes import *
if os.name == "nt":
_libc = CDLL("msvcrt")
else:
_libc = CDLL(None)
include("""\
#include <stdio.h>
#ifdef _MSC_VER
# include <fcntl.h>
#else
# include <sys/fcntl.h>
#endif
""",
persist=False)
|
Allow servers command to work without a password. | from BaseController import BaseController
from api.util import settings
class ServerListController(BaseController):
def get(self):
servers = {"servers": self.read_server_config()}
self.write(servers)
def read_server_config(self):
"""Returns a list of servers with the 'id' field added.... | from BaseController import BaseController
from api.util import settings
class ServerListController(BaseController):
def get(self):
servers = {"servers": self.read_server_config()}
self.write(servers)
def read_server_config(self):
"""Returns a list of servers with the 'id' field added.... |
Add nltk part to script | '''
Script used to query Wikipedia for summary of object
'''
import sys
import wikipedia
def main():
# Check that we have the right number of arguments
if (len(sys.argv) != 2):
print 'Incorrect number of arguments; please pass in only one string that contains the subject'
return 'Banana'
print wikipedia... | '''
Script used to query Wikipedia for summary of object
'''
import sys
import wikipedia
import nltk
def main():
# Check that we have the right number of arguments
if (len(sys.argv) != 2):
print 'Incorrect number of arguments; please pass in only one string that contains the query'
return 'Banana'
# Ge... |
Adjust doc strings in Fibonacci numbers implementation | def fib1(amount):
"""
Fibonacci generator example. The second variable is used to store
the result.
:param amount: Amount of numbers to produce.
:return: Generator.
>>> list(fib1(0))
[]
>>> list(fib1(1))
[0]
>>> list(fib1(3))
[0, 1, 1]
>>> list(fib1(9))
[0, 1, 1, 2, ... | """Implementations calculation of Fibonacci numbers."""
def fib1(amount):
"""
Calculate Fibonacci numbers.
The second variable is used to store the result.
:param amount: Amount of numbers to produce.
:return: Generator.
>>> list(fib1(0))
[]
>>> list(fib1(1))
[0]
>>> list(fib... |
Make it work with last fman version (0.7) on linux | from fman import DirectoryPaneCommand, show_alert
import distutils
from distutils import dir_util, file_util
import os.path
class DuplicateFileDir(DirectoryPaneCommand):
def __call__(self):
selected_files = self.pane.get_selected_files()
if len(selected_files) >= 1 or (len(selected_files) =... | from fman import DirectoryPaneCommand, show_alert
from urllib.parse import urlparse
import os.path
from shutil import copytree, copyfile
class DuplicateFileDir(DirectoryPaneCommand):
def __call__(self):
selected_files = self.pane.get_selected_files()
if len(selected_files) >= 1 or (len(sele... |
Change test function as existing method deprecated | import pytest
@pytest.mark.parametrize("name, enabled, running", [
("cron", "enabled", "running"),
("docker", "enabled", "running"),
("firewalld", "enabled", "running"),
("haveged", "enabled", "running"),
("ssh", "enabled", "running"),
])
def test_services(Service, name, enabled, running):
is_enabled = Se... | import pytest
@pytest.mark.parametrize("name, enabled, running", [
("cron", "enabled", "running"),
("docker", "enabled", "running"),
("firewalld", "enabled", "running"),
("haveged", "enabled", "running"),
("ssh", "enabled", "running"),
])
def test_services(host, name, enabled, running):
svc = host.servic... |
Add rev generation via normalized timestamps | '''
Misc utilities
'''
# Import python libs
import os
import binascii
def rand_hex_str(size):
'''
Return a random string of the passed size using hex encoding
'''
return binascii.hexlify(os.urandom(size/2))
def rand_raw_str(size):
'''
Return a raw byte string of the given size
'''
r... | '''
Misc utilities
'''
# Import python libs
import os
import time
import struct
import binascii
import datetime
# create a standard epoch so all platforms will count revs from
# a standard epoch of jan 1 2014
STD_EPOCH = time.mktime(datetime.datetime(2014, 1, 1).timetuple())
def rand_hex_str(size):
'''
Retu... |
Synchronize testing module with BetterBatch one - and integrate Coverage reporting | import unittest
import os.path
import os
import sys
sys.path.append(".")
#from pywinauto.timings import Timings
#Timings.Fast()
excludes = ['test_sendkeys']
def run_tests():
testfolder = os.path.abspath(os.path.split(__file__)[0])
sys.path.append(testfolder)
for root, dirs, files in... | import os
import sys
import unittest
import coverage
# needs to be called before importing the modules
cov = coverage.coverage(branch = True)
cov.start()
testfolder = os.path.abspath(os.path.dirname(__file__))
package_root = os.path.abspath(os.path.join(testfolder, r"..\.."))
sys.path.append(package_root... |
Use the more obvious linspace instead of arange | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Circular Layout
===============
This module contains several graph layouts which rely heavily on circles.
"""
import numpy as np
from ..util import _straight_line_vertic... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Circular Layout
===============
This module contains several graph layouts which rely heavily on circles.
"""
import numpy as np
from ..util import _straight_line_vertic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.