Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add required packages for pip install | #!/usr/bin/env python
from setuptools import setup
setup(
name='ckanapi',
version='3.3-dev',
description=
'A command line interface and Python module for '
'accessing the CKAN Action API',
license='MIT',
author='Ian Ward',
author_email='ian@excess.org',
url='https://github.... | #!/usr/bin/env python
from setuptools import setup
setup(
name='ckanapi',
version='3.3-dev',
description=
'A command line interface and Python module for '
'accessing the CKAN Action API',
license='MIT',
author='Ian Ward',
author_email='ian@excess.org',
url='https://github.... |
Remove absent extractor from entry points | import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
# XXX sometimes TestCommand is not a newstyle class
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
... | import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
# XXX sometimes TestCommand is not a newstyle class
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
... |
Add isodate to the required dependencies. | from setuptools import setup, find_packages
from version import get_git_version
setup(name='thecut-durationfield',
author='The Cut', author_email='development@thecut.net.au',
url='http://projects.thecut.net.au/projects/thecut-durationfield',
namespace_packages=['thecut'],
version=get_git_version(),
... | from setuptools import setup, find_packages
from version import get_git_version
setup(name='thecut-durationfield',
author='The Cut', author_email='development@thecut.net.au',
url='http://projects.thecut.net.au/projects/thecut-durationfield',
namespace_packages=['thecut'],
version=get_git_version(),
... |
Add build step to PyPI publish command. | import os
import sys
from setuptools import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
import quill
with open('README.md', 'r') as readme_file:
readme = readme_file.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup... | import os
import sys
from setuptools import setup
if sys.argv[-1] == 'publish':
os.system('make build')
os.system('python setup.py sdist upload')
sys.exit()
import quill
with open('README.md', 'r') as readme_file:
readme = readme_file.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__... |
Fix model name for BlogComment after previous refactoring | from .models import BlogPost, Comment
from django.forms import ModelForm
class BlogPostForm(ModelForm):
class Meta:
model = BlogPost
exclude = ('user',)
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ('post', 'user', 'date',)
| from .models import BlogPost, BlogComment
from django.forms import ModelForm
class BlogPostForm(ModelForm):
class Meta:
model = BlogPost
exclude = ('user',)
class CommentForm(ModelForm):
class Meta:
model = BlogComment
exclude = ('post', 'user', 'date',)
|
Add the 'status_code' attribute to the APIError exception if it's available | from requests.exceptions import HTTPError
class BaseException(Exception):
pass
class APIError(BaseException, HTTPError):
"""
The API responded with a non-200 status code.
"""
def __init__(self, http_error):
self.message = getattr(http_error, 'message', None)
self.response = geta... | from requests.exceptions import HTTPError
class BaseException(Exception):
pass
class APIError(BaseException, HTTPError):
"""
The API responded with a non-200 status code.
"""
def __init__(self, http_error):
self.message = getattr(http_error, 'message', None)
self.response = geta... |
Add StatementDescriptor for card direct payins | from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails
class PayInExecutionDetailsDirect(PayInExecutionDetails):
def __init__(self):
# direct card
self.CardId = None
self.SecureModeReturnURL = None
self.SecureModeRedirectURL = None
# Mode3DSType ... | from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails
class PayInExecutionDetailsDirect(PayInExecutionDetails):
def __init__(self):
# direct card
self.CardId = None
self.SecureModeReturnURL = None
self.SecureModeRedirectURL = None
# Mode3DSType ... |
Replace string interpolation with format() | '''
Created on Apr 4, 2016
@author: pab
'''
import inspect
import numpy as np
def rosen(x):
"""Rosenbrock function
This is a non-convex function used as a performance test problem for
optimization algorithms introduced by Howard H. Rosenbrock in 1960.[1]
"""
x = np.atleast_1d(x)
return (1 - ... | '''
Created on Apr 4, 2016
@author: pab
'''
import inspect
import numpy as np
def rosen(x):
"""Rosenbrock function
This is a non-convex function used as a performance test problem for
optimization algorithms introduced by Howard H. Rosenbrock in 1960.[1]
"""
x = np.atleast_1d(x)
return (1 - ... |
Fix a typo in the variable name | from flask.ext.login import current_user
def create(app=None):
if current_user.is_authenticated():
if current_user.admin is True:
return True
else:
return False
else:
return False
def read(app=None):
return True
def update(app):
return create(app)
... | from flask.ext.login import current_user
def create(category=None):
if current_user.is_authenticated():
if current_user.admin is True:
return True
else:
return False
else:
return False
def read(category=None):
return True
def update(category):
return... |
Use pkg_resources to resolve the version. Requires that the necessary package metadata have been built before building docs. | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
'rst.linker',
]
# General information about the project.
project = 'skeleton'
copyright = '2016 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version(root='..', relative_to=__fi... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pkg_resources
extensions = [
'sphinx.ext.autodoc',
'rst.linker',
]
# General information about the project.
project = 'skeleton'
copyright = '2016 Jason R. Coombs'
# The short X.Y version.
version = pkg_resources.require(project)[0].version
# The full ve... |
Include is still needed for the url patterns | from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth.views import login
from movies.urls import urlpatterns as movie_urls
urlpatterns = [
url(r'^', movie_urls, name='movies'),
url(r'^admin/', admin.site.urls),
]
| from django.conf.urls import include, url
from django.contrib import admin
from movies.urls import urlpatterns as movie_urls
urlpatterns = [
url(r'^', include(movie_urls), name='movies'),
url(r'^admin/', admin.site.urls),
]
|
Add the prefs and pref url | from django.conf.urls import url
from . import views
from django.conf import settings
urlpatterns=[
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^users/$', views.users, name='users'),
url(r'^users/(?P<username>[^/]*)/$', views.user, name='user'),
]
| from django.conf.urls import url
from . import views
from django.conf import settings
urlpatterns=[
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^users/$', views.users, name='users'),
url(r'^users/(?P<user>[^/]*)/$', views.user, name='user'),
url(r'^users/(?P<... |
Set content-type header of POST. | import requests
from Adafruit_BMP085 import BMP085
import json
#initialise sensor
print ('Initialising sensor...')
bmp = BMP085(0x77, 3) # ULTRAHIRES Mode
print ('Reading sensor...')
temp = bmp.readTemperature()
pressure = bmp.readPressure()
payload = {'temperature': temp, 'pressure': pressure}
print ('POSTing dat... | import requests
from Adafruit_BMP085 import BMP085
import json
#initialise sensor
print ('Initialising sensor...')
bmp = BMP085(0x77, 3) # ULTRAHIRES Mode
print ('Reading sensor...')
temp = bmp.readTemperature()
pressure = bmp.readPressure()
payload = {'temperature': temp, 'pressure': pressure}
print ('POSTing dat... |
Support correctly weird characters in filenames when downloading | from office365.runtime.http.http_method import HttpMethod
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
class DownloadFileQuery(ServiceOperationQuery):
def __init__(self, web, file_url, file_object):
"""
A download file content query
:type file_url: ... | from office365.runtime.http.http_method import HttpMethod
from office365.runtime.odata.odata_path_parser import ODataPathParser
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
class DownloadFileQuery(ServiceOperationQuery):
def __init__(self, web, file_url, file_object):
... |
Fix bug related to creating the log directory | import threading
import subprocess
class TestExecutor(threading.Thread):
"""
The general thread to perform the tests executions
"""
def __init__(self, run_id, test_name, queue):
super().__init__()
self.run_id = run_id
self.test_name = test_name
self.queue = queue
#... | import threading
import subprocess
import os
class TestExecutor(threading.Thread):
"""
The general thread to perform the tests executions
"""
def __init__(self, run_id, test_name, queue):
super().__init__()
self.run_id = run_id
self.test_name = test_name
self.queue = q... |
Change to make metaclass clearer | from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
fields[name] = value
setattr(cls, '_fie... | from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
cls._fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
cls._fields[name] = value
def __init__(se... |
Fix float diff comparison in dict differ function. | # coding=utf-8
__all__ = ['UTC']
from datetime import timedelta, tzinfo
_ZERO = timedelta(0)
def is_dict_different(d1, d2, epsilon=0.00000000001):
s1 = set(d1.keys())
s2 = set(d2.keys())
intersect = s1.intersection(s2)
added = s1 - intersect
removed = s2 - intersect
changed = []
for o ... | # coding=utf-8
__all__ = ['UTC']
from datetime import timedelta, tzinfo
_ZERO = timedelta(0)
def is_dict_different(d1, d2, epsilon=0.00000000001):
s1 = set(d1.keys())
s2 = set(d2.keys())
intersect = s1.intersection(s2)
added = s1 - intersect
removed = s2 - intersect
changed = []
for o ... |
Use a slightly friendlier string than UUID for email addresses. | from google.appengine.ext import db
import uuid
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=str(uuid.uuid4()))
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.Date... | from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 10 digits. Since
there are 62 choices per digit, this gives:
62 ** 10 = 8.39299366 x 10 ** 17
possible results. When there are a million accounts active,
we need:
... |
Add support for only searching specified column | #!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
exgrep TERM [options] EXCEL_FILE...
Options:
TERM The term to grep for. Can be any valid (python) regular expression.
EXCEL_FILE The list of files to search through
-o Only output the matched part
"""
import re
from docopt import docopt
import ... | #!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
Usage:
exgrep TERM [options] EXCEL_FILE...
Options:
TERM The term to grep for. Can be any valid (python) regular expression.
EXCEL_FILE The list of files to search through
-c COL Only search in the column specified by COL.
-o Only output the match... |
Comment out code to test first_date variable. | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
print(data["Date Text"].head())... | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
print(data["Date Text"].head())... |
Use only long form arguments | #!/usr/bin/env python
import begin
import twitterlib
@begin.subcommand
def timeline():
"Display recent tweets from users timeline"
for status in begin.context.api.timeline:
print u"%s: %s" % (status.user.screen_name, status.text)
@begin.subcommand
def mentions():
"Display recent tweets mentionin... | #!/usr/bin/env python
import begin
import twitterlib
@begin.subcommand
def timeline():
"Display recent tweets from users timeline"
for status in begin.context.api.timeline:
print u"%s: %s" % (status.user.screen_name, status.text)
@begin.subcommand
def mentions():
"Display recent tweets mentionin... |
Create documentation of DataSource Settings | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... |
Add a check to see if the bot's in the channel the message should go to | from CommandTemplate import CommandTemplate
class Command(CommandTemplate):
triggers = ['say']
helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')"
adminOnly = True
showInCommandList = False
def execute(self, bot, user, target, triggerInMsg, msg, msgWithout... | from CommandTemplate import CommandTemplate
class Command(CommandTemplate):
triggers = ['say']
helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')"
adminOnly = True
showInCommandList = False
def execute(self, bot, user, target, triggerInMsg, msg, msgWithout... |
Remove unused import from tests | import inspect
from collections import defaultdict
import pytest
from funcy.funcmakers import *
def test_callable():
assert make_func(lambda x: x + 42)(0) == 42
def test_int():
assert make_func(0)('abc') == 'a'
assert make_func(2)([1,2,3]) == 3
assert make_func(1)({1: 'a'}) == 'a'
with pytest.r... | from collections import defaultdict
import pytest
from funcy.funcmakers import *
def test_callable():
assert make_func(lambda x: x + 42)(0) == 42
def test_int():
assert make_func(0)('abc') == 'a'
assert make_func(2)([1,2,3]) == 3
assert make_func(1)({1: 'a'}) == 'a'
with pytest.raises(IndexErro... |
Use uniform instead of random | #! /usr/bin/env python
# coding:utf-8
from mod import Mod
import random
import os
class ModDefault(Mod):
def __init__(
self,
filename=None,
logger=None
):
Mod.__init__(self, logger)
text_path = filename or os.path.join(
os.path.abspath(os.path.dirname(__fi... | #! /usr/bin/env python
# coding:utf-8
from mod import Mod
import random
import os
class ModDefault(Mod):
def __init__(
self,
filename=None,
logger=None
):
Mod.__init__(self, logger)
text_path = filename or os.path.join(
os.path.abspath(os.path.dirname(__fi... |
Add routes for new views | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'event_manager.views.home', name='home'),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'event_manager.views.home', name='home'),
url(r'^s/$', 'event_manager.views.my_suggestions', name='suggestions'),
url(r'^e/$', 'event_manager.views.my_events', na... |
Add avacon-style payment ids like the ones used at svscon |
from selvbetjening.core.events.models import request_attendee_pks_signal, find_attendee_signal, Attend
def avacon_style_attendee_pks_handler(sender, **kwargs):
attendee = kwargs['attendee']
key = 'Avacon.%s.%s.%s' % (attendee.event.pk,
attendee.user.pk,
... | |
Mark as python 3 compatable. | #!/usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
import os
from setuptools import setup, find_packages
here = os.path.dirname(__file__)
version_file = os.path.join(here, 'src/iptools/__init__.py')
d = {}
execfile(version_file, d)
version = d['__version__']
setup(
name = 'iptools',
... | #!/usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
import os
from setuptools import setup, find_packages
here = os.path.dirname(__file__)
version_file = os.path.join(here, 'src/iptools/__init__.py')
d = {}
execfile(version_file, d)
version = d['__version__']
setup(
name = 'iptools',
... |
Add missing dependency on Pillow | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
requirements = [
'pyzmq',
'docopt',
'virtualenv',
'requests'
]
setup(
name='tingbot... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
requirements = [
'pyzmq',
'docopt',
'virtualenv',
'requests',
'Pillow',
]
setup(
... |
Bump to next dev 0.1.2.dev1 | #!/usr/bin/env python3
# encoding: utf-8
from setuptools import setup, find_packages
setup(
name='pyatv',
version='0.1.1',
license='MIT',
url='https://github.com/postlund/pyatv',
author='Pierre Ståhl',
author_email='pierre.staahl@gmail.com',
description='Library for controlling an Apple TV... | #!/usr/bin/env python3
# encoding: utf-8
from setuptools import setup, find_packages
setup(
name='pyatv',
version='0.1.2.dev1',
license='MIT',
url='https://github.com/postlund/pyatv',
author='Pierre Ståhl',
author_email='pierre.staahl@gmail.com',
description='Library for controlling an App... |
Add support for null values in property mapping | from types import UnicodeType, StringType
class PropertyMappingFailedException(Exception):
pass
def get_transformed_properties(source_properties, prop_map):
results = {}
for key, value in prop_map.iteritems():
if type(value) in (StringType, UnicodeType):
if value in source_properties:
... | from types import UnicodeType, StringType
class PropertyMappingFailedException(Exception):
pass
def get_transformed_properties(source_properties, prop_map):
results = {}
for key, value in prop_map.iteritems():
if type(value) in (StringType, UnicodeType):
if value in source_properties:
... |
Correct detection on Garnet/Copper compute nodes | import platform
if platform.node().startswith('garnet') or platform.node().startswith('copper'):
from garnet import *
else:
from default import * | import os
if 'HOSTNAME' in os.environ:
if os.environ['HOSTNAME'].startswith('garnet') or os.environ['HOSTNAME'].startswith('copper'):
from garnet import *
else:
from default import * |
Include more tracks in jbrowsing of junctions | from collections import namedtuple
Junction = namedtuple('Junction',
['ref', 'ref_count', 'contig', 'contig_count'])
def get_ref_jbrowse_link(contig, loc):
return (contig.parent_reference_genome.get_client_jbrowse_link() +
'&loc=' + str(loc))
def decorate_with_link_to_loc(contig, lo... | from collections import namedtuple
import settings
Junction = namedtuple('Junction',
['ref', 'ref_count', 'contig', 'contig_count'])
def get_ref_jbrowse_link(contig, loc):
sample_alignment = contig.experiment_sample_to_alignment
bam_dataset = sample_alignment.dataset_set.get(
type='BWA ... |
Increase test coverage in utils.py | import pickle
from six.moves import range
from fuel.utils import do_not_pickle_attributes
@do_not_pickle_attributes("non_pickable", "bulky_attr")
class TestClass(object):
def __init__(self):
self.load()
def load(self):
self.bulky_attr = list(range(100))
self.non_pickable = lambda x: ... | from numpy.testing import assert_raises, assert_equal
from six.moves import range, cPickle
from fuel.iterator import DataIterator
from fuel.utils import do_not_pickle_attributes
@do_not_pickle_attributes("non_picklable", "bulky_attr")
class DummyClass(object):
def __init__(self):
self.load()
def loa... |
Fix path for saving imgs | import os
import json
from flask import Flask, request, Response
from flask import render_template, send_from_directory, url_for
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e"
ap... | import os
import json
from flask import Flask, request, Response
from flask import render_template, send_from_directory, url_for
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
basedir_img = os.path.abspath(os.path.dirname('angular_flask'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd... |
Make sure the customer has no plan nor is charged | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from ...actions import customers
class Command(BaseCommand):
help = "Create customer objects for existing users that do not have one"
def handle(self, *args, **options):
User = get_user_model()
... | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from ...actions import customers
class Command(BaseCommand):
help = "Create customer objects for existing users that do not have one"
def handle(self, *args, **options):
User = get_user_model()
... |
Use words for near zero and near one | """
Names of the modalities
"""
# Set constants of the names of the models so they can always be referenced
# as variables rather than strings
# Most of the density is at 0
NEAR_ZERO = '~0'
# Old "middle" modality - most of the density is at 0.5
NEAR_HALF = 'concurrent'
# Most of the density is at 1
NEAR_ONE = '~1'... | """
Names of the modalities
"""
# Set constants of the names of the models so they can always be referenced
# as variables rather than strings
# Most of the density is at 0
NEAR_ZERO = 'excluded'
# Old "middle" modality - most of the density is at 0.5
NEAR_HALF = 'concurrent'
# Most of the density is at 1
NEAR_ONE ... |
Remove the intentional throwing of internal server errors. | # -*- coding: utf-8 -*-
"""
Simple testing blueprint. Will be deleted once real functionality is added.
"""
import flask
import flask_classful
views = flask.Blueprint('views', __name__)
class IndexView(flask_classful.FlaskView):
"""
A simple home page.
"""
route_base = '/'
# noinspecti... | # -*- coding: utf-8 -*-
"""
Simple testing blueprint. Will be deleted once real functionality is added.
"""
import flask
import flask_classful
views = flask.Blueprint('views', __name__)
class IndexView(flask_classful.FlaskView):
"""
A simple home page.
"""
route_base = '/'
# noinspecti... |
Add commented-out test for init with no args | import os
from click.testing import CliRunner
from morenines import application
def test_init(data_dir):
runner = CliRunner()
result = runner.invoke(application.main, ['init', data_dir])
assert result.exit_code == 0
mn_dir = os.path.join(data_dir, '.morenines')
assert os.path.isdir(mn_dir) ==... | import os
from click.testing import CliRunner
from morenines import application
def test_init(data_dir):
runner = CliRunner()
result = runner.invoke(application.main, ['init', data_dir])
assert result.exit_code == 0
mn_dir = os.path.join(data_dir, '.morenines')
assert os.path.isdir(mn_dir) ==... |
Remove urlparse import as not used and also renamed in Python 3 to urllib.parse | from django.contrib.sites.shortcuts import get_current_site
from urlparse import urljoin
def site_url(request):
scheme = 'https' if request.is_secure() else 'http'
site = get_current_site(request)
#domain = "{}://{}".format(scheme, site.domain)
return {
'site_url': "{}://{}".format(scheme, sit... | from django.contrib.sites.shortcuts import get_current_site
def site_url(request):
scheme = 'https' if request.is_secure() else 'http'
site = get_current_site(request)
#domain = "{}://{}".format(scheme, site.domain)
return {
'site_url': "{}://{}".format(scheme, site.domain),
'site_nam... |
Add possibility of using apis with dashes without any workarounds | from types import ModuleType
from .resource import Resource
class SelfWrapper(ModuleType):
def __init__(self, self_module, baked_args={}):
for attr in ["__builtins__", "__doc__", "__name__", "__package__"]:
setattr(self, attr, getattr(self_module, attr, None))
self.__path__ = []
... | from types import ModuleType
from .resource import Resource
class SelfWrapper(ModuleType):
def __init__(self, self_module, baked_args={}):
for attr in ["__builtins__", "__doc__", "__name__", "__package__"]:
setattr(self, attr, getattr(self_module, attr, None))
self.__path__ = []
... |
Add expression slash to perhaps fix python3 bug | """
Tests for filetolist.py
filetolist.py:
http://www.github.com/samjabrahams/anchorhub/lib/filetolist.py
"""
from anchorhub.lib.filetolist import FileToList
from anchorhub.util.getanchorhubpath import get_anchorhub_path
from anchorhub.compatibility import get_path_separator
def test_file_to_list_basic():
sep = ... | """
Tests for filetolist.py
filetolist.py:
http://www.github.com/samjabrahams/anchorhub/lib/filetolist.py
"""
from anchorhub.lib.filetolist import FileToList
from anchorhub.util.getanchorhubpath import get_anchorhub_path
from anchorhub.compatibility import get_path_separator
def test_file_to_list_basic():
sep = ... |
Use importlib in favour of imp | import utilities
def parse(src):
if src == ':':
from ..description import default as desc
elif src.startswith(':'):
import importlib
desc = importlib.import_module(src[1:])
else:
import os, imp
from .. import description as parent_package # needs to be imported before its child modules
with open(src) a... | import importlib
def parse(src):
try:
if src == ':':
from ..description import default as desc
elif src.startswith(':'):
desc = importlib.import_module(src[1:], __package__.partition('.')[0])
else:
desc = importlib.machinery.SourceFileLoader(src, src).load_module()
except:
raise ImportError(src)
... |
Add docstrings to starting py program |
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def main(argv=None):
if argv is None:
argv = sys.argv
return 0
if __name__ == "__main__":
sys.exit(main())
| #!/usr/bin/env python3
# from __future__ import print_function #(if python2)
import sys
def eprint(*args, **kwargs):
""" Just like the print function, but on stderr
"""
print(*args, file=sys.stderr, **kwargs)
def main(argv=None):
""" Program starting point, it can started by the OS or as normal fun... |
Fix typo in cob migrate down | import click
import logbook
from .utils import appcontext_command
from ..ctx import context
import flask_migrate
_logger = logbook.Logger(__name__)
@click.group()
def migrate():
pass
@migrate.command()
@appcontext_command
def init():
flask_migrate.init('migrations', False)
@migrate.command()
@click.opt... | import click
import logbook
from .utils import appcontext_command
from ..ctx import context
import flask_migrate
_logger = logbook.Logger(__name__)
@click.group()
def migrate():
pass
@migrate.command()
@appcontext_command
def init():
flask_migrate.init('migrations', False)
@migrate.command()
@click.opt... |
Add a new invariant check: check blackholes *or* loops | from sts.invariant_checker import InvariantChecker
def check_for_loops_or_connectivity(simulation):
from sts.invariant_checker import InvariantChecker
result = InvariantChecker.check_loops(simulation)
if result:
return result
result = InvariantChecker.python_check_connectivity(simulation)
if not result:
... | from sts.invariant_checker import InvariantChecker
import sys
def bail_on_connectivity(simulation):
result = InvariantChecker.python_check_connectivity(simulation)
if not result:
print "Connectivity established - bailing out"
sys.exit(0)
return []
def check_for_loops_or_connectivity(simulation):
resul... |
Use a `TranslatableAdmin` for `Service`s | from django.contrib.admin import site, ModelAdmin
from .models import Issue, Jurisdiction, Service, Application
class ApplicationAdmin(ModelAdmin):
list_display = ('identifier', 'name', 'active')
list_filter = ('active',)
search_fields = ('identifier', 'name',)
def get_readonly_fields(self, requ... | from django.contrib.admin import site, ModelAdmin
from parler.admin import TranslatableAdmin
from .models import Issue, Jurisdiction, Service, Application
class ApplicationAdmin(ModelAdmin):
list_display = ('identifier', 'name', 'active')
list_filter = ('active',)
search_fields = ('identifier', 'name',)
... |
Enable ctrl-c control with rospy | #!/usr/bin/python
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
def main():
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
s.move_loop()
if __name__ == "__main__":
main()
| #!/usr/bin/python
import time
import rospy
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
def main():
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
while not rospy.is_shutdown():
s... |
Fix to test crontab dir | import unittest
from cronquot.cronquot import has_directory
class CronquotTest(unittest.TestCase):
def test_has_directory(self):
self.assertTrue(has_directory('/tmp'))
if __name__ == '__main__':
unittest.test()
| import unittest
import os
from cronquot.cronquot import has_directory
class CronquotTest(unittest.TestCase):
def test_has_directory(self):
sample_dir = os.path.join(
os.path.dirname(__file__), 'crontab')
self.assertTrue(has_directory(sample_dir))
if __name__ == '__main__':
un... |
Fix Brand and Owner public links (missing / would get a 404 on brand/ and owner/) | from django.conf.urls import patterns, url
from manager.apps.brand.views import BrandListView, BrandView
from manager.apps.brand.views import OwnerListView, OwnerView
urlpatterns = patterns(
'',
url(r'^brand$', BrandListView.as_view(), name='brandlist'),
url(r'^brand/(?P<bsin>[1-9A-NP-Z]{6})', BrandView.as... | from django.conf.urls import patterns, url
from manager.apps.brand.views import BrandListView, BrandView
from manager.apps.brand.views import OwnerListView, OwnerView
urlpatterns = patterns(
'',
url(r'^brand/$', BrandListView.as_view(), name='brandlist'),
url(r'^brand/(?P<bsin>[1-9A-NP-Z]{6})', BrandView.a... |
Test stable channel instead of testing channel for eigen | from conans.model.conan_file import ConanFile
from conans import CMake
import os
class DefaultNameConan(ConanFile):
name = "DefaultName"
version = "0.1"
settings = "os", "compiler", "arch", "build_type"
generators = "cmake"
requires = "eigen/3.2@jslee02/testing"
def build(self):
cmake ... | from conans.model.conan_file import ConanFile
from conans import CMake
import os
class DefaultNameConan(ConanFile):
name = "DefaultName"
version = "0.1"
settings = "os", "compiler", "arch", "build_type"
generators = "cmake"
requires = "eigen/3.2@jslee02/stable"
def build(self):
cmake =... |
Add script to move secrets file | """
Move the right secrets file into place for Travis CI.
"""
| """
Move the right secrets file into place for Travis CI.
"""
import os
import shutil
from pathlib import Path
def move_secrets_file() -> None:
"""
Move the right secrets file to the current directory.
"""
branch = os.environ['TRAVIS_BRANCH']
is_pr = os.environ['TRAVIS_PULL_REQUEST'] != 'false'
... |
Change dname of key test | from ev3.ev3dev import Key
import unittest
from util import get_input
import time
class TestTone(unittest.TestCase):
def test_tone(self):
d = Key()
get_input('Test keyboard. Hold Up key')
print(d.up)
get_input('Test keyboard. Release Up key')
print(d.up)
get_input(... | from ev3.ev3dev import Key
import unittest
from util import get_input
class TestKey(unittest.TestCase):
def test_key(self):
d = Key()
get_input('Test keyboard. Hold Up key')
print(d.up)
get_input('Test keyboard. Release Up key')
print(d.up)
get_input('Test keyboard... |
Fix bug with list formatting | from enum import Enum, unique
from inspect import signature, isclass
from mycroft.plugin.base_plugin import BasePlugin
from mycroft.util import log
@unique
class Format(Enum):
speech = 1
text = 2
class FormatterPlugin(BasePlugin):
and_ = 'and'
def __init__(self, rt):
super().__init__(rt)
... | from enum import Enum, unique
from inspect import signature, isclass
from mycroft.plugin.base_plugin import BasePlugin
from mycroft.util import log
@unique
class Format(Enum):
speech = 1
text = 2
class FormatterPlugin(BasePlugin):
and_ = 'and'
def __init__(self, rt):
super().__init__(rt)
... |
Sort out the server announce message |
import parse
import generate as gen
from repos import find_repos
from errors import *
def parse_client_greeting(msg_str):
msg = parse.msg(msg_str)
proto_ver = int(msg[0])
client_caps = msg[1]
url = parse.string(msg[2])
print "ver: %d" % proto_ver
print "caps: %s" % client_caps
print "url... |
import parse
import generate as gen
from repos import find_repos
from errors import *
server_capabilities = [
'edit-pipeline', # This is required.
'svndiff1', # We support svndiff1
'absent-entries', # We support absent-dir and absent-dir editor commands
#'commit-revprops', # We don't curr... |
Set Picking Type in Create | # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
@api.model
def _get_default_picking_type(self):
return self.env['stock.picki... | # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
@api.model
def _get_default_picking_type(self):
return self.env['stock.picki... |
Make sure test works with new API | import luigi
import sciluigi as sl
import os
TESTFILE_PATH = '/tmp/test.out'
class TestTask(sl.Task):
def out_data(self):
return sl.TargetInfo(self, TESTFILE_PATH)
def run(self):
with self.out_data().open('w') as outfile:
outfile.write('File written by luigi\n')
class TestRunTas... | import luigi
import sciluigi as sl
import os
TESTFILE_PATH = '/tmp/test.out'
class TestTask(sl.Task):
def out_data(self):
return sl.TargetInfo(self, TESTFILE_PATH)
def run(self):
with self.out_data().open('w') as outfile:
outfile.write('File written by luigi\n')
class TestRunTas... |
Remove unneeded shebang line that was triggering some linters. | #!/usr/bin/env python3
# Copyright 2016 The Meson development team
# 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 appl... | # Copyright 2016 The Meson development team
# 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 ... |
Add new-line at EOF, when dumping userdb | import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self... | import json
class Database(dict):
"""Holds a dict that contains all the information about the users in a channel"""
def __init__(self, irc):
super(Database, self).__init__(json.load(open("userdb.json")))
self.irc = irc
def remove_entry(self, event, nick):
try:
del self... |
Fix document format of as_strided | import cupy
def as_strided(x, shape=None, strides=None):
"""
Create a view into the array with the given shape and strides.
.. warning:: This function has to be used with extreme care, see notes.
Parameters
----------
x : ndarray
Array to create a new.
shape : sequence of int, opt... | import cupy
def as_strided(x, shape=None, strides=None):
"""
Create a view into the array with the given shape and strides.
.. warning:: This function has to be used with extreme care, see notes.
Parameters
----------
x : ndarray
Array to create a new.
shape : sequence of int, op... |
Add list_filter to example ArticleAdmin | from django.contrib import admin
from django.contrib.admin.widgets import AdminTextInputWidget, AdminTextareaWidget
from parler.admin import TranslatableAdmin
from .models import Article
from parler.forms import TranslatableModelForm, TranslatedField
class ArticleAdminForm(TranslatableModelForm):
"""
Example ... | from django.contrib import admin
from django.contrib.admin.widgets import AdminTextInputWidget, AdminTextareaWidget
from parler.admin import TranslatableAdmin
from .models import Article
from parler.forms import TranslatableModelForm, TranslatedField
class ArticleAdminForm(TranslatableModelForm):
"""
Example ... |
Add url leading to student council archive | from django.conf.urls import patterns, url
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
)
| from django.conf.urls import patterns, url
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
)
|
Enable livereload on dev by default | import logging
ENV = 'development'
APP_DEBUG = False # Avoid using this in debug mode
# CORS configuration
CORS_HEADERS = 'Content-Type'
CORS_ORIGINS = '*'
KEYSPACE = "annotator_supreme3"
#Logging
LOG_LEVEL = logging.INFO
| import logging
ENV = 'development'
APP_DEBUG = True # Avoid using this in debug mode
# CORS configuration
CORS_HEADERS = 'Content-Type'
CORS_ORIGINS = '*'
KEYSPACE = "annotator_supreme3"
#Logging
LOG_LEVEL = logging.INFO
|
Add ssa2, zp to baseline | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral =... | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral =... |
Read binary data file location from commandline | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
... | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline... |
Deploy smart contracts v0.0.6 to Ropsten | # -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
# Deployed to Ropsten revival on 2017-08-18 from commit 01554102f0a52fc5aec3f41dc46d53017108b400
ROPSTEN_REGISTRY_ADDRESS = '7205a22f083a12d1b22ee89d7e892d23b1f1438a'
ROPSTEN_DIS... | # -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
# Deployed to Ropsten revival on 2017-09-03 from commit f4f8dcbe791b7be8bc15475f79ad9cbbfe15435b
ROPSTEN_REGISTRY_ADDRESS = 'ce30a13daa47c0f35631e5ed750e39c12172f325'
ROPSTEN_DIS... |
Update the models for Auth and User. | from django.shortcuts import render
# Create your views here.
| from django.shortcuts import render
from django.contrib.auth import login, logout
from django.contrib.auth.models import User
from rest_framework import viewsets
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views her... |
Use new line style for Generalization item | """
Generalization --
"""
from gi.repository import GObject
from gaphor import UML
from gaphor.diagram.diagramline import DiagramLine
class GeneralizationItem(DiagramLine):
__uml__ = UML.Generalization
__relationship__ = "general", None, "specific", "generalization"
def __init__(self, id=None, model=N... | """
Generalization --
"""
from gi.repository import GObject
from gaphor import UML
from gaphor.UML.modelfactory import stereotypes_str
from gaphor.diagram.presentation import LinePresentation
from gaphor.diagram.shapes import Box, Text
from gaphor.diagram.support import represents
@represents(UML.Generalization)
cl... |
Fix test helper once and for all | import github3
from .helper import IntegrationHelper
def find(func, iterable):
return next(filter(func, iterable))
class TestDeployment(IntegrationHelper):
def test_create_status(self):
"""
Test that using a Deployment instance, a user can create a status.
"""
self.basic_log... | import github3
from .helper import IntegrationHelper
def find(func, iterable):
return next(iter(filter(func, iterable)))
class TestDeployment(IntegrationHelper):
def test_create_status(self):
"""
Test that using a Deployment instance, a user can create a status.
"""
self.bas... |
Compress data sent to Coveralls using gzip | import requests
def upload(data):
r = requests.post('https://coveralls.io/api/v1/jobs', files={
'json_file': data
})
try:
print(r.json())
except ValueError:
raise Exception('Failure to submit data. Response [%s]: %s' % (r.status_code, r.text)) # NOQA
| import gzip
import requests
def upload(data):
r = requests.post('https://coveralls.io/api/v1/jobs', files={
'json_file': ('json_file', gzip.compress(data), 'gzip/json')
})
try:
print(r.json())
except ValueError:
raise Exception('Failure to submit data. Response [%s]: %s' % (r.... |
Standardize bar chat with labels example to use source consistent with other examples | """
Simple Bar Chart with Labels
============================
This example shows a basic horizontal bar chart with labels created with Altair.
"""
# category: bar charts
import altair as alt
import pandas as pd
source = pd.DataFrame({
'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
'b': [28, 55, 43, 91, 81... | """
Bar Chart with Labels
=====================
This example shows a basic horizontal bar chart with labels created with Altair.
"""
# category: bar charts
import altair as alt
from vega_datasets import data
source = data.wheat.url
bars = alt.Chart(source).mark_bar().encode(
x='wheat:Q',
y="year:O"
)
text = ... |
Change the background to reflect the color chosen | from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
class ColorPickerWidget(forms.TextInput):
class Media:
css = {
"all": ("%s/%s" % (settings.STATIC_URL, "paintstore/css/colorpicker.css"),)
}
js = (
("%s/%s" % (... | from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
class ColorPickerWidget(forms.TextInput):
class Media:
css = {
"all": ("%s/%s" % (settings.STATIC_URL, "paintstore/css/colorpicker.css"),)
}
js = (
("%s/%s" % (... |
Increase re-running limit of test_profiler | # -*- coding: utf-8 -*-
from __future__ import division
import sys
import pytest
from profiling.sampling import SamplingProfiler
from profiling.sampling.samplers import ItimerSampler
from utils import find_stat, spin
def spin_100ms():
spin(0.1)
def spin_500ms():
spin(0.5)
@pytest.mark.flaky(reruns=5)
de... | # -*- coding: utf-8 -*-
from __future__ import division
import sys
import pytest
from profiling.sampling import SamplingProfiler
from profiling.sampling.samplers import ItimerSampler
from utils import find_stat, spin
def spin_100ms():
spin(0.1)
def spin_500ms():
spin(0.5)
@pytest.mark.flaky(reruns=10)
d... |
Fix format issue with `__repr__` | import enum
from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum
from virtool.postgres import Base
class UploadType(str, enum.Enum):
hmm = "hmm"
reference = "reference"
reads = "reads"
subtraction = "subtraction"
class Upload(Base):
__tablename__ = "uploads"
id = Column... | import enum
from sqlalchemy import Column, String, Boolean, Integer, DateTime, Enum
from virtool.postgres import Base
class UploadType(str, enum.Enum):
hmm = "hmm"
reference = "reference"
reads = "reads"
subtraction = "subtraction"
class Upload(Base):
__tablename__ = "uploads"
id = Column... |
Make sure slugs are unique and not integer only. | from django.db import models
# Represents a category which articles can be part of
class Category(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255)
def __str__(self):
return self.name+" ["+str(self.id)+"]"
# Article model represents one article in the... | from django.db import models
import random
import re
import string
# Represents a category which articles can be part of
class Category(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255)
def __str__(self):
return self.name+" ["+str(self.id)+"]"
def... |
Add comment clarifying how it operates. | import string
def untokenize(tokens):
return "".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in tokens]).strip()
| import string
def untokenize(tokens):
#Joins all tokens in the list into a single string.
#If a token doesn't start with an apostrophe and isn't a punctuation mark, add a space in front of it before joining.
#Then strip the total string so that leading spaces and trailing spaces are removed.
return "".join([" "+i i... |
Set default taking access for GradingProjectSurvey to org. | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange 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... | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange 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... |
Add OCA as author of OCA addons | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 ABF OSIELL (<http://osiell.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 ABF OSIELL (<http://osiell.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... |
Fix Tempest tests failing on gate-solum-devstack-dsvm | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Noorul Islam K M
#
# 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 applic... | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Noorul Islam K M
#
# 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 applic... |
Support new versions with django-gm2m | """GM2MField support for autocomplete fields."""
class GM2MFieldMixin(object):
"""GM2MField ror FutureModelForm."""
def value_from_object(self, instance, name):
"""Return the list of objects in the GM2MField relation."""
return None if not instance.pk else [
x for x in getattr(ins... | """GM2MField support for autocomplete fields."""
class GM2MFieldMixin(object):
"""GM2MField ror FutureModelForm."""
def value_from_object(self, instance, name):
"""Return the list of objects in the GM2MField relation."""
return None if not instance.pk else [
getattr(x, 'gm2m_tgt',... |
Add pupular RC objects to index view. | from django.shortcuts import render, render_to_response
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback
def corporation_benefit_plan(request):
return render(request... | from django.shortcuts import render, render_to_response
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback
def corporation_benefit_plan(request):
return render(request... |
Add own tuple_index function to stay compatible with python 2.5 | from social_auth.backends import PIPELINE
from social_auth.utils import setting
PIPELINE_ENTRY = 'social_auth.backends.pipeline.misc.save_status_to_session'
def save_status_to_session(request, auth, *args, **kwargs):
"""Saves current social-auth status to session."""
next_entry = setting('SOCIAL_AUTH_PIPELI... | from social_auth.backends import PIPELINE
from social_auth.utils import setting
PIPELINE_ENTRY = 'social_auth.backends.pipeline.misc.save_status_to_session'
def tuple_index(t, e):
for (i, te) in enumerate(t):
if te == e:
return i
return None
def save_status_to_session(request, auth, *arg... |
Modify worker to requeue jobs if worker is killed | from scoring_engine.celery_app import celery_app
from celery.exceptions import SoftTimeLimitExceeded
import subprocess
from scoring_engine.logger import logger
@celery_app.task(name='execute_command', soft_time_limit=30)
def execute_command(job):
output = ""
# Disable duplicate celery log messages
if log... | from scoring_engine.celery_app import celery_app
from celery.exceptions import SoftTimeLimitExceeded
import subprocess
from scoring_engine.logger import logger
@celery_app.task(name='execute_command', acks_late=True, reject_on_worker_lost=True, soft_time_limit=30)
def execute_command(job):
output = ""
# Disa... |
Make Django 1.7 migrations compatible with Python3 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='File',
fields=[
('... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='File',
fields=[
('... |
Fix relative import (compatible with p3 | import os
from binstar_client import errors
from uploader import *
def parse(handle):
"""
Handle can take the form of:
notebook
path/to/notebook[.ipynb]
project:notebook[.ipynb]
:param handle: String
:return: (project, notebook)
:raises: NotebookNotFound
"""
if ':'... | import os
from binstar_client import errors
from .uploader import *
def parse(handle):
"""
Handle can take the form of:
notebook
path/to/notebook[.ipynb]
project:notebook[.ipynb]
:param handle: String
:return: (project, notebook)
:raises: NotebookNotFound
"""
if ':... |
Tweak the tastypie resource configuration. | from tastypie.resources import ModelResource
from olcc.models import Product, ProductPrice, Store
class ProductResource(ModelResource):
class Meta:
queryset = Product.objects.all()
resource_name = 'product'
class ProductPriceResource(ModelResource):
class Meta:
queryset = ProductPrice.... | from tastypie import fields
from tastypie.resources import ModelResource, ALL
from olcc.models import Product, ProductPrice, Store
class ProductResource(ModelResource):
class Meta:
queryset = Product.objects.all()
resource_name = 'product'
allowed_methods = ['get']
filtering = {
... |
Update help_text in api_auth initial migration | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Token',
fields=[
('token', models.CharField(hel... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Token',
fields=[
('token', models.CharField(hel... |
Use importlib.metadata to set __version__ | # coding:utf-8
"""
Function decoration for backoff and retry
This module provides function decorators which can be used to wrap a
function such that it will be retried until some condition is met. It
is meant to be of use when accessing unreliable resources with the
potential for intermittent failures i.e. network res... | # coding:utf-8
"""
Function decoration for backoff and retry
This module provides function decorators which can be used to wrap a
function such that it will be retried until some condition is met. It
is meant to be of use when accessing unreliable resources with the
potential for intermittent failures i.e. network res... |
Update tests to deal with changeset 41943013, in which the Royal Academy of Arts was changed to a museum. | # http://www.openstreetmap.org/node/2026996113
assert_has_feature(
16, 10485, 25328, 'pois',
{ 'id': 2026996113, 'kind': 'gallery', 'min_zoom': 17 })
# http://www.openstreetmap.org/way/31510288
assert_has_feature(
15, 16371, 10895, 'pois',
{ 'id': 31510288, 'kind': 'gallery' })
| # http://www.openstreetmap.org/node/2026996113
assert_has_feature(
16, 10485, 25328, 'pois',
{ 'id': 2026996113, 'kind': 'gallery', 'min_zoom': 17 })
# https://www.openstreetmap.org/way/83488820
assert_has_feature(
15, 16370, 10894, 'pois',
{ 'id': 83488820, 'kind': 'gallery' })
|
Allow more complex targetting in script test | from gevent import monkey
monkey.patch_all() # noqa
import sys
import time
from ethereum import slogging
from raiden.network.transport import UDPTransport
from raiden.network.sockfactory import socket_factory
class DummyProtocol(object):
def __init__(self):
self.raiden = None
def receive(self, da... | """
Usage:
transport_tester.py [--port=<port>] [<target_ip_optional_port>]
Options:
-p --port=<port> Number to use [default: 8885].
"""
from gevent import monkey
monkey.patch_all() # noqa
import time
from docopt import docopt
from ethereum import slogging
from raiden.network.transport impo... |
Add some draft weather types | class WeatherType:
def __init__(self, weathers, temperature_range, temperature_night_offset,
wind_range, humidity_range):
self.__weathers = weathers
self.__min_temp_day, self.__max_temp_day = \
tuple(temperature_range)
self.__min_temp_night, self.__max_temp_night ... | class WeatherType:
def __init__(self, weathers, temperature_range, temperature_night_offset,
wind_range, humidity_range):
self.__weathers = weathers
self.__min_temp_day, self.__max_temp_day = \
tuple(temperature_range)
self.__min_temp_night, self.__max_temp_night ... |
Add initi for beautiful API | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: balicanta
# @Date: 2014-11-01 21:02:00
# @Last Modified by: balicanta
# @Last Modified time: 2014-11-01 21:02:00
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: balicanta
# @Date: 2014-11-01 21:02:00
# @Last Modified by: balicanta
# @Last Modified time: 2014-11-05 22:19:01
from NewsParser import NewsParser
|
Change the name of module in the manifest | # -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Field(s) Required Res Partner",
"summary": "Customers and Suppliers Field Required",
"version": "9.0.1.0.0",
"category": "",
"website": "https://odoo-community.org/",
... | # -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Field Required in Partners",
"summary": "Customers and Suppliers Field Required",
"version": "9.0.1.0.0",
"category": "",
"website": "https://odoo-community.org/",
"a... |
Fix error where self.config was undefined | import zirc
import ssl
import socket
import utils
import commands
debug = False
class Bot(zirc.Client):
def __init__(self):
self.connection = zirc.Socket(family=socket.AF_INET6,
wrapper=ssl.wrap_socket)
self.config = zirc.IRCConfig(host="chat.freenode.net",
... | import zirc
import ssl
import socket
import utils
import commands
debug = False
class Bot(zirc.Client):
def __init__(self):
self.connection = zirc.Socket(family=socket.AF_INET6,
wrapper=ssl.wrap_socket)
self.config = zirc.IRCConfig(host="chat.freenode.net",
... |
Fix docstring in `PacmanUnpackGroup` fact. | from pyinfra.api import FactBase
from .util.packaging import parse_packages
PACMAN_REGEX = r'^([0-9a-zA-Z\-]+)\s([0-9\._+a-z\-]+)'
class PacmanUnpackGroup(FactBase):
'''
Returns a list of actual packages belonging to the provided package name,
expanding groups or virtual packages.
.. code:: python
... | from pyinfra.api import FactBase
from .util.packaging import parse_packages
PACMAN_REGEX = r'^([0-9a-zA-Z\-]+)\s([0-9\._+a-z\-]+)'
class PacmanUnpackGroup(FactBase):
'''
Returns a list of actual packages belonging to the provided package name,
expanding groups or virtual packages.
.. code:: python
... |
Add read image in color | import numpy as np
import cv2
# Load an image in color
img = cv2.imread("doge.jpeg", 1)
cv2.imshow("image", img)
key = cv2.waitKey(0)
cv2.destroyAllWindows() | |
Add explanatory docstring for the purpose of the go api proxy view | from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from go.api.go_api import client
import logging
logger = logging.getLogger(__name__)
@login_required
@csr... | from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from go.api.go_api import client
import logging
logger = logging.getLogger(__name__)
@login_required
@csr... |
Add allowed_system as a class variable | import platform
class OSXDodger(object):
allowed_version = "10.12.1"
def __init__(self, applications_dir):
self.app_dir = applications_dir
def load_applications(self):
"""
Read all applications in the `/Applications/` dir
"""
self.pc_is_macintosh()
def select... | import platform
class OSXDodger(object):
allowed_version = "10.6.1"
allowed_system = "darwin"
def __init__(self, applications_dir):
self.app_dir = applications_dir
def load_applications(self):
"""
Read all applications in the `/Applications/` dir
"""
self.pc_i... |
Make RecordingManager work with new plugin system | # -*- coding: utf-8 -*-
##
## $Id: __init__.py,v 1.10 2009/04/09 13:13:18 dmartinc Exp $
##
## This file is part of CDS Indico.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
##
## CDS Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
##... | # -*- coding: utf-8 -*-
##
## $Id: __init__.py,v 1.10 2009/04/09 13:13:18 dmartinc Exp $
##
## This file is part of CDS Indico.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
##
## CDS Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
##... |
Increase version 3.0.0 -> 3.1.1 | #!/usr/bin/env python
from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code
version = '3.0.0'
author = 'David-Leon Pohl, Jens Janssen'
author_email = 'pohl@physik.uni-bonn.de, janssen@physik.uni-bonn.de'
# requirements for core functionali... | #!/usr/bin/env python
from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code
version = '3.1.1'
author = 'David-Leon Pohl, Jens Janssen'
author_email = 'pohl@physik.uni-bonn.de, janssen@physik.uni-bonn.de'
# requirements for core functionali... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.