Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix bug in getting long_description. | #!/usr/bin/env python
from distutils.core import setup
from vaspy import __version__ as version
maintainer = 'Shao-Zheng-Jiang'
maintainer_email = 'shaozhengjiang@gmail.com'
author = maintainer
author_email = maintainer_email
description = __doc__
requires = [
'numpy',
'matplotlib'
]
license = 'LICENSE'
lon... | #!/usr/bin/env python
from distutils.core import setup
from vaspy import __version__ as version
maintainer = 'Shao-Zheng-Jiang'
maintainer_email = 'shaozhengjiang@gmail.com'
author = maintainer
author_email = maintainer_email
description = __doc__
requires = [
'numpy',
'matplotlib'
]
license = 'LICENSE'
wit... |
Add collections package to required list. | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from setuptools import setup
from glob import glob
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python ::... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from setuptools import setup
from glob import glob
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python ::... |
Cut a new version to update the README on PyPi. | """A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspa... | """A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspa... |
Correct installation script to use the correct name for the package. | #!/usr/bin/env python
from setuptools import setup
setup(name='hyppocratic',
version='0.1',
description='Software to convert text files to EpiDoc compatible XML.',
author='Johathan Boyle, Nicolas Gruel',
packages=['CommentaryToEpidoc'],
install_requires=['docopt'],
entry_points={
... | #!/usr/bin/env python
#TODO: add data in the installation for the default xml_template.txt
from setuptools import setup
setup(name='hyppocratic',
version='0.1',
description='Software to convert text files to EpiDoc compatible XML.',
author='Johathan Boyle, Nicolas Gruel',
packages=['hyppocrat... |
Add requirements for developers necessary for tests | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.1.2dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oe... | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.1.2dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oe... |
Add feedback url to served client configuration |
import superdesk
from flask import current_app as app
from superdesk.utils import ListCursor
class ClientConfigResource(superdesk.Resource):
item_methods = []
public_methods = ['GET']
resource_methods = ['GET']
class ClientConfigService(superdesk.Service):
def get(self, req, lookup):
retu... |
import superdesk
from flask import current_app as app
from superdesk.utils import ListCursor
class ClientConfigResource(superdesk.Resource):
item_methods = []
public_methods = ['GET']
resource_methods = ['GET']
class ClientConfigService(superdesk.Service):
def get(self, req, lookup):
retu... |
Rename the DB initialization script | # There is a conflict with older versions on EL 6
__requires__ = ['PasteDeploy>=1.5.0',
'WebOb>=1.2b3',
]
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
CHANGES = open(os.path.j... | # There is a conflict with older versions on EL 6
__requires__ = ['PasteDeploy>=1.5.0',
'WebOb>=1.2b3',
]
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
CHANGES = open(os.path.j... |
Call the reset() method in the Markdown object to clear extensions (e.g. metadata) between processing each file. | __author__ = 'Chris Krycho'
__copyright__ = '2013 Chris Krycho'
from logging import error
from os import path, walk
from sys import exit
try:
from markdown import Markdown
from mixins import DictAsMember
except ImportError as import_error:
error(import_error)
exit()
def convert_source(config):
... | __author__ = 'Chris Krycho'
__copyright__ = '2013 Chris Krycho'
from logging import error
from os import path, walk
from sys import exit
try:
from markdown import Markdown
from mixins import DictAsMember
except ImportError as import_error:
error(import_error)
exit()
def convert_source(config):
... |
Enable the twitterbot since dateutil requirement is now gone. | from setuptools import setup, find_packages
import sys, os
version = '1.5.2'
install_requires = [
# -*- Extra requirements: -*-
]
if sys.version_info < (2,6,):
install_requires.append("simplejson>=1.7.1")
setup(name='twitter3',
version=version,
description="An API and command-line toolset fo... | from setuptools import setup, find_packages
import sys, os
version = '1.5.2'
install_requires = [
# -*- Extra requirements: -*-
]
setup(name='twitter3',
version=version,
description="An API and command-line toolset for Twitter (twitter.com)",
long_description=open("./README", "r").read(),
... |
Exclude tests from installed packages | from setuptools import setup, find_packages
setup(
name='click-man',
version='0.2.1',
license='MIT',
description='Generate man pages for click based CLI applications',
author='Timo Furrer',
author_email='tuxtimo@gmail.com',
install_requires=[
'click'
],
packages=find_package... | from setuptools import setup, find_packages
setup(
name='click-man',
version='0.2.1',
license='MIT',
description='Generate man pages for click based CLI applications',
author='Timo Furrer',
author_email='tuxtimo@gmail.com',
install_requires=[
'click'
],
packages=find_package... |
Make this more like a real python module. | import spyral.memoize
import spyral.point
import spyral.camera
import spyral.util
import spyral.sprite
import spyral.gui
import spyral.scene
import spyral._lib
import spyral.event
import pygame
director = scene.Director()
def init():
pygame.init()
pygame.font.init()
def quit():
pygame.quit()
spyr... | """
Spyral, an awesome library for making games.
"""
__version__ = '0.1'
__license__ = 'LGPLv2'
__author__ = 'Robert Deaton'
import spyral.memoize
import spyral.point
import spyral.camera
import spyral.util
import spyral.sprite
import spyral.gui
import spyral.scene
import spyral._lib
import spyral.event
import pygame... |
Split the HTTPServer line into multiple. | # encoding: utf-8
"""Basic class-based demonstration application.
Applications can be as simple or as complex and layered as your needs dictate.
"""
class Root(object):
def __init__(self, context):
self._ctx = context
def mul(self, a: int = None, b: int = None) -> 'json':
if not a and not b... | # encoding: utf-8
"""Basic class-based demonstration application.
Applications can be as simple or as complex and layered as your needs dictate.
"""
class Root(object):
def __init__(self, context):
self._ctx = context
def mul(self, a: int = None, b: int = None) -> 'json':
"""Multiply two va... |
Add trailing slash to chrome_proxy telemetry test page URL. | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page_module
from telemetry import story
class ReenableAfterBypassPage(page_module.Page):
"""A test page for the re-ena... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page_module
from telemetry import story
class ReenableAfterBypassPage(page_module.Page):
"""A test page for the re-ena... |
Update import location of TestPluginBase | # ----------------------------------------------------------------------------
# Copyright (c) 2016--, Ben Kaehler
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------... | # ----------------------------------------------------------------------------
# Copyright (c) 2016--, Ben Kaehler
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------... |
Print "still alive" progress when testing on travis | import pytest
def pytest_addoption(parser):
parser.addoption("--travis", action="store_true", default=False,
help="Only run tests marked for Travis")
def pytest_configure(config):
config.addinivalue_line("markers",
"not_travis: Mark a test that should not be ... | import pytest
def pytest_addoption(parser):
parser.addoption("--travis", action="store_true", default=False,
help="Only run tests marked for Travis")
def pytest_configure(config):
config.addinivalue_line("markers",
"not_travis: Mark a test that should not be ... |
Complete factorial_recur(), factorial_memo() & factorial_dp() from Hokaido | """Factorial series:
1!, 2!, 3!, ...
- Factorial(1) = 1! = 1
- Factorial(2) = 2! = 2
- Factorial(n) = n! = n * (n - 1)! = n * Factorial(n - 1)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def factorial_recur(n):
"""Get the nth number of Fibonac... | """Factorial series:
1!, 2!, 3!, ...
- Factorial(1) = 1! = 1
- Factorial(2) = 2! = 2
- Factorial(n) = n! = n * (n - 1)! = n * Factorial(n - 1)
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def factorial_recur(n):
"""Get the nth number of factori... |
Use StringIO.StringIO instead of the io.StringIO. | '''
Created on 20 Apr 2010
@author: Chris Filo Gorgolewski
'''
import ConfigParser, os
from io import StringIO
default_cfg = StringIO("""
[logging]
workflow_level = INFO
node_level = INFO
filemanip_level = INFO
[execution]
stop_on_first_crash = false
hash_method = content
""")
config = ConfigParser.ConfigParser()
c... | '''
Created on 20 Apr 2010
@author: Chris Filo Gorgolewski
'''
import ConfigParser, os
from StringIO import StringIO
default_cfg = StringIO("""
[logging]
workflow_level = INFO
node_level = INFO
filemanip_level = INFO
[execution]
stop_on_first_crash = false
hash_method = content
""")
config = ConfigParser.ConfigPars... |
Remove whitespace from name when checking for bye | from django.core.exceptions import ValidationError
from django.template.defaultfilters import slugify
import re
NAME_REGULAR_EXPRESSION = re.compile(r'^[a-zA-Z0-9]+[\w\-\.: ]*$')
def greater_than_zero(value):
"""Checks if value is greater than zero"""
if value <= 0:
raise ValidationError("Value must ... | from django.core.exceptions import ValidationError
from django.template.defaultfilters import slugify
import re
NAME_REGULAR_EXPRESSION = re.compile(r'^[a-zA-Z0-9]+[\w\-\.: ]*$')
def greater_than_zero(value):
"""Checks if value is greater than zero"""
if value <= 0:
raise ValidationError("Value must ... |
Remove test for use_setuptools, as it fails when running under pytest because the installed version of setuptools is already present. | import sys
import os
import tempfile
import unittest
import shutil
import copy
CURDIR = os.path.abspath(os.path.dirname(__file__))
TOPDIR = os.path.split(CURDIR)[0]
sys.path.insert(0, TOPDIR)
from ez_setup import (use_setuptools, _python_cmd, _install)
import ez_setup
class TestSetup(unittest.TestCase):
def url... | import sys
import os
import tempfile
import unittest
import shutil
import copy
CURDIR = os.path.abspath(os.path.dirname(__file__))
TOPDIR = os.path.split(CURDIR)[0]
sys.path.insert(0, TOPDIR)
from ez_setup import _python_cmd, _install
import ez_setup
class TestSetup(unittest.TestCase):
def urlopen(self, url):
... |
Add complete question constructor test | from pywatson.question.question import Question
class TestQuestion:
def test___init___basic(self, questions):
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
def test_ask_question_basic(self, watson):
answer = watson.ask_... | from pywatson.question.evidence_request import EvidenceRequest
from pywatson.question.filter import Filter
from pywatson.question.question import Question
class TestQuestion(object):
"""Unit tests for the Question class"""
def test___init___basic(self, questions):
"""Question is constructed properly ... |
Add a datetime localization function | import pandas as pd
def date_features(input_df, datetime_column='tms_gmt'):
"""
Given a datetime column, extracts useful date information
(minute, hour, dow...)
"""
df = input_df.copy()
return (df.set_index(time_column)
.assign(minute=lambda df: df.index.minute,
... | import pandas as pd
import pytz
def date_features(input_df, datetime_column='tms_gmt'):
"""
Given a datetime column, extracts useful date information
(minute, hour, dow...)
"""
df = input_df.copy()
return (df.set_index(time_column)
.assign(minute=lambda df: df.index.minute,
... |
Allow loading settings from brewmeister.cfg | from flask import Flask
from flask.ext.pymongo import PyMongo
from flask.ext.babel import Babel
from flask.ext.cache import Cache
from brew.io import TemperatureController
from brew.state import Machine
app = Flask(__name__)
app.config.from_object('brew.settings')
babel = Babel(app)
cache = Cache(app)
mongo = PyMong... | from flask import Flask
from flask.ext.pymongo import PyMongo
from flask.ext.babel import Babel
from flask.ext.cache import Cache
from brew.io import TemperatureController
from brew.state import Machine
app = Flask(__name__)
app.config.from_object('brew.settings')
app.config.from_pyfile('brewmeister.cfg', silent=True... |
Test hotfix with advanced develop and cloned repo | # -----------------------------------------------------------------------------
__title__ = 'lamana'
__version__ = '0.4.10'
__author__ = 'P. Robinson II'
__license__ = 'BSD3'
__copyright__ = 'Copyright 2015 P. Robinson II'
# DEPRECATE: Renaming in 0.4.5b1+
##import LamAna.input_
##import LamAna.distributions
##import... | # -----------------------------------------------------------------------------
__title__ = 'lamana'
__version__ = '0.4.11'
__author__ = 'P. Robinson II'
__license__ = 'BSD3'
__copyright__ = 'Copyright 2015 P. Robinson II'
# DEPRECATE: Renaming in 0.4.5b1+
##import LamAna.input_
##import LamAna.distributions
##import... |
Build interface w/ docopt and add POD | #!/usr/bin/env python
if __name__ == "__main__":
run()
| #!/usr/bin/env python
"""Simple Genetic Algorithm for solving TSP.
Usage:
main.py FILE --pop-size=POP_SIZE --max-gen=MAX_GENERATIONS --xover-rate=CROSSOVER_RATE --mute-rate=MUTATION_RATE --num-elites=NUM_ELITES --tournament-k=K
main.py (-h | --help)
main.py (-v | --version)
Options:
-h --help Show this s... |
Fix --check-fips invocation in test | import unittest
from .util import (DestructiveYubikeyTestCase, is_fips, ykman_cli)
class TestYkmanInfo(DestructiveYubikeyTestCase):
def test_ykman_info(self):
info = ykman_cli('info')
self.assertIn('Device type:', info)
self.assertIn('Serial number:', info)
self.assertIn('Firmwar... | import unittest
from .util import (DestructiveYubikeyTestCase, is_fips, ykman_cli)
class TestYkmanInfo(DestructiveYubikeyTestCase):
def test_ykman_info(self):
info = ykman_cli('info')
self.assertIn('Device type:', info)
self.assertIn('Serial number:', info)
self.assertIn('Firmwar... |
Check that export-contacts is included in the top-level command. | """ Tests for go_cli.main. """
from unittest import TestCase
from click.testing import CliRunner
from go_cli.main import cli
class TestCli(TestCase):
def test_help(self):
runner = CliRunner()
result = runner.invoke(cli, ['--help'])
self.assertEqual(result.exit_code, 0)
self.asse... | """ Tests for go_cli.main. """
from unittest import TestCase
from click.testing import CliRunner
from go_cli.main import cli
class TestCli(TestCase):
def test_help(self):
runner = CliRunner()
result = runner.invoke(cli, ['--help'])
self.assertEqual(result.exit_code, 0)
self.asse... |
Add type addaptation methods for generic field class. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
class SearchBackend(object):
pass
class Field(object):
"""
Base class for any field.
"""
name = None
def __init__(self, **kwargs)
self.options = kwargs
def set_name(self, name):
self.name... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
class SearchBackend(object):
pass
class Field(object):
"""
Base class for any field.
"""
name = None
def __init__(self, **kwargs)
for name, value in kwargs.items():
setattr(self, name, val... |
Add an dummy import statement so that freeze programs pick up _internal.p |
from info import __doc__
from numpy.version import version as __version__
import multiarray
import umath
import numerictypes as nt
multiarray.set_typeDict(nt.sctypeDict)
import _sort
from numeric import *
from fromnumeric import *
from defmatrix import *
import ma
import defchararray as char
import records as rec
fro... |
from info import __doc__
from numpy.version import version as __version__
import multiarray
import umath
import _internal # for freeze programs
import numerictypes as nt
multiarray.set_typeDict(nt.sctypeDict)
import _sort
from numeric import *
from fromnumeric import *
from defmatrix import *
import ma
import defchar... |
Revert "Fixed bug with imports" | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 24 11:01:10 2016
@author: ererkka
"""
__version__ = '1.2.2'
| # -*- coding: utf-8 -*-
"""
Created on Wed Feb 24 11:01:10 2016
@author: ererkka
"""
__version__ = '1.2.2'
from .gdxfile import GdxFile |
Add -v and -q options for more or less output | import asyncore
import logging
import multiprocessing
import os
import sys
sys.path.insert(0,
os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
from mopidy import settings, SettingsError
from mopidy.process import CoreProcess
from mopidy.utils import get_class
logger = logging.getLogger('mopidy.ma... | import asyncore
import logging
import multiprocessing
import optparse
import os
import sys
sys.path.insert(0,
os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
from mopidy import settings, SettingsError
from mopidy.process import CoreProcess
from mopidy.utils import get_class
logger = logging.getL... |
Use the base64 module for testing rather than md5 which is deprecated in python2.6 |
import tserver, sys, md5, math
from disco import Disco, result_iterator
def data_gen(path):
return path[1:] + "\n"
def fun_map(e, params):
k = str(int(math.ceil(float(e))) ** 2)
return [(md5.new(k).hexdigest(), "")]
tserver.run_server(data_gen)
disco = Disco(sys.argv[1])
inputs = [1, 485, 3... |
import tserver, sys, base64, math
from disco import Disco, result_iterator
def data_gen(path):
return path[1:] + "\n"
def fun_map(e, params):
k = str(int(math.ceil(float(e))) ** 2)
return [(base64.encodestring(k), "")]
tserver.run_server(data_gen)
disco = Disco(sys.argv[1])
inputs = [1, 485... |
Remove doct from the equation in attrs tests. | from __future__ import absolute_import, division, print_function
from databroker.core import Header
def test_header_dict_conformance(db):
# TODO update this if / when we add conformance testing to
# validate attrs in Header
target = {'start': {'uid': 'start'},
'stop': {'uid': 'stop', 'start... | from __future__ import absolute_import, division, print_function
import copy
from databroker.core import Header
def test_header_dict_conformance(db):
db.prepare_hook = lambda name, doc: copy.deepcopy(doc)
# TODO update this if / when we add conformance testing to
# validate attrs in Header
target = ... |
Fix logging directory njot existing | import sys
import os
import logging
if not os.path.exists(os.path.expanduser("~/.chatserver")):
os.makedirs(os.path.expanduser("~/.chatserver")
logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat.log"), level=logging.DEBUG)
from app import app, db, main, socketio
db.create_all()
app.register_bluep... | import sys
import os
import logging
if not os.path.exists(os.path.expanduser("~/.chatserver")):
os.makedirs(os.path.expanduser("~/.chatserver"))
logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat.log"), level=logging.DEBUG)
from app import app, db, main, socketio
db.create_all()
app.register_blue... |
Update dev version to 1.10 | # file findingaids/__init__.py
#
# Copyright 2012 Emory University Library
#
# 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
#
# U... | # file findingaids/__init__.py
#
# Copyright 2012 Emory University Library
#
# 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
#
# U... |
Remove implicit import of symbols | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2012 DataONE
#
# Licensed under the Apache... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2012 DataONE
#
# Licensed under the Apache... |
Bump version to fix previous bad version | from .pool import create_pool
from .pgsingleton import PG
from .connection import compile_query
__version__ = '0.11.0'
pg = PG()
| from .pool import create_pool
from .pgsingleton import PG
from .connection import compile_query
__version__ = '0.12.0'
pg = PG()
|
Make search term lower case so capitals match. | import json
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.utils.html import conditional_escape as escape
from .models import Search
def uikit(request):
searches = Search.objects.filter(term__matches='%s:*' % request.GET['search'])
return HttpResponse(json.dump... | import json
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.utils.html import conditional_escape as escape
from .models import Search
def uikit(request):
searches = Search.objects.filter(term__matches='%s:*' % request.GET['search'].lower())
return HttpResponse(j... |
Send RideRegistration id through with api response | import requests
from django.conf import settings
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from server.api.serializers.chapters import ChapterSerializer
from .riders import RiderSerializer
from server.core.models.rides import Ride, RideRiders
class RideSerial... | import requests
from django.conf import settings
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from server.api.serializers.chapters import ChapterSerializer
from .riders import RiderSerializer
from server.core.models.rides import Ride, RideRiders
class RideSerial... |
Change how PSNR is computed | import keras.backend as K
import numpy as np
def psnr(y_true, y_pred):
"""Peak signal-to-noise ratio averaged over samples and channels."""
mse = K.mean(K.square(y_true - y_pred), axis=(1, 2))
return K.mean(20 * K.log(255 / K.sqrt(mse)) / np.log(10))
def ssim(y_true, y_pred):
"""structural similarit... | import keras.backend as K
import numpy as np
def psnr(y_true, y_pred):
"""Peak signal-to-noise ratio averaged over samples."""
mse = K.mean(K.square(y_true - y_pred), axis=(-3, -2, -1))
return K.mean(20 * K.log(255 / K.sqrt(mse)) / np.log(10))
def ssim(y_true, y_pred):
"""structural similarity measu... |
Use safe load for yaml. | """
This file contains the code needed for dealing with some of the mappings. Usually a map is just a
dictionary that needs to be loaded inside a variable.
This file carries the function to parse the files and the variables containing the dictionaries
themselves.
"""
import yaml
def load_mapping(filename):
"""
... | """
This file contains the code needed for dealing with some of the mappings. Usually a map is just a
dictionary that needs to be loaded inside a variable.
This file carries the function to parse the files and the variables containing the dictionaries
themselves.
"""
import yaml
def load_mapping(filename):
"""
... |
Test edit - to check svn email hook | from distutils.core import setup
import os, glob, string, shutil
# Packages
packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat',... | import os, glob, string, shutil
from distutils.core import setup
# Packages
packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat',... |
Make sure that pip will install the template files too | from setuptools import setup
setup(
name='nchp',
version='0.1',
description='NGINX based Configurable HTTP Proxy for use with jupyterhub',
url='http://github.com/yuvipanda/jupyterhub-nginx-chp',
author='Yuvi Panda',
author_email='yuvipanda@riseup.net',
license='BSD',
packages=['nchp'],
... | from setuptools import setup
setup(
name='nchp',
version='0.1',
description='NGINX based Configurable HTTP Proxy for use with jupyterhub',
url='http://github.com/yuvipanda/jupyterhub-nginx-chp',
author='Yuvi Panda',
author_email='yuvipanda@riseup.net',
license='BSD',
packages=['nchp'],
... |
Use README.rst instead od README.md for doc. | from distutils.core import setup
setup(
name='permission',
version='0.2.0',
author='Zhipeng Liu',
author_email='hustlzp@qq.com',
url='https://github.com/hustlzp/permission',
packages=['permission'],
license='MIT',
description='Simple and flexible permission control for Flask app.',
... | from distutils.core import setup
setup(
name='permission',
version='0.2.0',
author='Zhipeng Liu',
author_email='hustlzp@qq.com',
url='https://github.com/hustlzp/permission',
packages=['permission'],
license='MIT',
description='Simple and flexible permission control for Flask app.',
... |
Test restarting with Stefan problem instead of heat driven cavity. Removed some redundant tests | """ This module runs the benchmark test suite. """
from .context import phaseflow
def test_lid_driven_cavity_benchmark__ci__():
phaseflow.helpers.run_simulation_with_temporary_output(
phaseflow.octadecane_benchmarks.LidDrivenCavityBenchmarkSimulation())
def test_lid_driven_cavity_benchmark_with... | """ This module runs the benchmark test suite. """
from .context import phaseflow
def test_lid_driven_cavity_benchmark_with_solid_subdomain__ci__():
phaseflow.helpers.run_simulation_with_temporary_output(
phaseflow.octadecane_benchmarks.LDCBenchmarkSimulationWithSolidSubdomain())
def test_h... |
Make HTTP01Responder's resource be at the token's path | """
``http-01`` challenge implementation.
"""
from twisted.web.http import OK
from twisted.web.resource import Resource
from zope.interface import implementer
from txacme.interfaces import IResponder
@implementer(IResponder)
class HTTP01Responder(object):
"""
An ``http-01`` challenge responder for txsni.
... | """
``http-01`` challenge implementation.
"""
from twisted.web.resource import Resource
from twisted.web.static import Data
from zope.interface import implementer
from txacme.interfaces import IResponder
@implementer(IResponder)
class HTTP01Responder(object):
"""
An ``http-01`` challenge responder for txsni... |
Fix unit tests for Version.objects.get_current(). | from datetime import datetime
from django.test.testcases import TestCase
from django_evolution.models import Version
class VersionManagerTests(TestCase):
"""Unit tests for django_evolution.models.VersionManager."""
def test_current_version_with_dup_timestamps(self):
"""Testing Version.current_versi... | from datetime import datetime
from django.test.testcases import TestCase
from django_evolution.models import Version
class VersionManagerTests(TestCase):
"""Unit tests for django_evolution.models.VersionManager."""
def test_current_version_with_dup_timestamps(self):
"""Testing Version.current_versi... |
Fix Python invokation (2.7 -> 3.7) in ledger-samples. | #!/usr/bin/env python
# a helper for gyp to do file globbing cross platform
# Usage: python glob.py root_dir pattern [pattern...]
import fnmatch
import os
import sys
root_dir = sys.argv[1]
patterns = sys.argv[2:]
for (dirpath, dirnames, files) in os.walk(root_dir):
for f in files:
match = False
f... | #!/usr/bin/env python
# a helper for gyp to do file globbing cross platform
# Usage: python glob.py root_dir pattern [pattern...]
import fnmatch
import os
import sys
root_dir = sys.argv[1]
patterns = sys.argv[2:]
for (dirpath, dirnames, files) in os.walk(root_dir):
for f in files:
match = False
f... |
Add command-line flags for spline order and accuracy. | import climate
import lmj.plot
import numpy as np
import source
import plots
@climate.annotate(
root='load experiment data from this directory',
pattern='plot data from files matching this pattern',
markers='plot traces of these markers',
)
def main(root, pattern='*5/*block00/*circuit00.csv.gz', markers=... | import climate
import lmj.plot
import numpy as np
import source
import plots
@climate.annotate(
root='load experiment data from this directory',
pattern=('plot data from files matching this pattern', 'option'),
markers=('plot traces of these markers', 'option'),
spline=('interpolate data with a splin... |
Add test for go correspondance file begin | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import argparse
import re
def format_go_correspondance(args):
go = {}
with open(args.go_correspondance_input, "r") as go_correspondance_input:
for line in go_correspondance_input.readlines():
split_line = line[:-1].split('\... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import argparse
import re
def format_go_correspondance(args):
go = {}
with open(args.go_correspondance_input, "r") as go_correspondance_input:
for line in go_correspondance_input.readlines():
if not line.startswith('GO'):
... |
Add plant names and childs | # File: kindergarten_garden.py
# Purpose: Write a program that, given a diagram, can tell you which plants each child in the kindergarten class is responsible for.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Thursday 10th September 2016, 10:51 PM
| # File: kindergarten_garden.py
# Purpose: Write a program that, given a diagram, can tell you which plants each child in the kindergarten class is responsible for.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Thursday 10th September 2016, 10:51 PM
class Garden(object):
plant_... |
Update relative imports in the Python library to support Python3 | import shim
tmpdir = None
def setUp():
global tmpdir
tmpdir = shim.setup_shim_for('kubectl')
def tearDown():
global tmpdir
shim.teardown_shim_dir(tmpdir)
| from . import shim
tmpdir = None
def setUp():
global tmpdir
tmpdir = shim.setup_shim_for('kubectl')
def tearDown():
global tmpdir
shim.teardown_shim_dir(tmpdir)
|
Rework the pip runner to use `PathFinder` | """Execute exactly this copy of pip, within a different environment.
This file is named as it is, to ensure that this module can't be imported via
an import statement.
"""
import importlib.util
import runpy
import sys
import types
from importlib.machinery import ModuleSpec
from os.path import dirname, join
from typin... | """Execute exactly this copy of pip, within a different environment.
This file is named as it is, to ensure that this module can't be imported via
an import statement.
"""
import runpy
import sys
import types
from importlib.machinery import ModuleSpec, PathFinder
from os.path import dirname
from typing import Optiona... |
Set wrapping to soft on textareas | from django import forms
import cube.diary.models
class DiaryIdeaForm(forms.ModelForm):
class Meta(object):
model = cube.diary.models.DiaryIdea
class EventForm(forms.ModelForm):
class Meta(object):
model = cube.diary.models.Event
class ShowingForm(forms.ModelForm):
class Meta(object):
... | from django import forms
import cube.diary.models
class DiaryIdeaForm(forms.ModelForm):
class Meta(object):
model = cube.diary.models.DiaryIdea
class EventForm(forms.ModelForm):
class Meta(object):
model = cube.diary.models.Event
# Ensure soft wrapping is set for textareas:
wid... |
Add test for cypress defaults | """"""
from penn_chime.parameters import Parameters
def test_cli_defaults():
"""Ensure if the cli defaults have been updated."""
# TODO how to make this work when the module is installed?
_ = Parameters.create({'PARAMETERS': './defaults/cli.cfg'}, [])
def test_webapp_defaults():
"""Ensure the webapp... | """Test Parameters."""
from penn_chime.parameters import Parameters
def test_cypress_defaults():
"""Ensure the cypress defaults have been updated."""
# TODO how to make this work when the module is installed?
_ = Parameters.create({"PARAMETERS": "./defaults/cypress.cfg"}, [])
def test_cli_defaults():
... |
Fix BaseHTTPAdapter for the SSL case | import requests.adapters
class BaseHTTPAdapter(requests.adapters.HTTPAdapter):
def close(self):
self.pools.clear()
| import requests.adapters
class BaseHTTPAdapter(requests.adapters.HTTPAdapter):
def close(self):
super(BaseHTTPAdapter, self).close()
if hasattr(self, 'pools'):
self.pools.clear()
|
Update test for largest stock | import cutplanner
import unittest
class TestPlanner(unittest.TestCase):
def setUp(self):
sizes = [80, 120]
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_get_largest(self):
largest = self.planner.get_largest_stock()
... | import cutplanner
import unittest
class TestPlanner(unittest.TestCase):
def setUp(self):
sizes = [80, 120]
needed = [10, 25, 75]
loss = 0.25
self.planner = cutplanner.Planner(sizes, needed, loss)
def test_largest_stock(self):
largest = self.planner.largest_stock
... |
Call super __init__ from Namespace.__init__ | """
Stuff for building namespace
"""
from _compat import *
class Namespace(object):
"""
Backport of SimpleNamespace() class added in Python 3.3
"""
__slots__ = '__doc__', '__dict__', '__weakref__'
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __iter__(self):
... | """
Stuff for building namespace
"""
from _compat import *
class Namespace(object):
"""
Backport of SimpleNamespace() class added in Python 3.3
"""
__slots__ = '__doc__', '__dict__', '__weakref__'
def __init__(self, **kwargs):
super(Namespace, self).__init__()
self.__dict__.update... |
Add first test for ccs | #!/usr/bin/env python3
import unittest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_ccs_log
class Test(unittest.TestCase):
def test_nothing(self):
... | #!/usr/bin/env python3
import unittest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_ccs_log
class Test(unittest.TestCase):
def test_parse_line(self):
... |
Fix semester url regex bug | """kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... | """kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... |
Prepare update Master to 0.12.0 | # This is the only location where the version will be written and changed.
# Based on https://packaging.python.org/single_source_version/
__version__ = '0.12.0b'
| # This is the only location where the version will be written and changed.
# Based on https://packaging.python.org/single_source_version/
__version__ = '0.12.0'
|
Rewrite based on factory one | #!/bin/env python
#
# Description:
# Check if a glideinFrontend is running
#
# Arguments:
# $1 = config file
#
# Author:
# Igor Sfiligoi Jul 17th 2008
#
import sys,os.path
sys.path.append(os.path.join(sys.path[0],"../lib"))
import glideinFrontendPidLib
config_dict={}
try:
execfile(sys.argv[1],config_dict)
... | #!/bin/env python
#
# Description:
# Check if a glideinFrontend is running
#
# Arguments:
# $1 = work_dir
#
# Author:
# Igor Sfiligoi
#
import sys,os.path
sys.path.append(os.path.join(sys.path[0],"../lib"))
import glideinFrontendPidLib
try:
work_dir=sys.argv[1]
frontend_pid=glideinFrontendPidLib.get_fr... |
Support development versions using an environment variable | VERSION = (0, 9, 0, "a", 1) # following PEP 386
def get_version():
version = "%s.%s" % (VERSION[0], VERSION[1])
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
return version
__version__ = get_versi... | import os
VERSION = (0, 9, 0, "a", 1) # following PEP 386
def get_version():
version = "%s.%s" % (VERSION[0], VERSION[1])
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
dev = os.environ.get("PI... |
Allow usage directly from the code (fix the _version import) | from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule
from ._version import version as __version__
| import warnings
from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule
try:
from ._version import version as __version__
except ImportError:
warnings.warn("pygtfs should be installed for the version to work")
__version__ = "0"
|
Remove redundant text from syslog returner | # -*- coding: utf-8 -*-
'''
Return data to the host operating system's syslog facility
Required python modules: syslog, json
The syslog returner simply reuses the operating system's syslog
facility to log return data
To use the syslog returner, append '--return syslog' to the salt command.
.. code-block:: bash
... | # -*- coding: utf-8 -*-
'''
Return data to the host operating system's syslog facility
Required python modules: syslog, json
The syslog returner simply reuses the operating system's syslog
facility to log return data
To use the syslog returner, append '--return syslog' to the salt command.
.. code-block:: bash
... |
Make stream redirection py3 compatible. Ensure flask reloader is off inside notebook | import inspect
import socket
import sys
from io import BytesIO
from threading import currentThread, Thread
from IPython.core.display import HTML, display
from werkzeug.local import LocalProxy
from werkzeug.serving import ThreadingMixIn
from birdseye import server, eye
thread_proxies = {}
def stream_proxy(original)... | import inspect
import socket
import sys
from io import BytesIO, StringIO
from threading import currentThread, Thread
from IPython.core.display import HTML, display
from werkzeug.local import LocalProxy
from werkzeug.serving import ThreadingMixIn
from birdseye import eye, PY2
from birdseye.server import app
fake_stre... |
Use separate node server when running the tests | from subprocess import Popen, PIPE
from django.test.runner import DiscoverRunner
class CustomTestRunner(DiscoverRunner):
"""
Same as the default Django test runner, except it also runs our node
server as a subprocess so we can render React components.
"""
def setup_test_environment(self, **kwargs... | from subprocess import Popen, PIPE
from django.test.runner import DiscoverRunner
from django.conf import settings
from react.render_server import render_server
TEST_REACT_SERVER_HOST = getattr(settings, 'TEST_REACT_SERVER_HOST', '127.0.0.1')
TEST_REACT_SERVER_PORT = getattr(settings, 'TEST_REACT_SERVER_PORT', 9008)
... |
Add tests to check loading library. | import unittest
from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
class TestDylib(TestCase):
def setUp(self):
llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
def test_bad_library(self)... | from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
from ctypes.util import find_library
import unittest
@unittest.skipUnless(platform.system() in {"Linux", "Darwin"}, "Unsupport test for current OS")
class TestDylib(TestCase):
def setUp(self):
ll... |
Add markdownx url, Add add-tutrorial url | from django.conf.urls import include, url
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
] | from django.conf.urls import include, url
from markdownx import urls as markdownx
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
# this not working correctly - some error in gatherTutorials
url... |
Add generic grid search function | """ Functions for determinig best-fit template parameters by convolution with a
grid """
| """ Functions for determinig best-fit template parameters by convolution with a
grid """
import dem
import WindowedTemplate as wt
import numpy as np
from scipy import signal
def calculate_best_fit_parameters(dem, template_function, **kwargs):
template_args = parse_args(**kwargs)
num_angles = 180/ang_ste... |
Add maximum length validator to about_me | from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.conf import settings
import markdown
import bleach
class UserProfile(models.Model):
user = models.OneToOneField(User)
about_me = ... | from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.conf import settings
from django.core.validators import MaxLengthValidator
import markdown
import bleach
class UserProfile(models.Model):
... |
Make the sync integration tests self-contained on autotest | # Copyright (c) 2010 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 autotest_lib.client.cros import chrome_test
class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase):
version = 1
def run_once(sel... | # Copyright (c) 2011 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 autotest_lib.client.cros import chrome_test
class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase):
version = 1
binary_to_run = ... |
Make importlib import compatible w/ Django>=1.8 | from __future__ import absolute_import
from random import random
import logging
from django.conf import settings
from django.utils.importlib import import_module
from django.core.exceptions import ImproperlyConfigured
from django.core.signals import request_started
logger = logging.getLogger(__name__)
def clear_exp... | from __future__ import absolute_import
from random import random
import logging
try:
# Python >= 2.7
import importlib
except ImportError:
# Python < 2.7; will be removed in Django 1.9
from django.utils import importlib
from django.conf import settings
from django.core.exceptions import ImproperlyConfi... |
Remove unused 'DITTO_FLICKR_USE_LOCAL_MEDIA' in context_processor | from .apps import ditto_apps
from ..flickr import app_settings
def ditto(request):
return {
'enabled_apps': ditto_apps.enabled(),
'DITTO_FLICKR_USE_LOCAL_MEDIA':
app_settings.DITTO_FLICKR_USE_LOCAL_MEDIA,
}
| from .apps import ditto_apps
from ..flickr import app_settings
def ditto(request):
return {
'enabled_apps': ditto_apps.enabled()
}
|
Add some PyPI tags to package | from setuptools import find_packages
from setuptools import setup
with open('requirements.txt') as fobj:
install_requires = [line.strip() for line in fobj]
with open('README.rst') as fobj:
long_description = fobj.read()
with open('version.txt') as fobj:
version = fobj.read().strip()
packages = find_... | from setuptools import find_packages
from setuptools import setup
with open('requirements.txt') as fobj:
install_requires = [line.strip() for line in fobj]
with open('README.rst') as fobj:
long_description = fobj.read()
with open('version.txt') as fobj:
version = fobj.read().strip()
packages = find_... |
Solve RuntimeWarning that arose without knowing why. | from setuptools import setup, find_packages
import sys, os
setup(name='cc.license',
version='0.01',
description="License selection based on ccREL-based metadata.",
classifiers=[],
keywords='',
author='Creative Commons',
author_email='software@creativecommons.org',
url='http://... | from setuptools import setup, find_packages
import sys, os
setup(name='cc.license',
version='0.01',
description="License selection based on ccREL-based metadata.",
classifiers=[],
keywords='',
author='Creative Commons',
author_email='software@creativecommons.org',
url='http://... |
Read package long description from readme | from setuptools import setup, find_packages
setup(
name='gears-coffeescript',
version='0.1.dev',
url='https://github.com/gears/gears',
license='ISC',
author='Mike Yumatov',
author_email='mike@yumatov.org',
description='CoffeeScript compiler for Gears',
packages=find_packages(),
inc... | import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='gears-coffeescript',
version='0.1.dev',
url='https://github.com/gears/gears',
license='ISC',
author='Mike Yumatov',
author_email='m... |
Add dev option to version string | """
Camoco Library - CoAnalysis of Molecular Components
CacheMoneyCorn
"""
__license__ = """
Creative Commons Non-Commercial 4.0 Generic
http://creativecommons.org/licenses/by-nc/4.0/
"""
__version__ = '0.3.0'
import sys
import os
import numpy
import pyximport
pyximport.install(setup_args={
"include_... | """
Camoco Library - CoAnalysis of Molecular Components
CacheMoneyCorn
"""
__license__ = """
Creative Commons Non-Commercial 4.0 Generic
http://creativecommons.org/licenses/by-nc/4.0/
"""
__version__ = '0.3.0-dev'
import sys
import os
import numpy
import pyximport
pyximport.install(setup_args={
"incl... |
Fix definition typo in patched module | from .. import types, alltlobjects
from ..custom.message import Message as _Message
class MessageEmpty(_Message, types.MessageEmpty):
pass
types.MessageEmpty = MessageEmpty
alltlobjects.tlobjects[MessageEmpty.CONSTRUCTOR_ID] = MessageEmpty
class MessageService(_Message, types.MessageService):
pass
types.Mes... | from .. import types, alltlobjects
from ..custom.message import Message as _Message
class MessageEmpty(_Message, types.MessageEmpty):
pass
types.MessageEmpty = MessageEmpty
alltlobjects.tlobjects[MessageEmpty.CONSTRUCTOR_ID] = MessageEmpty
class MessageService(_Message, types.MessageService):
pass
types.Mes... |
Add utility function for checking URL safety | def get_or_create(model, **kwargs):
""" Returns an instance of model and whether or not it already existed in a tuple. """
instance = model.query.filter_by(**kwargs).first()
if instance:
return instance, False
else:
instance = model(**kwargs)
return instance, True | from urllib.parse import urlparse, urljoin
from flask import request
def get_or_create(model, **kwargs):
""" Returns an instance of model and whether or not it already existed in a tuple. """
instance = model.query.filter_by(**kwargs).first()
if instance:
return instance, False
else:
in... |
Add latitude and longitude in api | from rest_framework import serializers
from .models import Conference, ConferenceVenue, Room
class ConferenceSerializer(serializers.HyperlinkedModelSerializer):
status = serializers.CharField(source='get_status_display')
class Meta:
model = Conference
fields = ('id', 'name', 'slug', 'descrip... | from rest_framework import serializers
from .models import Conference, ConferenceVenue, Room
class ConferenceSerializer(serializers.HyperlinkedModelSerializer):
status = serializers.CharField(source='get_status_display')
class Meta:
model = Conference
fields = ('id', 'name', 'slug', 'descrip... |
Put in call to to UsersService to actually change password | from flask_login import current_user
from app.brain.user_management.change_password_result import ChangePasswordResult
from app.brain.utilities import hash_password
class AccountUpdater(object):
@staticmethod
def change_password(old_password, new_password, confirm_password):
if new_password != confir... | from flask_login import current_user
from app.brain.user_management.change_password_result import ChangePasswordResult
from app.brain.utilities import hash_password
from app.service import UsersService
class AccountUpdater(object):
@staticmethod
def change_password(old_password, new_password, confirm_passwor... |
Fix survey_scenario (use core v20 syntax) | # -*- coding: utf-8 -*-
from openfisca_senegal import CountryTaxBenefitSystem as SenegalTaxBenefitSystem
from openfisca_survey_manager.scenarios import AbstractSurveyScenario
class SenegalSurveyScenario(AbstractSurveyScenario):
id_variable_by_entity_key = dict(
famille = 'id_famille',
)
role... | # -*- coding: utf-8 -*-
from openfisca_senegal import CountryTaxBenefitSystem as SenegalTaxBenefitSystem
from openfisca_survey_manager.scenarios import AbstractSurveyScenario
class SenegalSurveyScenario(AbstractSurveyScenario):
id_variable_by_entity_key = dict(
famille = 'id_famille',
)
role... |
Read standard input instead of hard-coded strings. | from telnetlib import Telnet
import time
tn = Telnet('192.168.1.15', 13666, None)
#tn.interact()
tn.write("hello\n")
tn.write("screen_add s1\n")
tn.write("screen_set s1 -priority 1\n")
tn.write("widget_add s1 w1 string\n")
tn.write("widget_add s1 w2 string\n")
tn.write("widget_set s1 w1 1 1 {It is a truth u}\n")
tn.w... | #!/usr/bin/env python
from telnetlib import Telnet
import time
import sys
tn = Telnet('192.168.1.15', 13666, None)
pipe_contents = sys.stdin.read()
pipe_contents = pipe_contents.replace('\n', ' ')
tn.write("hello\n")
tn.write("screen_add s1\n")
tn.write("screen_set s1 -priority 1\n")
tn.write("widget_add s1 w1 strin... |
Handle Nonetype values in `html_to_md` | import re
import textwrap
import html2text
text_maker = html2text.HTML2Text()
text_maker.body_width = 0
def strip_html_tags(text):
return re.sub('<[^<]+?>', '', text)
def html_to_md(string, strip_html=True, markdown=False):
if strip_html:
string = strip_html_tags(string)
if markdown:
s... | import re
import textwrap
import html2text
text_maker = html2text.HTML2Text()
text_maker.body_width = 0
def strip_html_tags(text):
return re.sub('<[^<]+?>', '', text)
def html_to_md(string, strip_html=True, markdown=False):
if not string:
return 'No Description Found'
if strip_html:
st... |
Remove obsolete TODO and add version | """
'Dusk' command system for Amethyst.
Based loosely (heh) off of discord.py's ext command system.
TODO: refactor arg parsing probably.
"""
from .context import Context # NOQA
from .command import * # NOQA
from .command_holder import CommandHolder # NOQA
from .constants import * # NOQA
| """
'Dusk' command system for Amethyst.
Based loosely (heh) off of discord.py's ext command system.
"""
from .context import Context # NOQA
from .command import * # NOQA
from .command_holder import CommandHolder # NOQA
from .constants import * # NOQA
__version__ = "1.0.0" |
Add test for dict.fromkeys where arg is a generator. | d = dict.fromkeys([1, 2, 3, 4])
l = list(d.keys())
l.sort()
print(l)
d = dict.fromkeys([1, 2, 3, 4], 42)
l = list(d.values())
l.sort()
print(l)
| d = dict.fromkeys([1, 2, 3, 4])
l = list(d.keys())
l.sort()
print(l)
d = dict.fromkeys([1, 2, 3, 4], 42)
l = list(d.values())
l.sort()
print(l)
# argument to fromkeys is a generator
d = dict.fromkeys(i + 1 for i in range(1))
print(d)
|
Add docstring, with an example. | import numpy as np
def LU(A):
m = A.shape[0]
U = A.copy()
L = np.eye( m )
for j in range(m):
for i in range(j+1,m):
L[i,j] = U[i,j]/U[j,j]
U[i,:] -= L[i,j]*U[j,:]
return L, U
| import numpy as np
def LU(A):
r"""Factor a square matrix by Gaussian elimination.
The argument A should be a square matrix (an m-by-m numpy array).
The outputs L and U are also m-by-m. L is lower-triangular with
unit diagonal entries and U is strictly upper-triangular.
This impl... |
Remove preffered binding, use obj.__class__ instead of type() | import sys
import os
os.environ["QT_PREFERRED_BINDING"] = "PySide"
from Qt import QtWidgets, load_ui
def setup_ui(uifile, base_instance=None):
ui = load_ui(uifile)
if not base_instance:
return ui
else:
for member in dir(ui):
if not member.startswith('__') and \
... | import sys
import os
# Set preferred binding
# os.environ["QT_PREFERRED_BINDING"] = "PySide"
from Qt import QtWidgets, load_ui
def setup_ui(uifile, base_instance=None):
ui = load_ui(uifile)
if not base_instance:
return ui
else:
for member in dir(ui):
if not member.startswith(... |
Rename Factory class to MaskedGenerator |
class Factory(object):
def __init__(self, generator, roi):
self.generator = generator
self.roi = roi
def iterator(self):
for point in self.generator.iterator():
if self.roi.contains_point(point):
yield point
|
class MaskedGenerator(object):
def __init__(self, generator, roi):
self.generator = generator
self.roi = roi
def iterator(self):
for point in self.generator.iterator():
if self.roi.contains_point(point):
yield point
|
Remove superfluous class from importer | import os
class loader:
modules = {};
def __init__(self):
self.load_modules();
def load_modules(self, path="./modules/"): # Consider adding recursive sorting at some point in the future
names = os.listdir(path);
pwd = os.getcwd();
os.chdir(path);
for name in names:... | import os
import imp
modules = {}
def load_modules(path="./modules/"): # Consider adding recursive sorting at some point in the future
names = os.listdir(path)
for name in names:
if not name.endswith(".py"): continue
print("Importing module {0}".format(name))
name = name.split('.')[0]
... |
Set random container name for tests | """Local workflow executor"""
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import shlex
import subprocess
from django.conf import settings
from .local import FlowExecutor as LocalFlowExecutor
class FlowExecutor(LocalFlowExecutor):
def start(self):
contain... | """Local workflow executor"""
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import random
import shlex
import subprocess
from django.conf import settings
from .local import FlowExecutor as LocalFlowExecutor
class FlowExecutor(LocalFlowExecutor):
def start(self):
... |
Convert branch to string explicitly | #!/usr/bin/env python
import argparse
from git import Repo
import configprocessor
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--path", help="Path to git working copy")
parser.add_argument("-c", "--configfile", help="Configuration file to parse")
parser.add_argument("-o",... | #!/usr/bin/env python
import argparse
from git import Repo
import configprocessor
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--path", help="Path to git working copy")
parser.add_argument("-c", "--configfile", help="Configuration file to parse")
parser.add_argument("-o",... |
Add logging of memory use | import torch
from torch import FloatTensor, LongTensor
from torch.autograd import Variable
from torch import nn, optim
from torch.nn import Parameter
from tqdm import trange
import util, logging, os, psutil
import hyper
logging.basicConfig(filename='memleak.log',level=logging.INFO)
torch.manual_seed(2)
B = 256
M =... | import torch
from torch import FloatTensor, LongTensor
from torch.autograd import Variable
from torch import nn, optim
from torch.nn import Parameter
from tqdm import trange
import util, logging, os, psutil
import hyper
logging.basicConfig(filename='memleak.log',level=logging.INFO)
torch.manual_seed(2)
B = 256
M =... |
Use xpath instead of regex | # -*- coding: utf-8 -*-
import scrapy
from locations.items import GeojsonPointItem
import json
import re
class LaSalsaSpider(scrapy.Spider):
name = "la_salsa"
allowed_domains = ["www.lasalsa.com"]
start_urls = (
'http://lasalsa.com/wp-content/themes/lasalsa-main/locations-search.php?lat=0&lng=0&rad... | # -*- coding: utf-8 -*-
import scrapy
from locations.items import GeojsonPointItem
class LaSalsaSpider(scrapy.Spider):
name = "la_salsa"
allowed_domains = ["www.lasalsa.com"]
start_urls = (
'http://lasalsa.com/wp-content/themes/lasalsa-main/locations-search.php?lat=0&lng=0&radius=99999999',
)... |
Update 0.6.4 - Fixed exception error |
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY").json()
image_url = apod_data["url"]
if image_url.endswith(".gif"):
return
image_data = requests.get(... |
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY").json()
image_url = apod_data["url"]
if image_url.endswith(".gif"):
raise TypeError
image_data = requ... |
Define WebtestUserBackend.authenticate based on Django version | from __future__ import absolute_import
from django.contrib.auth.backends import RemoteUserBackend
from .compat import from_wsgi_safe_string
class WebtestUserBackend(RemoteUserBackend):
""" Auth backend for django-webtest auth system """
def authenticate(self, request, django_webtest_user):
return sup... | from __future__ import absolute_import
from django.utils.version import get_complete_version
from django.contrib.auth.backends import RemoteUserBackend
from .compat import from_wsgi_safe_string
class WebtestUserBackend(RemoteUserBackend):
""" Auth backend for django-webtest auth system """
if get_complete_ver... |
Add public API entties from 'bigquery.table'. | # Copyright 2015 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 a... | # Copyright 2015 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 a... |
Tweak a test so it fails more usefully when mocking doesn't work, heh | from invoke import ctask
@ctask
def go(ctx):
return ctx
@ctask
def run(ctx):
ctx.run('x')
| from invoke import ctask
@ctask
def go(ctx):
return ctx
@ctask
def run(ctx):
ctx.run('false')
|
Update release version to 0.1.6 | """
A flat file database for json objects.
"""
from .db import Database
__version__ = '0.1.5'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/jsondb'
| """
A flat file database for json objects.
"""
from .db import Database
__version__ = '0.1.6'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/jsondb'
|
Fix bug some log output showing on screen not present in log file by changing logging file handler mode from 'w' write to 'a' append. | # https://docs.python.org/3.6/howto/logging.html#logging-basic-tutorial
import logging
import sys
def get_logger(name):
"""
https://stackoverflow.com/questions/28330317/print-timestamp-for-logging-in-python
https://docs.python.org/3/library/logging.html#formatter-objects
https://docs.python.org/3.6/ho... | # https://docs.python.org/3.6/howto/logging.html#logging-basic-tutorial
import logging
import sys
def get_logger(name):
"""
https://stackoverflow.com/questions/28330317/print-timestamp-for-logging-in-python
https://docs.python.org/3/library/logging.html#formatter-objects
https://docs.python.org/3.6/ho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.