Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Bump version number for release. | """
A collection of Django extensions that add content-management facilities to Django projects.
Developed by Dave Hall.
<http://etianen.com/>
"""
VERSION = (1, 7, 11)
| """
A collection of Django extensions that add content-management facilities to Django projects.
Developed by Dave Hall.
<http://etianen.com/>
"""
VERSION = (1, 8)
|
Bump version as instructed by bamboo. | # -*- coding: utf-8 -*-
__version__ = '2.3.5pbs.19'
# patch settings
try:
from django.conf import settings
if 'cms' in settings.INSTALLED_APPS:
from conf import patch_settings
patch_settings()
except ImportError: # pragma: no cover
"""
This exception means that either the application is... | # -*- coding: utf-8 -*-
__version__ = '2.3.5pbs.20'
# patch settings
try:
from django.conf import settings
if 'cms' in settings.INSTALLED_APPS:
from conf import patch_settings
patch_settings()
except ImportError: # pragma: no cover
"""
This exception means that either the application is... |
Use Fake redis for tests. | from roku import Roku
from app.core.messaging import Receiver
from app.core.servicemanager import ServiceManager
from app.services.tv_remote.service import RokuScanner, RokuTV
class TestRokuScanner(object):
@classmethod
def setup_class(cls):
cls.service_manager = ServiceManager(None)
cls.serv... | import os
from roku import Roku
from app.core.messaging import Receiver
from app.core.servicemanager import ServiceManager
from app.services.tv_remote.service import RokuScanner, RokuTV
class TestRokuScanner(object):
@classmethod
def setup_class(cls):
os.environ["USE_FAKE_REDIS"] = "TRUE"
cl... |
Add comment to test settings to advice disabling search indexing | import logging
from {{ project_name }}.settings import * # noqa
logging.disable(logging.CRITICAL)
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '{{ project_name }}',
'USER': 'postgres'
},
}
# Add middleware to add a meta tag with the re... | import logging
from {{ project_name }}.settings import * # noqa
logging.disable(logging.CRITICAL)
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '{{ project_name }}',
'USER': 'postgres'
},
}
# Add middleware to add a meta tag with the re... |
Raise error if migrations imported for old Django | """
Django migrations for easy_thumbnails app
This package does not contain South migrations. South migrations can be found
in the ``south_migrations`` package.
"""
SOUTH_ERROR_MESSAGE = """\n
For South support, customize the SOUTH_MIGRATION_MODULES setting like so:
SOUTH_MIGRATION_MODULES = {
'easy_thu... | |
Revert "stop reading fonts/input plugins from environ as we now have a working mapnik-config.bat on windows" | import os
settings = os.path.join(os.path.dirname(__file__),'lib','mapnik_settings.js')
# this goes into a mapnik_settings.js file beside the C++ _mapnik.node
settings_template = """
module.exports.paths = {
'fonts': %s,
'input_plugins': %s
};
"""
def write_mapnik_settings(fonts='undefined',input_plugins='un... | import os
settings = os.path.join(os.path.dirname(__file__),'lib','mapnik_settings.js')
# this goes into a mapnik_settings.js file beside the C++ _mapnik.node
settings_template = """
module.exports.paths = {
'fonts': %s,
'input_plugins': %s
};
"""
def write_mapnik_settings(fonts='undefined',input_plugins='un... |
Include statistics usage in existing tests. | import os
from neat.population import Population
from neat.config import Config
def test_minimal():
# sample fitness function
def eval_fitness(population):
for individual in population:
individual.fitness = 1.0
# creates the population
local_dir = os.path.dirname(__file__)
con... | import os
from neat.population import Population
from neat.config import Config
from neat.statistics import get_average_fitness
def test_minimal():
# sample fitness function
def eval_fitness(population):
for individual in population:
individual.fitness = 1.0
# creates the population
... |
Make io test cleanup after itself by removing 'testfile'. | import sys
try:
import _os as os
except ImportError:
import os
if not hasattr(os, "unlink"):
print("SKIP")
sys.exit()
try:
os.unlink("testfile")
except OSError:
pass
# Should create a file
f = open("testfile", "a")
f.write("foo")
f.close()
f = open("testfile")
print(f.read())
f.close()
f = ... | import sys
try:
import _os as os
except ImportError:
import os
if not hasattr(os, "unlink"):
print("SKIP")
sys.exit()
# cleanup in case testfile exists
try:
os.unlink("testfile")
except OSError:
pass
# Should create a file
f = open("testfile", "a")
f.write("foo")
f.close()
f = open("testfile... |
Test that DeployOptions sets two options | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Unit tests for the implementation ``flocker-deploy``.
"""
from twisted.trial.unittest import TestCase, SynchronousTestCase
from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin
from ..script import DeployScript, DeployOptions
cl... | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Unit tests for the implementation ``flocker-deploy``.
"""
from twisted.trial.unittest import TestCase, SynchronousTestCase
from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin
from ..script import DeployScript, DeployOptions
cl... |
Allow other characters in placeholder name | from django.template import loader, Context, TemplateDoesNotExist
from django.template.loader_tags import ExtendsNode
from cms.utils import get_template_from_request
import re
# must be imported like this for isinstance
from django.templatetags.cms_tags import PlaceholderNode #do not remove
def get_placeholders(reque... | from django.template import loader, Context, TemplateDoesNotExist
from django.template.loader_tags import ExtendsNode
from cms.utils import get_template_from_request
import re
# must be imported like this for isinstance
from django.templatetags.cms_tags import PlaceholderNode #do not remove
def get_placeholders(reque... |
Change doc setting for development. | """
Functions that return external URLs, for example for the Vesper documentation.
"""
import vesper.version as vesper_version
_USE_LATEST_DOCUMENTATION_VERSION = False
"""Set this `True` during development, `False` for release."""
def _create_documentation_url():
if _USE_LATEST_DOCUMENTATION_VERSION:
... | """
Functions that return external URLs, for example for the Vesper documentation.
"""
import vesper.version as vesper_version
_USE_LATEST_DOCUMENTATION_VERSION = True
"""Set this `True` during development, `False` for release."""
def _create_documentation_url():
if _USE_LATEST_DOCUMENTATION_VERSION:
... |
Add in dependency for flask cors | from setuptools import find_packages, setup
setup(name="umaineapi_pinchangeserver",
version = "0.1",
description = "A service for connecting to myHousing using a Maine ID and ",
author = "Noah Howard",
platforms = ["any"],
license = "BSD",
packages = find_packages(),
install_r... | from setuptools import find_packages, setup
setup(name="umaineapi_pinchangeserver",
version = "0.1",
description = "A service for connecting to myHousing using a Maine ID and ",
author = "Noah Howard",
platforms = ["any"],
license = "BSD",
packages = find_packages(),
install_r... |
Fix site when logged in |
from extensions.models import ExtensionVersion
def n_unreviewed_extensions(request):
if not request.user.has_perm("review.can-review-extensions"):
return dict()
return dict(n_unreviewed_extensions=ExtensionVersion.unreviewed().count())
|
from extensions.models import ExtensionVersion
def n_unreviewed_extensions(request):
if not request.user.has_perm("review.can-review-extensions"):
return dict()
return dict(n_unreviewed_extensions=ExtensionVersion.objects.unreviewed().count())
|
Fix syntax error in email service | from flask_mail import Message
from zou.app import mail, app
def send_email(subject, body, recipient_email, html=None):
"""
Send an email with given subject and body to given recipient.
"""
if html is None:
html = body
with app.app_context():
message = Message(
sender=... | from flask_mail import Message
from zou.app import mail, app
def send_email(subject, body, recipient_email, html=None):
"""
Send an email with given subject and body to given recipient.
"""
if html is None:
html = body
with app.app_context():
message = Message(
sender=... |
Remove an import which snuck in but does not belong. | """
Spyral, an awesome library for making games.
"""
__version__ = '0.1.1'
__license__ = 'MIT'
__author__ = 'Robert Deaton'
import compat
import memoize
import point
import camera
import sprite
import scene
import _lib
import event
import animator
import animation
import pygame
import image
import color
import rect
... | """
Spyral, an awesome library for making games.
"""
__version__ = '0.1.1'
__license__ = 'MIT'
__author__ = 'Robert Deaton'
import compat
import memoize
import point
import camera
import sprite
import scene
import _lib
import event
import animator
import animation
import pygame
import image
import color
import rect
... |
Remove last digit of version number if it's 0. | # coding=UTF8
import datetime
name = "Devo"
release_date = datetime.date(2012, 12, 13)
version = (1, 0, 0)
version_string = ".".join(str(x) for x in version)
identifier = "com.iogopro.devo"
copyright = u"Copyright © 2010-2012 Luke McCarthy"
developer = "Developer: Luke McCarthy <luke@iogopro.co.uk>"
company_na... | # coding=UTF8
import datetime
name = "Devo"
release_date = datetime.date(2012, 12, 13)
version = (1, 0, 0)
version_string = ".".join(str(x) for x in (version if version[2] != 0 else version[:2]))
identifier = "com.iogopro.devo"
copyright = u"Copyright © 2010-2012 Luke McCarthy"
developer = "Developer: Luke McCa... |
Mark as test as "todo" for now. | from twisted.trial import unittest
from formal import util
class TestUtil(unittest.TestCase):
def test_validIdentifier(self):
self.assertEquals(util.validIdentifier('foo'), True)
self.assertEquals(util.validIdentifier('_foo'), True)
self.assertEquals(util.validIdentifier('_foo_'), True)
... | from twisted.trial import unittest
from formal import util
class TestUtil(unittest.TestCase):
def test_validIdentifier(self):
self.assertEquals(util.validIdentifier('foo'), True)
self.assertEquals(util.validIdentifier('_foo'), True)
self.assertEquals(util.validIdentifier('_foo_'), True)
... |
Use full URI for build failure reasons | from __future__ import absolute_import
from jinja2 import Markup
from changes.buildfailures.base import BuildFailure
class TestFailure(BuildFailure):
def get_html_label(self, build):
link = '/projects/{0}/builds/{1}/tests/?result=failed'.format(build.project.slug, build.id.hex)
try:
... | from __future__ import absolute_import
from jinja2 import Markup
from changes.buildfailures.base import BuildFailure
from changes.utils.http import build_uri
class TestFailure(BuildFailure):
def get_html_label(self, build):
link = build_uri('/projects/{0}/builds/{1}/tests/?result=failed'.format(build.pr... |
Allow for comments in the sql file that do not start the line. | import os.path
from django.core.management.commands import syncdb
from django.db import models, connection, transaction
try:
from south.management.commands import syncdb
except ImportError:
pass
from ...models import Schema, template_schema
class Command(syncdb.Command):
def handle_noargs(self, **option... | import os.path
from django.core.management.commands import syncdb
from django.db import models, connection, transaction
try:
from south.management.commands import syncdb
except ImportError:
pass
from ...models import Schema, template_schema
class Command(syncdb.Command):
def handle_noargs(self, **option... |
Fix the AvailableActionsPrinter to support the new multiplayer action spec. | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
Create an admin user on db initialisation. | from flask.ext.script import Manager
from datawire.core import app, db
from datawire.model import Service
from datawire.views import index
manager = Manager(app)
@manager.command
def create_db():
""" Create the database entities. """
db.create_all()
if __name__ == "__main__":
manager.run()
| from flask.ext.script import Manager
from datawire.core import app, db
from datawire.model import User
from datawire.views import index
manager = Manager(app)
@manager.command
def createdb():
""" Create the database entities. """
db.create_all()
admin_data = {'screen_name': 'admin', 'display_name': 'Sys... |
Update to run on port 5002 | #!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager
application = create_app(os.getenv('FLASH_CONFIG') or 'default')
manager = Manager(application)
if __name__ == '__main__':
manager.run()
| #!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager, Server
application = create_app(os.getenv('FLASH_CONFIG') or 'default')
manager = Manager(application)
manager.add_command("runserver", Server(port=5002))
if __name__ == '__main__':
manager.run()
|
Prepare kill test for mock - use hyperspeed | # Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
from __future__ import print_function
import sys, os, signal, time, subprocess32
def _killer(pid, sleep_time, num_kills):
print("\nKiller going to sleep for", sleep_time, "sec... | # Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
from __future__ import print_function
import sys, os, signal, time, subprocess32
sys.path.append('../../..')
from jenkinsflow.mocked import hyperspeed
def _killer(pid, sleep_time... |
Add tests for TCP flow interception | import pytest
from mitmproxy.addons import intercept
from mitmproxy import exceptions
from mitmproxy.test import taddons
from mitmproxy.test import tflow
def test_simple():
r = intercept.Intercept()
with taddons.context(r) as tctx:
assert not r.filt
tctx.configure(r, intercept="~q")
a... | import pytest
from mitmproxy.addons import intercept
from mitmproxy import exceptions
from mitmproxy.test import taddons
from mitmproxy.test import tflow
def test_simple():
r = intercept.Intercept()
with taddons.context(r) as tctx:
assert not r.filt
tctx.configure(r, intercept="~q")
a... |
Add route for commenting page test | from flask import Flask, jsonify, render_template, request, current_app, redirect, flash
from functools import wraps
import json
app = Flask(__name__)
def jsonp(f):
'''Wrap JSONified output for JSONP'''
@wraps(f)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callbac... | from flask import Flask, jsonify, render_template, request, current_app, redirect, flash
from functools import wraps
import json
app = Flask(__name__)
def jsonp(f):
'''Wrap JSONified output for JSONP'''
@wraps(f)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callbac... |
Allow for case insensitivity (and any other flag). | from re import search
"Some baseline features for testing the classifier."
def make_searcher(substring, field='content'):
def result(datum):
if search(substring, datum.__dict__[field]):
return ['has_substring_' + substring]
else:
return []
return result
def f2(datum):
return [str(len(datum.content) % 8)... | from re import search, IGNORECASE
"Some baseline features for testing the classifier."
def make_searcher(substring, field='content', flags=IGNORECASE):
def result(datum):
if search(substring, datum.__dict__[field], flags):
return ['has_substring_' + substring]
else:
return []
return result
def f2(datum):... |
Check password strength when resetting password | from radar.validation.core import Field, Validation
from radar.validation.validators import required
class ResetPasswordValidation(Validation):
token = Field([required()])
username = Field([required()])
password = Field([required()])
| from radar.validation.core import Field, Validation, ValidationError
from radar.validation.validators import required
from radar.auth.passwords import is_strong_password
class ResetPasswordValidation(Validation):
token = Field([required()])
username = Field([required()])
password = Field([required()])
... |
Extend Admin instead of Base controller | from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
class AdminController(BaseController):
def email(self):
... | from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
from ckan.controllers.admin import AdminController
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
class Admi... |
Remove multiple users capability from initailize_db | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Entry,
Base,
)
def usage(argv):
cmd = os.path.basename(ar... | import os
import sys
import transaction
from sqlalchemy import engine_from_config
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models import (
DBSession,
Entry,
Base,
)
def usage(argv):
cmd = os.path.basename(ar... |
Revert "Corrected issue with Navigation change controller so it uses 'local' directory instead of 'default'." | import os
import shutil
import splunk.appserver.mrsparkle.controllers as controllers
from splunk.appserver.mrsparkle.lib.decorators import expose_page
APP = 'SplunkforPaloAltoNetworks'
ENABLED_NAV = os.path.join(os.environ['SPLUNK_HOME'], 'etc', 'apps', APP, 'default', 'data', 'ui', 'nav', 'default.xml.nfi_enabled')
D... | import os
import shutil
import splunk.appserver.mrsparkle.controllers as controllers
from splunk.appserver.mrsparkle.lib.decorators import expose_page
APP = 'SplunkforPaloAltoNetworks'
ENABLED_NAV = os.path.join(os.environ['SPLUNK_HOME'], 'etc', 'apps', APP, 'default', 'data', 'ui', 'nav', 'default.xml.nfi_enabled')
D... |
Add note about required additional packages installation |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
#
# From https://twistedmatrix.com/documents/current/_downloads/simpleserv.py
from twisted.internet import reactor, protocol
import rollbar
def bar(p):
# These local variables will be sent to Rollbar and available in the UI
a = 33
... |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
#
# From https://twistedmatrix.com/documents/current/_downloads/simpleserv.py
# NOTE: pyrollbar requires both `Twisted` and `treq` packages to be installed
from twisted.internet import reactor, protocol
import rollbar
def bar(p):
# These ... |
Use lambda function with method | import string
UPPER = string.ascii_uppercase
LOWER = string.ascii_lowercase
def rotate(s, n):
return "".join(rot_gen(s,n))
def shift_rules(n):
shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n]
return {k:v for k,v in zip(UPPER+LOWER, shifted)}
def rot_gen(s, n):
rules = shift_rules(n)
f... | import string
UPPER = string.ascii_uppercase
LOWER = string.ascii_lowercase
def rotate(s, n):
rules = shift_rules(n)
return "".join(map(lambda k: rules.get(k, k), s))
def shift_rules(n):
shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n]
return {k:v for k,v in zip(UPPER+LOWER, shifted)}
|
Use plural for slurm endpoints | from . import views
def register_in(router):
router.register(r'slurm', views.SlurmServiceViewSet, basename='slurm')
router.register(
r'slurm-service-project-link',
views.SlurmServiceProjectLinkViewSet,
basename='slurm-spl',
)
router.register(
r'slurm-allocation', views.... | from . import views
def register_in(router):
router.register(r'slurm', views.SlurmServiceViewSet, basename='slurm')
router.register(
r'slurm-service-project-link',
views.SlurmServiceProjectLinkViewSet,
basename='slurm-spl',
)
router.register(
r'slurm-allocations', views... |
Add assertion that no options are passed to LCTD | """
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015 Dirk Beyer
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
... | """
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015 Dirk Beyer
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
... |
Update export building fires command. | from django.core.management.base import BaseCommand
from firecares.firestation.models import FireDepartment
class Command(BaseCommand):
"""
This command is used to export data that department heat maps visualize.
"""
help = 'Creates a sql file to export building fires from.'
def handle(self, *ar... | from django.core.management.base import BaseCommand
from firecares.firestation.models import FireDepartment
class Command(BaseCommand):
"""
This command is used to export data that department heat maps visualize.
"""
help = 'Creates a sql file to export building fires from.'
def handle(self, *ar... |
Add input file name and output file name setting function | #!/usr/bin/env python
from __future__ import print_function
import sys
from chainer.functions import caffe
import cPickle as pickle
import_model = "bvlc_googlenet.caffemodel"
print('Loading Caffe model file %s...' % import_model, file=sys.stderr)
model = caffe.CaffeFunction(import_model)
print('Loaded', file=sys.std... | #!/usr/bin/env python
from __future__ import print_function
import sys
from chainer.functions import caffe
import cPickle as pickle
# import_model = "bvlc_googlenet.caffemodel"
#
# print('Loading Caffe model file %s...' % import_model, file=sys.stderr)
#
# model = caffe.CaffeFunction(import_model)
# print('Loaded', fi... |
Set AppUserModelID so that the app has the right icon on Windows | # -*- coding:utf-8 -*-
#
# Copyright © 2015 The Spyder Development Team
# Copyright © 2014 Gonzalo Peña-Castellanos (@goanpeca)
#
# Licensed under the terms of the MIT License
"""
Application entry point.
"""
# Standard library imports
import sys
# Local imports
from conda_manager.utils.qthelpers import qapplication... | # -*- coding:utf-8 -*-
#
# Copyright © 2015 The Spyder Development Team
# Copyright © 2014 Gonzalo Peña-Castellanos (@goanpeca)
#
# Licensed under the terms of the MIT License
"""
Application entry point.
"""
# Standard library imports
import sys
# Local imports
from conda_manager.utils.qthelpers import qapplication... |
Use relative imports again to support python 3 | # inbuild python imports
# inbuilt django imports
from django.test import LiveServerTestCase
# third party imports
# inter-app imports
# local imports
import mixins
from mixins import SimpleTestCase
class MongoTestCase(mixins.MongoTestMixin, SimpleTestCase):
""" TestCase that creates a mongo collection and c... | # inbuild python imports
# inbuilt django imports
from django.test import LiveServerTestCase
# third party imports
# inter-app imports
# local imports
from . import mixins
from .mixins import SimpleTestCase
class MongoTestCase(mixins.MongoTestMixin, SimpleTestCase):
""" TestCase that creates a mongo collecti... |
Fix a string type-checking bug. | from selenium import webdriver
from selenium.webdriver.remote.switch_to import SwitchTo
from selenium.webdriver.remote.mobile import Mobile
from selenium.webdriver.remote.errorhandler import ErrorHandler
from selenium.webdriver.remote.remote_connection import RemoteConnection
class ResumableRemote(webdriver.Remote):
... | from selenium import webdriver
from selenium.webdriver.remote.switch_to import SwitchTo
from selenium.webdriver.remote.mobile import Mobile
from selenium.webdriver.remote.errorhandler import ErrorHandler
from selenium.webdriver.remote.remote_connection import RemoteConnection
class ResumableRemote(webdriver.Remote):
... |
Fix catalan since me is dumb |
def factorial(n):
res = 1
for i in range(2, n+1):
res *= i
return res
def binomial(n,k):
if k > n:
return 0
if n-k < k:
k = n-k
res = 1
for i in range(1,k+1):
res = res * (n - (k - i)) // i
return res
def catalan(n):
return binomial(2*n,n)//n+1
|
def factorial(n):
res = 1
for i in range(2, n+1):
res *= i
return res
def binomial(n,k):
if k > n:
return 0
if n-k < k:
k = n-k
res = 1
for i in range(1,k+1):
res = res * (n - (k - i)) // i
return res
def catalan(n):
return binomial(2*n,n)//(n+1)
|
Update start process to reflect new path for /cmd | import subprocess
import sys
import os
import setup_util
import time
def start(args):
setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)")
subprocess.call("go get github.com/robfig/revel/cmd", shell=True, cwd="revel")
subprocess.call("go build -o ... | import subprocess
import sys
import os
import setup_util
import time
def start(args):
setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)")
subprocess.call("go get -u github.com/robfig/revel/revel", shell=True, cwd="revel")
subprocess.call("go buil... |
Add test for link redirect | from django.test import TestCase
from .models import Category, Link
class CategoryModelTests(TestCase):
def test_category_sort(self):
Category(title='Test 2', slug='test2').save()
Category(title='Test 1', slug='test1').save()
self.assertEqual(['Test 1', 'Test 2'], map(str, Category.objec... | from django.test import Client, TestCase
from .models import Category, Link
class CategoryModelTests(TestCase):
def test_category_sort(self):
Category(title='Test 2', slug='test2').save()
Category(title='Test 1', slug='test1').save()
self.assertEqual(['Test 1', 'Test 2'], map(str, Catego... |
Add index for storefront's shop ID | """
byceps.services.shop.storefront.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ....database import db
from ....util.instances import ReprBuilder
from ..sequence.transfer.models import NumberSequenceID
from ..shop.... | """
byceps.services.shop.storefront.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ....database import db
from ....util.instances import ReprBuilder
from ..sequence.transfer.models import NumberSequenceID
from ..shop.... |
Tweak file list script to print obf names | import sys
import os
import commands
import fnmatch
import re
import subprocess, shlex
def cmdsplit(args):
if os.sep == '\\':
args = args.replace('\\', '\\\\')
return shlex.split(args)
def main():
md5dir = os.path.abspath(sys.argv[1])
list_file = os.path.abspath(sys.argv[2])
prelist = os.p... | import sys
import os
import commands
import fnmatch
import re
import subprocess, shlex
mcp_root = os.path.abspath(sys.argv[1])
sys.path.append(os.path.join(mcp_root,"runtime"))
from filehandling.srgshandler import parse_srg
def cmdsplit(args):
if os.sep == '\\':
args = args.replace('\\', '\\\\')
retur... |
Add test to ensure only one conn object is created | # coding: utf-8
from pysuru.base import BaseAPI, ObjectMixin
def test_baseapi_headers_should_return_authorization_header():
api = BaseAPI(None, 'TOKEN')
assert {'Authorization': 'bearer TOKEN'} == api.headers
def test_build_url_should_return_full_api_endpoint():
api = BaseAPI('http://example.com/', None... | # coding: utf-8
from pysuru.base import BaseAPI, ObjectMixin
def test_baseapi_headers_should_return_authorization_header():
api = BaseAPI(None, 'TOKEN')
assert {'Authorization': 'bearer TOKEN'} == api.headers
def test_baseapi_conn_should_return_same_object():
api = BaseAPI(None, None)
obj1 = api.con... |
Make realtim fco bucket names match format of others | """
Add capped collections for real time data
"""
import logging
log = logging.getLogger(__name__)
def up(db):
capped_collections = [
"fco_realtime_pay_legalisation_post",
"fco_realtime_pay_legalisation_drop_off",
"fco_realtime_pay_register_birth_abroad",
"fco_realtime_pay_registe... | """
Add capped collections for real time data
"""
import logging
log = logging.getLogger(__name__)
def up(db):
capped_collections = [
"fco_pay_legalisation_post_realtime",
"fco_pay_legalisation_drop_off_realtime",
"fco_pay_register_birth_abroad_realtime",
"fco_pay_register_death_a... |
Set level on module logger instead | import logging
import warnings
warnings.filterwarnings("ignore")
###
# REVIEWER NOTE: THE ORIGINAL IMPLEMENTATION WAS HEAVY HANDED AND I BELIEVE WAS A TEMPORARY WORKAROUND.
# PLEASE CAREFULLY REVIEW TO ENSURE REMOVING THIS DOES NOT AFFECT DESIRED BEHAVIOR
###
logger = logging.getLogger("great_expectations.cli")
de... | import logging
import warnings
warnings.filterwarnings("ignore")
###
# REVIEWER NOTE: THE ORIGINAL IMPLEMENTATION WAS HEAVY HANDED AND I BELIEVE WAS A TEMPORARY WORKAROUND.
# PLEASE CAREFULLY REVIEW TO ENSURE REMOVING THIS DOES NOT AFFECT DESIRED BEHAVIOR
###
logger = logging.getLogger("great_expectations.cli")
de... |
Fix in port number initialisation |
from os import getenv
from webapp import create_app
from argparse import ArgumentParser
app = create_app(getenv('FLASK_CONFIG') or 'development')
def main():
parser = ArgumentParser()
parser.add_argument("-p", "--port", help="port number")
args = parser.parse_args()
port = int(args.port or None)
... |
from os import getenv
from webapp import create_app
from argparse import ArgumentParser
app = create_app(getenv('FLASK_CONFIG') or 'development')
def main():
parser = ArgumentParser()
parser.add_argument("-p", "--port", help="port number")
args = parser.parse_args()
port = int(args.port or 5000)
... |
Call setup() before testing on Django 1.7+ | import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
from django.core import management
apps = sys.argv[1:]
if not apps:
apps = [
'resources',
'forms',
'base',
]
management.call_command('test', *apps, interactive=False)
| import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
if hasattr(django, 'setup'):
django.setup()
from django.core import management
apps = sys.argv[1:]
if not apps:
apps = [
'resources',
'forms',
'base',
]
management.call_command('test', *a... |
Add a function to list absolute path to demo files | """
Demonstration files --- :mod:`pbxplore.demo`
============================================
PBxplore bundles a set of demonstration files. This module ease the access to
these files.
The path to the demonstration files is stored in :const:`DEMO_DATA_PATH`. This
constant can be accessed as :const:`pbxplore.demo.DEMO... | """
Demonstration files --- :mod:`pbxplore.demo`
============================================
PBxplore bundles a set of demonstration files. This module ease the access to
these files.
The path to the demonstration files is stored in :const:`DEMO_DATA_PATH`. This
constant can be accessed as :const:`pbxplore.demo.DEMO... |
Create documentation of DataSource Settings | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... |
Fix path to test file. | """ Run this file to check your python installation.
"""
from os.path import dirname, join
HERE = dirname(__file__)
def test_import_pandas():
import pandas
def test_pandas_version():
import pandas
version_found = pandas.__version__.split(".")
version_found = tuple(int(num) for num in version_found)
... | """ Run this file to check your python installation.
"""
from os.path import dirname, join
HERE = dirname(__file__)
def test_import_pandas():
import pandas
def test_pandas_version():
import pandas
version_found = pandas.__version__.split(".")
version_found = tuple(int(num) for num in version_found)
... |
Set Development Status to "Stable" | from distutils.core import setup
from setuptools import find_packages
setup(name="django-image-cropping",
version="0.6.4",
description="A reusable app for cropping images easily and non-destructively in Django",
long_description=open('README.rst').read(),
author="jonasvp",
author_email="jvp@jonasun... | from distutils.core import setup
from setuptools import find_packages
setup(name="django-image-cropping",
version="0.6.4",
description="A reusable app for cropping images easily and non-destructively in Django",
long_description=open('README.rst').read(),
author="jonasvp",
author_email="jvp@jonasun... |
Add tests. For exclude packages | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
# TODO: put package requirements here
]
test_requirement... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
# TODO: put package requirements here
]
test_requirement... |
Include package data specified in MANIFEST | #!/usr/bin/env python
import os
from setuptools import find_packages, setup
def read(filename):
with open(os.path.join(os.path.dirname(__file__), filename)) as f:
return f.read()
setup(
name="devsoc-contentfiles",
version="0.3a1",
description="DEV Content Files",
long_description=read("... | #!/usr/bin/env python
import os
from setuptools import find_packages, setup
def read(filename):
with open(os.path.join(os.path.dirname(__file__), filename)) as f:
return f.read()
setup(
name="devsoc-contentfiles",
version="0.3a1",
description="DEV Content Files",
long_description=read("... |
Add the test name and change testUrl to just url | # encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Trung Do (chin.bimbo@gmail.com)
#
from __future__ import division
from __future__ import ... | # encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Trung Do (chin.bimbo@gmail.com)
#
from __future__ import division
from __future__ import ... |
Revert "move temporally URL to juandebravo" | from setuptools import setup, find_packages
try:
# HACK: Avoid "TypeError: 'NoneType' object is not callable"
# Related to issue http://bugs.python.org/issue15881
# https://hg.python.org/cpython/rev/0a58fa8e9bac
import multiprocessing
except ImportError:
pass
setup(
name='di-py',
... | from setuptools import setup, find_packages
try:
# HACK: Avoid "TypeError: 'NoneType' object is not callable"
# Related to issue http://bugs.python.org/issue15881
# https://hg.python.org/cpython/rev/0a58fa8e9bac
import multiprocessing
except ImportError:
pass
setup(
name='di-py',
... |
Fix unintended late finalization of memoized functions | import atexit
import functools
from cupy import cuda
_memoized_funcs = []
def memoize(for_each_device=False):
"""Makes a function memoizing the result for each argument and device.
This decorator provides automatic memoization of the function result.
Args:
for_each_device (bool): If True, it ... | import atexit
import functools
from cupy import cuda
_memos = []
def memoize(for_each_device=False):
"""Makes a function memoizing the result for each argument and device.
This decorator provides automatic memoization of the function result.
Args:
for_each_device (bool): If True, it memoizes ... |
Convert to py3, fix style issues (flake8, pylint). | import argparse
import os
import re
import sys
def main(cmdline):
parser = argparse.ArgumentParser(
description='Ensure zero padding in numbering of files.')
parser.add_argument('path', type=str,
help='path to the directory containing the files')
args = parser.parse_args()
path = args.... | #!/usr/bin/env python3
import argparse
import os
import re
import sys
def main():
parser = argparse.ArgumentParser(
description='Ensure zero padding in numbering of files.')
parser.add_argument(
'path',
type=str,
help='path to the directory containing the files')
args = p... |
Make basestring work in Python 3 | #! /usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
import urllib
from .base import AuthenticationMixinBase
from . import GrantFailed
class AuthorizationCodeMixin(AuthenticationMixinBase):
"""Implement helpers for the Authorization Code grant for OAuth2."""
def auth_url(self, sco... | #! /usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
import urllib
from .base import AuthenticationMixinBase
from . import GrantFailed
try:
basestring
except NameError:
basestring = str
class AuthorizationCodeMixin(AuthenticationMixinBase):
"""Implement helpers for the Authori... |
Add h.site.domain() to return the domian without the port | from pylons import config, g
from pylons.i18n import _
def name():
return config.get('adhocracy.site.name', _("Adhocracy"))
def base_url(instance, path=None):
url = "%s://" % config.get('adhocracy.protocol', 'http').strip()
if instance is not None and g.single_instance is None:
url += instance.k... | from pylons import config, g
from pylons.i18n import _
def domain():
return config.get('adhocracy.domain').split(':')[0]
def name():
return config.get('adhocracy.site.name', _("Adhocracy"))
def base_url(instance, path=None):
url = "%s://" % config.get('adhocracy.protocol', 'http').strip()
if insta... |
Fix python3 tests for simbad. | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import simbad
def test_simbad():
r = simbad.QueryAroundId('m31', radius='0.5s').execute()
print r.table
assert "M 31" in r.table["MAIN_ID"]
def test_multi():
result = simbad.QueryMulti(
[simbad.QueryId('m31'),
... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import simbad
import sys
is_python3 = (sys.version_info >= (3,))
def test_simbad():
r = simbad.QueryAroundId('m31', radius='0.5s').execute()
print r.table
if is_python3:
m31 = b"M 31"
else:
m31 = "M 31"
asse... |
Hide secret channels from /NAMES users | from txircd.modbase import Mode
class SecretMode(Mode):
def listOutput(self, command, data):
if command != "LIST":
return data
cdata = data["cdata"]
if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
data["cdata"].clear()
# other +s stuff is hiding in other modules.
... | from twisted.words.protocols import irc
from txircd.modbase import Mode
class SecretMode(Mode):
def checkPermission(self, user, cmd, data):
if cmd != "NAMES":
return data
remove = []
for chan in data["targetchan"]:
if "p" in chan.mode and chan.name not in user.channels:
user.sendMessage(irc.ERR_NOSUCH... |
Add uuid to be readable in Admin-panel | from django.contrib import admin
from .models import Tviit
admin.site.register(Tviit) | from django.contrib import admin
from .models import Tviit
class TviitAdmin(admin.ModelAdmin):
readonly_fields=('uuid',)
admin.site.register(Tviit, TviitAdmin) |
Fix sharepoint tenant cost tracking | from django.contrib.contenttypes.models import ContentType
from nodeconductor.cost_tracking import CostTrackingBackend
from nodeconductor.cost_tracking.models import DefaultPriceListItem
from .models import SharepointTenant
class Type(object):
USAGE = 'usage'
STORAGE = 'storage'
STORAGE_KEY = '1 MB'
... | from django.contrib.contenttypes.models import ContentType
from nodeconductor.cost_tracking import CostTrackingBackend
from nodeconductor.cost_tracking.models import DefaultPriceListItem
from .models import SharepointTenant
class Type(object):
USAGE = 'usage'
STORAGE = 'storage'
STORAGE_KEY = '1 MB'
... |
Remove README from pypi descriptioj | from setuptools import setup, find_packages
install_requires = [
'dill==0.2.5',
'easydict==1.6',
'h5py==2.6.0',
'jsonpickle==0.9.3',
'Keras==1.2.0',
'nflgame==1.2.20',
'numpy==1.11.2',
'pandas==0.19.1',
'scikit-learn==0.18.1',
'scipy==0.18.1',
'tensorflow==0.12.0rc1',
'... | from setuptools import setup, find_packages
install_requires = [
'dill==0.2.5',
'easydict==1.6',
'h5py==2.6.0',
'jsonpickle==0.9.3',
'Keras==1.2.0',
'nflgame==1.2.20',
'numpy==1.11.2',
'pandas==0.19.1',
'scikit-learn==0.18.1',
'scipy==0.18.1',
'tensorflow==0.12.0rc1',
'... |
Prepare for making alpha release | 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='backlash',
version=version,
description="standalone version of the Wer... | 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.1a"
setup(name='backlash',
version=version,
description="Standalone WebOb port of the... |
Adjust phrasing of PyPI long_description | #!/usr/bin/env python
"""setup.py for get_user_headers"""
__author__ = "Stephan Sokolow (deitarion/SSokolow)"
__license__ = "MIT"
import sys
if __name__ == '__main__' and 'flake8' not in sys.modules:
# FIXME: Why does this segfault flake8 under PyPy?
from setuptools import setup
setup(
name="get... | #!/usr/bin/env python
"""setup.py for get_user_headers"""
__author__ = "Stephan Sokolow (deitarion/SSokolow)"
__license__ = "MIT"
import sys
if __name__ == '__main__' and 'flake8' not in sys.modules:
# FIXME: Why does this segfault flake8 under PyPy?
from setuptools import setup
setup(
name="get... |
Add all used packages to tests_requires (for Readthedocs) | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#
# Copyright 2012 ShopWiki
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#
# Copyright 2012 ShopWiki
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
Add scatterplot matrix for college.csv. | import pandas as pd
print('\nKNN\n---')
d = {'X1': [ 0, 2, 0, 0, -1, 1 ],
'X2': [ 3, 0, 1, 1, 0, 1 ],
'X3': [ 0, 0, 3, 2, 1, 1 ],
'Y': ['R', 'R', 'R', 'G', 'G', 'R']}
df = pd.DataFrame(data = d)
df = df.assign(dist = (df.X1**2 + df.X2**2 + df.X3**2)**(0.5))
df = df.sort_val... | import matplotlib.pyplot as plt
import pandas as pd
print('\nKNN\n---')
d = {'X1': [ 0, 2, 0, 0, -1, 1 ],
'X2': [ 3, 0, 1, 1, 0, 1 ],
'X3': [ 0, 0, 3, 2, 1, 1 ],
'Y': ['R', 'R', 'R', 'G', 'G', 'R']}
df = pd.DataFrame(data = d)
df = df.assign(dist = (df.X1**2 + df.X2**2 + df... |
Fix header to short version | # -*- coding: utf-8 -*-
# Odoo, Open Source Management Solution
# Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version ... | # -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Contact's birthdate",
"version": "9.0.1.0.0",
"author": "Odoo Community Association (OCA)",
"category": "Customer Relationship Management",
"website": "https://odoo-comm... |
Fix problem in previous version | import sys
import itertools
import re
from md5 import md5
puzzle_input = 'abc' # 'yjdafjpo'
def key(n):
return md5(puzzle_input + str(n)).hexdigest()
def otp_keys(horizon):
lookahead = {k: -1 for k in '0123456789abcdef'}
def update_lookahead(n):
for quint in re.finditer(r'(.)\1{4}', key(n)):
lookahea... | import sys
import itertools
import re
from md5 import md5
puzzle_input = 'yjdafjpo'
def key(n):
return md5(puzzle_input + str(n)).hexdigest()
def otp_keys(horizon):
lookahead = {k: -1 for k in '0123456789abcdef'}
def update_lookahead(n):
for quint in re.finditer(r'(.)\1{4}', key(n)):
lookahead[quint.... |
Add test for learners help link | from unittest import skipUnless
from bok_choy.web_app_test import WebAppTest
from acceptance_tests import ENABLE_LEARNER_ANALYTICS
from acceptance_tests.mixins import CoursePageTestsMixin
from acceptance_tests.pages import CourseLearnersPage
@skipUnless(ENABLE_LEARNER_ANALYTICS, 'Learner Analytics must be enabled t... | from unittest import skipUnless
from bok_choy.web_app_test import WebAppTest
from acceptance_tests import ENABLE_LEARNER_ANALYTICS
from acceptance_tests.mixins import CoursePageTestsMixin
from acceptance_tests.pages import CourseLearnersPage
@skipUnless(ENABLE_LEARNER_ANALYTICS, 'Learner Analytics must be enabled t... |
Test for dropout probability be a tensor | # Copyright 2015-present Scikit Flow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | # Copyright 2015-present Scikit Flow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
Use nose as the test driver. | #
# This file is part of gruvi. Gruvi is free software available under the terms
# of the MIT license. See the file "LICENSE" that was provided together with
# this source file for the licensing terms.
#
# Copyright (c) 2012 the gruvi authors. See the file "AUTHORS" for a complete
# list.
from setuptools import setup
... | #
# This file is part of gruvi. Gruvi is free software available under the terms
# of the MIT license. See the file "LICENSE" that was provided together with
# this source file for the licensing terms.
#
# Copyright (c) 2012 the gruvi authors. See the file "AUTHORS" for a complete
# list.
from setuptools import setup
... |
Add comment for updated Pandas requirement | import os.path
# Install setuptools if not installed.
try:
import setuptools
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
# read README as the long description
readme = 'README' if os.path.exists('README') else 'README.md'
with open... | import os.path
# Install setuptools if not installed.
try:
import setuptools
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
# read README as the long description
readme = 'README' if os.path.exists('README') else 'README.md'
with open... |
Fix backward compatiblity for MDTrajTopology | def missing_openmm(*args, **kwargs):
raise RuntimeError("Install OpenMM to use this feature")
try:
import simtk.openmm
import simtk.openmm.app
except ImportError:
HAS_OPENMM = False
Engine = missing_openmm
empty_snapshot_from_openmm_topology = missing_openmm
snapshot_from_pdb = missing_open... | def missing_openmm(*args, **kwargs):
raise RuntimeError("Install OpenMM to use this feature")
try:
import simtk.openmm
import simtk.openmm.app
except ImportError:
HAS_OPENMM = False
Engine = missing_openmm
empty_snapshot_from_openmm_topology = missing_openmm
snapshot_from_pdb = missing_open... |
Update to move and run | class State(object):
def __init__(self, ix):
self.index = ix
self.link = None # placeholder, not None if Snake or Ladder
def process(self):
"""Action when landed upon"""
if self.link:
if self.link > self.index:
# Ladder!
return self.l... | class State(object):
def __init__(self, ix):
self.index = ix
self.link = None # placeholder, not None if Snake or Ladder
def process(self):
"""Action when landed upon"""
if self.link:
if self.link > self.index:
# Ladder!
return self.l... |
Use either file input or stdin for filtering length | #!/usr/bin/env python
"""filter_fasta_on_length.py
Filter a fasta file so that the resulting sequences are all longer
or equal to the length threshold parameter. Only accepts stdin."""
import argparse
import sys
from Bio import SeqIO
def main(args):
seqs = []
for i, seq in enumerate(SeqIO.parse(sys.stdin, ... | #!/usr/bin/env python
"""filter_fasta_on_length.py
Filter a fasta file so that the resulting sequences are all longer
or equal to the length threshold parameter. Only accepts stdin."""
import argparse
import sys
from Bio import SeqIO
def main(args):
seqs = []
if args.input_fasta is not None:
input_... |
Call RunSQL instead of RunPython in pagecounter data migration. | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-11-12 17:18
from __future__ import unicode_literals
from django.db import migrations, connection
def reverse_func(state, schema):
with connection.cursor() as cursor:
cursor.execute(
"""
UPDATE osf_pagecounter
... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-11-12 17:18
from __future__ import unicode_literals
from django.db import migrations
reverse_func = [
"""
UPDATE osf_pagecounter
SET (action, guid_id, file_id, version) = ('download', NULL, NULL, NULL);
"""
]
# Splits the data in pagecount... |
Test the ability to append new email address to the person | from copy import copy
from unittest import TestCase
from address_book import Person
class PersonTestCase(TestCase):
def test_get_groups(self):
pass
def test_add_address(self):
basic_address = ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42']
person = Pers... | from copy import copy
from unittest import TestCase
from address_book import Person
class PersonTestCase(TestCase):
def test_get_groups(self):
pass
def test_add_address(self):
basic_address = ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42']
person = Pers... |
Create a factory for Thumbnails. | import factory
from . import models
class ChannelFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = models.Channel
class VideoFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = models.Video
| import factory
from . import models
class ChannelFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = models.Channel
class VideoFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = models.Video
channel = factory.SubFactory(ChannelFactory)
class ThumbnailFactory(factory.django.DjangoModelFa... |
Fix cfg_manager not existing in AbstractDatabaseGateway | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individuals,
# list... | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individuals,
# list... |
Fix the order of importing | from chainer.training.triggers import interval_trigger # NOQA
from chainer.training.triggers import minmax_value_trigger # NOQA
# import class and function
from chainer.training.triggers.early_stopping_trigger import EarlyStoppingTrigger # NOQA
from chainer.training.triggers.interval_trigger import IntervalTrigger... | from chainer.training.triggers import interval_trigger # NOQA
from chainer.training.triggers import minmax_value_trigger # NOQA
# import class and function
from chainer.training.triggers.early_stopping_trigger import EarlyStoppingTrigger # NOQA
from chainer.training.triggers.interval_trigger import IntervalTrigger... |
Fix post_process_fieldsets: This filter is only called for FeinCMS inlines anyway | from django import template
register = template.Library()
@register.filter
def post_process_fieldsets(fieldset):
"""
Removes a few fields from FeinCMS admin inlines, those being
``id``, ``DELETE`` and ``ORDER`` currently.
"""
process = fieldset.model_admin.verbose_name_plural.startswith('Feincm... | from django import template
register = template.Library()
@register.filter
def post_process_fieldsets(fieldset):
"""
Removes a few fields from FeinCMS admin inlines, those being
``id``, ``DELETE`` and ``ORDER`` currently.
"""
excluded_fields = ('id', 'DELETE', 'ORDER')
fieldset.fields = [f ... |
Revert "Remove name from organisation" | """empty message
Revision ID: 0093_data_gov_uk
Revises: 0092_add_inbound_provider
Create Date: 2017-06-05 16:15:17.744908
"""
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects imp... | """empty message
Revision ID: 0093_data_gov_uk
Revises: 0092_add_inbound_provider
Create Date: 2017-06-05 16:15:17.744908
"""
# revision identifiers, used by Alembic.
revision = '0093_data_gov_uk'
down_revision = '0092_add_inbound_provider'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects imp... |
Fix IMWRITE_JPEG_QUALITY ref for the newest OpenCV | __author__ = 'paulo'
import cv2
class OpenCVIntegration(object):
@staticmethod
def adaptive_threshold(filename_in, filename_out):
img = cv2.imread(filename_in)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_B... | __author__ = 'paulo'
import cv2
class OpenCVIntegration(object):
@staticmethod
def adaptive_threshold(filename_in, filename_out):
img = cv2.imread(filename_in)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_B... |
Add pacakge object for working with conda compressed archives. | import tarfile
import os
import json
class Package(object):
def __init__(self, path, mode='r'):
self.path = path
self.mode = mode
self._tarfile = tarfile.open(path, mode=mode)
| import tarfile
import json
from pathlib import PurePath, PureWindowsPat
from os.path import realpath, abspath, join
from hashlib import md5
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from .common import lazyproperty
class BadLinkError(Exception):
pass
... |
Fix response tests in py3 | import json
from echo.response import EchoResponse, EchoSimplePlainTextResponse
from echo.tests import BaseEchoTestCase
class TestEchoSimplePlainTextResponse(BaseEchoTestCase):
def test_populates_text_in_response(self):
"""The Plain text response should populate the outputSpeech"""
expected = "Th... | import json
from echo.response import EchoResponse, EchoSimplePlainTextResponse
from echo.tests import BaseEchoTestCase
class TestEchoSimplePlainTextResponse(BaseEchoTestCase):
def test_populates_text_in_response(self):
"""The Plain text response should populate the outputSpeech"""
expected = "Th... |
Rewrite to replace IC_FLAG by FLAG_from_IC. | '''
>>> IC_FLAG[2]
array([[1, 3],
[1, 4]])
>>> IC_FLAG[3]
array([[1, 4, 6],
[1, 5, 8],
[1, 6, 9]])
'''
# For Python2 compatibility
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__metaclass__... | '''
>>> FLAG_from_IC[2]
array([[1, 1],
[3, 4]])
The flag vector of ICC is [1, 6, 9].
>>> numpy.dot(FLAG_from_IC[3], [0, 0, 1])
array([1, 6, 9])
>>> FLAG_from_IC[3]
array([[1, 1, 1],
[4, 5, 6],
[6, 8, 9]])
'''
# For Python2 compatibility
from __future__ import absolute_import
from __future__ i... |
Convert the adapter into a pytest fixture | from schematics.models import Model
from schematics.types import IntType
from hyp.adapters.schematics import SchematicsSerializerAdapter
class Post(object):
def __init__(self):
self.id = 1
class Simple(Model):
id = IntType()
def test_object_conversion():
adapter = SchematicsSerializerAdapter(... | import pytest
from schematics.models import Model
from schematics.types import IntType
from hyp.adapters.schematics import SchematicsSerializerAdapter
class Post(object):
def __init__(self):
self.id = 1
class Simple(Model):
id = IntType()
@pytest.fixture
def adapter():
return SchematicsSerial... |
Fix linting errors in GoBot | from minibot.bot import Bot
from minibot.hardware.rpi.gpio import PWM
from minibot.interface.servo import Servo
import math
import time
L_MOTOR_PIN = 12
R_MOTOR_PIN = 18
class GoBot(Bot):
def __init__(self):
Bot.__init__(self, "GoBot")
self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15))
self.r... | """
GoBot Example
"""
from minibot.bot import Bot
from minibot.hardware.rpi.gpio import PWM
from minibot.interface.servo import Servo
L_MOTOR_PIN = 12
R_MOTOR_PIN = 18
class GoBot(Bot):
"""
GoBot
"""
def __init__(self):
Bot.__init__(self, "GoBot")
self.l_motor = Servo(PWM(L_MOTOR_PIN... |
Simplify our own test suite | from attest import Tests
suite = lambda mod: 'attest.tests.' + mod + '.suite'
all = Tests([suite('asserts'),
suite('collections'),
suite('classy'),
suite('reporters'),
suite('eval'),
])
| from attest import Tests
all = Tests('.'.join((__name__, mod, 'suite'))
for mod in ('asserts',
'collections',
'classy',
'reporters',
'eval'))
|
Fix verbose level index out of range error | import logging
LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
def init_console_logger(logging_verbosity=3):
logging_levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
if logging_verbosity > len(logging_levels):
logging_verbosity = 3
lvl = loggin... | import logging
LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
def init_console_logger(logging_verbosity=3):
logging_levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
if logging_verbosity > (len(logging_levels) - 1):
logging_verbosity = 3
lvl = ... |
Fix o8d importer to read card IDs to make the sanitized cards | # Read an OCTGN deck
from xml.etree import ElementTree
def read_file(filename):
filedata = open(filename).read()
return read(filedata)
def read(filedata):
root = ElementTree.fromstring(filedata)
identity = []
cards = []
for section in root.getchildren():
if len(section) == 1:
dest = identity
... | # Read an OCTGN deck
from xml.etree import ElementTree
def read_file(filename):
filedata = open(filename).read()
return read(filedata)
def read(filedata):
root = ElementTree.fromstring(filedata)
identity = []
cards = []
for section in root.getchildren():
if len(section) == 1:
dest = identity
... |
Remove the doc that describes the setup. Setup is automated now | '''
$ mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 211
Server version: 5.6.15 Homebrew
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks... | import mysql.connector
from luigi.contrib.mysqldb import MySqlTarget
import unittest
host = 'localhost'
port = 3306
database = 'luigi_test'
username = None
password = None
table_updates = 'table_updates'
def _create_test_database():
con = mysql.connector.connect(user=username,
p... |
Add "localhost" in the allowed hosts for testing purposes | """GeoKey settings."""
from geokey.core.settings.dev import *
DEFAULT_FROM_EMAIL = 'no-reply@travis-ci.org'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'geokey',
'... | """GeoKey settings."""
from geokey.core.settings.dev import *
DEFAULT_FROM_EMAIL = 'no-reply@travis-ci.org'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'geokey',
'... |
Add postsecondary stats to the StatsBase model | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from .staff_student import StaffStudentBase
@python_2_unicode_compatible
class SchoolYear(models.Model):
name = models.CharField(max_length=... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from .staff_student import StaffStudentBase
from .postsecondary_readiness import PostSecondaryReadinessBase
@python_2_unicode_compatible
class S... |
Prepare for twython-django pip release | #!/usr/bin/python
from setuptools import setup
from setuptools import find_packages
__author__ = 'Ryan McGrath <ryan@venodesigns.net>'
__version__ = '1.5.0'
setup(
name='twython-django',
version=__version__,
install_requires=['twython>=3.0.0', 'django'],
author='Ryan McGrath',
author_email='ryan@... | #!/usr/bin/env python
import os
import sys
from setuptools import setup
from setuptools import find_packages
__author__ = 'Ryan McGrath <ryan@venodesigns.net>'
__version__ = '1.5.1'
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
setup(
name='twython-django',
vers... |
Change package name to use hyphen | #! /usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from csdms.dakota import __version__, plugin_script
package_name = 'csdms.dakota'
setup(name=package_name,
version=__version__,
author='Mark Piper',
author_email='mark.piper@colora... | #! /usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from csdms.dakota import __version__, plugin_script
setup(name='csdms-dakota',
version=__version__,
author='Mark Piper',
author_email='mark.piper@colorado.edu',
license='MIT',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.