Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Set Content-Type header for S3 uploads | import os
import boto
import datetime
class S3(object):
def __init__(self, bucket_name=None, host='s3-eu-west-1.amazonaws.com'):
conn = boto.connect_s3(host=host)
self.bucket_name = bucket_name
self.bucket = conn.get_bucket(bucket_name)
def save(self, path, name, file, acl='public-re... | import os
import boto
import datetime
import mimetypes
class S3(object):
def __init__(self, bucket_name=None, host='s3-eu-west-1.amazonaws.com'):
conn = boto.connect_s3(host=host)
self.bucket_name = bucket_name
self.bucket = conn.get_bucket(bucket_name)
def save(self, path, name, fil... |
Fix missing githubIssue field when the corresponding issue already existed. | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repositor... | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repositor... |
Fix silly boiler plate copy issue. | from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
... | from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
... |
Update to v1.6.1 for release | # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.6.0"
| # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.6.1"
|
Remove some debug logging config | default_app_config = 'promgen.apps.PromgenConfig'
import logging
logging.basicConfig(level=logging.DEBUG)
| default_app_config = 'promgen.apps.PromgenConfig'
|
Update Arch package to 2.7 | #
# Biicode Arch Linux package settings.
#
# Check PKGBUILD_template docs for those settings and
# what they mean.
#
def settings():
return { "version": "2.6.1",
"release_number": "1",
"arch_deps": ["cmake>=3.0.2",
"zlib",
"glibc",
"sqlite",
... | #
# Biicode Arch Linux package settings.
#
# Check PKGBUILD_template docs for those settings and
# what they mean.
#
def settings():
return { "version": "2.7",
"release_number": "1",
"arch_deps": ["cmake>=3.0.2",
"zlib",
"glibc",
"sqlite",
... |
Convert JSON into Tweet and TwitterUser objects | from requests_oauthlib import OAuth1
from TweetPoster import User, config
class Twitter(User):
def __init__(self, *a, **kw):
super(Twitter, self).__init__(*a, **kw)
self.session.auth = OAuth1(
config['twitter']['consumer_key'],
config['twitter']['consumer_secret'],
... | from datetime import datetime
from requests_oauthlib import OAuth1
from TweetPoster import User, config
class Twitter(User):
def __init__(self, *a, **kw):
super(Twitter, self).__init__(*a, **kw)
self.session.auth = OAuth1(
config['twitter']['consumer_key'],
config['twit... |
Fix `vintageous_enter_insert_mode` for NeoVintageous 1.22.0 | from sublime_plugin import TextCommand
from ...core.git_command import GitCommand
__all__ = (
"gs_handle_vintageous",
"gs_handle_arrow_keys"
)
class gs_handle_vintageous(TextCommand, GitCommand):
"""
Set the vintageous_friendly view setting if needed.
Enter insert mode if vintageous_enter_inser... | from sublime_plugin import TextCommand
from ...core.git_command import GitCommand
__all__ = (
"gs_handle_vintageous",
"gs_handle_arrow_keys"
)
class gs_handle_vintageous(TextCommand, GitCommand):
"""
Set the vintageous_friendly view setting if needed.
Enter insert mode if vintageous_enter_inser... |
Add trigger to module import | __version__ = '0.2'
__author__ = 'Dan Persons <dpersonsdev@gmail.com>'
__license__ = 'MIT License'
__github__ = 'https://github.com/dogoncouch/siemstress'
__all__ = ['core', 'querycore', 'query']
import siemstress.query
| __version__ = '0.2'
__author__ = 'Dan Persons <dpersonsdev@gmail.com>'
__license__ = 'MIT License'
__github__ = 'https://github.com/dogoncouch/siemstress'
__all__ = ['core', 'querycore', 'query']
import siemstress.query
import siemstress.trigger
|
Add a (temporary) bounding box around an added mesh | from PyQt5.QtCore import QObject, QCoreApplication, pyqtSlot, QUrl
from Cura.Application import Application
from Cura.Scene.SceneNode import SceneNode
class ControllerProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._controller = Application.getInstance().getControl... | from PyQt5.QtCore import QObject, QCoreApplication, pyqtSlot, QUrl
from Cura.Application import Application
from Cura.Scene.SceneNode import SceneNode
from Cura.Scene.BoxRenderer import BoxRenderer
class ControllerProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._co... |
Change the new endpoint function name | from flask import Flask
import relay_api.api.backend as backend
server = Flask(__name__)
backend.init_relays()
@server.route("/relay-api/relays/", methods=["GET"])
def get_all_relays():
js = backend.get_all_relays()
return js, 200
@server.route("/relay-api/relays/<relay_name>", methods=["GET"])
def get_r... | from flask import Flask
import relay_api.api.backend as backend
server = Flask(__name__)
backend.init_relays()
@server.route("/relay-api/relays/", methods=["GET"])
def get_all_relays():
js = backend.get_all_relays()
return js, 200
@server.route("/relay-api/relays/<relay_name>", methods=["GET"])
def get_r... |
Add check for `micawber` existance in `oembeditem` plugin. | VERSION = (0, 1, 0)
# Do some version checking
try:
import micawber
except ImportError:
raise ImportError("The 'micawber' package is required to use the 'oembeditem' plugin.")
| |
Add import statement for os | #!/usr/bin/env python
##########################################################################
# scripts/ec2/terminate_all.py
#
# Part of Project Thrill - http://project-thrill.org
#
# Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
#
# All rights reserved. Published under the BSD-2 license in the LICENSE file.
##... | #!/usr/bin/env python
##########################################################################
# scripts/ec2/terminate_all.py
#
# Part of Project Thrill - http://project-thrill.org
#
# Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
#
# All rights reserved. Published under the BSD-2 license in the LICENSE file.
##... |
Fix charts() test (now there are only 174 charts) | # -*- coding: utf-8 -*-
import billboard
import unittest
from nose.tools import raises
from requests.exceptions import ConnectionError
import six
class MiscTest(unittest.TestCase):
@raises(ConnectionError)
def testTimeout(self):
"""Checks that using a very small timeout prevents connection."""
... | # -*- coding: utf-8 -*-
import billboard
import unittest
from nose.tools import raises
from requests.exceptions import ConnectionError
import six
class MiscTest(unittest.TestCase):
@raises(ConnectionError)
def testTimeout(self):
"""Checks that using a very small timeout prevents connection."""
... |
Address model testing coverage: 100% | # -*- coding: utf-8
from __future__ import unicode_literals
from django.test import TestCase
from django.contrib.auth import get_user_model
from shop.models.defaults.address import ShippingAddress, BillingAddress # noqa
from shop.models.defaults.customer import Customer
class AddressTest(TestCase):
def setUp(se... | # -*- coding: utf-8
from __future__ import unicode_literals
from django.test import TestCase
from django.contrib.auth import get_user_model
from shop.models.defaults.address import ShippingAddress
from shop.models.defaults.customer import Customer
class AddressTest(TestCase):
def setUp(self):
super(Addre... |
Check if service is working | # -*- coding: utf-8 -*-
from dbaas.celery import app
from account.models import User
from logical.models import Database
from util.decorators import only_one
from simple_audit.models import AuditRequest
from dbaas_services.analyzing.integration import AnalyzeService
@app.task
@only_one(key="analyze_databases_service_... | # -*- coding: utf-8 -*-
import logging
from dbaas.celery import app
from account.models import User
from logical.models import Database
from util.decorators import only_one
from simple_audit.models import AuditRequest
from dbaas_services.analyzing.integration import AnalyzeService
from dbaas_services.analyzing.exceptio... |
Add note to misleading test | """Plot to test custom date axis tick locations and labels"""
from datetime import datetime
import matplotlib.pyplot as plt
import mpld3
def create_plot():
times = [datetime(2013, 12, i) for i in range(1, 20)]
ticks = [times[0], times[1], times[2], times[6], times[-2], times[-1]]
labels = [t.strftime("%Y-... | """
Plot to test custom date axis tick locations and labels
NOTE (@vladh): We may see different behaviour in mpld3 vs d3 for the y axis, because we never
specified exactly how we want the y axis formatted. This is ok.
"""
from datetime import datetime
import matplotlib.pyplot as plt
import mpld3
def create_plot():
... |
Remove 'TAS' from games blacklist | from bs4 import BeautifulSoup
import requests
import json
import sys
html = requests.get("http://gamesdonequick.com/schedule").text
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('tbody')
first_rows = table.findAll('tr', attrs={'class': None})
games = list()
for row in first_rows:
second_row = row.fi... | from bs4 import BeautifulSoup
import requests
import json
import sys
html = requests.get("http://gamesdonequick.com/schedule").text
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('tbody')
first_rows = table.findAll('tr', attrs={'class': None})
games = list()
for row in first_rows:
second_row = row.fi... |
Make environ context helper test more accurate | """
Tests for our tests helpers 8-}
"""
import os
import sys
from helpers import ArgvContext, EnvironContext
def test_argv_context():
"""
Test if ArgvContext sets the right argvs and resets to the old correctly
"""
old = sys.argv
new = ["Alice", "Bob", "Chris", "Daisy"]
assert sys.argv == o... | """
Tests for our tests helpers 8-}
"""
import os
import sys
from helpers import ArgvContext, EnvironContext
def test_argv_context():
"""
Test if ArgvContext sets the right argvs and resets to the old correctly
"""
old = sys.argv
new = ["Alice", "Bob", "Chris", "Daisy"]
assert sys.argv == o... |
Use division_id in place of bounary_id | import os
import logging
import unicodecsv
from billy.core import settings, db
from billy.bin.commands import BaseCommand
logger = logging.getLogger('billy')
class LoadDistricts(BaseCommand):
name = 'loaddistricts'
help = 'Load in the Open States districts'
def add_args(self):
self.add_argument... | import os
import logging
import unicodecsv
from billy.core import settings, db
from billy.bin.commands import BaseCommand
logger = logging.getLogger('billy')
class LoadDistricts(BaseCommand):
name = 'loaddistricts'
help = 'Load in the Open States districts'
def add_args(self):
self.add_argument... |
Add helper function to save state | """Module for Enaml widgets that are generally useful"""
from enaml.widgets.api import PushButton, Timer
from atom.api import Typed, observe, Event
from enaml.core.declarative import d_
from enaml.layout.api import (grid, align)
class ProgrammaticButton(PushButton):
clicked = d_(Event(bool), writable=True)
tog... | """Module for Enaml widgets that are generally useful"""
from enaml.widgets.api import PushButton, Timer
from atom.api import Typed, observe, Event
from enaml.core.declarative import d_
from enaml.layout.api import (grid, align)
class ProgrammaticButton(PushButton):
clicked = d_(Event(bool), writable=True)
tog... |
Use __all__ to shut up Flake8 | # IMPORT ORDER MATTERS!
# inherit from BaseConfig
from cumulusci.core.keychain.BaseProjectKeychain import BaseProjectKeychain
from cumulusci.core.keychain.BaseProjectKeychain import DEFAULT_CONNECTED_APP
# inherit from BaseProjectKeychain
from cumulusci.core.keychain.BaseEncryptedProjectKeychain import (
BaseEncr... | # IMPORT ORDER MATTERS!
# inherit from BaseConfig
from cumulusci.core.keychain.BaseProjectKeychain import BaseProjectKeychain
from cumulusci.core.keychain.BaseProjectKeychain import DEFAULT_CONNECTED_APP
# inherit from BaseProjectKeychain
from cumulusci.core.keychain.BaseEncryptedProjectKeychain import (
BaseEncr... |
Fix hello world sample flow | from viewflow import flow, lock, views as flow_views
from viewflow.base import this, Flow
from viewflow.site import viewsite
from .models import HelloWorldProcess
from .tasks import send_hello_world_request
class HelloWorldFlow(Flow):
"""
Hello world
This process demonstrates hello world approval reque... | from viewflow import flow, lock, views as flow_views
from viewflow.base import this, Flow
from viewflow.site import viewsite
from .models import HelloWorldProcess
from .tasks import send_hello_world_request
class HelloWorldFlow(Flow):
"""
Hello world
This process demonstrates hello world approval reque... |
Print test names when running full testsuite | import sys, os
import unittest
try: # use the 'installed' mpi4py
import mpi4py
except ImportError: # or the no yet installed mpi4py
from distutils.util import get_platform
plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3])
os.path.split(__file__)[0]
path = os.path.join(os.path.split(__f... | import sys, os
import unittest
try: # use the 'installed' mpi4py
import mpi4py
except ImportError: # or the no yet installed mpi4py
from distutils.util import get_platform
plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3])
os.path.split(__file__)[0]
path = os.path.join(os.path.split(__f... |
Fix PicleCache error on Python3 | from __future__ import with_statement
import os
import pickle
from contextlib import closing
try:
from redis import Redis
except ImportError:
Redis = None
class Cache(object):
def __init__(self):
self._cache = {}
def get(self, k):
return self._cache.get(k)
def set(self, k, v):
... | from __future__ import with_statement
import os
import pickle
from contextlib import closing
try:
from redis import Redis
except ImportError:
Redis = None
class Cache(object):
def __init__(self):
self._cache = {}
def get(self, k):
return self._cache.get(k)
def set(self, k, v):
... |
Fix test cases for Python2 | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import unicode_literals
import itertools
import pytest
import six
from six import MAXSIZE
from typepy import Binary, StrictLevel, Typecode
nan = float("nan")
inf = float("inf")
class Test_Binary_is_type(ob... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import unicode_literals
import itertools
import pytest
from six import MAXSIZE
from typepy import Binary, StrictLevel, Typecode
nan = float("nan")
inf = float("inf")
class Test_Binary_is_type(object):
... |
Validate email the correct way | from django.contrib.auth.backends import ModelBackend
from django.core.validators import email_re
from django.contrib.auth import models, load_backend, login
from django.conf import settings
class EmailBackend(ModelBackend):
def authenticate(self, username=None, password=None):
if email_re.search(username... | from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.contrib.auth import models, load_backend, login
from django.conf import settings
class EmailBackend(ModelBackend):
def authenticate(self, username=... |
Set default Db to inmemory storage | class DefaultConfig(object):
SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
SQLALCHEMY_DATABASE_URI = 'sqlite://'
class DevelopmentConfig(DefaultConfig):
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_toke... | class DefaultConfig(object):
SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
SQLALCHEMY_DATABASE_URI = 'sqlite://'
class DevelopmentConfig(DefaultConfig):
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_toke... |
Add say alias to echo | import time
class Plugin:
def __call__(self, bot):
bot.on_respond(r"ping$", lambda bot, msg, reply: reply("PONG"))
bot.on_respond(r"echo (.*)$", lambda bot, msg, reply: reply(msg["match"][0]))
bot.on_respond(r"time$", lambda bot, msg, reply: reply(time.time()))
bot.on_help("debug", ... | import time
class Plugin:
def __call__(self, bot):
bot.on_respond(r"ping$", lambda bot, msg, reply: reply("PONG"))
bot.on_respond(r"(?:echo|say) (.*)$", lambda bot, msg, reply: reply(msg["match"][0]))
bot.on_respond(r"time$", lambda bot, msg, reply: reply(time.time()))
bot.on_help("... |
Fix a small styling error in the lazy_resolve definition | from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.utils.functional import lazy
from django.views.generic.base import TemplateView
from django.views.generic import CreateView
from .forms import PinForm
from .models import Pin
reve... | from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.utils.functional import lazy
from django.views.generic.base import TemplateView
from django.views.generic import CreateView
from .forms import PinForm
from .models import Pin
reve... |
Fix user token endpoint authorization | from flask import Response
from sqlalchemy.exc import IntegrityError
from zeus import auth
from zeus.config import db
from zeus.models import UserApiToken
from .base import Resource
from ..schemas import TokenSchema
token_schema = TokenSchema(strict=True)
class UserTokenResource(Resource):
def dispatch_request... | from sqlalchemy.exc import IntegrityError
from zeus import auth
from zeus.config import db
from zeus.models import UserApiToken
from .base import Resource
from ..schemas import TokenSchema
token_schema = TokenSchema(strict=True)
class UserTokenResource(Resource):
def get(self):
"""
Return the A... |
Add compatibility for Haystack 2.0. | # -*- coding: utf-8 -*-
from haystack import indexes
from haystack.sites import site
from faq.settings import SEARCH_INDEX
from faq.models import Topic, Question
class FAQIndexBase(SEARCH_INDEX):
text = indexes.CharField(document=True, use_template=True)
url = indexes.CharField(model_attr='get_absolute_url... | # -*- coding: utf-8 -*-
"""
Haystack SearchIndexes for FAQ objects.
Note that these are compatible with both Haystack 1.0 and Haystack 2.0-beta.
The super class for these indexes can be customized by using the
``FAQ_SEARCH_INDEX`` setting.
"""
from haystack import indexes
from faq.settings import SEARCH_INDEX
fro... |
Store rows as dictionaries of lists. | # -*- coding: utf-8 -*-
"""
lilkv.columnfamily
This module implements the client-facing aspect of the `lilkv` app. All
requests are handled through this interface.
"""
class ColumnFamily(object):
"""Column Family objects store information about all rows.
daily_purchases_cf = ColumnFamily("daily... | # -*- coding: utf-8 -*-
"""
lilkv.columnfamily
This module implements the client-facing aspect of the `lilkv` app. All
requests are handled through this interface.
"""
class ColumnFamily(object):
"""Column Family objects store information about all rows.
daily_purchases_cf = ColumnFamily("daily... |
Read JSON file to be processed | #!/usr/bin/env python
"""
This script cleans and processes JSON data scraped, using Scrapy, from
workabroad.ph.
"""
import argparse
import json
import sys
def main():
parser = argparse.ArgumentParser(description="Sanitize workabroad.ph scraped data")
parser.add_argument("export", help="Export file format, 'cs... | #!/usr/bin/env python
"""
This script cleans and processes JSON data scraped, using Scrapy, from
workabroad.ph.
"""
import argparse
import codecs
import os
import json
import sys
def main():
parser = argparse.ArgumentParser(description="Sanitize workabroad.ph scraped data")
parser.add_argument("export", help=... |
Test Endpoint.endpoints has all endpoints | from noopy.endpoint import methods
from noopy.endpoint.decorators import endpoint
@endpoint('/foo', methods.GET)
def sample_view(event, context):
pass
def test_resources_added():
from noopy.endpoint.resource import Resource
resources = Resource.resources
assert set(resources.keys()) == {'/', '/foo'... | from noopy.endpoint import methods
from noopy.endpoint.decorators import endpoint
@endpoint('/foo', methods.GET)
def sample_view(event, context):
pass
def test_resources_added():
from noopy.endpoint.resource import Resource
resources = Resource.resources
assert set(resources.keys()) == {'/', '/foo'... |
Use matlab.exe instead of matlab in Windows | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
from .imdb import imdb
from .pascal_voc import pascal_voc
from . import... | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
from .imdb import imdb
from .pascal_voc import pascal_voc
from . import... |
Add encoding hint (and which python version is required). | from behave import given, then, step
from behave.api.async_step import use_or_create_async_context, AsyncContext
from hamcrest import assert_that, equal_to, empty
import asyncio
@asyncio.coroutine
def async_func(param):
yield from asyncio.sleep(0.2)
return str(param).upper()
@given('I dispatch an async-call w... | # -*- coding: UTF-8 -*-
# REQUIRES: Python >= 3.5
from behave import given, then, step
from behave.api.async_step import use_or_create_async_context, AsyncContext
from hamcrest import assert_that, equal_to, empty
import asyncio
@asyncio.coroutine
def async_func(param):
yield from asyncio.sleep(0.2)
return str(... |
Fix a minor typo in the EndpointNotDefined exception | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pyrax
from pyrax.base_identity import BaseAuth
import pyrax.exceptions as exc
class KeystoneIdentity(BaseAuth):
"""
Implements the Keystone-specific behaviors for Identity. In most
cases you will want to create specific subclasses to implement the
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pyrax
from pyrax.base_identity import BaseAuth
import pyrax.exceptions as exc
class KeystoneIdentity(BaseAuth):
"""
Implements the Keystone-specific behaviors for Identity. In most
cases you will want to create specific subclasses to implement the
... |
Remove import from testing packages | '''
Created on Sep 24, 2016
@author: rtorres
'''
from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column
from sqlalchemy.dialects.postgresql.base import ENUM
from sqlalchemy_utils.types.url import URLType
from flask_validator.constraints.internet import ValidateURL
AREAS = ('Poli... | '''
Created on Sep 24, 2016
@author: rtorres
'''
from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column
from sqlalchemy.dialects.postgresql.base import ENUM
AREAS = ('Policies', 'Billing', 'Claims', 'Reports')
class Target(SurrogatePK, Model):
"""A user of the app."""
... |
Add logging to python webserver | import os
import pgdb
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
conn = pgdb.connect( host='pg', user='postgres', password='testnet', database='testnet' )
cur = conn.cursor()
cur.execute( "SELECT value FROM kv WHERE key='provider'" )
provider = cur.fetchone()[0]
co... | import os
import pgdb
import logging
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
conn = pgdb.connect( host='pg', user='postgres', password='testnet', database='testnet' )
cur = conn.cursor()
cur.execute( "SELECT value FROM kv WHERE key='provider'" )
provider = cur.fetch... |
Use a mixin for get-/setProps | from u2flib_server.jsapi import (JSONDict, RegisterRequest, RegisterResponse,
SignRequest, SignResponse)
__all__ = [
'RegisterRequestData',
'RegisterResponseData',
'AuthenticateRequestData',
'AuthenticateResponseData'
]
class RegisterRequestData(JSONDict):
@prope... | # Copyright (C) 2014 Yubico AB
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is ... |
Configure debug_toolbar to not fail. | from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'schwag.views.home', name='home'),
url(r'^... | from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'schwag.views.home', name='home'),
url(r'^... |
Use NovaVMPort type; otherwise the agent will believe it is a Use NovaVMPort as type; otherwise the agent will believe it is dealing with a service-instance and will not send a VM registration. |
from contrail_vrouter_api.vrouter_api import ContrailVRouterApi
def interface_register(vm, vmi, iface_name):
api = ContrailVRouterApi()
mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0]
api.add_port(vm.uuid, vmi.uuid, iface_name, mac)
def interface_unregister(vmi_uuid):
api = Contrail... |
from contrail_vrouter_api.vrouter_api import ContrailVRouterApi
def interface_register(vm, vmi, iface_name):
api = ContrailVRouterApi()
mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0]
api.add_port(vm.uuid, vmi.uuid, iface_name, mac, port_type='NovaVMPort')
def interface_unregister(vmi_u... |
Solve pythagorean_triple - reference solution | def triplets_with_sum(n):
pass
| from math import ceil, gcd, sqrt
def triplets_in_range(range_start, range_end):
for limit in range(range_start, range_end, 4):
for x, y, z in primitive_triplets(limit):
a, b, c = (x, y, z)
# yield multiples of primitive triplet
while a < range_start:
a,... |
Check for exit code > 0 instead of existence of stderr | import sublime, sublime_plugin, subprocess, os
importjs_path = os.path.expanduser('~/.rbenv/shims/import-js')
class ImportJsCommand(sublime_plugin.TextCommand):
def run(self, edit):
entire_file_region = sublime.Region(0, self.view.size())
current_file_contents = self.view.substr(entire_file_region)
env... | import sublime, sublime_plugin, subprocess, os
importjs_path = os.path.expanduser('~/.rbenv/shims/import-js')
class ImportJsCommand(sublime_plugin.TextCommand):
def run(self, edit):
entire_file_region = sublime.Region(0, self.view.size())
current_file_contents = self.view.substr(entire_file_region)
env... |
Change import statement for external library yaml | import pathlib
import socket
import pyflare
import yaml
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 53))
myip = s.getsockname()[0]
s.close()
with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r:
update_list = yaml.load(r)
for account in update_list:
r... | import pathlib
import socket
import pyflare
from yaml import load
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 53))
myip = s.getsockname()[0]
s.close()
with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r:
update_list = load(r)
for account in update_list:
... |
Use timer class instead of weird list | from contextlib import contextmanager
from time import time
import numpy as np
from skan.vendored import thresholding as th
@contextmanager
def timer():
result = [0.]
t = time()
yield result
result[0] = time() - t
def test_fast_sauvola():
image = np.random.rand(512, 512)
w0 = 25
w1 = 251... | from time import time
import numpy as np
from skan.vendored import thresholding as th
class Timer:
def __init__(self):
self.interval = 0
def __enter__(self):
self.t0 = time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.interval = time() - self.t0
def... |
Make the usermode +i check for WHO slightly neater. | from txircd.modbase import Mode
class InvisibleMode(Mode):
def namesListEntry(self, recipient, channel, user, representation):
if channel.name not in recipient.channels and "i" in user.mode:
return ""
return representation
def checkWhoVisible(self, user, targetUser, filters, fi... | from txircd.modbase import Mode
class InvisibleMode(Mode):
def namesListEntry(self, recipient, channel, user, representation):
if channel.name not in recipient.channels and "i" in user.mode:
return ""
return representation
def checkWhoVisible(self, user, targetUser, filters, fi... |
Fix isincluded for List operators. | """Utilities for using the PPP datamodel."""
from . import Resource, Triple, Missing, Intersection, List, Union, And, Or, Exists, First, Last, Sort
def contains_missing(tree):
def predicate(node, childs):
if isinstance(node, Missing):
return True
else:
return any(childs.val... | """Utilities for using the PPP datamodel."""
from . import Resource, Triple, Missing, Intersection, List, Union, And, Or, Exists, First, Last, Sort
def contains_missing(tree):
def predicate(node, childs):
if isinstance(node, Missing):
return True
else:
return any(childs.val... |
Remove admin restictions to movies endpoint | from .serializers import MovieSerializer
from .models import Movie
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework import permissions
class MovieList(generics.ListCreateAPIView):
"""
... | from .serializers import MovieSerializer
from .models import Movie
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework import permissions
class MovieList(generics.ListAPIView):
"""
API ... |
Use timezones=[] to underline that we only care about dates. | import unittest
from hypothesis import given
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date
class TestIsoUtils(unittest.TestCase):
@given(datetimes())
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d.isocalendar... | import unittest
from hypothesis import given
from hypothesis.extra.datetime import datetimes
import qual
from datetime import date
class TestIsoUtils(unittest.TestCase):
@given(datetimes(timezones=[]))
def test_round_trip_date(self, dt):
d = dt.date()
self.assertEqual(qual.iso_to_gregorian(*d... |
Use next method of reader object | import csv
from datetime import datetime
from django.shortcuts import render
from django.utils import timezone
from django.views.generic import TemplateView
from .forms import FeedbackUploadForm
from .models import Feedback
class FeedbackView(TemplateView):
template_name = 'index.html'
def get(self, reques... | import csv
from datetime import datetime
from django.shortcuts import render
from django.utils import timezone
from django.views.generic import TemplateView
from .forms import FeedbackUploadForm
from .models import Feedback
class FeedbackView(TemplateView):
template_name = 'index.html'
def get(self, reques... |
Add test for qisrc list | from qisys import ui
def test_list_tips_when_empty(qisrc_action, record_messages):
qisrc_action("init")
qisrc_action("list")
assert ui.find_message("Tips")
| from qisys import ui
def test_list_tips_when_empty(qisrc_action, record_messages):
qisrc_action("init")
qisrc_action("list")
assert ui.find_message("Tips")
def test_list_with_pattern(qisrc_action, record_messages):
qisrc_action.git_worktree.create_git_project("foo")
qisrc_action.git_worktree.creat... |
Fix IndexError bug in _hydrate | import requests
API_URL = 'http://data.police.uk/api/'
class APIError(Exception):
pass
def api_request(method):
r = requests.get(API_URL + method)
if r.status_code != 200:
raise APIError(r.status_code)
return r.json()
class Resource(object):
_requested = False
api_method = None
... | import requests
API_URL = 'http://data.police.uk/api/'
class APIError(Exception):
pass
def api_request(method):
r = requests.get(API_URL + method)
if r.status_code != 200:
raise APIError(r.status_code)
return r.json()
class Resource(object):
_requested = False
api_method = None
... |
Use backend picker in storefront search form | from __future__ import unicode_literals
from django import forms
from django.utils.translation import pgettext
from .backends import elasticsearch
class SearchForm(forms.Form):
q = forms.CharField(
label=pgettext('Search form label', 'Query'), required=True)
def search(self):
return elastics... | from __future__ import unicode_literals
from django import forms
from django.utils.translation import pgettext
from .backends import picker
class SearchForm(forms.Form):
q = forms.CharField(
label=pgettext('Search form label', 'Query'), required=True)
def search(self):
search = picker.pick_b... |
Use shlex to split parameters | # coding: utf-8
# 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/.
import os
from ..quokka import ExternalProcess, PluginException
class ConsoleApplication(ExternalProce... | # coding: utf-8
# 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/.
import os
import shlex
from ..quokka import ExternalProcess, PluginException
class ConsoleApplication(... |
Remove usage of built-in 'type' name | class BaseHandler(object):
"""
Abstract base class for handlers.
"""
def __init__(self, base):
"""
Initialize a new handler to handle `type`.
:Parameters:
- `base`: reference to pickler/unpickler
"""
self._base = base
def flatten(self, obj, data):... | class BaseHandler(object):
"""
Abstract base class for handlers.
"""
def __init__(self, base):
"""
Initialize a new handler to handle `type`.
:Parameters:
- `base`: reference to pickler/unpickler
"""
self._base = base
def flatten(self, obj, data):... |
Repair 500 viewing contact person | import os
from django.core.urlresolvers import NoReverseMatch
from fluent_contents.models import ContentItem
from fluent_pages.urlresolvers import app_reverse, PageTypeNotMounted
from icekit.publishing.models import PublishingModel
from timezone import timezone
from django.db import models
from django.utils.encoding im... | from fluent_contents.models import ContentItem
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class ContactPerson(models.Model):
name = models.CharField(max_length=255)
title = mode... |
Fix Rule: pass convs argument to match | # -*- coding: utf-8 -*-
import json
from webob.exc import status_map
from webob import Response
from .core import cases
from . import filters
__all__ = ['redirect_to', 'http_error', 'to_json', 'Rule']
def redirect_to(endpoint, _code=303, qs=None, **kwargs):
def handle(env, data):
url = env.root.build_url(... | # -*- coding: utf-8 -*-
import json
from webob.exc import status_map
from webob import Response
from .core import cases
from . import filters
__all__ = ['redirect_to', 'http_error', 'to_json', 'Rule']
def redirect_to(endpoint, _code=303, qs=None, **kwargs):
def handle(env, data):
url = env.root.build_url(... |
Update StringIO import for Python3 compat | # USEFUL FUNCTIONS DESIGNED FOR TESTS ##############################################################
import glob
import os
import uuid
from django.core.files.base import ContentFile
from PIL import Image
from StringIO import StringIO
def new_test_image():
"""
Creates an automatically generated test image.
... | # USEFUL FUNCTIONS DESIGNED FOR TESTS ##############################################################
import glob
import os
import uuid
from PIL import Image
from django.core.files.base import ContentFile
from django.utils import six
def new_test_image():
"""
Creates an automatically generated test image.
... |
Update test for current evidence aggregation | from nose.plugins.attrib import attr
from indra.sources.tas import process_from_web
@attr('slow')
def test_processor():
tp = process_from_web(affinity_class_limit=10)
assert tp
assert tp.statements
num_stmts = len(tp.statements)
# This is the total number of statements about human genes
assert... | from nose.plugins.attrib import attr
from indra.sources.tas import process_from_web
@attr('slow')
def test_processor():
tp = process_from_web(affinity_class_limit=10)
assert tp
assert tp.statements
num_stmts = len(tp.statements)
# This is the total number of statements about human genes
assert... |
Change Game form score input to select | from django import forms
from django_select2.forms import ModelSelect2MultipleWidget
from django_superform import ModelFormField, SuperForm
from .models import Team, Game
from .utils import clean_team_forms
from foosball.users.models import User
class MultiPlayerWidget(ModelSelect2MultipleWidget):
model = User
... | from django import forms
from django_select2.forms import ModelSelect2MultipleWidget
from django_superform import ModelFormField, SuperForm
from .models import Team, Game
from .utils import clean_team_forms
from foosball.users.models import User
class MultiPlayerWidget(ModelSelect2MultipleWidget):
model = User
... |
Update slack username for JD | import time
import random
crontable = []
outputs = []
buddies = ["tim.jenks", "mark.simpson", "scott", "malcolm.brown", "ian.hutchinson", "jonty", "oliver.norton", "vimarsh.raina", "paul.harris", "john.bell"]
cursor = -1
def usage():
return "usage: :cow: buddy"
def commandname():
return "buddy"
def process... | import time
import random
crontable = []
outputs = []
buddies = ["tim.jenks", "mark.simpson", "scott", "malcolm.brown", "ian.hutchinson", "jonty.dawson", "oliver.norton", "vimarsh.raina", "paul.harris", "john.bell"]
cursor = -1
def usage():
return "usage: :cow: buddy"
def commandname():
return "buddy"
def ... |
Install six for Python 2 & 3 compatibility | #!/usr/bin/env python2
from setuptools import setup
setup(name="sagbescheid",
author="Wieland Hoffmann",
author_email="themineo@gmail.com",
packages=["sagbescheid", "sagbescheid.notifiers"],
package_dir={"sagbescheid": "sagbescheid"},
download_url="https://github.com/mineo/sagbescheid/ta... | #!/usr/bin/env python2
from setuptools import setup
setup(name="sagbescheid",
author="Wieland Hoffmann",
author_email="themineo@gmail.com",
packages=["sagbescheid", "sagbescheid.notifiers"],
package_dir={"sagbescheid": "sagbescheid"},
download_url="https://github.com/mineo/sagbescheid/ta... |
Fix readme to be able to build a wheel | """
django-gstorage
"""
import re
from setuptools import setup
version = ''
with open('gstorage/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
setup(
name='django-gstorage',
version=version,
description='Allow easy i... | """
django-gstorage
"""
import re
from setuptools import setup
version = ''
with open('gstorage/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
with open('HISTORY.... |
Change version and license for 0.2 |
from setuptools import setup
setup(name = 'OWSLib',
version = '0.1.0',
description = 'OGC Web Service utility library',
license = 'GPL',
keywords = 'gis ogc ows wfs wms capabilities metadata',
author = 'Sean Gillies',
author_email = 'sgillies@fri... |
from setuptools import setup
setup(name = 'OWSLib',
version = '0.2.0',
description = 'OGC Web Service utility library',
license = 'BSD',
keywords = 'gis ogc ows wfs wms capabilities metadata',
author = 'Sean Gillies',
author_email = 'sgillies@fri... |
Include README in PyPi release | """Lusmu setup information
Copyright 2013 Eniram Ltd. See the LICENSE file at the top-level directory of
this distribution and at https://github.com/akaihola/lusmu/blob/master/LICENSE
"""
from setuptools import setup
setup(name='lusmu',
version='0.2.4.dev',
packages=['lusmu'],
author='Antti Kaih... | """Lusmu setup information
Copyright 2013 Eniram Ltd. See the LICENSE file at the top-level directory of
this distribution and at https://github.com/akaihola/lusmu/blob/master/LICENSE
"""
import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.r... |
Add test for denying get requests | """accounts app unittests for views
"""
from django.test import TestCase
from django.urls import reverse
class WelcomePageTest(TestCase):
"""Tests relating to the welcome_page view.
"""
def test_uses_welcome_template(self):
"""The root url should respond with the welcome page template.
... | """accounts app unittests for views
"""
from django.test import TestCase
from django.urls import reverse
class WelcomePageTest(TestCase):
"""Tests relating to the welcome_page view.
"""
def test_uses_welcome_template(self):
"""The root url should respond with the welcome page template.
... |
Add console as email backend | # Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': "wye",
'USER': "",
'PASSWORD': "",
'HOST': "localhost",
'PORT': "5432",
}
}
| # Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': "wye",
'USER': "",
'PASSWORD': "",
'HOST': "localhost",
'PORT': "5432",
}
}
# E-Mail S... |
Update version 0.7.0 -> 0.7.1 | # Copyright 2018 D-Wave Systems Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | # Copyright 2018 D-Wave Systems Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
Fix UnicodeDecodeError: Return text string, not bytes | # -*- encoding: utf-8 -*-
from django.db.models import Q
from django.core.management.base import NoArgsCommand
from django.template.loader import render_to_string
from django.conf import settings
from membership.models import *
from membership.public_memberlist import public_memberlist_data
class Command(NoArgsComma... | # -*- encoding: utf-8 -*-
from django.db.models import Q
from django.core.management.base import NoArgsCommand
from django.template.loader import render_to_string
from django.conf import settings
from membership.models import *
from membership.public_memberlist import public_memberlist_data
class Command(NoArgsComma... |
Fix smart_u for Django 1.3 | # coding=utf-8
# flake8: noqa
import sys
if sys.version_info[0] == 3:
from django.utils.encoding import smart_bytes as smart_b, force_str as force_u, smart_text as smart_u
# noinspection PyUnresolvedReferences
from urllib.parse import quote
ifilter = filter
b_str = bytes
u_str = str
iterite... | # coding=utf-8
# flake8: noqa
import sys
if sys.version_info[0] == 3:
from django.utils.encoding import smart_bytes as smart_b, force_str as force_u, smart_text as smart_u
# noinspection PyUnresolvedReferences
from urllib.parse import quote
ifilter = filter
b_str = bytes
u_str = str
iterite... |
Configure django correctly when we setup our env | #!/usr/bin/env python
import multiprocessing
import optparse
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from hurricane.utils import run_until_stopped
class ApplicationManager(object):
@run_until_stopped
def run(self):
parser = optparse.Op... | #!/usr/bin/env python
import multiprocessing
import optparse
from django.conf import settings as django_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from hurricane.utils import run_until_stopped
class ApplicationManager(object):
@run_until_sto... |
Reduce result broker message timeout |
# Wait up to 15 minutes for each iteration.
BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} # Seconds = 1 hour.
# Do not pre-fetch work.
CELERYD_PREFETCH_MULTIPLIER = 1
# Do not ack messages until work is completed.
CELERY_ACKS_LATE = True
# Stop warning me about PICKLE.
CELERY_ACCEPT_CONTENT = ['pickle']
|
# Wait up to 15 minutes for each iteration.
BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 60*60} # 60*60 Seconds = 1 hour.
# Do not pre-fetch work.
CELERYD_PREFETCH_MULTIPLIER = 1
# Do not ack messages until work is completed.
CELERY_ACKS_LATE = True
# Stop warning me about PICKLE.
CELERY_ACCEPT_CONTENT = ['pickl... |
Make matrix exercise compatible with Python3 | class Matrix(object):
def __init__(self, s):
self.rows = [[int(n) for n in row.split()]
for row in s.split('\n')]
@property
def columns(self):
return map(list, zip(*self.rows))
| class Matrix(object):
def __init__(self, s):
self.rows = [[int(n) for n in row.split()]
for row in s.split('\n')]
@property
def columns(self):
return [list(tup) for tup in zip(*self.rows)]
|
Fix incorrect import reference to nw_similarity | import unittest
from similarity.nw_similarity import NWAlgorithm
class Test(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_nw_algorithm(self):
t = NWAlgorithm('abcdefghij', 'dgj')
t.print_matrix()
(a, b) = t.alignments()
prin... | import unittest
from similarity.nw_similarity import NWAlgorithm
class TestNewSimilarity(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_nw_algorithm(self):
t = NWAlgorithm('abcdefghij', 'dgj')
t.print_matrix()
(a, b) = t.alignments()... |
Implement command line option parse program. | from .BloArticle import BloArticle
class Blo:
def __init__(self):
pass
if __name__ == '__main__':
# TODO: implement main routine of Blo.
# blo [-c config_file] markdown_file.md
# -- if no -c option then load config file from default path (current directory).
# ---- if no configuration fil... | import configparser
import optparse
from .BloArticle import BloArticle
class Blo:
def __init__(self):
pass
if __name__ == '__main__':
parser = optparse.OptionParser("usage: %prog [option] markdown_file.md")
parser.add_option("-c", "--config", dest="config_file",
default="./b... |
Fix typo in unit test class of the sphere manifold | import unittest
import numpy as np
import numpy.linalg as la
import numpy.random as rnd
import numpy.testing as np_testing
from pymanopt.manifolds import Sphere
class TestSphereManifold(unittest.TestCase):
def setUp(self):
self.m = m = 100
self.n = n = 50
self.sphere = Sphere(m, n)
... | import unittest
import numpy as np
import numpy.linalg as la
import numpy.random as rnd
import numpy.testing as np_testing
from pymanopt.manifolds import Sphere
class TestSphereManifold(unittest.TestCase):
def setUp(self):
self.m = m = 100
self.n = n = 50
self.sphere = Sphere(m, n)
... |
Add a title to the print_method problem | import codecs
import io
import sys
from workshopper.problems import BaseProblem
class Problem(BaseProblem):
def test(self, file):
old_stdout = sys.stdout
sys.stdout = io.StringIO()
eval(codecs.open(file).read())
message = sys.stdout.getvalue()
sys.stdout = old_stdout
... | import codecs
import io
import sys
from workshopper.problems import BaseProblem
class Problem(BaseProblem):
title = 'Print method'
def test(self, file):
old_stdout = sys.stdout
sys.stdout = io.StringIO()
eval(codecs.open(file).read())
message = sys.stdout.getvalue()
s... |
Enable face culling in sponza example | import moderngl as mgl
from demosys.effects import effect
class SceneEffect(effect.Effect):
"""Generated default effect"""
def __init__(self):
self.scene = self.get_scene("Sponza/glTF/Sponza.gltf", local=True)
self.proj_mat = self.create_projection(fov=75.0, near=0.01, far=1000.0)
def dr... | import moderngl
from demosys.effects import effect
class SceneEffect(effect.Effect):
"""Generated default effect"""
def __init__(self):
self.scene = self.get_scene("Sponza/glTF/Sponza.gltf", local=True)
self.proj_mat = self.create_projection(fov=75.0, near=0.01, far=1000.0)
def draw(self... |
Add simple Attempt submit test | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
from rest_framework.test import APIClient
from users.models import User
# Create your tests here.
class TokenLoginTestCase(TestCase):
fixtures = ['users.json']
def testAttemptSubmit(self):
user = User.objects.get(username='matija')
client = APIClient()
... |
Update ILAMB BMI to use Configuration | #! /usr/bin/env python
import sys
import subprocess
from basic_modeling_interface import Bmi
class BmiIlamb(Bmi):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._a... | """Basic Model Interface (BMI) for the ILAMB benchmarking system."""
import os
import subprocess
from basic_modeling_interface import Bmi
from .config import Configuration
class BmiIlamb(Bmi):
_component_name = 'ILAMB'
_command = 'ilamb-run'
_args = None
def __init__(self):
self._time = self... |
Fix typo in login_required decorator | from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorat... | from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorat... |
Improve how we abort MPI runs. | # -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is n... | # -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is n... |
Replace customzied test failure assertion with ResultReasonRE from engine | # Copyright 2019 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 recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclien... | # Copyright 2019 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 recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclien... |
Fix bug with arguments handling in JSON API content decorator | from functools import wraps
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
context = kwargs.get('context')
... | from functools import wraps
from aiohttp import web
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI, JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
... |
Check for right kind of error in invalid creds test | from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_sessio... | from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_sessio... |
Add images to snapshot details | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqpar... | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.api.serializer.models.snapshot import SnapshotWithImagesSerializer
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snaps... |
Fix REPL and add quit() command | '''
Sample REPL code to integrate with Diesel
Using InteractiveInterpreter broke block handling (if/def/etc.), but exceptions
were handled well and the return value of code was printed.
Using exec runs the input in the current context, but exception handling and other
features of InteractiveInterpreter are lost.
'''
... | import sys
import code
import traceback
from diesel import Application, Pipe, until
QUIT_STR = "quit()\n"
DEFAULT_PROMPT = '>>> '
def diesel_repl():
'''Simple REPL for use inside a diesel app'''
# Import current_app into locals for use in REPL
from diesel.app import current_app
print 'Diesel Console'... |
Fix settings; tests now passing | from . import model
from . import routes
from . import views
MODELS = [model.AddonDropboxUserSettings] # TODO Other models needed? , model.AddonDropboxNodeSettings, model.DropboxGuidFile]
USER_SETTINGS_MODEL = model.AddonDropboxNodeSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.setti... | from . import model
from . import routes
from . import views
MODELS = [model.DropboxUserSettings]
USER_SETTINGS_MODEL = model.DropboxUserSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbo... |
Update docstring with parameter listing | '''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
:message str:
'''
Exception.__init__(self, message)
| '''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
message -- string. Message describing the exception.
'''
Exception.__init__(self, message)
|
Switch to relative imports and fix pep-8 | """
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \
macrodata, nile, randhie, scotland, spector, stackloss, star98, \
strikes, sunspots, fair, heart, statecrime
| """
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino,
grunfeld, longley, macrodata, nile, randhie, scotland, spector,
stackloss, star98, strikes, sunspots, fair, heart, statecrime)
|
Remove extra newlines added during editing | from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
st... | from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
st... |
Test execution: Remove unneeded variable | #! /bin/python3
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be us... | #! /bin/python3
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be us... |
Add smoketest for convering CoverageDataset to str. | # Copyright (c) 2016 Unidata.
# Distributed under the terms of the MIT License.
# SPDX-License-Identifier: MIT
import warnings
from siphon.testing import get_recorder
from siphon.cdmr.coveragedataset import CoverageDataset
recorder = get_recorder(__file__)
# Ignore warnings about CoverageDataset
warnings.simplefilte... | # Copyright (c) 2016 Unidata.
# Distributed under the terms of the MIT License.
# SPDX-License-Identifier: MIT
import warnings
from siphon.testing import get_recorder
from siphon.cdmr.coveragedataset import CoverageDataset
recorder = get_recorder(__file__)
# Ignore warnings about CoverageDataset
warnings.simplefilte... |
Add Framework::Pytest to list of classifiers | from setuptools import setup
setup(
name="pytest-cpp",
version='0.4',
packages=['pytest_cpp'],
entry_points={
'pytest11': ['cpp = pytest_cpp.plugin'],
},
install_requires=['pytest', 'colorama'],
# metadata for upload to PyPI
author="Bruno Oliveira",
author_email="nicoddemu... | from setuptools import setup
setup(
name="pytest-cpp",
version='0.4',
packages=['pytest_cpp'],
entry_points={
'pytest11': ['cpp = pytest_cpp.plugin'],
},
install_requires=['pytest', 'colorama'],
# metadata for upload to PyPI
author="Bruno Oliveira",
author_email="nicoddemu... |
Patch 0.2.1 to remove print | from setuptools import setup
setup(
name='icapservice',
version='0.2.0',
description='ICAP service library for Python',
author='Giles Brown',
author_email='giles_brown@hotmail.com',
url='https://github.com/gilesbrown/icapservice',
license='MIT',
packages=['icapservice'],
zip_safe=F... | from setuptools import setup
setup(
name='icapservice',
version='0.2.1',
description='ICAP service library for Python',
author='Giles Brown',
author_email='giles_brown@hotmail.com',
url='https://github.com/gilesbrown/icapservice',
license='MIT',
packages=['icapservice'],
zip_safe=F... |
Add missing 'boltons' package & clean up | #!/usr/bin/env python
import os
import sys
from setuptools import setup
readme = open('README.rst').read()
doclink = """
Documentation
-------------
The full documentation is at http://gryaml.rtfd.org."""
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
setup(
name='gryaml',
use_scm_versi... | #!/usr/bin/env python
"""Setuptools setup."""
from setuptools import setup
readme = open('README.rst').read()
doclink = """
Documentation
-------------
The full documentation is at http://gryaml.rtfd.org."""
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
setup(
name='gryaml',
use_scm_ver... |
Simplify description and MANIFEST.in suits me fine. | from setuptools import setup, find_packages
setup(name='django-forge',
version=__import__('forge').__version__,
author='Justin Bronn',
author_email='jbronn@gmail.com',
description='A Django implementation of the Puppet Forge web API.',
url='https://github.com/jbronn/django-forge',
... | from setuptools import setup, find_packages
setup(name='django-forge',
version=__import__('forge').__version__,
author='Justin Bronn',
author_email='jbronn@gmail.com',
description='A Django implementation of the Puppet Forge API.',
url='https://github.com/jbronn/django-forge',
down... |
Fix homepage url to point to the correct repo | #!/usr/bin/env python
from setuptools import find_packages, setup
setup(
name='Flask-uWSGI-WebSocket',
version='0.6.1',
url='https://github.com/zeekay/flask_uwsgi_websocket',
license='MIT',
author='Zach Kelling',
author_email='zk@monoid.io',
description='High-performance WebSockets for your... | #!/usr/bin/env python
from setuptools import find_packages, setup
setup(
name='Flask-uWSGI-WebSocket',
version='0.6.1',
url='https://github.com/zeekay/flask-uwsgi-websocket',
license='MIT',
author='Zach Kelling',
author_email='zk@monoid.io',
description='High-performance WebSockets for your... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.