Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add a context processor that adds the UserProfile to each context. | from django.conf import settings
from django.contrib.sites.models import Site
from settings import DeploymentType
def default(request):
context = {}
context['DEPLOYMENT'] = settings.DEPLOYMENT
context['current_site'] = Site.objects.get_current()
if settings.DEPLOYMENT != DeploymentType.PRODUCTION:
... | from django.conf import settings
from django.contrib.sites.models import Site
from settings import DeploymentType
def default(request):
context = {}
context['DEPLOYMENT'] = settings.DEPLOYMENT
context['current_site'] = Site.objects.get_current()
if settings.DEPLOYMENT != DeploymentType.PRODUCTION:
... |
Fix typo in for_guest function. | from functools import wraps
from flask import flash, redirect, url_for, session
from app import views
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash("Please login to continue.", "... | from functools import wraps
from flask import flash, redirect, url_for, session
from app import views
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash("Please login to continue.", "... |
Make errors a bit easier to copy | import sys
class ConfigError(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + str(message) + "\n\n")
class ParseError(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + st... | import sys
class GenericException(Exception):
def __init__(self, message):
self.message = message
sys.stdout.write("\nERROR: " + str(message) + "\n\n")
class ConfigError(GenericException):
pass
class ParseError(GenericException):
pass
|
Change test name for the _reinit() method. | from nose.tools import assert_true, assert_false, assert_equal
from ..base import BaseEstimator
class MyEstimator(BaseEstimator):
def __init__(self, l1=0):
self.l1 = l1
def test_renew():
"""Tests that BaseEstimator._new() creates a correct deep copy.
We create an estimator, make a copy of its or... | from nose.tools import assert_true, assert_false, assert_equal
from ..base import BaseEstimator
class MyEstimator(BaseEstimator):
def __init__(self, l1=0):
self.l1 = l1
def test_reinit():
"""Tests that BaseEstimator._new() creates a correct deep copy.
We create an estimator, make a copy of its o... |
Move imports to top of module | # -*- coding: utf-8 -*-
# Copyright 2014 John Vandenberg
# Licensed under the MIT License, see LICENSE file for details.
"""Sphinx epytext support."""
from sphinx_epytext.process_docstring import process_docstring
def setup(app):
"""Sphinx extension setup function.
When the extension is loaded, Sphinx impo... | # -*- coding: utf-8 -*-
# Copyright 2014-5 John Vandenberg
# Licensed under the MIT License, see LICENSE file for details.
"""Sphinx epytext support."""
from sphinx.application import Sphinx
from sphinx_epytext.process_docstring import process_docstring
def setup(app):
"""Sphinx extension setup function.
... |
Call rnasync after truncating db on dev deploy | import logging
from commander.deploy import task
from deploy_base import * # noqa
log = logging.getLogger(__name__)
@task
def database(ctx):
with ctx.lcd(settings.SRC_DIR):
# only ever run this one on demo and dev.
ctx.local("python2.6 manage.py bedrock_truncate_database --yes-i-am-sure")
... | import logging
from commander.deploy import task
from deploy_base import * # noqa
log = logging.getLogger(__name__)
@task
def database(ctx):
with ctx.lcd(settings.SRC_DIR):
# only ever run this one on demo and dev.
ctx.local("python2.6 manage.py bedrock_truncate_database --yes-i-am-sure")
... |
Remove prefix from URL paths | """
URLconf for CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.decorators.cache import never_cache
from mama_cas.views import login
from mama_cas.views import logout
from mama_cas.views import validate
from mama_cas.views ... | """
URLconf for CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.decorators.cache import never_cache
from mama_cas.views import login
from mama_cas.views import logout
from mama_cas.views import validate
from mama_cas.views ... |
Set the default device to native in Python binding | from xchainer._core import * # NOQA
_global_context = Context()
_global_context.get_backend('native')
set_global_default_context(_global_context)
| from xchainer._core import * # NOQA
_global_context = Context()
set_global_default_context(_global_context)
set_default_device('native')
|
Allow passing None for function, and use the executable name in that case. Save error list anonymously | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This software is under a BSD license. See LICENSE.txt for details.
__all__ = ["DTErrorMessage", "DTSaveError"]
import sys
_errors = []
def DTErrorMessage(fcn, msg):
"""Accumulate a message and echo to standard error.
Arguments:
fcn -- typically a fu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This software is under a BSD license. See LICENSE.txt for details.
__all__ = ["DTErrorMessage", "DTSaveError"]
import sys
import os
_errors = []
def DTErrorMessage(fcn, msg):
"""Accumulate a message and echo to standard error.
Arguments:
fcn -- typi... |
Remove "temp" from temporal workers, as they may have max_seconds_idle to None, not being temp at all | class WorkerPoolNameGenerator:
def __init__(self, base_name: str, max_workers: int, max_seconds_idle: int):
self.base_name = base_name
self.max_workers = max_workers
self.max_seconds_idle = max_seconds_idle
def get_name(self, number: int, is_temporal: bool = False):
name = self.... | class WorkerPoolNameGenerator:
def __init__(self, base_name: str, max_workers: int, max_seconds_idle: int):
self.base_name = base_name
self.max_workers = max_workers
self.max_seconds_idle = max_seconds_idle
def get_name(self, number: int, is_temporal: bool = False):
name = self.... |
Clean titles before querying the DB | import MySQLdb
import mwparserfromhell
class Plugin():
def get_wikicode(self, title):
# TODO Make this a conf
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="BigData")
cursor = db.cursor()
cursor.execute("""
SELECT old_text
FROM text
INNER... | import MySQLdb
import mwparserfromhell
class Plugin():
def get_wikicode(self, title):
# TODO Make this a conf
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="BigData")
clean_title = title.replace(" ", "_")
cursor = db.cursor()
cursor.execute("""
... |
Allow test client to be created with kwargs | from elasticsearch.helpers.test import get_test_client, ElasticsearchTestCase as BaseTestCase
client = None
def get_client():
global client
if client is not None:
return client
# try and locate manual override in the local environment
try:
from test_elasticsearch.local import get_clie... | from elasticsearch.helpers.test import get_test_client, ElasticsearchTestCase as BaseTestCase
client = None
def get_client(**kwargs):
global client
if client is not None and not kwargs:
return client
# try and locate manual override in the local environment
try:
from test_elasticsearc... |
Allow render to take a template different from the default one. | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... |
Fix error when making first migrations in a new project | from django.views import generic
from django.db.models import Sum
from cassupload import models
class CassListView(generic.ListView):
template_name = 'casslist/index.html'
context_object_name = 'cass_sound_list'
total_plays = models.Sound.objects.all().aggregate(Sum('play_count'))['play_count__sum']
... | from django.db import OperationalError
from django.views import generic
from django.db.models import Sum
from cassupload import models
class CassListView(generic.ListView):
template_name = 'casslist/index.html'
context_object_name = 'cass_sound_list'
try:
total_plays = models.Sound.objects.all()... |
Add better exception to viewer resolver | from django.contrib.auth import get_user_model
from graphene import AbstractType, Field, String
from users.jwt_util import get_token_user_id
from .definitions import Viewer
class UserQueries(AbstractType):
viewer = Field(Viewer)
@staticmethod
def resolve_viewer(self, args, context, info):
try:
... | from django.contrib.auth import get_user_model
from graphene import AbstractType, Field, String
from users.jwt_util import get_token_user_id
from .definitions import Viewer
class UserQueries(AbstractType):
viewer = Field(Viewer)
@staticmethod
def resolve_viewer(self, args, context, info):
users ... |
Add parent directory in path by default | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import os.path
import sys
if __name__ == "__main__":
#Include parent directory in the path by default
path = os.path.abspath('../')
if path not in sys.path:
sys.path.append(path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "observatory.settings")
from... |
Correct unicode for access tokens | import datetime
import functools
from django.db import models
from django.utils.crypto import get_random_string
from .managers import GroupManager
class Group(models.Model):
"""
Instances must be created using ``Group.objects.create_group`` to ensure
Stripe is configured correctly.
"""
name = mo... | import datetime
import functools
from django.db import models
from django.utils.crypto import get_random_string
from .managers import GroupManager
class Group(models.Model):
"""
Instances must be created using ``Group.objects.create_group`` to ensure
Stripe is configured correctly.
"""
name = mo... |
Introduce Markup abstract base class | """ Various kinds of markup (static content) widgets.
"""
from __future__ import absolute_import
from ...properties import abstract
from ...properties import Int, String
from ..widget import Widget
class Paragraph(Widget):
""" A block (paragraph) of text.
"""
text = String(help="""
The contents of ... | """ Various kinds of markup (static content) widgets.
"""
from __future__ import absolute_import
from ...properties import abstract
from ...properties import Int, String
from ..widget import Widget
@abstract
class Markup(Widget):
""" Base class for HTML markup widget models. """
class Paragraph(Markup):
"""... |
Add url logging in google shortener | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
... | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
... |
Hide unnecessary fields in the admins | from django.contrib import admin
from nested_admin.nested import NestedAdmin, NestedStackedInline
from democracy import models
# Inlines
class HearingImageInline(NestedStackedInline):
model = models.HearingImage
extra = 0
class SectionImageInline(NestedStackedInline):
model = models.SectionImage
... | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from nested_admin.nested import NestedAdmin, NestedStackedInline
from democracy import models
# Inlines
class HearingImageInline(NestedStackedInline):
model = models.HearingImage
extra = 0
exclude = ("public", "tit... |
Fix error handling on aggregate status report | UNDERSTOCK_THRESHOLD = 0.5 # months
OVERSTOCK_THRESHOLD = 2. # months
def months_of_stock_remaining(stock, daily_consumption):
try:
return stock / (daily_consumption * 30)
except (TypeError, ZeroDivisionError):
return None
def stock_category(stock, daily_consumption):
if stock is None:... | from decimal import Decimal
UNDERSTOCK_THRESHOLD = 0.5 # months
OVERSTOCK_THRESHOLD = 2. # months
def months_of_stock_remaining(stock, daily_consumption):
if daily_consumption:
return stock / Decimal((daily_consumption * 30))
else:
return None
def stock_category(stock, daily_consumption):... |
Add dateutils to the requirements | import sys
from setuptools import setup, find_packages
import populous
requirements = [
"click",
"cached-property",
"fake-factory",
]
if sys.version_info < (3, 2):
requirements.append('functools32')
setup(
name="populous",
version=populous.__version__,
url=populous.__url__,
descript... | import sys
from setuptools import setup, find_packages
import populous
requirements = [
"click",
"cached-property",
"fake-factory",
"dateutils"
]
if sys.version_info < (3, 2):
requirements.append('functools32')
setup(
name="populous",
version=populous.__version__,
url=populous.__url... |
Increment minor version once more | import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tes... | import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tes... |
Fix TEMPLATES warning on Django 1.9 | import dj_database_url
DATABASES = {
'default': dj_database_url.config(
default='postgres://localhost/test_utils',
),
}
INSTALLED_APPS = (
'incuna_test_utils',
'tests',
'feincms.module.page',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'... | import dj_database_url
DATABASES = {
'default': dj_database_url.config(
default='postgres://localhost/test_utils',
),
}
INSTALLED_APPS = (
'incuna_test_utils',
'tests',
'feincms.module.page',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'... |
Allow rechttp prefix for source field. | import re
from django.core import validators
class URLValidator(validators.URLValidator):
"""Custom url validator to include git urls and urls with http+ like prefixes
"""
regex = re.compile(
r'^(?:(?:(?:(?:http|git|hg)\+)?' # optional http+ or git+ or hg+
r'(?:http|ftp|)s?|git)://|git... | import re
from django.core import validators
class URLValidator(validators.URLValidator):
"""Custom url validator to include git urls and urls with http+ like prefixes
"""
regex = re.compile(
r'^(?:(?:(?:(?:http|git|hg|rechttp)\+)?' # optional http+ or git+ or hg+
r'(?:http|ftp|)s?|git... |
Fix for PythonAnywhere LoadBalancer IP | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ephemeral by st0le
# quick way share text between your network devices
from flask import Flask, request, render_template, redirect, url_for
db = {}
app = Flask(__name__)
@app.route('/')
def get():
ip = request.remote_addr
return render_template("index.html", t... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ephemeral by st0le
# quick way share text between your network devices
from flask import Flask, request, render_template, redirect, url_for
db = {}
app = Flask(__name__)
def get_client_ip(request):
# PythonAnywhere.com calls our service through a loabalancer
#... |
Add hypothesis test to randomly generate CompressionParameters | try:
import unittest2 as unittest
except ImportError:
import unittest
import zstd
class TestCompressionParameters(unittest.TestCase):
def test_init_bad_arg_type(self):
with self.assertRaises(TypeError):
zstd.CompressionParameters()
with self.assertRaises(TypeError):
... | try:
import unittest2 as unittest
except ImportError:
import unittest
try:
import hypothesis
import hypothesis.strategies as strategies
except ImportError:
hypothesis = None
import zstd
class TestCompressionParameters(unittest.TestCase):
def test_init_bad_arg_type(self):
with self.ass... |
Remove `pkg_resources` from the top-level package | import pkg_resources
__author__ = "Martin Larralde <martin.larralde@embl.de>"
__license__ = "MIT"
__version__ = pkg_resources.resource_string(__name__, "_version.txt").decode('utf-8').strip()
from .ontology import Ontology # noqa: F401
from .term import Term # noqa: F401
from .definition import Definition # noqa: ... | import pkg_resources
__author__ = "Martin Larralde <martin.larralde@embl.de>"
__license__ = "MIT"
__version__ = (
__import__('pkg_resources')
.resource_string(__name__, "_version.txt")
.decode('utf-8')
.strip()
)
from .ontology import Ontology # noqa: F401
from .term import Term # noqa: F401
from .d... |
Add tools general imports to talkbox namespace. | from lpc import *
import lpc
__all__ = lpc.__all__
| from lpc import *
import lpc
__all__ = lpc.__all__
from tools import *
import tools
__all__ += tools.__all__
|
Add a route to admin/news | from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user
from . import admin
from .forms import ProfileForm
from .. import db
from ..models import User
@admin.route('/')
@login_required
def index():
return render_template('admin/user.html', user=... | from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user
from . import admin
from .forms import ProfileForm
from .. import db
from ..models import User
@admin.route('/')
@login_required
def index():
return render_template('admin/user.html', user=... |
Fix config file path error on the server | # coding: utf-8
from flask import Flask, abort, request, redirect, render_template, url_for
from log import log
import util
app = Flask(__name__)
app.config.from_pyfile('config.cfg', silent=True)
@app.route('/')
def home():
log.info('Fetching demo gist.')
gist_id = '5123482'
gist = util.get_gist_by_id(gis... | # coding: utf-8
from flask import Flask, abort, request, redirect, render_template, url_for
from log import log
import util
import os
app = Flask(__name__)
app.config.from_pyfile(os.path.join(os.path.dirname(__file__), 'config.cfg'), silent=True)
@app.route('/')
def home():
log.info('Fetching demo gist.')
gis... |
Add indicator for how many datapoints have been loaded | import csv
from chemtools.ml import get_decay_feature_vector
from chemtools.mol_name import get_exact_name
from models import DataPoint
def main(path):
with open(path, "r") as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
points = []
for row in reader:
if... | import csv
from chemtools.ml import get_decay_feature_vector
from chemtools.mol_name import get_exact_name
from models import DataPoint
def main(path):
with open(path, "r") as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
points = []
count = 0
for row in read... |
Make transpiler test remove files if they already exist | import os
import unittest
import transpiler
class TestTranspiler:
def test_transpiler_creates_files_without_format(self):
transpiler.main(["--output-dir", "/tmp"])
assert os.path.isfile("/tmp/auto_functions.cpp")
assert os.path.isfile("/tmp/auto_functions.h")
def test_transpiler_cre... | import os
import unittest
import transpiler
class TestTranspiler:
def test_transpiler_creates_files_without_format(self):
try:
os.remove("/tmp/auto_functions.cpp")
os.remove("/tmp/auto_functions.h")
except FileNotFoundError:
pass
transpiler.main(["--ou... |
Add text only mode to get game modes | from flask.views import MethodView
from flask_helpers.build_response import build_response
from flask_helpers.ErrorHandler import ErrorHandler
from python_cowbull_game.GameObject import GameObject
class GameModes(MethodView):
def get(self):
digits = GameObject.digits_used
guesses = GameObject.gues... | from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response
from flask_helpers.ErrorHandler import ErrorHandler
from python_cowbull_game.GameObject import GameObject
class GameModes(MethodView):
def get(self):
textonly = request.args.get('textmode',... |
Replace double quote by simple quote, no need interpolation | #! /usr/bin/env python2.7
from collections import Counter
from pprint import pprint
from re import search
from sys import argv
def count_extension(filename):
with open(filename, 'r') as file:
# New empty counter.
ext_dict = Counter()
for line in file:
# Remove newlines / carria... | #! /usr/bin/env python2.7
from collections import Counter
from pprint import pprint
from re import search
from sys import argv
def count_extension(filename):
with open(filename, 'r') as file:
# New empty counter.
ext_dict = Counter()
for line in file:
# Remove newlines / carria... |
Make sure to use the relative path for all C extension source files. Otherwise distuils' MSVC compiler generates some potentially long (too long for Windows) pathnames in the build\temp dir for various compiler artifacts. (This was particularly problematic in Jenkins, where having multiple configuration matrix axes can... | from distutils.core import Extension
from os.path import dirname, join
def get_extensions():
ROOT = dirname(__file__)
return [
Extension('astropy.utils._compiler',
[join(ROOT, 'src', 'compiler.c')])
]
| from distutils.core import Extension
from os.path import dirname, join, relpath
def get_extensions():
ROOT = dirname(__file__)
return [
Extension('astropy.utils._compiler',
[relpath(join(ROOT, 'src', 'compiler.c'))])
]
|
Fix typo in inventory API test script. | #!/usr/bin/env python
import json
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-l', '--list', default=False, dest="list_hosts", action="store_true")
parser.add_option('-H', '--host', default=None, dest="host")
parser.add_option('-e', '--extra-vars', default=None, dest="extr... | #!/usr/bin/env python
import json
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-l', '--list', default=False, dest="list_hosts", action="store_true")
parser.add_option('-H', '--host', default=None, dest="host")
parser.add_option('-e', '--extra-vars', default=None, dest="extr... |
Revert "use pop instead of get because it doens't cause uncaught exceptions." | from core.build.subnet import build_subnet
from core.network.models import Network
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse
import pdb
def build_network(request, network_pk):
network = get_object_or_404(Network, pk=network_pk)
if request.GET.pop(... | from core.build.subnet import build_subnet
from core.network.models import Network
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse
import pdb
def build_network(request, network_pk):
network = get_object_or_404(Network, pk=network_pk)
if request.GET.get(... |
Add test for app creation with config file. | from marvin import create_app
import unittest
class AppCreationTest(unittest.TestCase):
def test_create_app(self):
app = create_app(MY_CONFIG_VALUE='foo')
self.assertEqual(app.config['MY_CONFIG_VALUE'], 'foo')
| from marvin import create_app
import os
import tempfile
import unittest
class AppCreationTest(unittest.TestCase):
def setUp(self):
self.config_file = tempfile.NamedTemporaryFile(delete=False)
self.config_file.write('OTHER_CONFIG = "bar"'.encode('utf-8'))
self.config_file.close()
def... |
Revert r67, which was not the changeset intended for commit. | #!/usr/bin/env python
import sys
sys.path.append("../zvm")
from zmemory import ZMemory
from zlexer import ZLexer
story = file("../stories/zork.z1").read()
mem = ZMemory(story)
lexer = ZLexer(mem)
print "This story is z version", mem.version
print "Standard dictionary:"
print " word separators are", lexer._separ... | #!/usr/bin/env python
import sys
sys.path.append("../zvm")
from zmemory import ZMemory
from zlexer import ZLexer
story = file("../stories/zork.z1").read()
mem = ZMemory(story)
lexer = ZLexer(mem)
print "This story is z version", mem.version
print "Standard dictionary:"
print " word separators are", lexer._separ... |
Improve parsing of short strings by adding period. | from ufal.udpipe import Model, Pipeline, ProcessingError
class Parser:
MODELS = {
"swe": "data/swedish-ud-2.0-170801.udpipe",
}
def __init__(self, language):
model_path = self.MODELS.get(language, None)
if not model_path:
raise ParserException("Cannot find model for lan... | import re
from ufal.udpipe import Model, Pipeline, ProcessingError
class Parser:
MODELS = {
"swe": "data/swedish-ud-2.0-170801.udpipe",
}
def __init__(self, language):
model_path = self.MODELS.get(language, None)
if not model_path:
raise ParserException("Cannot find mod... |
Restructure session handling in sqlalchemy. | import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import ConvertRequest, Base
class Database(object):
db_connection_string = None
engine = None
Session = None
def __init__(self, path, echo):
if not os.path.exists(os.path.dirname(path)):
... | import os
import sqlite3
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import ConvertRequest, Base
class Database(object):
db_connection_string = None
engine = None
session_maker = None
def __init__(self, path, echo):
if not os.path.exists(os.pat... |
Fix spacing. Add docstrings to helpers | import os
import sys
import platform
# Various helpers for the build scripts
def get_lib_dir():
if sys.platform.startswith("win"):
if platform.architecture()[0] == '32bit':
# 32 bit
return ['prebuilt-x86/lib']
else:
# 64 bit
return ['prebuilt-x64/lib... | import os
import sys
import platform
# Various helpers for the build scripts
def get_lib_dir():
"""Return the library path for SDL and other libraries.
Assumes we're using the pygame prebuilt zipfile on windows"""
if sys.platform.startswith("win"):
if platform.architecture()[0] == '32bit':
... |
Fix SHARE capitalization, use self-referential query | from __future__ import unicode_literals
import logging
from django.core.management.base import BaseCommand
from scripts import utils as script_utils
from osf.models import PreprintService
from website.preprints.tasks import on_preprint_updated
logger = logging.getLogger(__name__)
def update_share_preprint_modified_... | from __future__ import unicode_literals
import logging
from django.core.management.base import BaseCommand
from django.db.models import F
from scripts import utils as script_utils
from osf.models import PreprintService
from website.preprints.tasks import on_preprint_updated
logger = logging.getLogger(__name__)
def ... |
Make base_url a global variable | # -*- coding: utf-8 -*-
class Grok(object):
"""stats.grok.se article statistics."""
def __init__(self, title, site):
self.site = site
self.title = title
def _make_url(self, year, month):
"""Make the URL to the JSON output of stats.grok.se service."""
base_url = "http://s... | # -*- coding: utf-8 -*-
BASE_URL = "http://stats.grok.se/json/"
class Grok(object):
"""stats.grok.se article statistics."""
def __init__(self, title, site):
self.site = site
self.title = title
def _make_url(self, year, month):
"""Make the URL to the JSON output of stats.grok.se... |
Print something from stats script so you can see it works! | import urllib2
import json
import sys
from statsd import statsd
statsd.connect('localhost', 8125)
topology = sys.argv[1]
toporoot = sys.argv[2]
topic = sys.argv[3]
state = urllib2.urlopen(
"http://localhost:9000/api/status?toporoot={}&topic={}".format(
toporoot, topic
)
).read()
data = json.loads(st... | import urllib2
import json
import sys
from statsd import statsd
statsd.connect('localhost', 8125)
topology = sys.argv[1]
toporoot = sys.argv[2]
topic = sys.argv[3]
state = urllib2.urlopen(
"http://localhost:9000/api/status?toporoot={}&topic={}".format(
toporoot, topic
)
).read()
data = json.loads(st... |
Allow for directories argument to be optional | """A set of functions to standardize some options for python scripts."""
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
----------
parser : `ArgumentParser`
The parser to be modified.
additional_d... | """A set of functions to standardize some options for python scripts."""
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
----------
parser : `ArgumentParser`
The parser to be modified.
additional_d... |
Remove old tests and add TODOs | #!/usr/bin/python3
import unittest
import ok
import sys
class TestProtocol(ok.Protocol):
name = "test"
def __init__(self, args, src_files):
ok.Protocol.__init__(args, src_files)
self.called_start = 0
self.called_interact = 0
def on_start(self):
self.called_start += 1
... | #!/usr/bin/python3
import unittest
import ok
import sys
class TestProtocol(ok.Protocol):
name = "test"
def __init__(self, args, src_files):
ok.Protocol.__init__(args, src_files)
self.called_start = 0
self.called_interact = 0
def on_start(self):
self.called_start += 1
... |
Add *.json to the list of artifacts backed up by Workspace Runner. | #!/usr/bin/env python
import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products/ver... | #!/usr/bin/env python
import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products/ver... |
Use PY2 check instead of PY3 check. | # -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY3 = sys.version_info[0] == 3
if PY3:
import configparser as ConfigParser
else:
import ConfigParser
if PY3:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if PY3:
from urll... | # -*- coding: utf-8 -*-
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
import configparser as ConfigParser
else:
import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote
else:
from urllib import quote as url_quote
if not PY2:
... |
Add a crappy form that will hopefully inspire me to write something else. Tired of staring into space. | """
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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... |
Test that self-repair endpoint does not set cookies | from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.djan... | from django.core.urlresolvers import reverse
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
class TestSelfRepair:
def test_url_is_right(self):
url = reverse('selfrepair:index', args=['en-US'])
assert url == '/en-US/repair'
@pytest.mark.djan... |
Fix Activity CSV field test | import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activ... | import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activ... |
Change current language only within context when building search indexes | from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated title... | from django.apps import AppConfig
from django.db.models.signals import post_save
from django.utils import translation
from django.conf import settings
from watson import search
from localized_fields.fields import LocalizedField
class MaterialSearchAdapter(search.SearchAdapter):
"""
Dumps all translated title... |
Adjust pulling tags in CI | #!/usr/bin/env python3
import os
import subprocess
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list... | #!/usr/bin/env python3
import os
import subprocess
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git fetch --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(lis... |
Fix missing parentheses in exception | # -*- coding: utf-8 -*-
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def enabled(test... | # -*- coding: utf-8 -*-
import ssl
from src.testers.decorators import requires_userinfo
@requires_userinfo
def available(test):
"""
Check if MongoDB is compiled with OpenSSL support
"""
return 'OpenSSLVersion' in test.tester.info \
or 'openssl' in test.tester.info
@requires_userinfo
def... |
Change record output to strict GeoJSON. | # The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='sto... | # The Fiona data tool.
if __name__ == '__main__':
import argparse
import fiona
import json
import pprint
import sys
parser = argparse.ArgumentParser(
description="Serialize a file to GeoJSON or view its description")
parser.add_argument('-i', '--info',
action='sto... |
Expand default test years for PUDL to 2011-2015 | """Tests excercising the pudl module for use with PyTest."""
import pytest
import pudl.pudl
import pudl.ferc1
import pudl.constants as pc
def test_init_db():
"""Create a fresh PUDL DB and pull in some FERC1 & EIA923 data."""
pudl.ferc1.init_db(refyear=2015,
years=range(2007, 2016),
... | """Tests excercising the pudl module for use with PyTest."""
import pytest
import pudl.pudl
import pudl.ferc1
import pudl.constants as pc
def test_init_db():
"""Create a fresh PUDL DB and pull in some FERC1 & EIA923 data."""
pudl.ferc1.init_db(refyear=2015,
years=range(2007, 2016),
... |
Use tracer in debug IR interpretation mode | # -*- coding: utf-8 -*-
"""
IR interpreter. Run a series of translation phases on a numba function, and
interpreter the IR with the arguments.
"""
from __future__ import print_function, division, absolute_import
from numba2 import typeof, jit
from numba2.compiler.frontend import translate, interpret
from numba2.pipe... | # -*- coding: utf-8 -*-
"""
IR interpreter. Run a series of translation phases on a numba function, and
interpreter the IR with the arguments.
"""
from __future__ import print_function, division, absolute_import
from numba2 import typeof, jit
from numba2.compiler.frontend import translate, interpret
from numba2.pipe... |
Clear sites cache on SiteInfo save | from django.db import models
from django.contrib.sites.models import Site
class DatedModel(models.Model):
created_time = models.DateTimeField(auto_now_add=True, null=True)
updated_time = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
get_latest_by = 'updated_ti... | from django.db import models
from django.contrib.sites.models import Site
class DatedModel(models.Model):
created_time = models.DateTimeField(auto_now_add=True, null=True)
updated_time = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
get_latest_by = 'updated_ti... |
Test transaction list in table is ordered | from __future__ import absolute_import
import captable
import unittest
import datetime
from ._helpers import StubTransaction
class TransactionTests(unittest.TestCase):
"""Test adding transactions and processing them"""
def setUp(self):
"""Initialize a blank captable and authorize multiple classes of... | from __future__ import absolute_import
import captable
import unittest
import datetime
from ._helpers import StubTransaction
class TransactionTests(unittest.TestCase):
"""Test adding transactions and processing them"""
def setUp(self):
"""Initialize a blank captable and authorize multiple classes of... |
Remove the backwards compatibility as it wasn't working for some reason. | """
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '1.3.4'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFV... | """
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '1.3.4'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFV... |
Fix wrong url regxp for accoutns | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^', include('api.urls')),
url('r^accounts/', include('accounts.urls')),
url('', include('social.apps.django_app.urls', namespace='social'... | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^', include('api.urls')),
url(r'^accounts/', include('accounts.urls')),
url('', include('social.apps.django_app.urls', namespace='social'... |
Make aether package initialisation work for both Python 3.7 and 3.8. | import os
import platform
import sys
if platform.system() == "Windows":
os.add_dll_directory(os.path.join(sys.prefix, "Library", "bin"))
| import os
import platform
import sys
if platform.system() == "Windows":
version_info = sys.version_info
if sys.version_info.major == 3 && sys.version_info.minor < 8:
sys.path.append(os.path.join(sys.prefix, "Library", "bin"))
else:
os.add_dll_directory(os.path.join(sys.prefix, "Library", "... |
Handle TZ change in iso8601 >=0.1.12 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... |
Set dummy address info for tests. | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Alexander Shorin
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
class DummyMixIn(object):
_input_buffer = ''
def flush(self):
pass
def close(sel... | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Alexander Shorin
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
class DummyMixIn(object):
_input_buffer = ''
addr = ('localhost', '15200')
def flush(self... |
Fix bug with SQLAlchemy, change TEXT to STRING | from app import db
class Sprinkler(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text(25))
status = db.Column(db.Text(25))
flow = db.Column(db.Integer)
moisture = db.Column(db.Integer)
def __init__(self, name, status, flow, moisture):
self.name = name
... | from app import db
class Sprinkler(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(25))
status = db.Column(db.String(25))
flow = db.Column(db.Integer)
moisture = db.Column(db.Integer)
def __init__(self, name, status, flow, moisture):
self.name = name
... |
Change version back to 0.2.0a post-release. | from setuptools import setup, find_packages
setup(
name='vumi-wikipedia',
version='0.1.2',
description='Vumi Wikipedia App',
packages=find_packages(),
include_package_data=True,
install_requires=[
'vumi>=0.5',
'unidecode',
],
url='http://github.com/praekelt/vumi-wikiped... | from setuptools import setup, find_packages
setup(
name='vumi-wikipedia',
version='0.2.0a',
description='Vumi Wikipedia App',
packages=find_packages(),
include_package_data=True,
install_requires=[
'vumi>=0.5',
'unidecode',
],
url='http://github.com/praekelt/vumi-wikipe... |
Fix config name error for autocloud service | # -*- 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', ... | # -*- 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 = ConfigParser.RawConfigParser()
config.read(name)
KO... |
Include README as long description. | # -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='Weitersager',
version='0.1',
description='A proxy to forward messages received via HTTP to to IRC',
author='Jochen Kupperschmidt',
author_email='homework@nwsnet.de',
url='http://homework.nwsnet.de/',
)
| # -*- coding: utf-8 -*-
import codecs
from setuptools import setup
with codecs.open('README.rst', encoding='utf-8') as f:
long_description = f.read()
setup(
name='Weitersager',
version='0.1',
description='A proxy to forward messages received via HTTP to to IRC',
long_description=long_descripti... |
Add 'jump consistent hash' keyword. | from __future__ import print_function
import sys
from setuptools import setup
if sys.version_info < (3, 2):
print('ERROR: jump-consistent-hash requires Python version 3.2 or newer.',
file=sys.stderr)
sys.exit(1)
setup(name='jump_consistent_hash',
version='1.0.3',
description='Impleme... | from __future__ import print_function
import sys
from setuptools import setup
if sys.version_info < (3, 2):
print('ERROR: jump-consistent-hash requires Python version 3.2 or newer.',
file=sys.stderr)
sys.exit(1)
setup(name='jump_consistent_hash',
version='1.0.3',
description='Impleme... |
Remove useless requirement on Python 3.2+ | # -*- coding: utf-8 -*-
import io
from setuptools import setup, find_packages
setup(
name='django-pipeline',
version='1.5.2',
description='Pipeline is an asset packaging library for Django.',
long_description=io.open('README.rst', encoding='utf-8').read() + '\n\n' +
io.open('HISTORY.rst', enc... | # -*- coding: utf-8 -*-
import io
from setuptools import setup, find_packages
install_requires = []
try:
from concurrent import futures
except ImportError:
futures = None
install_requires.append('futures>=2.1.3')
setup(
name='django-pipeline',
version='1.5.2',
description='Pipeline is an asset... |
Upgrade dependency prompt-toolkit to ==1.0 | import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_... | import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_... |
Prepare for development of next release | '''
XBMC Addon Manager
------------------
A CLI utility for searching and listing XBMC Addon Repositories.
Setup
`````
::
$ pip install xam
$ xam --help
Links
`````
* `website <http://github.com/jbeluch/xam/>`_
'''
from setuptools import setup
def get_requires():
'''If python > 2.7, argparse and Ord... | '''
XBMC Addon Manager
------------------
A CLI utility for searching and listing XBMC Addon Repositories.
Setup
`````
::
$ pip install xam
$ xam --help
Links
`````
* `website <http://github.com/jbeluch/xam/>`_
'''
from setuptools import setup
def get_requires():
'''If python > 2.7, argparse and Ord... |
Make small molecules read only | from unittest import TestCase
import unittest.mock
from molecupy.structures import Model, AtomicStructure, SmallMolecule
class ModelTest(TestCase):
def setUp(self):
self.small_molecule1 = unittest.mock.Mock(spec=SmallMolecule)
self.small_molecule2 = unittest.mock.Mock(spec=SmallMolecule)
class ... | from unittest import TestCase
import unittest.mock
from molecupy.structures import Model, AtomicStructure, SmallMolecule
class ModelTest(TestCase):
def setUp(self):
self.small_molecule1 = unittest.mock.Mock(spec=SmallMolecule)
self.small_molecule2 = unittest.mock.Mock(spec=SmallMolecule)
class ... |
Make SimRun a new-style Python class. | #!/usr/bin/env python
from .s_ref import RefTypes
import s_options as o
class SimRun:
def __init__(self, options = None, mode = None):
# the options and mode
if options is None:
options = o.default_options[mode]
self.options = options
self.mode = mode
self._exits = [ ]
self._refs = { }
self.option... | #!/usr/bin/env python
from .s_ref import RefTypes
import s_options as o
class SimRun(object):
def __init__(self, options = None, mode = None):
# the options and mode
if options is None:
options = o.default_options[mode]
self.options = options
self.mode = mode
self._exits = [ ]
self._refs = { }
sel... |
Fix some typos in concurrency test | import unittest
from requests import Request
from unittest.mock import patch, MagicMock
from concurrency.get_websites import load_url as load_url
class MockResponse():
def __init__(self):
self.text = "foo"
self.status_code = 200
class TestGetWebsites(unittest.TestCase):
@patch('concurrency.g... | import unittest
from requests import Request
from unittest.mock import patch, MagicMock
from concurrency.get_websites import load_url as load_url
class MockResponse():
def __init__(self):
self.text = "foo"
self.status_code = 200
class TestGetWebsites(unittest.TestCase):
@patch('concurrency.g... |
Replace abc.abstractproperty with property and abc.abstractmethod | # 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 agreed to in writing, software
# distributed under th... | # 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 agreed to in writing, software
# distributed under th... |
Create TaggedImage, unique marker for image | # -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.managers import TaggableManager
from opps.core.models import Publishable
def get_file_path(instance, filenam... | # -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.models import TaggedItemBase
from taggit.managers import TaggableManager
from opps.core.models import Publisha... |
Set with add, update, discard, remove, union, intersection, difference | # Set
#Removes the duplicates from the given group of values to create the set.
flight_set = {500,520,600,345,520,634,600,500,200,200}
print("Flight Set : ", flight_set)
# Converting List into Set
passengers_list=["George", "Annie", "Jack", "Annie", "Henry", "Helen", "Maria", "George", "Jack", "Remo"]
unique_passenger... | # Set
#Removes the duplicates from the given group of values to create the set.
flight_set = {500,520,600,345,520,634,600,500,200,200}
print("Flight Set : ", flight_set)
# Converting List into Set
passengers_list=["George", "Annie", "Jack", "Annie", "Henry", "Helen", "Maria", "George", "Jack", "Remo"]
unique_passenger... |
Return jsonapi error when parsing filters failed. | import contextlib
import flask
class FilterSchema:
def __init__(self, fields: dict):
self.fields = fields
def parse(self):
result = {}
for name, field in self.fields.items():
with contextlib.suppress(KeyError):
result[name] = field.parse(name)
retu... | import contextlib
import flask
from flask_jsonapi import exceptions
class FilterSchema:
def __init__(self, fields: dict):
self.fields = fields
def parse(self):
result = {}
for name, field in self.fields.items():
with contextlib.suppress(KeyError):
result[... |
Fix media-combining in formsets on Django 2.2 | """
Internal utils
"""
import django
def add_media(dest, media):
"""
Optimized version of django.forms.Media.__add__() that doesn't create new objects.
Only required for Django < 2.0
"""
if django.VERSION >= (2, 0):
combined = dest + media
dest._css = combined._css
dest._j... | """
Internal utils
"""
import django
def add_media(dest, media):
"""
Optimized version of django.forms.Media.__add__() that doesn't create new objects.
"""
if django.VERSION >= (2, 2):
dest._css_lists += media._css_lists
dest._js_lists += media._js_lists
elif django.VERSION >= (2, ... |
Configure the command that's executed. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, render_template
from sh import git
app = Flask(__name__)
version = git("rev-parse", "--short", "HEAD").strip()
@app.route("/", methods=["GET"])
def status():
"""
Status check. Display the current version of heatlamp, some basic
diag... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from flask import Flask, render_template
from sh import git
app = Flask(__name__)
version = git("rev-parse", "--short", "HEAD").strip()
command = os.getenv("HEATLAMP_COMMAND")
def validate():
"""
Validate the application configuration befor... |
Change imports to work with new scheme | import hive
import threading
import time
import sys
import worker
# import pash from another directory
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test():
apiary = hive.Hive()
apiary.crea... | import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test():
apiary = hive.Hive()
apiary.create_quee... |
Refactor get_console_size to close file after reading | import os
def get_console_size():
'''
returns no of rows, no of cols
'''
return map(int, os.popen('stty size', 'r').read().split())
def get_print_size_for_repo(data):
name, lang, star = [0]*3
for each in data:
repo_name, desc, [stars, language] = each
name = max(len(repo_name... | import os
def get_console_size():
'''
returns no of rows, no of cols
'''
with os.popen('stty size', 'r') as f:
size = map(int, f.read().split())
return size
def get_print_size_for_repo(data):
name, lang, star = [0]*3
for each in data:
repo_name, desc, [stars, language] = e... |
Fix the blog content form | from django import forms
from ideascube.widgets import LangSelect
from .models import Content
class ContentForm(forms.ModelForm):
class Meta:
model = Content
widgets = {
# We need a normalized date string for JS datepicker, so we take
# control over the format to bypass ... | from django import forms
from ideascube.widgets import LangSelect
from .models import Content
class ContentForm(forms.ModelForm):
use_required_attribute = False
class Meta:
model = Content
widgets = {
# We need a normalized date string for JS datepicker, so we take
#... |
Add alternate function to create or update database item | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import session_scope
def commit_db_item(db_item, add=False):
with session_scope() as session:
if add:
session.add(db_item)
else:
session.merge(db_item)
session.commit()
def create_or_update_db_item(db_ite... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from .common import session_scope
logger = logging.getLogger()
def commit_db_item(db_item, add=False):
with session_scope() as session:
if add:
session.add(db_item)
else:
session.merge(db_item)
session.... |
Fix people list breaking due to deleted photo. | from django.utils.html import format_html
from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
from .models import Person
class PeopleAdmin(ModelAdmin):
model = Person
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
list_display = ('profile_photo', 'full_name', '... | from django.utils.html import format_html
from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
from .models import Person
class PeopleAdmin(ModelAdmin):
model = Person
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
list_display = ('profile_photo', 'full_name', '... |
Revert "[FIX] website_quote: make 'Pay & Confirm' work without website_sale" | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Online Proposals',
'category': 'Website',
'summary': 'Sales',
'website': 'https://www.odoo.com/page/quote-builder',
'version': '1.0',
'description': "",
'depends': ['website', 'sale_... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Online Proposals',
'category': 'Website',
'summary': 'Sales',
'website': 'https://www.odoo.com/page/quote-builder',
'version': '1.0',
'description': "",
'depends': ['website', 'sale_... |
Test all the code paths | import unittest
import cbs
class AttrSettings():
PROJECT_NAME = 'fancy_project'
class MethodSettings():
def PROJECT_NAME(self):
return 'fancy_project'
class TestApply(unittest.TestCase):
def test_apply_settings_attr(self):
g = {}
cbs.apply(AttrSettings, g)
self.assert... | import unittest
import cbs
class AttrSettings():
PROJECT_NAME = 'fancy_project'
class MethodSettings():
def PROJECT_NAME(self):
return 'fancy_project'
class TestApply(unittest.TestCase):
def test_apply_settings_attr(self):
g = {}
cbs.apply(AttrSettings, g)
self.assert... |
Comment typo fix and move newline. | # -*- coding: utf-8 -*-
"""
requests._oauth
~~~~~~~~~~~~~~~
This module comtains the path hack neccesary for oauthlib to be vendored into requests
while allowing upstream changes.
"""
import os
import sys
try:
from oauthlib.oauth1 import rfc5849
from oauthlib.common import extract_params
from oauthlib.o... | # -*- coding: utf-8 -*-
"""
requests._oauth
~~~~~~~~~~~~~~~
This module contains the path hack necessary for oauthlib to be vendored into
requests while allowing upstream changes.
"""
import os
import sys
try:
from oauthlib.oauth1 import rfc5849
from oauthlib.common import extract_params
from oauthlib.o... |
Fix in string representation of product model. | from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
from ckeditor.fields import RichTextField
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('... | from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
from ckeditor.fields import RichTextField
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('... |
Add test for ExtInt when doing swint while disabled. | import pyb
ext = pyb.ExtInt('X1', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l:print('line:', l))
ext.disable()
ext.enable()
print(ext.line())
ext.swint()
ext.disable()
| import pyb
# test basic functionality
ext = pyb.ExtInt('X1', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l:print('line:', l))
ext.disable()
ext.enable()
print(ext.line())
ext.swint()
# test swint while disabled, then again after re-enabled
ext.disable()
ext.swint()
ext.enable()
ext.swint()
# disable now that th... |
Replace raise with return for Ctrl+C in Windows | import sys
import msvcrt
import win_unicode_console
from .. import const
def init_output():
import colorama
win_unicode_console.enable()
colorama.init()
def get_key():
ch = msvcrt.getch()
if ch in (b'\x00', b'\xe0'): # arrow or function key prefix?
ch = msvcrt.getch() # second call ret... | import sys
import msvcrt
import win_unicode_console
from .. import const
def init_output():
import colorama
win_unicode_console.enable()
colorama.init()
def get_key():
ch = msvcrt.getch()
if ch in (b'\x00', b'\xe0'): # arrow or function key prefix?
ch = msvcrt.getch() # second call ret... |
Update tests for new redirect-after-create stream. | from tornado.httpclient import HTTPRequest
from nose.tools import eq_, ok_
import json
import faker
from astral.api.tests import BaseTest
from astral.models import Stream
from astral.models.tests.factories import StreamFactory
class StreamsHandlerTest(BaseTest):
def test_get_streams(self):
[StreamFactory(... | from tornado.httpclient import HTTPRequest
from nose.tools import eq_, ok_
import json
import faker
from astral.api.tests import BaseTest
from astral.models import Stream
from astral.models.tests.factories import StreamFactory
class StreamsHandlerTest(BaseTest):
def test_get_streams(self):
[StreamFactory(... |
Store data set as dict instead of list | class PrefixList:
""" The PrefixList holds the data received from routing registries and
the validation results of this data. """
def __init__(self, name):
self.name = name
self.members = []
def __iter__(self):
for member in self.members:
yield member
def a... | class PrefixList:
""" The PrefixList holds the data received from routing registries and
the validation results of this data. """
def __init__(self, name):
self.name = name
self.members = {}
def __iter__(self):
for asn in self.members:
yield self.members[asn]
... |
Add OTP to test filters | # Test for one implementation of the interface
from lexicon.providers.dnsimple import Provider
from integration_tests import IntegrationTests
from unittest import TestCase
# Hook into testing framework by inheriting unittest.TestCase and reuse
# the tests which *each and every* implementation of the interface must
# p... | # Test for one implementation of the interface
from lexicon.providers.dnsimple import Provider
from integration_tests import IntegrationTests
from unittest import TestCase
# Hook into testing framework by inheriting unittest.TestCase and reuse
# the tests which *each and every* implementation of the interface must
# p... |
Add testing for the WebAuthn implementation | """
This test file tests the lib.tokens.webauthntoken, along with lib.tokens.webauthn.
This depends on lib.tokenclass
"""
from .base import MyTestCase
from privacyidea.lib.tokens.webauthntoken import WebAuthnTokenClass, WEBAUTHNACTION
from privacyidea.lib.token import init_token
from privacyidea.lib.policy import set_... | """
This test file tests the lib.tokens.webauthntoken, along with lib.tokens.webauthn.
This depends on lib.tokenclass
"""
import unittest
from copy import copy
from privacyidea.lib.tokens import webauthn
from privacyidea.lib.tokens.webauthn import COSEALGORITHM
from .base import MyTestCase
from privacyidea.lib.tokens... |
Use 'rb' mode for reading files | import os
custom_path = os.path.expanduser('~/user-fixes.py')
if os.path.exists(custom_path):
with open(custom_path, 'r') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to help people catch misspelt config
del cust... | import os
custom_path = os.path.expanduser('~/user-fixes.py')
if os.path.exists(custom_path):
with open(custom_path, 'rb') as f:
exec(compile(f.read(), custom_path, 'exec'), globals())
del f
# Clean up temp variables, since pwb issues a warning otherwise
# to help people catch misspelt config
del cus... |
Remove at exit handler it doesnt work... |
import subprocess
import atexit
from delivery.models.execution import ExecutionResult, Execution
class ExternalProgramService():
@staticmethod
def run(cmd):
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
... |
import subprocess
from delivery.models.execution import ExecutionResult, Execution
class ExternalProgramService():
@staticmethod
def run(cmd):
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.