Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Set the modification dates of the created files to that of the notes | import os, sys, json
from simperium.core import Api as SimperiumApi
appname = 'chalk-bump-f49' # Simplenote
token = os.environ['TOKEN']
backup_dir = sys.argv[1] if len(sys.argv) > 1 else (os.path.join(os.environ['HOME'], "Dropbox/SimplenoteBackups"))
print "Starting backup your simplenote to: %s" % backup_dir
if not o... | import os, sys, json
from simperium.core import Api as SimperiumApi
appname = 'chalk-bump-f49' # Simplenote
token = os.environ['TOKEN']
backup_dir = sys.argv[1] if len(sys.argv) > 1 else (os.path.join(os.environ['HOME'], "Dropbox/SimplenoteBackups"))
print "Starting backup your simplenote to: %s" % backup_dir
if not o... |
Write minimal code to implement MutableMapping | # Copyright (c) 2016 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class VanillaXMP:
pass
| # Copyright (c) 2016 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from collections.abc import MutableMapping
class VanillaXMP (MutableMapping):
def __delitem__ (self, key):
pass
def __getite... |
Add a mock API path for project details, used in e.g. test_init | from uuid import uuid4
import requests_mock
from tests.utils import get_project_list_data
from valohai_cli.utils import get_random_string
def get_project_mock(create_project_name=None, existing_projects=None):
username = get_random_string()
m = requests_mock.mock()
if isinstance(existing_projects, int):... | from uuid import uuid4
import requests_mock
from tests.utils import get_project_list_data
from valohai_cli.utils import get_random_string
def get_project_mock(create_project_name=None, existing_projects=None):
username = get_random_string()
project_id = uuid4()
m = requests_mock.mock()
if isinstance... |
Set maxDiff to 'None' on the base ScraperTest class | import os
import unittest
import pytest
class ScraperTest(unittest.TestCase):
online = False
test_file_name = None
def setUp(self):
os.environ[
"RECIPE_SCRAPERS_SETTINGS"
] = "tests.test_data.test_settings_module.test_settings"
test_file_name = (
self.te... | import os
import unittest
import pytest
class ScraperTest(unittest.TestCase):
maxDiff = None
online = False
test_file_name = None
def setUp(self):
os.environ[
"RECIPE_SCRAPERS_SETTINGS"
] = "tests.test_data.test_settings_module.test_settings"
test_file_name = (
... |
Add form to create a bucketlist item | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="... | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="... |
Check make exit codes and stop on error | # LIBTBX_SET_DISPATCHER_NAME dev.xia2.make_sphinx_html
from __future__ import division
from libtbx import easy_run
import libtbx.load_env
import os.path as op
import shutil
import os
import sys
if (__name__ == "__main__") :
xia2_dir = libtbx.env.find_in_repositories("xia2", optional=False)
assert (xia2_dir is not... | # LIBTBX_SET_DISPATCHER_NAME dev.xia2.make_sphinx_html
from __future__ import division
import libtbx.load_env
from dials.util.procrunner import run_process
import shutil
import os
if (__name__ == "__main__") :
xia2_dir = libtbx.env.find_in_repositories("xia2", optional=False)
assert (xia2_dir is not None)
dest_... |
Change to_user to CharField for message model | from __future__ import unicode_literals
from django.db import models
class Activity(models.Model):
datetime = models.DateTimeField(auto_now_add=True)
detail = models.TextField(editable=False)
to_user = models.ForeignKey('employees.Employee',
related_name='%(class)s_to',
... | from __future__ import unicode_literals
from django.db import models
class Activity(models.Model):
datetime = models.DateTimeField(auto_now_add=True)
detail = models.TextField(editable=False)
to_user = models.ForeignKey('employees.Employee',
related_name='%(class)s_to',
... |
Move assignments in Table.__init__ around | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
def __init__ (self, tab_separated_text = None):
... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
def __init__ (self, tab_separated_text = None):
... |
Fix error due to missing package in packages list | from distutils.core import setup
VERSION = '0.0.2.8'
setup(
name='jpp',
version=VERSION,
packages=['jpp', 'jpp.parser', 'jpp.cli_test', 'jpp.cli_test.sub_path'],
url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION),
license='MIT',
author='asherbar',
author_em... | from distutils.core import setup
VERSION = '0.0.2.8'
setup(
name='jpp',
version=VERSION,
packages=['jpp', 'jpp.parser', 'jpp.cli_test'],
url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION),
license='MIT',
author='asherbar',
author_email='asherbare@gmail.com'... |
Copy data files for numpy | #!/usr/bin/env python
# Copyright (c) 2014, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE>
from distutils.core import setup
setup(name='spherical_functions',
version='1.0',
description='Python/numba implementation of Wigner D Matrices, spi... | #!/usr/bin/env python
# Copyright (c) 2014, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE>
from distutils.core import setup
setup(name='spherical_functions',
version='1.0',
description='Python/numba implementation of Wigner D Matrices, spi... |
Add a short alias for bin/openprocurement_tests | from setuptools import find_packages, setup
version = '2.3'
setup(name='op_robot_tests',
version=version,
description="",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='',
author_email... | from setuptools import find_packages, setup
version = '2.3'
setup(name='op_robot_tests',
version=version,
description="",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='',
author_email... |
Make description a string, not a tuple. | #!/usr/bin/env python
from distutils.core import setup
with open('README.rst') as file:
long_description = file.read()
setup(name='parmap',
version='1.2.1',
description=('map and starmap implementations passing additional',
'arguments and parallelizing if possible'),
long_des... | #!/usr/bin/env python
from distutils.core import setup
with open('README.rst') as file:
long_description = file.read()
setup(name='parmap',
version='1.2.1',
description=('map and starmap implementations passing additional '
'arguments and parallelizing if possible'),
long_des... |
Drop `author_email` - oops, excessive copy-paste | import os
from setuptools import setup, find_packages
__version__ = '0.1'
HERE = os.path.dirname(__file__)
try:
long_description = open(os.path.join(HERE, 'README.rst')).read()
except:
long_description = None
setup(
name='rubberjack-cli',
version=__version__,
packages=find_packages(exclude=['tes... | import os
from setuptools import setup, find_packages
__version__ = '0.1'
HERE = os.path.dirname(__file__)
try:
long_description = open(os.path.join(HERE, 'README.rst')).read()
except:
long_description = None
setup(
name='rubberjack-cli',
version=__version__,
packages=find_packages(exclude=['tes... |
Validate user when favorite a show | from rest_framework import serializers as drf_serializers
from cinemair.common.api import serializers
from cinemair.shows.serializers import ShowRelatedSerializer
from . import models
class FavoriteSerializer(serializers.ModelSerializer):
show_info = drf_serializers.SerializerMethodField()
class Meta:
... | from rest_framework import serializers as drf_serializers
from cinemair.common.api import serializers
from cinemair.shows.serializers import ShowRelatedSerializer
from . import models
class FavoriteSerializer(serializers.ModelSerializer):
show_info = drf_serializers.SerializerMethodField()
class Meta:
... |
Change code because failed the random test | def array_diff(a, b):
return a if not b else [x for x in a if x != b[0]]
| def array_diff(a, b):
return [x for x in a if x not in set(b)]
|
Update migration history to include trackchanges migrations | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('assessment', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='StaffW... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('assessment', '0004_edited_content_migration'),
]
operations = [
migrations.CreateModel(
... |
Remove default filter that breaks unknown users export filter | from corehq.apps.es import CaseES, GroupES
from corehq.apps.es import FormES
def get_form_export_base_query(domain, app_id, xmlns, include_errors):
query = (FormES()
.domain(domain)
.app(app_id)
.xmlns(xmlns)
.sort("received_on"))
if include_errors:
quer... | from corehq.apps.es import CaseES, GroupES
from corehq.apps.es import FormES
def get_form_export_base_query(domain, app_id, xmlns, include_errors):
query = (FormES()
.domain(domain)
.app(app_id)
.xmlns(xmlns)
.sort("received_on")
.remove_default_filter('... |
Allow custon io loops for ConnectionPools | from __future__ import absolute_import
import celery
from tornado import ioloop
from .connection import ConnectionPool
from .producer import NonBlockingTaskProducer
from .result import AsyncResult
VERSION = (0, 3, 0)
__version__ = '.'.join(map(str, VERSION)) + '-dev'
def setup_nonblocking_producer(celery_app=None... | from __future__ import absolute_import
import celery
from tornado import ioloop
from .connection import ConnectionPool
from .producer import NonBlockingTaskProducer
from .result import AsyncResult
VERSION = (0, 3, 0)
__version__ = '.'.join(map(str, VERSION)) + '-dev'
def setup_nonblocking_producer(celery_app=None... |
Add route to get specific group | """Group manangement."""
from flask import jsonify
from flask_restplus import Namespace, Resource
import api.team
import api.user
ns = Namespace('groups', description='Group management')
@ns.route('/')
class GroupList(Resource):
"""Get the list of groups, or add a new group."""
# @TODO allow admins to see ... | """Group manangement."""
from flask import jsonify
from flask_restplus import Namespace, Resource
import api.group
import api.team
import api.user
from api.common import PicoException
ns = Namespace('groups', description='Group management')
@ns.route('/')
class GroupList(Resource):
"""Get the list of groups, or... |
Add specification of output directory from command line | #!/usr/bin/env python
# Grab runs from S3 and do analysis
#
# Daniel Klein, 2015-08-14
import sys
import subprocess
import glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('remote_dir', help = 'S3 directory with completed runs')
parser.add_argument('run_ids', help = 'IDs of runs to analyze... | #!/usr/bin/env python
# Grab runs from S3 and do analysis
#
# Daniel Klein, 2015-08-14
import sys
import subprocess
import glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('remote_dir', help = 'S3 directory with completed runs')
parser.add_argument('output_dir', help = 'Local destination f... |
Add docstrings to Users class | from .base import AuthenticationBase
class Users(AuthenticationBase):
def __init__(self, domain):
self.domain = domain
def userinfo(self, access_token):
return self.get(
url='https://%s/userinfo' % self.domain,
headers={'Authorization': 'Bearer %s' % access_token}
... | from .base import AuthenticationBase
class Users(AuthenticationBase):
"""Userinfo related endpoints.
Args:
domain (str): Your auth0 domain (e.g: username.auth0.com)
"""
def __init__(self, domain):
self.domain = domain
def userinfo(self, access_token):
"""Returns the us... |
Add testcases for "complicated" args to generator functions. | # Handling of "complicated" arg forms to generators
# https://github.com/micropython/micropython/issues/397
def gen(v=5):
for i in range(v):
yield i
print(list(gen()))
# Still not supported, ditto for *args and **kwargs
#print(list(gen(v=10)))
| # Handling of "complicated" arg forms to generators
# https://github.com/micropython/micropython/issues/397
def gen(v=5):
for i in range(v):
yield i
print(list(gen()))
print(list(gen(v=10)))
def g(*args, **kwargs):
for i in args:
yield i
for k, v in kwargs.items():
yield (k, v)
p... |
Remove mixins from namespace after monkey patching | # Copyright (c) 2014, German Neuroinformatics Node (G-Node)
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted under the terms of the BSD License. See
# LICENSE file in the root of the Project.
from nix.core import File, FileMode, Block, DataTy... | # Copyright (c) 2014, German Neuroinformatics Node (G-Node)
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted under the terms of the BSD License. See
# LICENSE file in the root of the Project.
from nix.core import File, FileMode, Block, DataTy... |
Revert "Deliberately break status check" | from django.db import connection, DatabaseError
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from cla_common.smoketest import smoketest
from moj_irat.views import PingJsonView as BasePingJsonView
class JSONResponse(HttpRes... | from django.db import connection, DatabaseError
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from cla_common.smoketest import smoketest
from moj_irat.views import PingJsonView as BasePingJsonView
class JSONResponse(HttpRes... |
Read config file passed as --appopts param. | """
Cyclone application for Vumi Go contacts API.
"""
from go_api.cyclone import ApiApplication
from go_contacts.backends.riak import RiakContactsBackend
class ContactsApi(ApiApplication):
"""
:param IContactsBackend backend:
A backend that provides a contact collection factory.
"""
def __in... | """
Cyclone application for Vumi Go contacts API.
"""
from go_api.cyclone.handlers import ApiApplication
from go_contacts.backends.riak import RiakContactsBackend
class ContactsApi(ApiApplication):
"""
:param IContactsBackend backend:
A backend that provides a contact collection factory.
"""
... |
Use class-based generic view for redirect. | from django.conf.urls import patterns, url
from surlex.dj import surl
from .feeds import NewspeakRSSFeed, NewspeakAtomFeed
urlpatterns = patterns('',
# surl(r'^$', SomeView.as_view(),
# name='newspeak_home'
# ),)
# Static redirect to the RSS feed, until we have a
# page to show here.
(... | from django.conf.urls import patterns, url
from django.views.generic.base import RedirectView
from surlex.dj import surl
from .feeds import NewspeakRSSFeed, NewspeakAtomFeed
urlpatterns = patterns('',
# surl(r'^$', SomeView.as_view(),
# name='newspeak_home'
# ),)
# Static redirect to the RSS f... |
Remove debug mode default setting of true | from bucky import create_app
app = create_app('development')
if __name__ == "__main__":
app.run(debug=True)
| from bucky import create_app
app = create_app('development')
if __name__ == "__main__":
app.run()
|
Fix parameters on test nodes | """
Nodetree test nodes.
"""
from __future__ import absolute_import
import types
from . import node
class Number(node.Node):
"""A number constant."""
intypes = []
outtype = types.IntType
_parameters = [
dict(name="num", value=0),
]
def _eval(self):
return self._params.g... | """
Nodetree test nodes.
"""
from __future__ import absolute_import
import types
from . import node
class Number(node.Node):
"""A number constant."""
intypes = []
outtype = types.IntType
parameters = [
dict(name="num", value=0),
]
def _eval(self):
return self._params.ge... |
Use rpop/rpush instead of deprecated pop/push (conforming to redis 1.x) | from redis import Redis as Redis
from ghettoq.backends.base import BaseBackend
class RedisBackend(BaseBackend):
def establish_connection(self):
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message):
self.clie... | from redis import Redis as Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
class RedisBackend(BaseBackend):
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=s... |
Validate TLS certificate for connections to Elastsearch | from flask import Flask
from config import config as configs
from flask.ext.bootstrap import Bootstrap
from flask.ext.elasticsearch import FlaskElasticsearch
from dmutils import init_app, flask_featureflags
bootstrap = Bootstrap()
feature_flags = flask_featureflags.FeatureFlag()
elasticsearch_client = FlaskElasticsear... | from flask import Flask
from config import config as configs
from flask.ext.bootstrap import Bootstrap
from flask.ext.elasticsearch import FlaskElasticsearch
from dmutils import init_app, flask_featureflags
bootstrap = Bootstrap()
feature_flags = flask_featureflags.FeatureFlag()
elasticsearch_client = FlaskElasticsear... |
Use __version__ from fuzzywuzzy package | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014 SeatGeek
# This file is part of fuzzywuzzy.
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def open_file(fname):
return open(os.path.join(os.path.dirname(__file__), fname))
setup(
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014 SeatGeek
# This file is part of fuzzywuzzy.
from fuzzywuzzy import __version__
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def open_file(fname):
return open(os.path.join(os.path.dirn... |
Add sanity checks for temperature readings | # coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" i... | # coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" i... |
Fix for case when file can't be opened due to IOError or similar | # -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoq... | # -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]):
return
els... |
Add option to Python line ending conversion to specify a single filename on the command line | #!/usr/bin/python
import os
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.wr... | #!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
... |
Clean up unused imports and add docstrings | from app_factory.create_app import db
from models import User
from forms import RegistrationForm, LoginForm
def load_user(user_id):
return User.query.filter_by(id=user_id).first()
def login(request):
form = LoginForm.from_json(request.form)
if request.method == 'POST' and form.validate():
return... | from models import User
from forms import LoginForm
def load_user(user_id):
"""Returns a user from the database based on their id"""
return User.query.filter_by(id=user_id).first()
def login(request):
"""Handle a login request from a user."""
form = LoginForm.from_json(request.form)
if request.m... |
Complete quick attempt at function. | def balanceness(paren_series):
indicator = 0
for paren in paren_series:
if paren == u'(':
indicator += 1
elif paren == u')':
indicator -= 1
# At any point in time, if a ')' precedes a '(', then the series
# of parenthesis is broken.
if indicator <... | def balanceness(paren_series):
indicator = 0
for paren in paren_series:
print paren
if paren == u'(':
indicator += 1
elif paren == u')':
indicator -= 1
# At any point in time, if a ')' precedes a '(', then the series
# of parenthesis is broken, an... |
Add simple test to fail in case of duplicate migration ids. | # -*- coding: utf-8 -*-
import pytest
from olympia.core.tests.db_tests_testapp.models import TestRegularCharField
@pytest.mark.django_db
@pytest.mark.parametrize('value', [
u'a',
u'🔍', # Magnifying Glass Tilted Left (U+1F50D)
u'❤', # Heavy Black Heart (U+2764, U+FE0F)
])
def test_max_length_utf8mb4(va... | # -*- coding: utf-8 -*-
import os
import pytest
from olympia.core.tests.db_tests_testapp.models import TestRegularCharField
@pytest.mark.django_db
@pytest.mark.parametrize('value', [
u'a',
u'🔍', # Magnifying Glass Tilted Left (U+1F50D)
u'❤', # Heavy Black Heart (U+2764, U+FE0F)
])
def test_max_length_... |
Fix task email recipients list format | from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def... | from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def... |
Update for Django version 1.11 | """
Contains some common filter as utilities
"""
from django.template import Library, loader, Context
from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions
register = Library()
admin_actions = admin_actions
@register.simple_tag(takes_context=True)
def... | """
Contains some common filter as utilities
"""
from django.template import Library, loader
from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions
register = Library()
admin_actions = admin_actions
@register.simple_tag(takes_context=True)
def totalsum... |
Replace string withe nvironment variable | import slackclient
import time
import os
slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
lastPingTime = 0
while True:
for message in slackClient.rtm_read():
if message["type"] == "team_join":
username = message["user"]["name"]
message = "We... | import slackclient
import time
import os
slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
lastPingTime = 0
while True:
for message in slackClient.rtm_read():
if message["type"] == "team_join":
username = message["user"]["name"]
message = {}.... |
Add test for break from within try within a for-loop. | # Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3... | # Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3... |
Add kill_adb() and increase python-adb logging to WARNING. | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional serv... | # Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional serv... |
Add get_absolute_url to Page model | from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)... | from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)... |
Add install process for docker | from genes import apt
import platform
class Config:
OS = platform.system()
DIST = platform.linux_distribution()
def main():
if Config.OS == 'Linux':
if Config.DIST[0] == 'Ubuntu' or Config.DIST[0] == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
| from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C07... |
Add missing return of Event methods | class Event:
def __init__(self, bot, data):
self.bot = bot
self.data = data
def post_message(self, text, channel=None):
if channel is None:
channel = self.data['channel']
self.bot.post_message(text, channel)
def add_reaction(self, emoji, channel=None, timestamp=No... | class Event:
def __init__(self, bot, data):
self.bot = bot
self.data = data
def post_message(self, text, channel=None):
if channel is None:
channel = self.data['channel']
return self.bot.post_message(text, channel)
def add_reaction(self, emoji, channel=None, times... |
Hide last task and services with negative score from main page | from django.shortcuts import render
from main.models import UserProfile, Transaction, Task, Service
from django.db.models import Avg
def index(request):
users = UserProfile.objects.all()
return render(request, 'main/index.html', {
'users_top_spend': sorted(users, key=lambda a: a.spend(), reverse=True)... | from django.shortcuts import render
from main.models import UserProfile, Transaction, Task, Service
from django.db.models import Avg
from voting.models import Vote
def index(request):
users = UserProfile.objects.all()
tasks_last = Task.objects.filter(status=True).order_by('-timestamp_create')[:10]
votes ... |
Add logging message when plugin fails to render custom panels | import sys
import traceback
from django.conf import settings
from django.views.debug import ExceptionReporter
from error_report.models import Error
from plugin.registry import registry
class InvenTreePluginViewMixin:
"""
Custom view mixin which adds context data to the view,
based on loaded plugins.
... | import logging
import sys
import traceback
from django.conf import settings
from django.views.debug import ExceptionReporter
from error_report.models import Error
from plugin.registry import registry
logger = logging.getLogger('inventree')
class InvenTreePluginViewMixin:
"""
Custom view mixin which adds ... |
Remove dependency links for pybloom. | from setuptools import setup
setup(
name = 'fastqp',
provides = 'fastqp',
version = "0.1.5",
author = 'Matthew Shirley',
author_email = 'mdshw5@gmail.com',
url = 'http://mattshirley.com',
description = 'Simple NGS read quality assessment using Python',
l... | from setuptools import setup
setup(
name = 'fastqp',
provides = 'fastqp',
version = "0.1.6",
author = 'Matthew Shirley',
author_email = 'mdshw5@gmail.com',
url = 'http://mattshirley.com',
description = 'Simple NGS read quality assessment using Python',
l... |
Add migrations to package. Bump version. | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='pybbm-private-messages',
version='0... | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='pybbm-private-messages',
version='0... |
Set facebook_crendentials_backend_2's url to https | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends import form_based_credentials_backend
class FacebookCredentialsBackend(
form_based_credentials_backend.FormBasedCredential... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends import form_based_credentials_backend
class FacebookCredentialsBackend(
form_based_credentials_backend.FormBasedCredential... |
Clean up the upgrader logic and add a config option for it | from flask_sqlalchemy import SQLAlchemy
from flask_alembic import Alembic
db = SQLAlchemy()
alembic = Alembic()
def init_db():
# import all modules here that might define models so that
# they will be registered properly on the metadata. Otherwise
# you will have to import them first before calling init_... | from flask_sqlalchemy import SQLAlchemy
from flask_alembic import Alembic
from . import app
db = SQLAlchemy()
alembic = Alembic()
def init_db():
# import all modules here that might define models so that
# they will be registered properly on the metadata. Otherwise
# you will have to import them first be... |
Add -c option to continue if one file has a SyntaxError | import sys
import getopt
from compiler import compile, visitor
def main():
VERBOSE = 0
DISPLAY = 0
opts, args = getopt.getopt(sys.argv[1:], 'vqd')
for k, v in opts:
if k == '-v':
VERBOSE = 1
visitor.ASTVisitor.VERBOSE = visitor.ASTVisitor.VERBOSE + 1
if k == '-q... | import sys
import getopt
from compiler import compile, visitor
##import profile
def main():
VERBOSE = 0
DISPLAY = 0
CONTINUE = 0
opts, args = getopt.getopt(sys.argv[1:], 'vqdc')
for k, v in opts:
if k == '-v':
VERBOSE = 1
visitor.ASTVisitor.VERBOSE = visitor.ASTVis... |
Use a sortable list instead of a dictionary of values for the return value | import os
import json
from kitchen.settings import KITCHEN_LOCATION
def load_data(data_type):
retval = {}
nodes_dir = os.path.join(KITCHEN_LOCATION, data_type)
if not os.path.isdir(nodes_dir):
raise IOError('Invalid data type or kitchen location. Check your settings.')
for filename in os.listd... | import os
import json
from kitchen.settings import KITCHEN_LOCATION
def load_data(data_type):
retval = []
nodes_dir = os.path.join(KITCHEN_LOCATION, data_type)
if not os.path.isdir(nodes_dir):
raise IOError('Invalid data type or kitchen location. Check your settings.')
for filename in os.listd... |
Allow users with the permission 'blog.can_read_private' to see posts from the future. | from lithium.blog.models import Post
def decorator(request, view, author=None, tag=None, *args, **kwargs):
"""
A view decotator to change the queryset depending on whether
a user may read private posts.
"""
if request.user.has_perm('blog.can_read_private'):
kwargs['queryset'] = Post.on... | from lithium.blog.models import Post
def decorator(request, view, author=None, tag=None, *args, **kwargs):
"""
A view decotator to change the queryset depending on whether
a user may read private posts.
"""
if request.user.has_perm('blog.can_read_private'):
kwargs['queryset'] = Post.on... |
Update Version to 0.0.3 caused by pypi's limit | import os
from setuptools import setup, find_packages
HERE = os.path.abspath(os.path.dirname(__file__))
install_requires = (
"argparse",
"six>=1.10.0",
)
setup(
name='cmdtree',
version='0.0.2',
packages=find_packages(HERE, include=['cmdtree']),
install_requires=install_requires,
url='htt... | import os
from setuptools import setup, find_packages
HERE = os.path.abspath(os.path.dirname(__file__))
install_requires = (
"argparse",
"six>=1.10.0",
)
setup(
name='cmdtree',
version='0.0.3',
packages=find_packages(HERE, include=['cmdtree']),
install_requires=install_requires,
url='htt... |
Revert "Use HTTPS to retrieve ranking from DBB" | """
dbbrankingparser.httpclient
~~~~~~~~~~~~~~~~~~~~~~~~~~~
HTTP client utilities
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
from urllib.request import Request, urlopen
USER_AGENT = (
'Mozilla/5.0 (X11; Linux x86_64; rv:38.0) '
'Gecko/20100101 Firefox/38.0 Icewea... | """
dbbrankingparser.httpclient
~~~~~~~~~~~~~~~~~~~~~~~~~~~
HTTP client utilities
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
from urllib.request import Request, urlopen
USER_AGENT = (
'Mozilla/5.0 (X11; Linux x86_64; rv:38.0) '
'Gecko/20100101 Firefox/38.0 Icewea... |
Allow filtering of registrations by complete status. | from django.contrib import admin
from commoner.registration.models import PartialRegistration
class PartialRegistrationAdmin(admin.ModelAdmin):
pass
admin.site.register(PartialRegistration, PartialRegistrationAdmin)
| from django.contrib import admin
from commoner.registration.models import PartialRegistration
class PartialRegistrationAdmin(admin.ModelAdmin):
list_filter = ('complete',)
admin.site.register(PartialRegistration, PartialRegistrationAdmin)
|
Support layout on template endpoints | from dataclasses import dataclass
from datetime import datetime
@dataclass
class AuthResponse:
email: str
image_access: bool
search_access: bool
created: datetime
modified: datetime
@dataclass
class FontResponse:
filename: str
id: str
alias: str
_self: str
@dataclass
class Meme... | from dataclasses import dataclass
from datetime import datetime
@dataclass
class AuthResponse:
email: str
image_access: bool
search_access: bool
created: datetime
modified: datetime
@dataclass
class FontResponse:
filename: str
id: str
alias: str
_self: str
@dataclass
class Meme... |
Add path field to preview file | from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class PreviewFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is aimed at being reviewed. It is not a publication
neither a wo... | from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class PreviewFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is aimed at being reviewed. It is not a publication
neither a wo... |
Select and Create and List | from dumpster import Dumpster
import os
i = input('\r>')
if i == 'list':
cwd = os.getcwd()
lcd = os.listdir()
dump = ''
for file in lcd:
if '.dmp' in file:
dump+= ' '+file
print(dump)
| from dumpster import Dumpster
import os
running = True
selected = ''
while running:
#cwd = os.getcwd()
i = input('\r%s>'%(selected))
if i == 'exit':
running = False
if i[0:6] == 'create':
name = i[7:]
Dumpster(name).write_to_dump()
if i == 'list':
if selected is... |
Use the new version of traitlets. | from setuptools import setup
from sys import version_info
def install_requires():
requires = [
'traitlets>=4.0',
'six>=1.9.0',
'pyyaml>=3.11',
]
if (version_info.major, version_info.minor) < (3, 4):
requires.append('singledispatch>=3.4.0')
return requires
def extras_r... | from setuptools import setup
from sys import version_info
def install_requires():
requires = [
'traitlets>=4.1',
'six>=1.9.0',
'pyyaml>=3.11',
]
if (version_info.major, version_info.minor) < (3, 4):
requires.append('singledispatch>=3.4.0')
return requires
def extras_r... |
Correct the pip download URL | #!/usr/bin/env python
"""
setup.py file for afnumpy
"""
from distutils.core import setup
from afnumpy import __version__
setup (name = 'afnumpy',
version = __version__,
author = "Filipe Maia",
author_email = "filipe.c.maia@gmail.com",
url = 'https://github.com/FilipeMaia/afnumpy',
... | #!/usr/bin/env python
"""
setup.py file for afnumpy
"""
from distutils.core import setup
from afnumpy import __version__
setup (name = 'afnumpy',
version = __version__,
author = "Filipe Maia",
author_email = "filipe.c.maia@gmail.com",
url = 'https://github.com/FilipeMaia/afnumpy',
... |
Add long description content-type for PyPI | import io
import os
from setuptools import setup, find_packages
version = io.open('rubyenv/_version.py').readlines()[-1].split()[-1].strip('"\'')
setup(
name='rubyenv',
version=version,
description='manage ruby in your virtualenv',
long_description=io.open('README.md', encoding='utf-8').read(),
a... | import io
import os
from setuptools import setup, find_packages
version = io.open('rubyenv/_version.py').readlines()[-1].split()[-1].strip('"\'')
setup(
name='rubyenv',
version=version,
description='manage ruby in your virtualenv',
long_description=io.open('README.md', encoding='utf-8').read(),
l... |
Enable with statement tests for Python 2.5 | import sys
if sys.version_info[:2] > (2, 5):
from tests._testwith import *
else:
from tests.support import unittest2
class TestWith(unittest2.TestCase):
@unittest2.skip('tests using with statement skipped on Python 2.4')
def testWith(self):
pass
if __name__ == '_... | import sys
if sys.version_info[:2] >= (2, 5):
from tests._testwith import *
else:
from tests.support import unittest2
class TestWith(unittest2.TestCase):
@unittest2.skip('tests using with statement skipped on Python 2.4')
def testWith(self):
pass
if __name__ == '... |
Add test that sync is now destructive | from ...testcases import DustyIntegrationTestCase
from ...fixtures import busybox_single_app_bundle_fixture
class TestSyncCLI(DustyIntegrationTestCase):
def setUp(self):
super(TestSyncCLI, self).setUp()
busybox_single_app_bundle_fixture()
self.run_command('bundles activate busyboxa')
... | from ...testcases import DustyIntegrationTestCase
from ...fixtures import busybox_single_app_bundle_fixture
class TestSyncCLI(DustyIntegrationTestCase):
def setUp(self):
super(TestSyncCLI, self).setUp()
busybox_single_app_bundle_fixture()
self.run_command('bundles activate busyboxa')
... |
Update dict pin in prep for release | from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.... | from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.... |
Tag 0.1.5, tweaks for PyPI compatibility | #from distribute_setup import use_setuptools
#use_setuptools()
from setuptools import setup, find_packages
from os.path import dirname, join
here = dirname(__file__)
setup(
name='ledgerblue',
version='0.1.4',
author='Ledger',
author_email='hello@ledger.fr',
description='Python library to communica... | #from distribute_setup import use_setuptools
#use_setuptools()
from setuptools import setup, find_packages
from os.path import dirname, join
import os
os.environ['SECP_BUNDLED_EXPERIMENTAL'] = "1"
here = dirname(__file__)
setup(
name='ledgerblue',
version='0.1.5',
author='Ledger',
author_email='hello... |
Fix Charged Hammer / Lightning Jolt | from ..utils import *
##
# Hero Powers
# Lightning Jolt
class AT_050t:
play = Hit(TARGET, 2)
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class... | from ..utils import *
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class AT_049:
inspire = Buff(FRIENDLY_MINIONS + TOTEM, "AT_049e")
# The Mistc... |
Use get_manager() for Counter direct | # -*- coding: utf-8 -*-
# Copyright 2017 - 2019 Avram Lubkin, All Rights Reserved
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
**Enlighten counter submodule**
... | # -*- coding: utf-8 -*-
# Copyright 2017 - 2019 Avram Lubkin, All Rights Reserved
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
**Enlighten counter submodule**
... |
Expand alternatives to import aio module | # Copyright 2019 The gRPC Authors.
#
# 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 wri... | # Copyright 2019 The gRPC Authors.
#
# 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 wri... |
Use default arguments removed by mypy | from typing import Any
from flask import Flask
from relayer import Relayer
class FlaskRelayer(object):
def __init__(self, app: Flask, logging_topic: str, kafka_hosts: str = None, **kwargs: str) -> None:
if app:
self.init_app(
app,
logging_topic,
... | from typing import Any
from flask import Flask
from relayer import Relayer
class FlaskRelayer(object):
def __init__(self, app: Flask = None, logging_topic: str = None, kafka_hosts: str = None, **kwargs: str) -> None:
if app:
self.init_app(
app,
logging_topic,
... |
Extend Broadcast protocol abstraction with a Handler interface for message delivery | from abc import ABCMeta, abstractmethod
import socket, json
class Broadcast(metaclass=ABCMeta):
"""
An interface for defining a broadcast protocol.
The 'propose' and 'decide' methods need to be defined
"""
BUFFER_SIZE = 1024
def __init__(self, peer_list):
self.peers = peer_list
... | from abc import ABCMeta, abstractmethod
import socket, json
class Broadcast(metaclass=ABCMeta):
"""
An interface for defining a broadcast protocol.
The 'propose' and 'decide' methods need to be defined
"""
BUFFER_SIZE = 1024
def __init__(self, peer_list):
self.peers = peer_list
... |
Set up test environment when launching tests. | #!/usr/bin/env python
"""
Default manage.py for django-configurations
"""
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
os.environ.setdefault("DJANGO_CONFIGURATION", "Development")
from configurations.management import ex... | #!/usr/bin/env python
"""
Default manage.py for django-configurations
"""
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
os.environ.setdefault("DJANGO_CONFIGURATION", "Development")
if len(sys.argv) > 1 and sys.argv[1] == ... |
Change version for master status. | """
django-all-access is a reusable application for user registration and authentication
from OAuth 1.0 and OAuth 2.0 providers such as Twitter and Facebook.
"""
__version__ = '0.9.0'
default_app_config = 'allaccess.apps.AllAccessConfig'
import logging
class NullHandler(logging.Handler):
"No-op logging hand... | """
django-all-access is a reusable application for user registration and authentication
from OAuth 1.0 and OAuth 2.0 providers such as Twitter and Facebook.
"""
__version__ = '0.10.0.dev.0'
default_app_config = 'allaccess.apps.AllAccessConfig'
import logging
class NullHandler(logging.Handler):
"No-op loggi... |
Implement GET Product using ListAPIView | from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Product
from .serializers import ProductSerializer
class ProductList(APIView):
def get(self, request, format=None):
products = Product.objects.all()
serial... | from django.http import HttpResponse
from rest_framework import generics
from rest_framework.response import Response
from .models import Product
from .serializers import ProductSerializer
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
|
Add a further path inside /sys to test | #!/usr/bin/env python3
import os.path
import sys
# File in /sys seem to vary between Linux systems. Thus, try a few candidates
# and use the first one that exists. What we want is any file under /sys with
# permissions root:root -rw-------.
sys_file = None
for f in ("/sys/devices/cpu/rdpmc",
"/sys/kernel/mm... | #!/usr/bin/env python3
import os.path
import sys
# File in /sys seem to vary between Linux systems. Thus, try a few candidates
# and use the first one that exists. What we want is any file under /sys with
# permissions root:root -rw-------.
sys_file = None
for f in ("/sys/devices/cpu/rdpmc",
"/sys/kernel/mm... |
Set port by environment variable | import recommender
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('template.html')
@app.route('/graph')
def my_link():
# here we want to get the value of user (i.e. ?user=some-value)
seed = request.args.get('seed')
nsfw = boo... | import recommender
import os
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('template.html')
@app.route('/graph')
def my_link():
# here we want to get the value of user (i.e. ?user=some-value)
seed = request.args.get('seed')
... |
Drop FK before dropping instance_id column. | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... |
Include URL of request in error reports | import bugsnag
from sanic.handlers import ErrorHandler
from . import settings
if settings.BUGSNAG_API_KEY:
bugsnag.configure(
api_key=settings.BUGSNAG_API_KEY,
project_root="/app",
release_state=settings.ENVIRONMENT,
)
class BugsnagErrorHandler(ErrorHandler):
def default(self, re... | import bugsnag
from sanic.handlers import ErrorHandler
from . import settings
if settings.BUGSNAG_API_KEY:
bugsnag.configure(
api_key=settings.BUGSNAG_API_KEY,
project_root="/app",
release_state=settings.ENVIRONMENT,
)
class BugsnagErrorHandler(ErrorHandler):
def default(self, re... |
Fix encoding detection in python (shebang line was not parsed anymore) | """
Contains the python specific FileManager.
"""
import ast
import re
from pyqode.core.managers import FileManager
class PyFileManager(FileManager):
"""
Extends file manager to override detect_encoding. With python, we can
detect encoding by reading the two first lines of a file and extracting its
en... | """
Contains the python specific FileManager.
"""
import ast
import re
from pyqode.core.managers import FileManager
class PyFileManager(FileManager):
"""
Extends file manager to override detect_encoding. With python, we can
detect encoding by reading the two first lines of a file and extracting its
en... |
Use SlugRelatedField for foreign keys for better readability | import uuid
import jsonschema
from rest_framework import serializers
from .models import (
Api,
Consumer,
ConsumerKey,
Plugin,
)
from .schemas import plugins
class ApiSerializer(serializers.ModelSerializer):
class Meta:
model = Api
fields = '__all__'
class ConsumerSerializer(se... | import uuid
import jsonschema
from rest_framework import serializers
from .models import (
Api,
Consumer,
ConsumerKey,
Plugin,
)
from .schemas import plugins
class ConsumerSerializer(serializers.ModelSerializer):
class Meta:
model = Consumer
fields = '__all__'
class ConsumerKey... |
Allow file paths to be given to set_log_target. | """
.. module:: dbsync.logs
:synopsis: Logging facilities for the library.
"""
import logging
#: All the library loggers
loggers = set()
log_handler = None
def get_logger(name):
logger = logging.getLogger(name)
logger.setLevel(logging.WARNING)
loggers.add(logger)
if log_handler is not None:
... | """
.. module:: dbsync.logs
:synopsis: Logging facilities for the library.
"""
import logging
#: All the library loggers
loggers = set()
log_handler = None
def get_logger(name):
logger = logging.getLogger(name)
logger.setLevel(logging.WARNING)
loggers.add(logger)
if log_handler is not None:
... |
Add create action for os-scheduler-partner | """
Scheduler Partner interface (v2 extension).
"""
from novaclient import base
from novaclient.openstack.common.gettextutils import _
from novaclient import utils
class SchedulerPartner(base.Resource):
def __repr__(self):
return "<SchedulerPartner: %s>" % self.name
class SchedulerPartnerManager(base.Man... | |
Remove the try/except clause from get_user(). | from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
User = get_user_model()
class HelloBaseIDBackend(ModelBackend):
def authenticate(self, username=None):
try:
user = User.objects.filter(username=username)[0]
except IndexError:
... | from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
User = get_user_model()
class HelloBaseIDBackend(ModelBackend):
def authenticate(self, username=None):
try:
user = User.objects.filter(username=username)[0]
except IndexError:
... |
Support for newer versions of django | # -*- coding: utf-8 -*-
from django.conf.urls import url
from freeze import views
urlpatterns = [
url(r'^download-static-site/$', views.download_static_site, name='freeze_download_static_site'),
url(r'^generate-static-site/$', views.generate_static_site, name='freeze_generate_static_site'),
]
| # -*- coding: utf-8 -*-
if django.VERSION < (2, 0):
from django.conf.urls import include, url as path
else:
from django.urls import include, path
from freeze import views
urlpatterns = [
path("download-static-site/", views.download_static_site, name="freeze_download_static_site"),
path("generate-sta... |
Add logic for db host during runtime | from decouple import config
from jobs.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': 'pass1234',
'HOST': 'db',
'PORT': 5432,
}
}
#DATABASES = {
# 'default': ... | from decouple import config
from jobs.settings import *
try:
host = config('DB_HOST')
except:
host = 'db'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': 'pass1234',
'HOST': host,
... |
Fix to use binary read format | from struct import unpack
from os import walk, sep
from os.path import expanduser
from re import search
shared_objects_dirs = [
'Library/Application Support/Google/Chrome/Default/Pepper Data/Shockwave Flash/WritableRoot/#SharedObjects',
'Library/Preferences/Macromedia/Flash Player/#SharedObjects',
'AppData\Local... | from struct import unpack
from os import walk, sep
from os.path import expanduser
from re import search
shared_objects_dirs = [
'Library/Application Support/Google/Chrome/Default/Pepper Data/Shockwave Flash/WritableRoot/#SharedObjects',
'Library/Preferences/Macromedia/Flash Player/#SharedObjects',
'AppData\Local... |
Fix pylama integration to work with file skip comments | import os
import sys
from contextlib import contextmanager
from typing import Any, Dict, List
from pylama.lint import Linter as BaseLinter
from . import api
@contextmanager
def supress_stdout():
stdout = sys.stdout
with open(os.devnull, "w") as devnull:
sys.stdout = devnull
yield
sys... | import os
import sys
from contextlib import contextmanager
from typing import Any, Dict, List
from pylama.lint import Linter as BaseLinter
from isort.exceptions import FileSkipped
from . import api
@contextmanager
def supress_stdout():
stdout = sys.stdout
with open(os.devnull, "w") as devnull:
sys.... |
Modify Barcode Checksum Poster resource to dynamically overlay text | """Class for Barcode Checksum Poster resource generator."""
from PIL import Image
from utils.BaseResourceGenerator import BaseResourceGenerator
class BarcodeChecksumPosterResourceGenerator(BaseResourceGenerator):
"""Class for Grid resource generator."""
additional_valid_options = {
"barcode_length":... | """Class for Barcode Checksum Poster resource generator."""
from PIL import Image, ImageDraw
from utils.BaseResourceGenerator import BaseResourceGenerator
from utils.TextBoxDrawer import TextBoxDrawer
from django.utils.translation import ugettext as _
class BarcodeChecksumPosterResourceGenerator(BaseResourceGenerato... |
Put configurable product in Picking list | # -*- coding: utf-8 -*-
from odoo import models, fields
class StockMove(models.Model):
_inherit = 'stock.move'
product_id = fields.Many2one(domain=[('config_ok', '=', False)])
| # -*- coding: utf-8 -*-
from ast import literal_eval
from odoo import models, fields
class StockMove(models.Model):
_inherit = 'stock.move'
def _get_product_domain(self):
if literal_eval(self.env['ir.config_parameter'].sudo().get_param('product_configurator.product_selectable', default='False')):
... |
Add more expected star str | from metafunctions.util import node, star
from metafunctions.tests.util import BaseTestCase
class TestUnit(BaseTestCase):
def test_simple_star(self):
@node
def f(*args):
return args
cmp = (a | b) | star(f)
self.assertEqual(cmp('_'), ('_', 'a', 'b'))
def test_str_r... | from metafunctions.util import node, star
from metafunctions.tests.util import BaseTestCase
class TestUnit(BaseTestCase):
def test_simple_star(self):
@node
def f(*args):
return args
cmp = (a | b) | star(f)
self.assertEqual(cmp('_'), ('_', 'a', 'b'))
def test_str_r... |
Move create method as example implementation | # -*- coding: utf-8 -*-
"""Module providing an image asset asignment factory."""
class AssetAssignmentTool(object):
""" Factory providing CRUD oparations for project assets """
| # -*- coding: utf-8 -*-
"""Module providing an image asset asignment factory."""
import json
import time
from plone import api
from Products.CMFPlone.utils import safe_unicode
from zope.lifecycleevent import modified
class AssetAssignmentTool(object):
""" Factory providing CRUD oparations for project assets """
... |
Fix encoding on error page. | import traceback
import sys
class SessionHackException(Exception):
"""
Raised when something goes wrong.
"""
class SessionHack(object):
"""
The SessionHack middleware is used to catch any exceptions that occur;
this makes debugging easier. Typically debugging can be painful because
... | import traceback
import sys
class SessionHackException(Exception):
"""
Raised when something goes wrong.
"""
class SessionHack(object):
"""
The SessionHack middleware is used to catch any exceptions that occur;
this makes debugging easier. Typically debugging can be painful because
... |
Add descriptions/links for meta fields | name = 'package-name'
path = name.lower().replace("-", "_").replace(" ", "_")
version = '0.0.0'
author = 'Author Name'
author_email = ''
description = ''
url = '' # project homepage
license = 'MIT' # See https://choosealicense.com
| name = 'package-name' # See https://www.python.org/dev/peps/pep-0008/
path = name.lower().replace("-", "_").replace(" ", "_")
version = '0.1.0' # See https://www.python.org/dev/peps/pep-0440/ and https://semver.org/
author = 'Author Name'
author_email = ''
description = '' # One-liner
url = '' # your project homepa... |
Update question about computer access | from django import forms
from studygroups.models import Application
from studygroups.models import Reminder
from localflavor.us.forms import USPhoneNumberField
class ApplicationForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
def clean(self):
cleaned_data = super(ApplicationForm, se... | from django import forms
from studygroups.models import Application
from studygroups.models import Reminder
from localflavor.us.forms import USPhoneNumberField
class ApplicationForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
def clean(self):
cleaned_data = super(ApplicationForm, se... |
Update link in the comment and change saved image format to .png | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from libavg import app, avg
from PIL import Image
# Demonstrates interoperability with pillow (https://pillow.readthedocs.org/index.html)
class MyMainDiv(app.MainDiv):
def onInit(self):
self.toggleTouchVisualization()
srcbmp = avg.Bitmap("rgb24-64x64.... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from libavg import app, avg
from PIL import Image
# Demonstrates interoperability with pillow (https://pillow.readthedocs.io)
class MyMainDiv(app.MainDiv):
def onInit(self):
self.toggleTouchVisualization()
srcbmp = avg.Bitmap("rgb24-64x64.png")
... |
Make the string translator return the actual right values! | #
# A ZString-to-ASCII Universal Translator.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
class ZStringEndOfString(Exception):
"""No more data left in string."""
class ZStringStream(object):
"""This class takes an address and a ZMemory, and ... | #
# A ZString-to-ASCII Universal Translator.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
class ZStringEndOfString(Exception):
"""No more data left in string."""
class ZStringStream(object):
"""This class takes an address and a ZMemory, and ... |
Use var named "rpc" and not "a" | #!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')])
redis_url=config.get('Main', 'redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
... | #!/srv/python/venv/bin/ipython -i
import bqueryd
import os
import sys
import logging
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read(['/etc/bqueryd.cfg', os.path.expanduser('~/.bqueryd.cfg')])
redis_url=config.get('Main', 'redis_url')
if __name__ == '__main__':
if '-v' in sys.argv:
... |
Add active field to form. | # -*- coding: utf-8 -*-
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder
from Instanssi.ext_programme.models import ProgrammeEvent
class ProgrammeEventForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super... | # -*- coding: utf-8 -*-
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder
from Instanssi.ext_programme.models import ProgrammeEvent
class ProgrammeEventForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super... |
Add slug to the db and allow querying it | import json
from flaskext.mongoalchemy import BaseQuery
import requests
from api import app
from api import db
ENDPOINT = 'http://data.nasa.gov/api/'
class DatasetQuery(BaseQuery):
def get_by_remote_id(self, pk):
return self.filter(self.type.remote_id==pk)
class Dataset(db.Document):
""" Represen... | import json
from flaskext.mongoalchemy import BaseQuery
import requests
from api import app
from api import db
ENDPOINT = 'http://data.nasa.gov/api/'
class DatasetQuery(BaseQuery):
def get_by_remote_id(self, pk):
return self.filter(self.type.remote_id==pk).first()
def get_by_slug(self, slug):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.