Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix testing on update_game_info management command | from django.core.management import call_command
from django.test import TestCase
class ServerTest(TestCase):
def test_update_game_info(self):
call_command('update_game_info')
| from django.core.management import call_command
from django.test import TestCase
from game_info.models import Server
class ServerTest(TestCase):
def create_server(self, title="Test Server", host="example.org", port=27015):
return Server.objects.create(title=title, host=host, port=port)
def test_updat... |
Complete two pointers char count dict sol w/ time/space complexity | """Leetcode 340. Longest Substring with At Most K Distinct Characters
Hard
URL: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
Given a string, find the length of the longest substring T that contains at most k
distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Ex... | """Leetcode 340. Longest Substring with At Most K Distinct Characters
Hard
URL: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
Given a string, find the length of the longest substring T that contains at most k
distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Ex... |
Tag commit for v0.0.22-master generated by gitmake.py | major = 0
minor=0
patch=21
branch="master"
timestamp=1376526439.16 | major = 0
minor=0
patch=22
branch="master"
timestamp=1376526477.22 |
Set end_paragraph to True by default | # -*- coding: utf-8 -*-
"""
This module implements the class that deals with sections.
.. :copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
from . import Container, Command
class SectionBase(Container):
"""A class that is the base for all section type classes."""
... | # -*- coding: utf-8 -*-
"""
This module implements the class that deals with sections.
.. :copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
from . import Container, Command
class SectionBase(Container):
"""A class that is the base for all section type classes."""
... |
Format with Black and sort | __version__ = VERSION = (0, 5, 1)
from humanize.time import *
from humanize.number import *
from humanize.filesize import *
from humanize.i18n import activate, deactivate
__all__ = ['__version__', 'VERSION', 'naturalday', 'naturaltime', 'ordinal', 'intword',
'naturaldelta', 'intcomma', 'apnumber', 'fractional', '... | __version__ = VERSION = (0, 5, 1)
from humanize.time import *
from humanize.number import *
from humanize.filesize import *
from humanize.i18n import activate, deactivate
__all__ = [
"__version__",
"activate",
"apnumber",
"deactivate",
"fractional",
"intcomma",
"intword",
"naturaldate"... |
Add a Content-type when it's not clear | import web
from os import path
rootdir = path.abspath('./build')
def getFile(filename):
filename = path.join(rootdir, filename)
print filename
if (not filename.startswith(rootdir)):
return None
if (not path.exists(filename)):
return None
f = open(filename, 'r')
contents = f.read... | import web
from os import path
rootdir = path.abspath('./build')
def getFile(filename):
filename = path.join(rootdir, filename)
print filename
if (not filename.startswith(rootdir)):
return None
if (not path.exists(filename)):
return None
f = open(filename, 'r')
contents = f.read... |
Add explicit language specifier to test. | """Test that importing modules in C++ works as expected."""
from __future__ import print_function
from distutils.version import StrictVersion
import unittest2
import os
import time
import lldb
import platform
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import ll... | """Test that importing modules in C++ works as expected."""
from __future__ import print_function
from distutils.version import StrictVersion
import unittest2
import os
import time
import lldb
import platform
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import ll... |
Set the correct content type according to the amazon metadata | from pyramid.httpexceptions import HTTPUnauthorized, HTTPNotFound
from pyramid.security import forget
from pyramid.response import Response
from pyramid.view import view_config, forbidden_view_config
@forbidden_view_config()
def basic_challenge(request):
response = HTTPUnauthorized()
response.headers.update(f... | from pyramid.httpexceptions import HTTPUnauthorized, HTTPNotFound
from pyramid.security import forget
from pyramid.response import Response
from pyramid.view import view_config, forbidden_view_config
@forbidden_view_config()
def basic_challenge(request):
response = HTTPUnauthorized()
response.headers.update(f... |
Fix some parameters for pytest to pickup the test | """Tests for plugin.py."""
import pytest
from ckan.tests import factories
import ckan.tests.helpers as helpers
from ckan.plugins.toolkit import NotAuthorized
@pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes')
@pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context')
class Apicatalog_Rout... | """Tests for plugin.py."""
import pytest
from ckan.tests import factories
import ckan.tests.helpers as helpers
from ckan.plugins.toolkit import NotAuthorized
@pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes')
@pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context')
class ApicatalogRoute... |
Remove django installed apps init opps | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf import settings
VERSION = (0, 1, 2)
__version__ = ".".join(map(str, VERSION))
__status__ = "Development"
__description__ = u"Opps CMS websites magazines and high-traffic"
__author__ = u"Thiago Avelino"
__credits__ = []
__email__ = u"opps-developers@googl... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
VERSION = (0, 1, 2)
__version__ = ".".join(map(str, VERSION))
__status__ = "Development"
__description__ = u"Opps CMS websites magazines and high-traffic"
__author__ = u"Thiago Avelino"
__credits__ = []
__email__ = u"opps-developers@googlegroups.com"
__license__ = u"BSD"... |
Fix the run command on Linux | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A module to hold linux specific action implementations."""
import cr
class LinuxRunner(cr.Runner):
"""An implementation of cr.Runner for the linux pl... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A module to hold linux specific action implementations."""
import cr
class LinuxRunner(cr.Runner):
"""An implementation of cr.Runner for the linux pl... |
Revert 5505 - introduced numerous regressions into the test suite | from axiom import iaxiom, userbase
from xmantissa import website, offering, provisioning
import hyperbola
from hyperbola import hyperbola_model
from hyperbola.hyperbola_theme import HyperbolaTheme
hyperbolaer = provisioning.BenefactorFactory(
name = u'hyperbolaer',
description = u'A wonderful ready to use a... | from axiom import iaxiom, userbase
from xmantissa import website, offering, provisioning
import hyperbola
from hyperbola import hyperbola_model
from hyperbola.hyperbola_theme import HyperbolaTheme
hyperbolaer = provisioning.BenefactorFactory(
name = u'hyperbolaer',
description = u'A wonderful ready to use a... |
Make Intercal executor not fail to start at times. | from .base_executor import CompiledExecutor
class Executor(CompiledExecutor):
ext = '.i'
name = 'ICK'
command = 'ick'
test_program = '''\
PLEASE DO ,1 <- #1
DO .4 <- #0
DO .5 <- #0
DO COME FROM (30)
DO WRITE IN ,1
DO .1 <- ,1SUB#1
DO (10) NEXT
... | from .base_executor import CompiledExecutor
class Executor(CompiledExecutor):
ext = '.i'
name = 'ICK'
command = 'ick'
test_program = '''\
PLEASE DO ,1 <- #1
DO .4 <- #0
DO .5 <- #0
DO COME FROM (30)
DO WRITE IN ,1
DO .1 <- ,1SUB#1
DO (10) NEXT
... |
Update dsub version to 0.4.7 | # 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 a... | # 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 a... |
Print better logs for Dylos | import logging
import Adafruit_BBIO.UART as UART
import serial
LOGGER = logging.getLogger(__name__)
def setup(port, baudrate):
# Setup UART
UART.setup("UART1")
ser = serial.Serial(port=port, baudrate=baudrate,
parity=serial.PARITY_NONE,
stopbits=serial.STO... | import logging
import Adafruit_BBIO.UART as UART
import serial
LOGGER = logging.getLogger(__name__)
def setup(port, baudrate):
# Setup UART
UART.setup("UART1")
ser = serial.Serial(port=port, baudrate=baudrate,
parity=serial.PARITY_NONE,
stopbits=serial.STO... |
Add exp and task ids to API | from rest_framework import serializers, viewsets
from rest_framework import filters
from django.contrib.auth.models import User
from dakis.core.models import Experiment, Task
class ExperimentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Experiment
exclude = ('author',)
... | from rest_framework import serializers, viewsets
from rest_framework import filters
from django.contrib.auth.models import User
from dakis.core.models import Experiment, Task
class ExperimentSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(label='ID', read_only=True)
class ... |
Test string form of verify_unit | # coding: utf-8
from __future__ import absolute_import, division, print_function
import pytest
from astropy import units as u
from astrodynamics.util import verify_unit
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.... | # coding: utf-8
from __future__ import absolute_import, division, print_function
import pytest
from astropy import units as u
from astrodynamics.util import verify_unit
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.... |
Update TODO for MPD command 'kill' | from mopidy import settings
from mopidy.frontends.mpd.protocol import handle_pattern
from mopidy.frontends.mpd.exceptions import MpdPasswordError
@handle_pattern(r'^close$')
def close(context):
"""
*musicpd.org, connection section:*
``close``
Closes the connection to MPD.
"""
context.... | from mopidy import settings
from mopidy.frontends.mpd.protocol import handle_pattern
from mopidy.frontends.mpd.exceptions import MpdPasswordError
@handle_pattern(r'^close$')
def close(context):
"""
*musicpd.org, connection section:*
``close``
Closes the connection to MPD.
"""
context.... |
Fix typo in upgrade script | import os.path
import shutil
sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';
-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
... | import os.path
import shutil
sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';
-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
... |
Allow zeros for recurring interval | from ckan.lib.navl.validators import ignore_empty, not_empty
from ckan.logic.validators import (
name_validator, boolean_validator, is_positive_integer, isodate,
group_id_exists)
def default_inventory_entry_schema():
schema = {
'id': [unicode, ignore_empty],
'title': [unicode, not_empty],
... | from ckan.lib.navl.validators import ignore_empty, not_empty
from ckan.logic.validators import (
name_validator, boolean_validator, natural_number_validator, isodate,
group_id_exists)
def default_inventory_entry_schema():
schema = {
'id': [unicode, ignore_empty],
'title': [unicode, not_emp... |
Return 404 if no message so we can poll from cucumber tests | from kombu import Connection, Exchange, Queue
from flask import Flask
import os
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
@app.route("/getnextqueuemessage")
#Gets the next message from target queue. Returns the signed JSON.
def get_last_queue_message():
#: By default messages sent ... | from kombu import Connection, Exchange, Queue
from flask import Flask
import os
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
@app.route("/getnextqueuemessage")
#Gets the next message from target queue. Returns the signed JSON.
def get_last_queue_message():
#: By default messages sent ... |
Format with two spaces instead of four | import os
import h5py
import numpy as np
ref = h5py.File(
os.path.expanduser(
"~/tensorflow_datasets/downloads/extracted/TAR_GZ.datasets.lids.mit.edu_fastdept_nyudepthBjtXYu6zBBYUv0ByLqXPgFy4ygUuVvPRxjz9Ip5_97M.tar.gz/nyudepthv2/val/official/00001.h5"
),
"r",
)
rgb = ref["rgb"][:]
depth = ref["de... | import os
import h5py
import numpy as np
ref = h5py.File(
os.path.expanduser(
"~/tensorflow_datasets/downloads/extracted/TAR_GZ.datasets.lids.mit.edu_fastdept_nyudepthBjtXYu6zBBYUv0ByLqXPgFy4ygUuVvPRxjz9Ip5_97M.tar.gz/nyudepthv2/val/official/00001.h5"
),
"r",
)
rgb = ref["rgb"][:]
depth = ref["de... |
Use more consistent example for map | arr = [1, 5, 10, 20]
print(*map(lambda num: num * 2, arr))
| arr = [1, 5, 10, 20]
print([num * 2 for num in arr])
|
Make reddit url a constant | import json
import pprint
import requests
def sample_valid_reddit_response():
r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json')
response_json = r.json()
if 'data' not in response_json:
print("Trying again")
response_json = sample_valid_reddit_response()
return response_json
def save_samp... | import json
import pprint
import requests
SAMPLE_REDDIT_URL = 'http://www.reddit.com/r/cscareerquestions/top.json'
def sample_valid_reddit_response():
r = requests.get(SAMPLE_REDDIT_URL)
response_json = r.json()
if 'data' not in response_json:
print("Trying again")
response_json = sample_valid_reddit_response... |
Use request.data to access file uploads | from rest_framework.exceptions import ValidationError
class ModelSerializerMixin(object):
"""Provides generic model serializer classes to views."""
model_serializer_class = None
def get_serializer_class(self):
if self.serializer_class:
return self.serializer_class
class Defaul... | from rest_framework.exceptions import ValidationError
class ModelSerializerMixin(object):
"""Provides generic model serializer classes to views."""
model_serializer_class = None
def get_serializer_class(self):
if self.serializer_class:
return self.serializer_class
class Defaul... |
Change version number to 0.2.0 | # -*- coding: utf-8 -*-
#
# Copyright © 2013 Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
__version__ = '0.2.dev0'
# =============================================================================
# The following statements are required to register this 3rd p... | # -*- coding: utf-8 -*-
#
# Copyright © 2013 Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
__version__ = '0.2.0'
# =============================================================================
# The following statements are required to register this 3rd part... |
Allow MONGO_HOST env var override. | # This file specifies the Eve configuration.
import os
# The run environment default is production.
# Modify this by setting the NODE_ENV environment variable.
env = os.getenv('NODE_ENV') or 'production'
# The MongoDB database.
if env == 'production':
MONGO_DBNAME = 'qiprofile'
else:
MONGO_DBNAME = 'qiprofile_test... | """This ``settings`` file specifies the Eve configuration."""
import os
# The run environment default is production.
# Modify this by setting the NODE_ENV environment variable.
env = os.getenv('NODE_ENV') or 'production'
# The MongoDB database.
if env == 'production':
MONGO_DBNAME = 'qiprofile'
else:
MONGO_DB... |
Use a fixed thumbnail size rather then a relative scale. | """An overview window showing thumbnails of the image set.
"""
from __future__ import division
import math
from PySide import QtCore, QtGui
class ThumbnailWidget(QtGui.QLabel):
def __init__(self, image, scale):
super(ThumbnailWidget, self).__init__()
pixmap = image.getPixmap()
size = sca... | """An overview window showing thumbnails of the image set.
"""
from __future__ import division
import math
from PySide import QtCore, QtGui
class ThumbnailWidget(QtGui.QLabel):
ThumbnailSize = QtCore.QSize(128, 128)
def __init__(self, image):
super(ThumbnailWidget, self).__init__()
pixmap =... |
Add note to remove file | # -*- coding: utf-8 -*-
# This file is here to ensure that upgrades of salt remove the external_ip
# grain
| # -*- coding: utf-8 -*-
# This file is here to ensure that upgrades of salt remove the external_ip
# grain, this file should be removed in the Boron release
|
Add docstrings for sigproc benchmarks | from timeit import default_timer as timer
import bifrost as bf
from bifrost import pipeline as bfp
from bifrost import blocks as blocks
from bifrost_benchmarks import PipelineBenchmarker
class SigprocBenchmarker(PipelineBenchmarker):
def run_benchmark(self):
with bf.Pipeline() as pipeline:
fil_... | """ Test the sigproc read function """
from timeit import default_timer as timer
import bifrost as bf
from bifrost import pipeline as bfp
from bifrost import blocks as blocks
from bifrost_benchmarks import PipelineBenchmarker
class SigprocBenchmarker(PipelineBenchmarker):
""" Test the sigproc read function """
... |
Return User and download count | from waterbutler.core import metadata
class BaseOsfStorageMetadata:
@property
def provider(self):
return 'osfstorage'
class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata):
@property
def name(self):
return self.raw['name']
@property
def path(self):
... | from waterbutler.core import metadata
class BaseOsfStorageMetadata:
@property
def provider(self):
return 'osfstorage'
class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata):
@property
def name(self):
return self.raw['name']
@property
def path(self):
... |
Make DotDict repr() use class name so that it doesn't print misleading results if subclassed | class DotDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def __init__(self, d={}):
for key, value in d.items():
if hasattr(value, 'keys'):
value = DotDict(value)
if isinstance(value, list):
... | class DotDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def __init__(self, d={}):
for key, value in d.items():
if hasattr(value, 'keys'):
value = DotDict(value)
if isinstance(value, list):
... |
Undo error changes for now | from traceback import format_exc
from django.conf import settings
class GraphQLError(Exception):
def __init__(self, message):
super(GraphQLError, self).__init__(message)
self.message = message
self.location = {'line': 0, 'column': 0}
if settings.DEBUG:
print(format_exc... | from traceback import format_exc
from django.conf import settings
class GraphQLError(Exception):
def __init__(self, message):
super(GraphQLError, self).__init__(message)
self.message = message
if settings.DEBUG:
self.traceback = format_exc().split('\n')
def format(self):
... |
Hide password in terminal input | from FbFeed import NewsFeed
username = raw_input('Enter your email id registered with facebook : ')
password = raw_input('Enter your Password : ')
print('Creating new session on Firefox..')
fb = NewsFeed(username,password)
print('Logging into your facebook account')
fb.login()
#Add people to group
print('Add people ... | from FbFeed import NewsFeed
import getpass
username = raw_input('Enter your email id registered with facebook : ')
password = getpass.getpass(prompt='Enter your Password : ',stream=None)
print('Creating new session on Firefox..')
fb = NewsFeed(username,password)
print('Logging into your facebook account')
fb.login()
... |
Add basic coverage for the setup_logging method | from raven.conf import load
from unittest2 import TestCase
class LoadTest(TestCase):
def test_basic(self):
dsn = 'https://foo:bar@sentry.local/1'
res = {}
load(dsn, res)
self.assertEquals(res, {
'SENTRY_PROJECT': '1',
'SENTRY_SERVERS': ['https://sentry.local... | import logging
import mock
from raven.conf import load, setup_logging
from unittest2 import TestCase
class LoadTest(TestCase):
def test_basic(self):
dsn = 'https://foo:bar@sentry.local/1'
res = {}
load(dsn, res)
self.assertEquals(res, {
'SENTRY_PROJECT': '1',
... |
Make the readers tests a bit more verbose. | # coding: utf-8
try:
import unittest2
except ImportError, e:
import unittest as unittest2
import datetime
import os
from pelican import readers
CUR_DIR = os.path.dirname(__file__)
CONTENT_PATH = os.path.join(CUR_DIR, 'content')
def _filename(*args):
return os.path.join(CONTENT_PATH, *args)
class RstRe... | # coding: utf-8
try:
import unittest2 as unittest
except ImportError, e:
import unittest
import datetime
import os
from pelican import readers
CUR_DIR = os.path.dirname(__file__)
CONTENT_PATH = os.path.join(CUR_DIR, 'content')
def _filename(*args):
return os.path.join(CONTENT_PATH, *args)
class RstRe... |
Add program name to parser | #!/usr/bin/env python
from .command import Command
from matador import utils
class DeployTicket(Command):
def _add_arguments(self, parser):
parser.add_argument(
'-e', '--environment',
type=str,
required=True,
help='Agresso environment name')
def _execu... | #!/usr/bin/env python
from .command import Command
from matador import utils
class DeployTicket(Command):
def _add_arguments(self, parser):
parser.prog = 'matador deploy-ticket'
parser.add_argument(
'-e', '--environment',
type=str,
required=True,
he... |
Implement a test for an ini option | # -*- coding: utf-8 -*-
def test_bar_fixture(testdir):
"""Make sure that pytest accepts our fixture."""
# create a temporary pytest test module
testdir.makepyfile("""
def test_sth(bar):
assert bar == "europython2015"
""")
# run pytest with the following cmd args
result = t... | # -*- coding: utf-8 -*-
def test_bar_fixture(testdir):
"""Make sure that pytest accepts our fixture."""
# create a temporary pytest test module
testdir.makepyfile("""
def test_sth(bar):
assert bar == "europython2015"
""")
# run pytest with the following cmd args
result = t... |
Increase display size Use argument for filename Make a movie from images | import h5py
import time
from SimpleCV import Image
recordFilename = '20130727_17h34_simpleTrack'
print recordFilename + '.hdf5'
#recordFile = h5py.File('20130722_21h53_simpleTrack.hdf5')
recordFile = h5py.File(recordFilename + '.hdf5', 'r')
imgs = recordFile.get('image')
img = imgs[100,:,:,:]
r = img[:,:,0]
g = img[:,... | import h5py
import time
import sys
from SimpleCV import Image, Display
#recordFilename = '/media/bat/DATA/Baptiste/Nautilab/kite_project/robokite/ObjectTracking/filming_small_kite_20130805_14h03_simpleTrack.hdf5'
print('')
print('This script is used to display the images saved in hdf5 file generated by simpleTrack.py ... |
Use differing cases after reading the log back... case is still insensitve. | from ADIF_log import ADIF_log
import datetime
import os
# Create a new log...
log = ADIF_log('Py-ADIF Example')
entry = log.newEntry()
# New entry from K6BSD to WD1CKS
entry['OPerator'] = 'K6BSD'
entry['Call'] = 'WD1CKS'
entry['QSO_Date']=datetime.datetime.now().strftime('%Y%m%d')
entry['baNd']='20M'
entry['mODe']='P... | from ADIF_log import ADIF_log
import datetime
import os
# Create a new log...
log = ADIF_log('Py-ADIF Example')
entry = log.newEntry()
# New entry from K6BSD to WD1CKS
entry['OPerator'] = 'K6BSD'
entry['Call'] = 'WD1CKS'
entry['QSO_Date']=datetime.datetime.now().strftime('%Y%m%d')
entry['baNd']='20M'
entry['mODe']='P... |
Add some calibration default values. | """
This module is responsible for handling configuration and files related to it,
including calibration parameters.
"""
import configparser
import os
"""
Default options
"""
#TODO: more default options...
_CONFIG_DEFAULTS = {
"paths": {
# default database path is ../db/test.db relative to this file
... | """
This module is responsible for handling configuration and files related to it,
including calibration parameters.
"""
import configparser
import os
"""
Default options
"""
#TODO: more default options...
_CONFIG_DEFAULTS = {
"paths": {
# default database path is ../db/test.db relative to this file
... |
Update version 1.0.0.dev7 -> 0.6.0.dev | __version__ = '1.0.0.dev7'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.'
| __version__ = '0.6.0.dev'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.'
|
Document behavior when item args are omitted. | from __future__ import print_function
import argparse
import shcol
import sys
__all__ = ['main']
def main(cmd_args):
parser = argparse.ArgumentParser(
description='Generate columnized output for given string items.',
version='shcol {}'.format(shcol.__version__)
)
parser.add_argument(
... | from __future__ import print_function
import argparse
import shcol
import sys
__all__ = ['main']
def main(cmd_args):
parser = argparse.ArgumentParser(
description='Generate columnized output for given string items.',
version='shcol {}'.format(shcol.__version__)
)
item_help = (
'an... |
Make test module for Copy runnable | import unittest
import numpy
import chainer
from chainer import functions
from chainer import gradient_check
class Copy(unittest.TestCase):
def setUp(self):
self.x_data = numpy.random.uniform(
-1, 1, (10, 5)).astype(numpy.float32)
self.gy = numpy.random.uniform(-1, 1, (10, 5)).astyp... | import unittest
import numpy
import chainer
from chainer import functions
from chainer import gradient_check
from chainer import testing
class Copy(unittest.TestCase):
def setUp(self):
self.x_data = numpy.random.uniform(
-1, 1, (10, 5)).astype(numpy.float32)
self.gy = numpy.random.u... |
Delete timer_end in same migration as total_duration | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def set_total_duration_as_duration(apps, schema_editor):
Music = apps.get_model("music", "Music")
for music in Music.objects.all():
music.total_duration = music.duration
music.save()
cla... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def set_total_duration_as_duration(apps, schema_editor):
Music = apps.get_model("music", "Music")
for music in Music.objects.all():
music.total_duration = music.duration
music.save()
cla... |
Add operation to update campaign. | """
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
... | """
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
... |
Fix reference to python binary | import logging
import pytest
from io import StringIO
from teuthology.exceptions import CommandFailedError
log = logging.getLogger(__name__)
class TestRun(object):
"""
Tests to see if we can make remote procedure calls to the current cluster
"""
def test_command_failed_label(self, ctx, config):
... | import logging
import pytest
from io import StringIO
from teuthology.exceptions import CommandFailedError
log = logging.getLogger(__name__)
class TestRun(object):
"""
Tests to see if we can make remote procedure calls to the current cluster
"""
def test_command_failed_label(self, ctx, config):
... |
Add a requirement for serving the assets in all tests | import os
from unittest import TestCase
import re
from app import generate_profiles
class TestGenerateProfiles(TestCase):
gen = generate_profiles.GenerateProfiles
network_environment = "%s/misc/network-environment" % gen.bootcfg_path
@classmethod
def setUpClass(cls):
cls.gen = generate_prof... | import os
import subprocess
from unittest import TestCase
import re
from app import generate_profiles
class TestGenerateProfiles(TestCase):
gen = generate_profiles.GenerateProfiles
network_environment = "%s/misc/network-environment" % gen.bootcfg_path
@classmethod
def setUpClass(cls):
subpr... |
Fix importing * (star) from package | """ This package contains native Python implementations of several `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ algorithms for generating B-spline / NURBS curves and surfaces. It also provides a data structure for storing elements required for evaluation these curves and surfaces.
Please follow the... | """ This package contains native Python implementations of several `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ algorithms for generating B-spline / NURBS curves and surfaces. It also provides a data structure for storing elements required for evaluation these curves and surfaces.
Please follow the... |
Update django.VERSION in trunk per previous discussion | VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
| VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if ... |
Rename frontend_app fixture to app | import pytest
import config
from skylines import model, create_frontend_app
from skylines.app import SkyLines
from tests import setup_app, setup_db, teardown_db, clean_db
from tests.data.bootstrap import bootstrap
@pytest.yield_fixture(scope="session")
def frontend_app():
"""Set up global front-end app for funct... | import pytest
import config
from skylines import model, create_frontend_app
from skylines.app import SkyLines
from tests import setup_app, setup_db, teardown_db, clean_db
from tests.data.bootstrap import bootstrap
@pytest.yield_fixture(scope="session")
def app():
"""Set up global front-end app for functional tes... |
Move location from core to geozones | # coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Region(models.Model):
'''
Common regional zones. All messages can be grouped by this territorial
cluster.
TODO: use django-mptt
TODO: make nested regions
TODO: link message to nested re... | # coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Region(models.Model):
'''
Region
======
Common regional zones. All messages can be grouped by this territorial
cluster.
* TODO: use django-mptt
* TODO: make nested regions
* TOD... |
Make the app externally visible | import wol
import json
from flask import request
from app_factory import create_app
app = create_app(__name__)
@app.route('/help', methods=['GET'])
def help():
return json.dumps({'help message': wol.help_message().strip()})
@app.route('/ports', methods=['GET'])
def get_wol_ports():
return json.dumps({"port... | import wol
import json
from flask import request
from app_factory import create_app
app = create_app(__name__)
@app.route('/help', methods=['GET'])
def help():
return json.dumps({'help message': wol.help_message().strip()})
@app.route('/ports', methods=['GET'])
def get_wol_ports():
return json.dumps({"port... |
Fix up some settings for start_zone() | import xmlrpclib
from supervisor.xmlrpc import SupervisorTransport
def start_zone(port=1300, zoneid="defaultzone", processgroup='zones', autorestart=False):
s = xmlrpclib.ServerProxy('http://localhost:9001')
import socket
try:
version = s.twiddler.getAPIVersion()
except(socket.error), exc:
... | import xmlrpclib
from supervisor.xmlrpc import SupervisorTransport
def start_zone(port=1300, zoneid="defaultzone", processgroup='zones', autorestart=False):
s = xmlrpclib.ServerProxy('http://localhost:9001')
import socket
try:
version = s.twiddler.getAPIVersion()
except(socket.error), exc:
... |
Test TeeStdOutCustomWrite writes through to stdout | import sys
from girder_worker.utils import TeeStdOutCustomWrite, TeeStdErrCustomWrite, JobManager
def test_TeeStdOutCustomeWrite(capfd):
_nonlocal = {'data': ''}
def _append_to_data(message, **kwargs):
_nonlocal['data'] += message
with TeeStdOutCustomWrite(_append_to_data):
sys.stdout.wr... | import sys
from girder_worker.utils import TeeStdOutCustomWrite
def test_TeeStdOutCustomWrite(capfd):
nonlocal_ = {'data': ''}
def _append_to_data(message, **kwargs):
nonlocal_['data'] += message
with TeeStdOutCustomWrite(_append_to_data):
sys.stdout.write('Test String')
sys.stdo... |
Add loads-dumps test for Appinfo | import io
import os
import pickle
import pytest
from steamfiles import appinfo
test_file_name = os.path.join(os.path.dirname(__file__), 'test_data/appinfo.vdf')
@pytest.yield_fixture
def vdf_data():
with open(test_file_name, 'rb') as f:
yield f.read()
@pytest.mark.usefixtures('vdf_data')
def test_load_... | import io
import os
import pickle
import pytest
from steamfiles import appinfo
test_file_name = os.path.join(os.path.dirname(__file__), 'test_data/appinfo.vdf')
@pytest.yield_fixture
def vdf_data():
with open(test_file_name, 'rb') as f:
yield f.read()
@pytest.mark.usefixtures('vdf_data')
def test_loads... |
Disable union wrap for clickhouse | from .enums import Dialects
from .queries import (
Query,
QueryBuilder,
)
class MySQLQuery(Query):
"""
Defines a query class for use with MySQL.
"""
@classmethod
def _builder(cls):
return QueryBuilder(quote_char='`', dialect=Dialects.MYSQL, wrap_union_queries=False)
class Vertic... | from .enums import Dialects
from .queries import (
Query,
QueryBuilder,
)
class MySQLQuery(Query):
"""
Defines a query class for use with MySQL.
"""
@classmethod
def _builder(cls):
return QueryBuilder(quote_char='`', dialect=Dialects.MYSQL, wrap_union_queries=False)
class Vertic... |
Update recommended libspotify and pyspotify version | """A backend for playing music from Spotify
`Spotify <http://www.spotify.com/>`_ is a music streaming service. The backend
uses the official `libspotify
<http://developer.spotify.com/en/libspotify/overview/>`_ library and the
`pyspotify <http://github.com/mopidy/pyspotify/>`_ Python bindings for
libspotify. This backe... | """A backend for playing music from Spotify
`Spotify <http://www.spotify.com/>`_ is a music streaming service. The backend
uses the official `libspotify
<http://developer.spotify.com/en/libspotify/overview/>`_ library and the
`pyspotify <http://github.com/mopidy/pyspotify/>`_ Python bindings for
libspotify. This backe... |
Add default rank to User for simplified tests | import re
class User:
Groups = {' ':0,'+':1,'☆':1,'%':2,'@':3,'*':3.1,'&':4,'#':5,'~':6}
@staticmethod
def compareRanks(rank1, rank2):
try:
return User.Groups[rank1] >= User.Groups[rank2]
except:
if not rank1 in User.Groups:
print('{rank} is not a supp... | import re
class User:
Groups = {' ':0,'+':1,'☆':1,'%':2,'@':3,'*':3.1,'&':4,'#':5,'~':6}
@staticmethod
def compareRanks(rank1, rank2):
try:
return User.Groups[rank1] >= User.Groups[rank2]
except:
if not rank1 in User.Groups:
print('{rank} is not a supp... |
Fix serious file overwriting problem. | #! /usr/bin/env python3
import sys
import json
for arg in sys.argv[1:]:
with open(arg) as f:
equajson = json.load(f)
field_list = [
"always-an-integer",
"always-positive",
"always-dimensionless",
"bound-variable",
"fixed-constant",
"special-function"
... | #! /usr/bin/env python3
import sys
import json
for arg in sys.argv[1:]:
with open(arg) as f:
equajson = json.load(f)
field_list = [
"always-an-integer",
"always-positive",
"always-dimensionless",
"bound-variable",
"fixed-constant",
"special-function"
... |
Remove meta from source class (belongs to issue not source) | from mythril.solidity.soliditycontract import SolidityContract
from mythril.ethereum.evmcontract import EVMContract
class Source:
def __init__(
self, source_type=None, source_format=None, source_list=None, meta=None
):
self.source_type = source_type
self.source_format = source_format
... | from mythril.solidity.soliditycontract import SolidityContract
from mythril.ethereum.evmcontract import EVMContract
class Source:
def __init__(
self, source_type=None, source_format=None, source_list=None, meta=None
):
self.source_type = source_type
self.source_format = source_format
... |
Use absolute paths for dependencies | from __future__ import (unicode_literals, division,
absolute_import, print_function)
from reggae.build import Build, DefaultOptions
from inspect import getmembers
def get_build(module):
builds = [v for n, v in getmembers(module) if isinstance(v, Build)]
assert len(builds) == 1
re... | from __future__ import (unicode_literals, division,
absolute_import, print_function)
from reggae.build import Build, DefaultOptions
from inspect import getmembers
def get_build(module):
builds = [v for n, v in getmembers(module) if isinstance(v, Build)]
assert len(builds) == 1
re... |
Delete cookie on reset inline mode | from .. import inline_translations as _
from django.conf import settings
class InlineTranslationsMiddleware(object):
""" Turn off/on inline tranlations with cookie """
def process_request(self, request, *args, **kwargs):
""" Check signed cookie for inline tranlations """
try:
... | # encoding: UTF-8
from .. import inline_translations as _
from django.conf import settings
class InlineTranslationsMiddleware(object):
""" Turn off/on inline tranlations with cookie """
def process_request(self, request, *args, **kwargs):
""" Check signed cookie for inline tranlations """
try:
... |
Fix default refirect when url is /control/ | # -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
@login_required(login_url='/control/auth/login/')
def index(request):
return HttpResponseRedirect("/control/files/")
@login_required(login_url='/control/auth/login/')
def eventchange... | # -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
@login_required(login_url='/control/auth/login/')
def index(request):
return HttpResponseRedirect("/control/events/")
@login_required(login_url='/control/auth/login/')
def eventchang... |
Use os.path.join() to join paths |
import numpy as np
import pickle
import os
import sys
import ws.bad as bad
mydir = os.path.abspath(os.path.dirname(__file__))
print(mydir)
lookupmatrix = pickle.load(open( \
mydir +'/accuweather_location_codes.dump','rb'))
lookuplist = lookupmatrix.tolist()
def build_url(city):
... | import numpy as np
import pickle
import os
import sys
import ws.bad as bad
mydir = os.path.abspath(os.path.dirname(__file__))
lookupmatrix = pickle.load(open(os.path.join(mydir, 'accuweather_location_codes.dump'), 'rb'))
lookuplist = lookupmatrix.tolist()
def build_url(city):
# check whether input is a string
... |
Fix bug in user pass code | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from sqlalchemy.sql import and_
from .models import Pass
def query_user_passes(session, user_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id,... | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from sqlalchemy.sql import and_
from .models import Pass
def query_user_passes(session, user_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id,... |
Use KSC auth's register_conf_options instead of oslo.cfg import | # Copyright (c) 2015 Akanda, 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 la... | # Copyright (c) 2015 Akanda, 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 la... |
Read the config file only from /etc/autocloud/autocloud.cfg file. | # -*- coding: utf-8 -*-
import ConfigParser
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
config = ConfigParser.RawConfigParser()
name = "{PROJECT_ROOT}/config/autocloud.cfg".format(
PROJECT_ROOT=PROJECT_ROOT)
if not os.path.exists(name):
name = '/etc/autocloud/autocloud.cfg'
conf... | # -*- coding: utf-8 -*-
import ConfigParser
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
name = '/etc/autocloud/autocloud.cfg'
if not os.path.exists(name):
raise Exception('Please add a proper cofig file under /etc/autocloud/')
config.read(name)
KOJI_SERVER_URL = config.get('autocloud', ... |
Fix error during merge commit | from django.conf import settings
from django.utils.module_loading import import_string
def select_for(data_type):
"""The storage class for each datatype is defined in a settings file. This
will look up the appropriate storage backend and instantiate it. If none
is found, this will default to the Django OR... | from django.conf import settings
from django.utils.module_loading import import_string
def select_for(data_type):
"""The storage class for each datatype is defined in a settings file. This
will look up the appropriate storage backend and instantiate it. If none
is found, this will default to the Django OR... |
Test the --nocram command line option | import pytest_cram
pytest_plugins = "pytester"
def test_version():
assert pytest_cram.__version__
def test_cramignore(testdir):
testdir.makeini("""
[pytest]
cramignore =
sub/a*.t
a.t
c*.t
""")
testdir.tmpdir.ensure("sub/a.t")
testdir.tmpdir.en... | import pytest_cram
pytest_plugins = "pytester"
def test_version():
assert pytest_cram.__version__
def test_nocram(testdir):
"""Ensure that --nocram collects .py but not .t files."""
testdir.makefile('.t', " $ true")
testdir.makepyfile("def test_(): assert True")
result = testdir.runpytest("--n... |
Fix ObjectType name and description attributes | from collections import OrderedDict
from graphql.type.definition import GraphQLObjectType
from marshmallow import Schema, SchemaOpts
from polygraph.utils.trim_docstring import trim_docstring
class ObjectTypeOpts(SchemaOpts):
def __init__(self, meta, **kwargs):
SchemaOpts.__init__(self, meta, **kwargs)
... | from collections import OrderedDict
from graphql.type.definition import GraphQLObjectType
from marshmallow import Schema, SchemaOpts
from polygraph.utils.trim_docstring import trim_docstring
class ObjectTypeOpts(SchemaOpts):
def __init__(self, meta, **kwargs):
SchemaOpts.__init__(self, meta, **kwargs)
... |
Fix location factory field name | # coding: utf-8
import factory
import random
from .models import Location, Region
class RegionFactory(factory.Factory):
FACTORY_FOR = Region
name = factory.Sequence(lambda n: "Region_%s" % n)
slug = factory.LazyAttribute(lambda a: a.name.lower())
latitude = random.uniform(-90.0, 90.0)
longitude... | # coding: utf-8
import factory
import random
from .models import Location, Region
class RegionFactory(factory.Factory):
FACTORY_FOR = Region
name = factory.Sequence(lambda n: "Region_%s" % n)
slug = factory.LazyAttribute(lambda a: a.name.lower())
latitude = random.uniform(-90.0, 90.0)
longitude... |
Add tests for function smoothing | #!/usr/bin/python
import unittest
import numpy as np
from corfunc import porod, guinier, fitguinier
class TestStringMethods(unittest.TestCase):
def test_porod(self):
self.assertEqual(porod(1, 1, 0), 1)
def test_guinier(self):
self.assertEqual(guinier(1, 1, 0), 1)
def test_sane_fit(self)... | #!/usr/bin/python
import unittest
import numpy as np
from corfunc import porod, guinier, fitguinier, smooth
class TestStringMethods(unittest.TestCase):
def test_porod(self):
self.assertEqual(porod(1, 1, 0), 1)
def test_guinier(self):
self.assertEqual(guinier(1, 1, 0), 1)
def test_sane_f... |
Connect request_sent for campaign connection | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class CampaignConfig(AppConfig):
name = "froide.campaign"
verbose_name = _("Campaign")
def ready(self):
from froide.foirequest.models import FoiRequest
from .listeners import connect_campaign
... | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class CampaignConfig(AppConfig):
name = "froide.campaign"
verbose_name = _("Campaign")
def ready(self):
from froide.foirequest.models import FoiRequest
from .listeners import connect_campaign
... |
Add global for default template name. | """
ydf/templating
~~~~~~~~~~~~~~
Contains functions to be exported into the Jinja2 environment and accessible from templates.
"""
import jinja2
import os
from ydf import instructions, __version__
DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates')
def render... | """
ydf/templating
~~~~~~~~~~~~~~
Contains functions to be exported into the Jinja2 environment and accessible from templates.
"""
import jinja2
import os
from ydf import instructions, __version__
DEFAULT_TEMPLATE_NAME = 'default.tpl'
DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname... |
Add render in index page | from flask import Flask
import os
app = Flask(__name__)
app.debug = True
# Secret Key setting based on debug setting
if app.debug:
app.secret_key = "T3st_s3cret_k3y!~$@"
else:
app.secret_key = os.urandom(30)
@app.route("/domain", methods=["GET", "POST"])
def domain():
if request.method == "GET":
... | from flask import Flask, request, render_template
import os
app = Flask(__name__)
app.debug = True
# Secret Key setting based on debug setting
if app.debug:
app.secret_key = "T3st_s3cret_k3y!~$@"
else:
app.secret_key = os.urandom(30)
@app.route("/domain", methods=["GET", "POST"])
def domain():
if requ... |
Load image from URL into buffer | import praw
import urllib
import cv2, numpy as np
DOWNSCALE = 2
r = praw.Reddit('/u/powderblock Glasses Bot')
foundImage = False
for post in r.get_subreddit('all').get_new(limit=15):
if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url):
print str(post.url)
... | import praw
import urllib
import cv2, numpy as np
from PIL import Image
DOWNSCALE = 2
r = praw.Reddit('/u/powderblock Glasses Bot')
foundImage = False
for post in r.get_subreddit('all').get_new(limit=15):
if "imgur.com" in post.url and (".jpg" in post.url or ".png" in post.url):
prin... |
Add welcome message for /r/splatoon chat. | import discord
import commands
bot = discord.Client()
@bot.event
def on_ready():
print('Logged in as:')
print('Username: ' + bot.user.name)
print('ID: ' + bot.user.id)
print('------')
@bot.event
def on_message(message):
commands.dispatch_messages(bot, message)
if __name__ == '__main__':
comm... | import discord
import commands
bot = discord.Client()
@bot.event
def on_ready():
print('Logged in as:')
print('Username: ' + bot.user.name)
print('ID: ' + bot.user.id)
print('------')
@bot.event
def on_message(message):
commands.dispatch_messages(bot, message)
@bot.event
def on_member_join(membe... |
Format file with python Black | #!/usr/bin/env python
# encoding: utf-8
'''
Created on Aug 29, 2014
@author: tmahrt
'''
from setuptools import setup
import io
setup(name='praatio',
version='4.2.1',
author='Tim Mahrt',
author_email='timmahrt@gmail.com',
url='https://github.com/timmahrt/praatIO',
package_dir={'praatio':'p... | #!/usr/bin/env python
# encoding: utf-8
"""
Created on Aug 29, 2014
@author: tmahrt
"""
from setuptools import setup
import io
setup(
name="praatio",
version="4.2.1",
author="Tim Mahrt",
author_email="timmahrt@gmail.com",
url="https://github.com/timmahrt/praatIO",
package_dir={"praatio": "praa... |
Set the version to 0.9 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os.path
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
README_FILE = os.path.join(ROOT_DIR, "README.rst")
with open(README_FILE) as f:
long_description = f.read()
setup(
name="xutils",
version="0... | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os.path
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
README_FILE = os.path.join(ROOT_DIR, "README.rst")
with open(README_FILE) as f:
long_description = f.read()
setup(
name="xutils",
version="0... |
Fix number of bills test | from tests import PMGTestCase
from tests.fixtures import dbfixture, BillData, BillTypeData
class TestBillAPI(PMGTestCase):
def setUp(self):
super(TestBillAPI, self).setUp()
self.fx = dbfixture.data(BillTypeData, BillData)
self.fx.setup()
def test_total_bill(self):
"""
... | from tests import PMGTestCase
from tests.fixtures import dbfixture, BillData, BillTypeData
class TestBillAPI(PMGTestCase):
def setUp(self):
super(TestBillAPI, self).setUp()
self.fx = dbfixture.data(BillTypeData, BillData)
self.fx.setup()
def test_total_bill(self):
"""
... |
Add heartbeat to install reqs | from setuptools import setup
setup(
name='downstream-farmer',
version='',
packages=['downstream-farmer'],
url='',
license='',
author='Storj Labs',
author_email='info@storj.io',
description=''
)
| from setuptools import setup
setup(
name='downstream-farmer',
version='',
packages=['downstream-farmer'],
url='',
license='',
author='Storj Labs',
author_email='info@storj.io',
description='',
install_requires=[
'heartbeat==0.1.2'
],
dependency_links = [
'htt... |
Use io.open for Python 2 compatibility. | #!/usr/bin/env python
# Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop)
import setuptools
with open('README.txt', encoding='utf-8') as readme:
long_description = readme.read()
with open('CHANGES.txt', encoding='utf-8') as changes:
long_description += '\n\n' + changes.read()
setup_params = ... | #!/usr/bin/env python
# Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop)
import io
import setuptools
with io.open('README.txt', encoding='utf-8') as readme:
long_description = readme.read()
with io.open('CHANGES.txt', encoding='utf-8') as changes:
long_description += '\n\n' + changes.read()... |
Handle illegal namedtuple field names, if found in a csv file. | from setuptools import setup, find_packages
setup(
version='0.35',
name="pydvkbiology",
packages=find_packages(),
description='Python scripts used in my biology/bioinformatics research',
author='DV Klopfenstein',
author_email='music_pupil@yahoo.com',
scripts=['./pydvkbiology/NCBI/cols.py'],... | from setuptools import setup, find_packages
setup(
version='0.36',
name="pydvkbiology",
packages=find_packages(),
description='Python scripts used in my biology/bioinformatics research',
author='DV Klopfenstein',
author_email='music_pupil@yahoo.com',
scripts=['./pydvkbiology/NCBI/cols.py'],... |
Switch to github and up the version | import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='django-uuslug',
version='0.3',
description = "A Unicode slug that is also guaranteed to be unique",
long_description = read('README'),
author='Val L33',
au... | import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='django-uuslug',
version='0.4',
description = "A Unicode slug that is also guaranteed to be unique",
long_description = read('README'),
author='Val L33',
au... |
Add login and logout stubs | from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def application(path):
return render_template('application.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
| from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/login')
def login():
return "LOGIN!"
@app.route('/logout')
def logout():
return "LOGOUT!"
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def application(path):
return render_template('applicat... |
Return event ids as int | # -*- coding: utf-8 -*-
import emarsys
from django.conf import settings
client = emarsys.Emarsys(settings.EMARSYS_ACCOUNT,
settings.EMARSYS_PASSWORD,
settings.EMARSYS_BASE_URI)
def get_events():
response = client.call('/api/v2/event', 'GET')
return {event[... | # -*- coding: utf-8 -*-
import emarsys
from django.conf import settings
client = emarsys.Emarsys(settings.EMARSYS_ACCOUNT,
settings.EMARSYS_PASSWORD,
settings.EMARSYS_BASE_URI)
def get_events():
response = client.call('/api/v2/event', 'GET')
return {event[... |
Print line after creating each csv | import csv
from datetime import date
from scraper.draft_scraper import scrape
CSV_FILE = 'datasets/%s_nbadraft.csv'
for year in range(1947, date.today().year):
draft = scrape(year)
header = [key for key in draft[1].keys()]
with open(CSV_FILE % year, 'w', newline='') as outfile:
dw = csv.DictWrite... | import csv
from datetime import date
from scraper.draft_scraper import scrape
CSV_FILE = 'datasets/%s_nbadraft.csv'
for year in range(1947, date.today().year):
draft = scrape(year)
header = [key for key in draft[1].keys()]
with open(CSV_FILE % year, 'w', newline='') as outfile:
dw = csv.DictWrite... |
Fix bug where column the function was being called, rather than class | import sqlalchemy
import sqlalchemy.ext.declarative
Base = sqlalchemy.ext.declarative.declarative_base()
class Post(Base):
__tablename__ = "posts"
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True)
title = sqlalchemy.Column(sqlalchemy.String)
body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text... | import sqlalchemy
import sqlalchemy.ext.declarative
Base = sqlalchemy.ext.declarative.declarative_base()
class Post(Base):
__tablename__ = "posts"
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True)
title = sqlalchemy.Column(sqlalchemy.String)
body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text... |
Refactor get args function from console interface | import argparse
from getpass import getpass
from pysswords.db import Database
from pysswords.crypt import CryptOptions
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('path')
parser.add_argument('--create', action='store_true')
parser.add_argument('--password', default=None)
... | import argparse
from getpass import getpass
from pysswords.db import Database
from pysswords.crypt import CryptOptions
def get_args():
parser = argparse.ArgumentParser()
main_group = parser.add_argument_group('Main options')
main_group.add_argument('path', help='Path to database file')
main_group.add_... |
Change name to reference new schema name | import pyxb.binding.generate
import os.path
schema_path = '%s/../../pyxb/standard/schemas/kml21.xsd' % (os.path.dirname(__file__),)
code = pyxb.binding.generate.GeneratePython(schema_file=schema_path)
rv = compile(code, 'test', 'exec')
eval(rv)
from pyxb.exceptions_ import *
import unittest
class TestKML (unittest.... | import pyxb.binding.generate
import os.path
schema_path = '%s/../../pyxb/standard/schemas/kml.xsd' % (os.path.dirname(__file__),)
code = pyxb.binding.generate.GeneratePython(schema_file=schema_path)
rv = compile(code, 'test', 'exec')
eval(rv)
from pyxb.exceptions_ import *
import unittest
class TestKML (unittest.Te... |
Add run_list to Role for testing. | from chef.base import ChefObject
class Role(ChefObject):
"""A model object for a Chef role."""
url = '/roles'
attributes = [
'description',
]
| from chef.base import ChefObject
class Role(ChefObject):
"""A model object for a Chef role."""
url = '/roles'
attributes = [
'description',
'run_list',
]
|
Fix cprint with unicode characters | from __future__ import print_function
import sys
import string
import json
from colors import *
def is_posix_filename(name, extra_chars=""):
CHARS = string.letters + string.digits + "._-" + extra_chars
return all(c in CHARS for c in name)
def cprint(color, msg, file=sys.stdout, end='\n'):
data = msg._... | from __future__ import print_function
import sys
import string
import json
from colors import *
def is_posix_filename(name, extra_chars=""):
CHARS = string.letters + string.digits + "._-" + extra_chars
return all(c in CHARS for c in name)
def cprint(color, msg, file=sys.stdout, end='\n'):
if type(msg)... |
Replace the trivial ctypes test (did only an import) with the real test suite. | # trivial test
import _ctypes
import ctypes
| import unittest
from test.test_support import run_suite
import ctypes.test
def test_main():
skipped, testcases = ctypes.test.get_tests(ctypes.test, "test_*.py", verbosity=0)
suites = [unittest.makeSuite(t) for t in testcases]
run_suite(unittest.TestSuite(suites))
if __name__ == "__main__":
test_main(... |
Return some text on a health check | from django.http import HttpResponse
def health_view(request):
return HttpResponse()
| from django.http import HttpResponse
def health_view(request):
return HttpResponse("I am okay.", content_type="text/plain")
|
Remove requirement to clear notebooks | import glob
from nbconvert.preprocessors import ExecutePreprocessor
import nbformat
import pytest
notebooks = sorted(glob.glob("*.ipynb"))
@pytest.mark.parametrize("notebook", notebooks)
def test_notebook_execution(notebook):
with open(notebook) as fin:
nb = nbformat.read(fin, as_version=4)
ep = Ex... | import glob
from nbconvert.preprocessors import ExecutePreprocessor
import nbformat
import pytest
notebooks = sorted(glob.glob("*.ipynb"))
@pytest.mark.parametrize("notebook", notebooks)
def test_notebook_execution(notebook):
with open(notebook) as fin:
nb = nbformat.read(fin, as_version=4)
ep = Ex... |
Update decode mirax a bit | #!/usr/bin/python
import struct, sys
f = open(sys.argv[1])
HEADER_OFFSET = 37
f.seek(HEADER_OFFSET)
try:
while True:
n = struct.unpack("<i", f.read(4))[0]
possible_lineno = (n - HEADER_OFFSET) / 4.0
if possible_lineno < 0 or int(possible_lineno) != possible_lineno:
print "%1... | #!/usr/bin/python
import struct, sys, os
f = open(sys.argv[1])
HEADER_OFFSET = 37
f.seek(HEADER_OFFSET)
filesize = os.stat(sys.argv[1]).st_size
num_items = (filesize - HEADER_OFFSET) / 4
skipped = False
i = 0
try:
while True:
n = struct.unpack("<i", f.read(4))[0]
possible_lineno = (n - HEADER... |
Add test coverage for save pages (happy path) | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import copy
from twisted.internet import defer
from mock import Mock
from testtools import ExpectedException, TestCase, run_test_with
from testtools.twistedsupport import AsynchronousDeferredRunTest
from s... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import copy
import pdfrw
from twisted.internet import defer
from mock import Mock, patch, mock_open, call
from testtools import ExpectedException, TestCase, run_test_with
from testtools.twistedsupport impor... |
Add test for osfclient's session object | from osfclient.models import OSFSession
def test_basic_auth():
session = OSFSession()
session.basic_auth('joe@example.com', 'secret_password')
assert session.auth == ('joe@example.com', 'secret_password')
assert 'Authorization' not in session.headers
def test_basic_build_url():
session = OSFSess... | from unittest.mock import patch
from unittest.mock import MagicMock
import pytest
from osfclient.models import OSFSession
from osfclient.exceptions import UnauthorizedException
def test_basic_auth():
session = OSFSession()
session.basic_auth('joe@example.com', 'secret_password')
assert session.auth == (... |
Change GroupSerializer to display attributes as strings | from rest_framework import serializers
from sigma_core.models.group import Group
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
| from rest_framework import serializers
from sigma_core.models.group import Group
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
visibility = serializers.SerializerMethodField()
membership_policy = serializers.SerializerMethodField()
validation_policy = seri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.