Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix failing tests on appveyor |
import ci_addons
import os
import pytest
import subprocess
from . import captured_lines
def test_home():
expected_home = os.path.abspath(os.path.dirname(__file__) + '/..')
assert ci_addons.home() == expected_home
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_path(addon):
... |
import ci_addons
import os
import pytest
import subprocess
from . import captured_lines
def test_home():
expected_home = os.path.abspath(os.path.dirname(__file__) + '/..')
assert ci_addons.home() == expected_home
@pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py'])
def test_path(addon):
... |
Fix default fixture to initialize database | import pytest
@pytest.fixture(scope='module')
def app():
from api import app
return app
| import pytest
@pytest.fixture(scope='module')
def app():
from api import app, db
app.config['TESTING'] = True
db.create_all()
return app
|
Increase the number of Gunicorn workers | bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
workers = 3
timeout = 60
| bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
workers = 6
timeout = 60
|
Make create_tokenizer work with Japanese | # encoding: utf8
from __future__ import unicode_literals, print_function
from os import path
from ..language import Language
from ..attrs import LANG
from ..tokens import Doc
from .language_data import *
class Japanese(Language):
lang = 'ja'
def make_doc(self, text):
try:
from janome.t... | # encoding: utf8
from __future__ import unicode_literals, print_function
from os import path
from ..language import Language, BaseDefaults
from ..tokenizer import Tokenizer
from ..attrs import LANG
from ..tokens import Doc
from .language_data import *
class JapaneseTokenizer(object):
def __init__(self, cls, nlp... |
Update help to indicate where the necessary script lives | """
Edits the spectide amplitude values to some factor of their original value.
WARNING: When using this on FVCOM input files, it will change the format of
the variables. changeNC presumes each variable has a value and unit associated
with it, whereas some of the variables in the FVCOM inputs are in fact not
that so... | """
Edits the spectide amplitude values to some factor of their original value.
WARNING: When using this on FVCOM input files, it will change the format of
the variables. changeNC presumes each variable has a value and unit associated
with it, whereas some of the variables in the FVCOM inputs are in fact not
that so... |
Add commit message for commits and for parents | from flask import Flask
from flask import render_template
app = Flask(__name__)
app.config['DEBUG'] = True
repo_path = '../ames-py'
@app.route("/")
def main():
return render_template("index.html")
@app.route("/data")
def data():
import json
import git
import networkx as nx
G = nx.DiGraph()
... | from flask import Flask
from flask import render_template
app = Flask(__name__)
app.config['DEBUG'] = True
repo_path = '../ames-py'
@app.route("/")
def main():
return render_template("index.html")
@app.route("/data")
def data():
import json
import git
import networkx as nx
G = nx.DiGraph()
... |
Use get_backend in proxy methods | from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.db.models.query import QuerySet
class FollowQuerySet(QuerySet):
pass
class FollowManager(models.Manager):
def get_query_set(self):
return FollowQuerySet(self.model)
@python_2_unicode_compatible
c... | from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.db.models.query import QuerySet
from .backends import get_backend
class FollowQuerySet(QuerySet):
pass
class FollowManager(models.Manager):
def get_query_set(self):
return FollowQuerySet(self.mode... |
Add delay to resize test | import webview
from .util import run_test
from time import sleep
def test_resize():
window = webview.create_window('Set Window Size Test', 'https://www.example.org', width=800, height=600)
run_test(webview, window, resize)
def resize(window):
assert window.width == 800
assert window.height == 600
... | import webview
from .util import run_test
from time import sleep
def test_resize():
window = webview.create_window('Set Window Size Test', 'https://www.example.org', width=800, height=600)
run_test(webview, window, resize)
def resize(window):
assert window.width == 800
assert window.height == 600
... |
Make path to sample project shorter | """Provide APP constant for the purposes of manually running the flask app
For example, build the front end, then run the app with environment variables::
cd smif/app/
npm run build
cd ../http_api/
FLASK_APP=smif.http_api.app FLASK_DEBUG=1 flask run
"""
import os
from smif.data_layer i... | """Provide APP constant for the purposes of manually running the flask app
For example, build the front end, then run the app with environment variables::
cd smif/app/
npm run build
cd ../http_api/
FLASK_APP=smif.http_api.app FLASK_DEBUG=1 flask run
"""
import os
from smif.data_layer i... |
Fix websockets process after celery upgrade | import os
import gevent.socket
import redis.connection
from manage import _set_source_root_parent, _set_source_root
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
_set_source_root_parent('submodules')
_set_source_root(os.path.join('corehq', 'ex-submodules'))
_set_source_root(os.path.join('custom', '_lega... | import os
import gevent.socket
import redis.connection
from manage import init_hq_python_path, run_patches
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
init_hq_python_path()
run_patches()
redis.connection.socket = gevent.socket
from ws4redis.uwsgi_runserver import uWSGIWebsocketServer
application = uW... |
Fix missing test probably got removed in my clumsy merge | import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
"IEEE14":"/Appl... | import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
"IEEE14":"/Appl... |
Fix featureCounts test following change in consensus nomenclature in FeatureCounts obj | import sequana.featurecounts as fc
from sequana import sequana_data
def test_featurecounts():
RNASEQ_DIR_0 = sequana_data("featurecounts") + "/rnaseq_0"
RNASEQ_DIR_1 = sequana_data("featurecounts") + "/rnaseq_1"
RNASEQ_DIR_2 = sequana_data("featurecounts") + "/rnaseq_2"
RNASEQ_DIR_undef = sequana_data... | import sequana.featurecounts as fc
from sequana import sequana_data
def test_featurecounts():
RNASEQ_DIR_0 = sequana_data("featurecounts") + "/rnaseq_0"
RNASEQ_DIR_1 = sequana_data("featurecounts") + "/rnaseq_1"
RNASEQ_DIR_2 = sequana_data("featurecounts") + "/rnaseq_2"
RNASEQ_DIR_undef = sequana_data... |
Fix Python 3 import error | """Image Processing SciKit (Toolbox for SciPy)"""
import os.path as _osp
data_dir = _osp.abspath(_osp.join(_osp.dirname(__file__), 'data'))
from version import version as __version__
def _setup_test():
import gzip
import functools
basedir = _osp.dirname(_osp.join(__file__, '../'))
args = ['', '--e... | """Image Processing SciKit (Toolbox for SciPy)"""
import os.path as _osp
data_dir = _osp.abspath(_osp.join(_osp.dirname(__file__), 'data'))
from version import version as __version__
def _setup_test():
import gzip
import functools
basedir = _osp.dirname(_osp.join(__file__, '../'))
args = ['', '--e... |
Break when done copying the working behaviour | class DiffAgentBase(object):
diff = []
noise_reduction = []
latest_observation = 0
current_prediction = []
name = ''
behaviour = None
working_behaviour_size = 2
def __init__(self, experience, knowledge, space):
self.space = space
self.experience = experience
sel... | class DiffAgentBase(object):
diff = []
noise_reduction = []
latest_observation = 0
current_prediction = []
name = ''
behaviour = None
working_behaviour_size = 2
def __init__(self, experience, knowledge, space):
self.space = space
self.experience = experience
sel... |
Call configure() on settings to ensure that the CELERY_PROGRESS_BACKEND variable can be picked up | from django.conf import settings
from django.utils.module_loading import import_by_path
BACKEND = getattr(settings, 'CELERY_PROGRESS_BACKEND',
'celery_progress.backends.CeleryBackend')
def get_backend():
return import_by_path(BACKEND)
backend = get_backend()()
| from django.conf import settings
from django.utils.module_loading import import_by_path
BACKEND = getattr(settings.configure(), 'CELERY_PROGRESS_BACKEND',
'celery_progress.backends.CeleryBackend')
def get_backend():
return import_by_path(BACKEND)
backend = get_backend()()
|
Enable '-h' help option from the pdtools root level. | """
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
... | """
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
... |
Add missing constant for ssl listener. |
SQL_PORT = 15000
JSON_RPC_PORT = 15598
HTTP_PORT = 15597
JSON_PUBSUB_PORT = 15596
|
SQL_PORT = 15000
JSON_RPC_PORT = 15598
HTTP_PORT = 15597
HTTPS_PORT = 443
JSON_PUBSUB_PORT = 15596
|
Update status when stopping experiments | from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
exper... | from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
exper... |
Fix a derp on argparse | __author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
... | __author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
... |
Add unit support for spacers | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (ca... | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of f... |
TEST - added more explicit tests for directory read | """ Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, ass... | """ Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
EXPECTED_PARAMS,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
... |
Add logger to env loader | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load... | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
import os
import logging
logger = logging.getLogger()
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `... |
Fix exception type in a test | # -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_fi... | # -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_fi... |
Add OAuth authentication and config settings load/save | #!/usr/bin/env python
#
from __future__ import print_function
import os
import sys
import argparse
import logging
| #!/usr/bin/env python
from __future__ import print_function
import os
import sys
import argparse
import json
import tweepy
import pystache
import webbrowser
CONFIG_FILE = '.shut-up-bird.conf'
def tweep_login(consumer_key, consumer_secret, token='', secret=''):
auth = tweepy.OAuthHandler(consumer_key, consumer_se... |
Clean it up a bit | letters = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ'
phrase = input()
output = ''
vowels = ''
phrase = phrase.replace(' ', '')
for char in phrase:
if char in letters:
output += char
else:
vowels += char
print(output)
print(vowels) | not_vowel = 'bcdfghjklmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ'
phrase = input()
output = ''
vowels = ''
# Remove sapces
phrase = phrase.replace(' ', '')
for char in phrase:
if char in not_vowel:
output += char # Add non vowel to output
else:
vowels += char # Add vowels to vowels
print(output)
pri... |
Raise KeyboardInterrupt to allow the run to handle logout | import discord
import asyncio
import os
import signal
import sys
#Set up Client State
CLIENT_TOKEN=os.environ['TOKEN']
#Create Discord client
client = discord.Client()
#Handle shutdown gracefully
def sigterm_handler(signum, frame):
print("Logging out...")
client.logout()
print('Shutting down...')
sy... | import discord
import asyncio
import os
import signal
import sys
#Set up Client State
CLIENT_TOKEN=os.environ['TOKEN']
#Create Discord client
client = discord.Client()
#Handle shutdown gracefully
async def sigterm_handler(signum, frame):
print("Logging out...")
raise KeyboardInterrupt
print('Shutting do... |
Switch from dictionary to namedtuple | #!/usr/bin/env python
def config():
return {
'is-oracle': True,
'version': 'oracle-java8',
}
| #!/usr/bin/env python
from collections import namedtuple
JavaConfig = namedtuple('JavaConfig', ['is_oracle', 'version'])
def config():
return JavaConfig(
is_oracle=True,
version='oracle-java8',
)
|
Set up the proposal tasks on app startup | from django.apps import AppConfig
class ProposalConfig(AppConfig):
name = "proposal"
def ready(self):
# Register tasks with Celery:
from . import tasks
| from django.apps import AppConfig
class ProposalConfig(AppConfig):
name = "proposal"
def ready(self):
# Register tasks with Celery:
from . import tasks
tasks.set_up_hooks()
|
Correct wrong inheritance on sponsorship_typo3 child_depart wizard. | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __open... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __open... |
Refactor JSONResponse views to include ListView | from django import http
from django.views.generic import DetailView
class JSONResponseDetailView(DetailView):
def render_to_json_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
def get_json_... | from django import http
from django.views.generic import DetailView, ListView
class JSONResponseMixin(object):
def render_to_json_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
def get_json... |
Fix unicode issues at url translation | # coding: utf-8
import re
from django.core.urlresolvers import reverse
from django.conf import settings
def reverse_no_i18n(viewname, *args, **kwargs):
result = reverse(viewname, *args, **kwargs)
m = re.match(r'(/[^/]*)(/.*$)', result)
return m.groups()[1]
def change_url_language(url, language):
if ... | # coding: utf-8
import re
from django.core.urlresolvers import reverse
from django.conf import settings
def reverse_no_i18n(viewname, *args, **kwargs):
result = reverse(viewname, *args, **kwargs)
m = re.match(r'(/[^/]*)(/.*$)', result)
return m.groups()[1]
def change_url_language(url, language):
if ... |
Add a User post_save hook for creating user profiles | from django.contrib.auth.models import User, Group
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.conf import settings
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=User)
def on_user_post_save(sender, instance=None, created=False, **kwar... | from authentication.models import UserProfile
from django.contrib.auth.models import User, Group
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.conf import settings
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=User)
def on_user_post_sav... |
Support custom actions in search router | """Search router."""
from rest_framework.routers import DefaultRouter, Route
class SearchRouter(DefaultRouter):
"""Custom router for search endpoints.
Search endpoints don't follow REST principles and thus don't need
routes that default router provides.
"""
routes = [
Route(
... | """Search router."""
from rest_framework.routers import DefaultRouter, DynamicRoute, Route
class SearchRouter(DefaultRouter):
"""Custom router for search endpoints.
Search endpoints don't follow REST principles and thus don't need
routes that default router provides.
"""
routes = [
Route... |
Fix sitemap memory consumption during generation | from django.contrib import sitemaps
from firecares.firestation.models import FireDepartment
from django.db.models import Max
from django.core.urlresolvers import reverse
class BaseSitemap(sitemaps.Sitemap):
protocol = 'https'
def items(self):
return ['media', 'models_performance_score', 'models_commu... | from django.contrib import sitemaps
from firecares.firestation.models import FireDepartment
from django.db.models import Max
from django.core.urlresolvers import reverse
class BaseSitemap(sitemaps.Sitemap):
protocol = 'https'
def items(self):
return ['media', 'models_performance_score', 'models_commu... |
Revert "Revert "Added script for cron job to load surveys to database."" | from surveyextractor import QualtricsExtractor
import getopt, sys
# Script for scheduling regular EdxQualtrics updates
# Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r"
qe = QualtricsExtractor()
opts, args = getopt.getopt(sys.argv[1:], 'amsr', ['--reset', '--loadmeta', '--loadsurveys', '--loadresponses... | from surveyextractor import QualtricsExtractor
import getopt
import sys
### Script for scheduling regular EdxQualtrics updates
### Usage for cron should be "cronRefreshEdxQualtrics.py -m -s -r"
# Append directory for dependencies to PYTHONPATH
sys.path.append("/home/dataman/Code/qualtrics_etl/src/qualtrics_etl/")
qe... |
Fix typo in description of config item | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Splatalogue Catalog Query Tool
-----------------------------------
:Author: Adam Ginsburg (adam.g.ginsburg@gmail.com)
:Originally contributed by:
Magnus Vilhelm Persson (magnusp@vilhelm.nu)
"""
from astropy import config as _config
class Conf... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Splatalogue Catalog Query Tool
-----------------------------------
:Author: Adam Ginsburg (adam.g.ginsburg@gmail.com)
:Originally contributed by:
Magnus Vilhelm Persson (magnusp@vilhelm.nu)
"""
from astropy import config as _config
class Conf... |
Use json instead of django.utils.simplejson. | from django import template
from django.utils import simplejson
from javascript_settings.configuration_builder import \
DEFAULT_CONFIGURATION_BUILDER
register = template.Library()
@register.tag(name='javascript_settings')
def do_javascript_settings(parser, token):
"""
Returns a node with generated c... | import json
from django import template
from javascript_settings.configuration_builder import \
DEFAULT_CONFIGURATION_BUILDER
register = template.Library()
@register.tag(name='javascript_settings')
def do_javascript_settings(parser, token):
"""
Returns a node with generated configuration.
"""
... |
Update script to use new way of calling class. | #!/usr/bin/env python
# -*- coding: utf8 -*-
import sys, os
import argparse
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
def main(argv=None):
parser = argparse.ArgumentParser(description='Print count of objects for a given collection.')
parser.add_argument('path', help="Nuxeo path to collection... | #!/usr/bin/env python
# -*- coding: utf8 -*-
import sys, os
import argparse
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
def main(argv=None):
parser = argparse.ArgumentParser(description='Print count of objects for a given collection.')
parser.add_argument('path', help="Nuxeo path to collection... |
Revert "adding delete hook so the attached User object is deleted properly when and OAuth object is deleted." | from django.contrib.auth.models import User,Group
from django.db import models
from django.contrib.postgres.fields import JSONField
from ..core.models import TimeStampedModelMixin, UIDMixin
class OAuth(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False)
identification = mod... | from django.contrib.auth.models import User,Group
from django.db import models
from django.contrib.postgres.fields import JSONField
from ..core.models import TimeStampedModelMixin, UIDMixin
class OAuth(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False)
identification = mod... |
Fix file open dialog for PySide | import os
from ..qt import QtGui
def open_file_dialog(default_format='png'):
"""Return user-selected file path."""
filename = str(QtGui.QFileDialog.getOpenFileName())
if len(filename) == 0:
return None
return filename
def save_file_dialog(default_format='png'):
"""Return user-selected f... | import os
from ..qt import QtGui
__all__ = ['open_file_dialog', 'save_file_dialog']
def _format_filename(filename):
if isinstance(filename, tuple):
# Handle discrepancy between PyQt4 and PySide APIs.
filename = filename[0]
if len(filename) == 0:
return None
return str(filename)
... |
Use command to list vaults | import logging
import sys
from glaciercmd.gcconfig import GCConfig
def run():
logging.basicConfig(format="%(asctime)s %(levelname)s %(module)s: %(message)s", level=logging.DEBUG)
config = GCConfig()
if config.has_errors():
config.log_errors()
sys.exit(1)
if __name__ == '__main__':
run()
| import logging
import sys
import argparse
import glob
import os
from glaciercmd.gcconfig import GCConfig
def load_commands():
commands = []
command_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'command_*.py')
command_files = glob.glob(command_dir)
for command_file in command_files:
com... |
Disable test that is non-deterministically failing. | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# test helper.run_tests function
import warnings
from .. import helper
from ... import _get_test_runner
from .. helper import pytest
# run_test... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# test helper.run_tests function
import warnings
from .. import helper
from ... import _get_test_runner
from .. helper import pytest
# run_test... |
Support loading pickled data referencing SortedDict. | """Picklers for working with serialized data."""
from __future__ import unicode_literals
import pickle
class DjangoCompatUnpickler(pickle.Unpickler):
"""Unpickler compatible with changes to Django class/module paths.
This provides compatibility across Django versions for various field types,
updating r... | """Picklers for working with serialized data."""
from __future__ import unicode_literals
import pickle
from django_evolution.compat.datastructures import OrderedDict
class SortedDict(dict):
"""Compatibility for unpickling a SortedDict.
Old signatures may use an old Django ``SortedDict`` structure, which d... |
Use /projects/ not /+projects/ when caching | # This file is part of OpenHatch.
# Copyright (C) 2010 OpenHatch, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | # This file is part of OpenHatch.
# Copyright (C) 2010 OpenHatch, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... |
Change fields to the schema agreed | from eduid_am.exceptions import UserDoesNotExist
def attribute_fetcher(db, user_id):
attributes = {}
user = db.registered.find_one({'_id': user_id})
if user is None:
raise UserDoesNotExist("No user matching _id='%s'" % user_id)
else:
# white list of valid attributes for security reas... | from eduid_am.exceptions import UserDoesNotExist
def attribute_fetcher(db, user_id):
attributes = {}
user = db.registered.find_one({'_id': user_id})
if user is None:
raise UserDoesNotExist("No user matching _id='%s'" % user_id)
else:
email = user.get('email', None)
if email:
... |
Add lpcres in linpred namespace. | import levinson_lpc
from levinson_lpc import *
__all__ = levinson_lpc.__all__
| import levinson_lpc
from levinson_lpc import *
__all__ = levinson_lpc.__all__
from common import lpcres
__all__ += ['lpcres']
|
Use vopen() to make DictFile works when reading remote repository meta data | import os
import json
import logging
LOGGER = logging.getLogger(__name__)
class DictFile(dict):
"""A ``dict``, storable as a JSON file.
"""
def __init__(self, file_path):
super(DictFile, self).__init__()
self.__file_path = file_path
self.reload()
def reload(self):
if... | import os
import json
import logging
from .vfiles import vopen
LOGGER = logging.getLogger(__name__)
class DictFile(dict):
"""A ``dict``, storable as a JSON file.
"""
def __init__(self, file_path):
super(DictFile, self).__init__()
self.__file_path = file_path
self.reload()
d... |
Set POST/GET/COOKIES on MockRequest so repr works | """
gargoyle.helpers
~~~~~~~~~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from django.http import HttpRequest
class MockRequest(HttpRequest):
"""
A mock request object which stores a user
instance and the ip address.
"""
def __init__(self, ... | """
gargoyle.helpers
~~~~~~~~~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from django.http import HttpRequest
class MockRequest(HttpRequest):
"""
A mock request object which stores a user
instance and the ip address.
"""
def __init__(self, ... |
Use default argument for StreamHandler (which is what want, sys.stderr) because they changed the name of the keyword argument in 2.7 | import sys
import logging
def init_logging():
logFormat = "%(asctime)s %(levelname)s %(filename)s:%(lineno)s %(message)s"
logFormatter = logging.Formatter(fmt=logFormat)
logHandler = logging.StreamHandler(stream=sys.stderr)
logHandler.setFormatter(logFormatter)
log = logging.getLogger(__name__)
... | import sys
import logging
def init_logging():
logFormat = "%(asctime)s %(levelname)s %(filename)s:%(lineno)s %(message)s"
logFormatter = logging.Formatter(fmt=logFormat)
logHandler = logging.StreamHandler()
logHandler.setFormatter(logFormatter)
log = logging.getLogger(__name__)
log.addHandler(l... |
Fix KeyError exception when called with no parameters | # coding: utf-8
from tapioca import (JSONAdapterMixin, TapiocaAdapter,
generate_wrapper_from_adapter)
from .resource_mapping import RESOURCE_MAPPING
class InstagramClientAdapter(JSONAdapterMixin, TapiocaAdapter):
api_root = 'https://api.instagram.com/v1/'
resource_mapping = RESOURCE_MAP... | # coding: utf-8
from tapioca import (JSONAdapterMixin, TapiocaAdapter,
generate_wrapper_from_adapter)
from .resource_mapping import RESOURCE_MAPPING
class InstagramClientAdapter(JSONAdapterMixin, TapiocaAdapter):
api_root = 'https://api.instagram.com/v1/'
resource_mapping = RESOURCE_MAP... |
Print message on completion, to aid debugging | from gpiozero import LED
import time
# GPIO 24 ... LED ... 470 ohm resistor ... GND
led = LED(24)
try:
led.blink()
time.sleep(20)
except KeyboardInterrupt:
led.off()
| from gpiozero import LED
import time
# GPIO 24 ... LED ... 470 ohm resistor ... GND
led = LED(24)
try:
led.blink()
time.sleep(20)
except KeyboardInterrupt:
led.off()
print "done"
|
Fix file URI in test (2nd attempt) | import os
from numpy.testing import *
import numpy as np
import skimage.io as io
from skimage import data_dir
def test_stack_basic():
x = np.arange(12).reshape(3, 4)
io.push(x)
assert_array_equal(io.pop(), x)
@raises(ValueError)
def test_stack_non_array():
io.push([[1, 2, 3]])
def test_imread_u... | import os
from numpy.testing import *
import numpy as np
import skimage.io as io
from skimage import data_dir
def test_stack_basic():
x = np.arange(12).reshape(3, 4)
io.push(x)
assert_array_equal(io.pop(), x)
@raises(ValueError)
def test_stack_non_array():
io.push([[1, 2, 3]])
def test_imread_u... |
Add classical_transport to init file | # 'physics' is a tentative name for this subpackage. Another
# possibility is 'plasma'. The organization is to be decided by v0.1.
from .parameters import Alfven_speed, ion_sound_speed, thermal_speed, kappa_thermal_speed, gyrofrequency, gyroradius, plasma_frequency, Debye_length, Debye_number, inertial_length, magne... | # 'physics' is a tentative name for this subpackage. Another
# possibility is 'plasma'. The organization is to be decided by v0.1.
from .parameters import Alfven_speed, ion_sound_speed, thermal_speed, kappa_thermal_speed, gyrofrequency, gyroradius, plasma_frequency, Debye_length, Debye_number, inertial_length, magne... |
Add complete field to task and timesheet api | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import User
from rest_framework import serializers
from core.models import Timesheet, Task, Entry
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id'... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import User
from rest_framework import serializers
from core.models import Timesheet, Task, Entry
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id'... |
Add max length to comment field | from django import forms
from django.utils.translation import gettext_lazy as _
from django_comments.forms import (
CommentForm as DjangoCommentForm,
COMMENT_MAX_LENGTH
)
class CommentForm(DjangoCommentForm):
name = forms.CharField(
label=_('Name'),
required=True,
help_text=_('You... | from django import forms
from django.utils.translation import gettext_lazy as _
from django_comments.forms import (
CommentForm as DjangoCommentForm,
COMMENT_MAX_LENGTH
)
class CommentForm(DjangoCommentForm):
name = forms.CharField(
label=_('Name'),
required=True,
max_length=50,
... |
Make service info available on v3 API | from django.conf.urls import include, url
from normandy.base import views
from normandy.base.api import views as api_views
from normandy.base.api.routers import MixedViewRouter
# API Router
router = MixedViewRouter()
router.register("user", api_views.UserViewSet)
router.register("group", api_views.GroupViewSet)
ur... | from django.conf.urls import include, url
from normandy.base import views
from normandy.base.api import views as api_views
from normandy.base.api.routers import MixedViewRouter
# API Router
router = MixedViewRouter()
router.register("user", api_views.UserViewSet)
router.register("group", api_views.GroupViewSet)
ur... |
Fix logging, add a sleep to molify Google's rate limit. | """Geocode Contact objects."""
import sys
from geopy import geocoders
from django.core.management.base import BaseCommand, CommandError
from portal import models
class Command(BaseCommand):
"""Set lat/long fields on contacts with a street address,
currently just using Google's geocoder."""
def handle(... | """Geocode Contact objects."""
import sys
import time
from geopy import geocoders
from django.core.management.base import BaseCommand, CommandError
from portal import models
class Command(BaseCommand):
"""Set lat/long fields on contacts with a street address,
currently just using Google's geocoder."""
... |
Make sure the version is displayed as r<revision number> if the information about the package version is not available. | # Copyright (c) 2011 Vit Suchomel and Jan Pomikalek
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
try:
__version__ = 'v' + __import__('pkg_resources').get_distribution('chared').version
except:
__version__ =... | # Copyright (c) 2011 Vit Suchomel and Jan Pomikalek
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
try:
__version__ = 'v' + __import__('pkg_resources').get_distribution('chared').version
except:
import re
... |
Use longer TIMEOUT defined in sos_notebook.test_utils. | # Test that sos kernel is installed
import jupyter_client
try:
jupyter_client.kernelspec.get_kernel_spec('sos')
except jupyter_client.kernelspec.NoSuchKernel:
print('sos kernel was not installed')
print('The following kernels are installed:')
print('jupyter_client.kernelspec.find_kernel_specs()')
... | # Test that sos kernel is installed
import jupyter_client
try:
jupyter_client.kernelspec.get_kernel_spec('sos')
except jupyter_client.kernelspec.NoSuchKernel:
print('sos kernel was not installed')
print('The following kernels are installed:')
print('jupyter_client.kernelspec.find_kernel_specs()')
... |
Add pytz as a test requirement | from distutils.core import setup
import skyfield # safe, because __init__.py contains no import statements
setup(
name='skyfield',
version=skyfield.__version__,
description=skyfield.__doc__.split('\n', 1)[0],
long_description=open('README.rst', 'rb').read().decode('utf-8'),
license='MIT',
auth... | from distutils.core import setup
import skyfield # safe, because __init__.py contains no import statements
setup(
name='skyfield',
version=skyfield.__version__,
description=skyfield.__doc__.split('\n', 1)[0],
long_description=open('README.rst', 'rb').read().decode('utf-8'),
license='MIT',
auth... |
Mark compatibility with Python 3.6 | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='pyaavso',
version=__import__('pyaavso').__version__,
description='A Python library for working with AAVSO data.',
long_description=read('README.rst... | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='pyaavso',
version=__import__('pyaavso').__version__,
description='A Python library for working with AAVSO data.',
long_description=read('README.rst... |
Add a compatibility hook to deal with creating django.contrib.auth permissions on migrated models. | """
South-specific signals
"""
from django.dispatch import Signal
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
... | """
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a par... |
Make the gfortran/vs2003 hack source file known to distutils. | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('distutils',parent_package,top_path)
config.add_subpackage('command')
config.add_subpackage('fcompiler')
config.add_data_dir('tests')
config.add_d... | #!/usr/bin/env python
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('distutils',parent_package,top_path)
config.add_subpackage('command')
config.add_subpackage('fcompiler')
config.add_data_dir('tests')
config.add_d... |
Split extra requires for store and restapi | from setuptools import setup, find_packages
def read(fname):
with open(fname) as fp:
content = fp.read()
return content
setup(
name='munerator',
version="0.10.11",
description='Manager of OpenArena battles',
long_description=read("README.rst"),
author='Johan Bloemberg',
author... | from setuptools import setup, find_packages
def read(fname):
with open(fname) as fp:
content = fp.read()
return content
setup(
name='munerator',
version="0.10.12",
description='Manager of OpenArena battles',
long_description=read("README.rst"),
author='Johan Bloemberg',
author... |
Add more idiomatic (and also portable) way to install `spellnum` script | #!/usr/bin/env python
from distutils.core import setup
setup(name='Numspell',
version='0.9',
description='A Python module for spelling numbers',
author='Alexei Sholik',
author_email='alcosholik@gmail.com',
url='https://github.com/alco/numspell',
license="MIT",
packages=['nums... | #!/usr/bin/env python
from distutils.core import setup
setup(name='Numspell',
version='0.9',
description='A Python module for spelling numbers',
author='Alexei Sholik',
author_email='alcosholik@gmail.com',
url='https://github.com/alco/numspell',
license="MIT",
packages=['nums... |
Update only phrases with user input | from django.core.management.base import BaseCommand
from django.conf import settings
from ...models import TranscriptPhrase
from ...tasks import assign_current_game
phrase_positive_limit = settings.TRANSCRIPT_PHRASE_POSITIVE_CONFIDENCE_LIMIT
phrase_negative_limit = settings.TRANSCRIPT_PHRASE_NEGATIVE_CONFIDENCE_LIMIT... | from django.core.management.base import BaseCommand
from django.conf import settings
from ...models import TranscriptPhraseVote
from ...tasks import assign_current_game
phrase_positive_limit = settings.TRANSCRIPT_PHRASE_POSITIVE_CONFIDENCE_LIMIT
phrase_negative_limit = settings.TRANSCRIPT_PHRASE_NEGATIVE_CONFIDENCE_L... |
Use color configurations from config file | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import click
def parse_page(page):
"""Parse the command man page."""
with open(page) as f:
lines = f.readlines()
for line in lines:
if line.startswith('#'):
continue
elif line.startsw... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import click
from tldr.config import get_config
def parse_page(page):
"""Parse the command man page."""
colors = get_config()['colors']
with open(page) as f:
lines = f.readlines()
for line in lines:
... |
Allow both -m and --message | from argparse import ArgumentParser
from dodo_commands.framework import Dodo
from dodo_commands.framework.config import Paths
import os
def _args():
parser = ArgumentParser()
parser.add_argument('-m', dest='message')
args = Dodo.parse_args(parser)
return args
if Dodo.is_main(__name__, safe=True):
... | from argparse import ArgumentParser
from dodo_commands.framework import Dodo
from dodo_commands.framework.config import Paths
import os
def _args():
parser = ArgumentParser()
parser.add_argument(
'--message', '-m', dest='message', help='The commit message')
args = Dodo.parse_args(parser)
retur... |
Change email to mail in LDAP | from django.contrib.auth import get_user_model
import ldap
User = get_user_model()
class UChicagoLDAPBackend(object):
LDAP_SERVER = "ldaps://ldap.uchicago.edu:636"
def authenticate(self, cnetid=None, password=None):
if cnetid and password:
cnetid = ldap.filter.escape_filter_chars(cnetid)
try:
conn.simp... | from django.contrib.auth import get_user_model
import ldap
User = get_user_model()
class UChicagoLDAPBackend(object):
LDAP_SERVER = "ldaps://ldap.uchicago.edu:636"
def authenticate(self, cnetid=None, password=None):
if cnetid and password:
cnetid = ldap.filter.escape_filter_chars(cnetid)
try:
conn.simp... |
Add web authentication actor on bootstrap | #!/usr/bin/env python
__author__ = 'Michael Meisinger'
from ion.core.bootstrap_process import BootstrapPlugin, AbortBootstrap
from pyon.public import IonObject, RT
from pyon.util.containers import get_safe
from interface.objects import ActorIdentity, Org
class BootstrapCore(BootstrapPlugin):
"""
Bootstrap ... | #!/usr/bin/env python
__author__ = 'Michael Meisinger'
from ion.core.bootstrap_process import BootstrapPlugin, AbortBootstrap
from pyon.public import IonObject, RT
from pyon.util.containers import get_safe
from interface.objects import ActorIdentity, Org
class BootstrapCore(BootstrapPlugin):
"""
Bootstrap ... |
Use importlib to load custom fields by str | from django import forms
from django.contrib import admin
from setmagic import settings
from setmagic.models import Setting
_denied = lambda *args: False
class SetMagicAdmin(admin.ModelAdmin):
list_display = 'label', 'current_value',
list_editable = 'current_value',
list_display_links = None
has_a... | from django import forms
from django.contrib import admin
from django.utils.importlib import import_module
from setmagic import settings
from setmagic.models import Setting
_denied = lambda *args: False
class SetMagicAdmin(admin.ModelAdmin):
list_display = 'label', 'current_value',
list_editable = 'current... |
Add documentation, tests, fix corr |
import numpy as np
def _check_stc(stc1, stc2):
# XXX What should we check? that the data is having the same size?
if stc1.data.shape != stc2.data.shape:
raise ValueError('Data in stcs must have the same size')
if stc1.times != stc2.times:
raise ValueError('Times of two stcs must match.')
... | # Authors: Yousra Bekhti
# Mark Wronkiewicz <wronk.mark@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
def _check_stc(stc1, stc2):
# XXX What should we check? that the data is having the same size?
if stc1.data.shape != stc2.data.shape:
raise ValueError('Data in stcs must have the... |
Fix migration that adds custom annotation permissions | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
('annotations', '0002_add_volume_uri'),
]
operations = [
migrations.Create... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
('annotations', '0002_add_volume_uri'),
]
operations = [
migrations.Create... |
Remove nargs param so that minutes is an int, not list. | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import argparse
from time import sleep
import pyttsx
parser = argparse.ArgumentParser(description='Presentation timer with spoken warnings.')
parser.add_argument('minutes', type=int, nargs=1, help='Length of talk in minutes')
args = parser.parse_args()
minutes = args.m... | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import argparse
from time import sleep
import pyttsx
parser = argparse.ArgumentParser(description='Presentation timer with spoken warnings.')
parser.add_argument('minutes', type=int, help='Length of talk in minutes')
args = parser.parse_args()
print "Timing a {0}-minut... |
Add intent sessionId siteId & customData | # -*-: coding utf-8 -*-
""" Auto-generated intent class. """
# *****************************************************************************
# *****************************************************************************
# *****************************************************************************
#
# WARNING: THIS ... | # -*-: coding utf-8 -*-
""" Auto-generated intent class. """
# *****************************************************************************
# *****************************************************************************
# *****************************************************************************
#
# WARNING: THIS ... |
Add FixedRankEmbedded to manifolds init. | from .grassmann import Grassmann
from .sphere import Sphere
from .stiefel import Stiefel
from .psd import PSDFixedRank, PSDFixedRankComplex, Elliptope, PositiveDefinite
from .oblique import Oblique
from .euclidean import Euclidean, Symmetric
from .product import Product
__all__ = ["Grassmann", "Sphere", "Stiefel", "PS... | from .grassmann import Grassmann
from .sphere import Sphere
from .stiefel import Stiefel
from .psd import PSDFixedRank, PSDFixedRankComplex, Elliptope, PositiveDefinite
from .oblique import Oblique
from .euclidean import Euclidean, Symmetric
from .product import Product
from .fixed_rank import FixedRankEmbedded
__all_... |
Implement a test for environment.datetime_format | # -*- coding: utf-8 -*-
import pytest
from freezegun import freeze_time
from jinja2 import Environment, exceptions
@pytest.fixture(scope='session')
def environment():
return Environment(extensions=['jinja2_time.TimeExtension'])
@pytest.yield_fixture(autouse=True)
def freeze():
freezer = freeze_time("2015-... | # -*- coding: utf-8 -*-
import pytest
from freezegun import freeze_time
from jinja2 import Environment, exceptions
@pytest.fixture
def environment():
return Environment(extensions=['jinja2_time.TimeExtension'])
@pytest.yield_fixture(autouse=True)
def freeze():
freezer = freeze_time("2015-12-09 23:33:01")
... |
Update new migration to match existing docstring | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(
name='Route',
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(
name='Route',
... |
Make it easier to run |
from remedy.radremedy import create_app
application, manager = create_app('remedy.config.ProductionConfig')
application.debug = True
if __name__ == '__main__':
manager.run()
| #!/usr/bin/env python
from remedy.radremedy import create_app
application, manager = create_app('remedy.config.ProductionConfig')
application.debug = True
if __name__ == '__main__':
manager.run()
|
Update our fake test for debugging purpose. | import sys
import TestSCons
test = TestSCons.TestSCons(match = TestSCons.match_re)
if sys.platform != 'win32':
msg = "Skipping Visual C/C++ test on non-Windows platform '%s'\n" % sys.platform
test.skip_test(msg)
#####
# Test the basics
test.write('SConstruct',"""
import os
env = Environment(tools = ['MSVCC... | import sys
import TestSCons
test = TestSCons.TestSCons(match = TestSCons.match_re)
if sys.platform != 'win32':
msg = "Skipping Visual C/C++ test on non-Windows platform '%s'\n" % sys.platform
test.skip_test(msg)
#####
# Test the basics
test.write('SConstruct',"""
from SCons.Tool.MSVCCommon import FindMSVSB... |
Use Exception instead of StandardError | # Copyright 2016 Red Hat, Inc.
#
# 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 agre... | # Copyright 2016 Red Hat, Inc.
#
# 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 agre... |
Build as 0.0.0-debug for now. | import os.path
from buildlib import *
CONFIGURATION = 'Debug'
project = Project(__file__, 'build')
project.version = '0.1.0'
project.versioninfo = 'alpha'
project.build_number = 0
project.configuration = 'Release'
project.start()
project.clean()
project.write_version('src/.version/VersionInfo.cs')
pr... | import os.path
from buildlib import *
project = Project(__file__, 'build')
project.version = '0.0.0'
project.versioninfo = 'alpha'
project.build_number = 0
project.configuration = 'Debug'
project.start()
project.clean()
project.write_version('src/.version/VersionInfo.cs')
project.msbuild('src/Dolstagis.... |
Remove old commented out code, and update version to 0.3 | # These lines ARE needed, as they actually set up sys.meta_path
from . import PatchWarnings
from . import PatchBaseScientific
from . import PatchScientific
from .log import *
from .utils import open
__version__ = '0.2.3'
# Patch built-in open function
# orig_open = __builtins__['open']
# def patched_open(*args, **k... | # These lines ARE needed, as they actually set up sys.meta_path
from . import PatchWarnings
from . import PatchBaseScientific
from . import PatchScientific
from .log import *
from .utils import open
__version__ = '0.3'
log_init()
|
Bump for icon harmattan build | __pretty_app_name__ = "e**(j pi) + 1 = 0"
__app_name__ = "ejpi"
__version__ = "1.0.7"
__build__ = 2
__app_magic__ = 0xdeadbeef
IS_MAEMO = True
| __pretty_app_name__ = "e**(j pi) + 1 = 0"
__app_name__ = "ejpi"
__version__ = "1.0.7"
__build__ = 3
__app_magic__ = 0xdeadbeef
IS_MAEMO = True
|
Enable GRPC Streaming in Python uppercase sample | import os,sys
sys.path.insert(0, os.path.abspath('.'))
import grpc
import time
import function_pb2_grpc as function
import fntypes_pb2 as types
from concurrent import futures
class StringFunctionServicer(function.StringFunctionServicer):
def Call(self, request, context):
reply = types.Reply()
rep... | import os,sys
sys.path.insert(0, os.path.abspath('.'))
import grpc
import time
import function_pb2_grpc as function
import fntypes_pb2 as types
from concurrent import futures
'''
This method’s semantics are a combination of those of the request-streaming method and the response-streaming method.
It is passed an iter... |
Support environment variables for the extraction | from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default='config',
)
@click.option(
"--database-string",
default="postgresql://grap... | from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
import os
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default="config",
)
@click.option(
"--database-string",
default=os.envi... |
Change admin index title: 'Dashboard' | from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
... | from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
admin.site.index_title = 'Dashboard'
urlpatterns = patterns('',
url(r'^$', 'herana.views.home', name='home'),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^acco... |
Add state change to sphinx plugin. | from docutils.parsers.rst import Directive
from twisted.python.reflect import namedAny
from docutils import nodes
from docutils.statemachine import StringList
class FakeRunner(object):
def __init__(self):
self.commands = []
def run(self, command):
self.commands.extend(command.splitlines())
... | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
from inspect import getsourcefile
from docutils.parsers.rst import Directive
from docutils import nodes
from docutils.statemachine import StringList
from twisted.python.reflect import namedAny
class FakeRunner(object):
def __init__(self):
self... |
Add url for user's profile | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', ... | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', ... |
Add POSIX as supported OS type | from setuptools import setup
def read(f):
try:
with open(f) as file:
return file.read()
except:
return ""
setup(name='shellvars-py',
version='0.1.2',
description='Read environment variables defined in a shell script into Python.',
author_email='aneil.mallavar@gmai... | from setuptools import setup
def read(f):
try:
with open(f) as file:
return file.read()
except:
return ""
setup(name='shellvars-py',
version='0.1.2',
description='Read environment variables defined in a shell script into Python.',
author_email='aneil.mallavar@gmai... |
Add friends to author view. | # Author: Braedy Kuzma
from rest_framework.views import APIView
from .serializers import AuthorSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorView(APIView):
"""
This view gets authors.
"""
def get(self, request, aid):
# Get author
author = ... | # Author: Braedy Kuzma
from rest_framework.views import APIView
from .serializers import AuthorSerializer
from .dataUtils import getAuthor
from .httpUtils import JSONResponse
class AuthorView(APIView):
"""
This view gets authors.
"""
def get(self, request, aid):
# Get author
author = ... |
Use a py3 compatible urlencode |
import urllib
from django import template
register = template.Library()
@register.inclusion_tag('bootstrap_paginator/paginator.html', takes_context=True)
def paginator(context, page=None):
"""
Based on: http://djangosnippets.org/snippets/2680/
To be used in conjunction with the object_list generic view.... |
from django.utils.six.moves.urllib.parse import urlencode
from django import template
register = template.Library()
@register.inclusion_tag('bootstrap_paginator/paginator.html', takes_context=True)
def paginator(context, page=None):
"""
Based on: http://djangosnippets.org/snippets/2680/
To be used in co... |
Fix failing mock of cache backend | # -*- coding: utf-8 -*-
import unittest
from thumbnails.backends import generate_filename, get_thumbnail
from thumbnails.images import SourceFile, Thumbnail
from .compat import mock
class BackendTestCase(unittest.TestCase):
def test_generate_filename(self):
self.assertEqual(
generate_filenam... | # -*- coding: utf-8 -*-
import unittest
from thumbnails.backends import generate_filename, get_thumbnail
from thumbnails.conf import settings
from thumbnails.images import SourceFile, Thumbnail
from .compat import mock
class BackendTestCase(unittest.TestCase):
def test_generate_filename(self):
self.asse... |
Add a descriptive docstring to main cclib module | # This file is part of cclib (http://cclib.sf.net), a library for parsing
# and interpreting the results of computational chemistry packages.
#
# Copyright (C) 2006-2013 the cclib development team
#
# The library is free software, distributed under the terms of
# the GNU Lesser General Public version 2.1 or later. You ... | """cclib is a library for parsing and interpreting results from computational chemistry packages.
The goals of cclib are centered around the reuse of data obtained from various
computational chemistry programs and typically contained in output files. Specifically,
cclib extracts (parses) data from the output files gen... |
Add comments to MapWidget class and MapWidget.render method | from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
def render(self, name, value, attrs=None):
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="tex... | from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
"""Custom map widget for displaying interactive google map to geocode
addresses of learning centers.
This widget displays a readonly input box to store lat+lng data, an empty
help div,... |
Replace base_name with basename base_name is deprecated | import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy... | import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy... |
Move from ps2ascii to ps2txt, for better results | # -*- coding: utf-8 -*-:
import urllib2
import hashlib
import os
def construct_body(link):
if link.content == u'˘':
# this signals that content generation previously failed
return
try:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8'), ('User-agen... | # -*- coding: utf-8 -*-:
import urllib2
import hashlib
import os
def construct_body(link):
if link.content == u'˘':
# this signals that content generation previously failed
return
try:
opener = urllib2.build_opener()
opener.addheaders = [('Accept-Charset', 'utf-8'), ('User-agen... |
Remove raw results from IPWhois object. | """
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from json import dumps
fro... | """
Views for the rdap_explorer project, query app.
"""
import ipwhois
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from json import dumps
fro... |
Fix the feed to work with new versions of django | from django.db.models.query import QuerySet
from django.db.models.fields.related import SingleRelatedObjectDescriptor
class InheritanceQuerySet(QuerySet):
def select_subclasses(self, *subclasses):
if not subclasses:
subclasses = [o for o in dir(self.model)
if isinstance(getattr(self.model, o)... | from django.db.models.query import QuerySet
from django.db.models.fields.related import SingleRelatedObjectDescriptor
from django.core.exceptions import ObjectDoesNotExist
class InheritanceQuerySet(QuerySet):
def select_subclasses(self, *subclasses):
if not subclasses:
subclasses = [o for o in dir(self.mod... |
Add default value for date | from django.db.models import ForeignKey, DateTimeField, ManyToManyField
from yunity.models.entities import User, Location, Mappable, Message
from yunity.models.utils import BaseModel, MaxLengthCharField
from yunity.utils.decorators import classproperty
class Chat(BaseModel):
participants = ManyToManyField(User)
... | from django.db.models import ForeignKey, DateTimeField, ManyToManyField
from yunity.models.entities import User, Location, Mappable, Message
from yunity.models.utils import BaseModel, MaxLengthCharField
from yunity.utils.decorators import classproperty
class Chat(BaseModel):
participants = ManyToManyField(User)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.