Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Make function! and Use 4 tabs, not 8 tabs. | ```python
i = -1
sum = 0
one_to_ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
while i < 10:
i += 1
sum += one_to_ten[i]
print(sum)
``` | ```python
i = -1
sum = 0
one_to_ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
while i < 10:
i += 1
sum += one_to_ten[i]
print(sum)
```
**Make function!**
`like:`
```python
def sum(number):
# .. TODO
return 0
```
`I want to reuse this function, like:`
```python
one_to_ten = sum(range(1,11))
one_to_five = sum(ra... |
Allow for local run of example and demos installed with tool. | from __future__ import division
import os
import numpy as np
import scipy.io
import scipy.ndimage.interpolation
def load_head_phantom(number_of_voxels=None):
if number_of_voxels is None:
number_of_voxels = np.array((128, 128, 128))
dirname = os.path.dirname(__file__)
dirname = os.path.join(dirname... | from __future__ import division
import os
import numpy as np
import scipy.io
import scipy.ndimage.interpolation
def load_head_phantom(number_of_voxels=None):
if number_of_voxels is None:
number_of_voxels = np.array((128, 128, 128))
dirname = os.path.dirname(__file__)
dirname = os.path.join(dirname... |
Fix typo in upgrade script | import os.path
import shutil
sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';
-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
... | import os.path
import shutil
sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';
-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
... |
Remove sensitive information from the example | # -*-coding:utf8 -*-
import json
import requests
import time
import uuid
import datetime
import time
ids = ["18576635456", "13512345432"]
url1 = "http://172.16.153.71:8059/federation/1.0/inference"
for i in range(2):
request_data_tmp = {
"head": {
"serviceId": "test_model_service",
... | # -*-coding:utf8 -*-
import json
import requests
import time
import uuid
import datetime
import time
ids = ["18576635456", "13512345432"]
url1 = "http://127.0.0.1:8059/federation/1.0/inference"
for i in range(2):
request_data_tmp = {
"head": {
"serviceId": "test_model_service",
"... |
Undo BC-breaking change, restore 'import onnx' providing submodules. | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .onnx_ml_pb2 import * # noqa
from .version import version as __version__ # noqa
import sys
def load(obj):
'''
Loads a binary protobuf that stores onnx gr... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .onnx_ml_pb2 import * # noqa
from .version import version as __version__ # noqa
# Import common subpackages so they're available when you 'import onnx'
import onn... |
Reorder imports in alphabetical order | import graphqlapi.utils as utils
from graphql.parser import GraphQLParser
from graphqlapi.interceptor import ExecuteBatch, TestDataSource
from graphqlapi.exceptions import RequestException
interceptors = [
ExecuteBatch(),
TestDataSource()
]
def proxy_request(payload: dict):
graphql_ast = parse_query(pay... | import graphqlapi.utils as utils
from graphqlapi.exceptions import RequestException
from graphqlapi.interceptor import ExecuteBatch, TestDataSource
from graphql.parser import GraphQLParser
interceptors = [
ExecuteBatch(),
TestDataSource()
]
def proxy_request(payload: dict):
graphql_ast = parse_query(pay... |
Check for deprecation on import is problematic. Rather just check that filter can be imported normally. | from skimage._shared.utils import all_warnings, skimage_deprecation
from numpy.testing import assert_warns
def import_filter():
from skimage import filter as F
assert('sobel' in dir(F))
def test_filter_import():
with all_warnings():
assert_warns(skimage_deprecation, import_filter)
| from numpy.testing import assert_warns
from warnings import catch_warnings, simplefilter
def test_import_filter():
with catch_warnings():
simplefilter('ignore')
from skimage import filter as F
assert('sobel' in dir(F))
|
Change directory where data is written to. | import utils
from os import environ
import os.path
MCDIR = environ.get("MCDIR") or '/mcfs/data'
def for_uid(uidstr):
pieces = uidstr.split('-')
path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4])
utils.mkdirp(path)
return path
| import utils
from os import environ
import os.path
MCDIR = environ.get("MCDIR") or '/mcfs/data/materialscommons'
def for_uid(uidstr):
pieces = uidstr.split('-')
path = os.path.join(MCDIR, pieces[1][0:2], pieces[1][2:4])
utils.mkdirp(path)
return path
|
Add port specification to gearhorn CLI | # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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 applica... | # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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 applica... |
Add a basic test for models. | from unittest import TestCase
from ..models import Tunnel
| from unittest import TestCase
from ..models import Tunnel
class TestModels(TestCase):
def test_defaults(self):
tunnel = Tunnel()
self.assertEquals(tunnel.name, 'unnamed')
self.assertEquals(tunnel.process, None)
self.assertEqual(tunnel.local_port, 0)
self.assertEqual(tunnel... |
FIX fix unit test by fixing import paths | import unittest
from autosklearn.pipeline.components.base import find_components, \
AutoSklearnClassificationAlgorithm
class TestBase(unittest.TestCase):
def test_find_components(self):
c = find_components('dummy_components', 'dummy_components',
AutoSklearnClassificationA... | import os
import sys
import unittest
from autosklearn.pipeline.components.base import find_components, \
AutoSklearnClassificationAlgorithm
this_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(this_dir)
class TestBase(unittest.TestCase):
def test_find_components(self):
c = find_com... |
Make stub image url a real one | from . import db
class Users(object):
@classmethod
def get_current(cls):
return {
'data': {
'id': 1,
'type': 'user',
'name': 'Albert Sheu',
'short_name': 'Albert',
'profile_image_url': 'https://google.com'
... | from . import db
class Users(object):
@classmethod
def get_current(cls):
return {
'data': {
'id': 1,
'type': 'user',
'name': 'Albert Sheu',
'short_name': 'Albert',
'profile_image_url': 'http://flubstep.com/imag... |
Add default exploit to user migration. | def migrate_user(self):
"""
Migrate to latest schema version.
"""
migrate_1_to_2(self)
migrate_2_to_3(self)
def migrate_1_to_2(self):
"""
Migrate from schema 1 to schema 2.
"""
if self.schema_version == 1:
self.schema_version = 2
notify_email = getattr(self.unsupp... | def migrate_user(self):
"""
Migrate to latest schema version.
"""
migrate_1_to_2(self)
migrate_2_to_3(self)
def migrate_1_to_2(self):
"""
Migrate from schema 1 to schema 2.
"""
if self.schema_version == 1:
self.schema_version = 2
notify_email = getattr(self.unsupp... |
Fix typo in requests helper | from __future__ import absolute_import
from __future__ import unicode_literals
import json
import requests
from django.conf import settings
from mesoshttp.acs import DCOSServiceAuth
DCOS_AUTH = None
DCOS_VERIFY = True
if settings.SERVICE_SECRET:
# We are in Enterprise mode and using service account
DCOS_AUT... | from __future__ import absolute_import
from __future__ import unicode_literals
import json
import requests
from django.conf import settings
from mesoshttp.acs import DCOSServiceAuth
DCOS_AUTH = None
DCOS_VERIFY = True
if settings.SERVICE_SECRET:
# We are in Enterprise mode and using service account
DCOS_AUT... |
Add newline at end of file | __all__ = ['CloneableMeta']
def attach_new_init_method(cls):
"""
Replace the existing cls.__init__() method with a new one which
also initialises the _clones attribute to an empty list.
"""
orig_init = cls.__init__
def new_init(self, *args, **kwargs):
orig_init(self, *args, **kwargs)... | __all__ = ['CloneableMeta']
def attach_new_init_method(cls):
"""
Replace the existing cls.__init__() method with a new one which
also initialises the _clones attribute to an empty list.
"""
orig_init = cls.__init__
def new_init(self, *args, **kwargs):
orig_init(self, *args, **kwargs)... |
Add test coverage for 1.10 CONTENT_LENGTH hack | from django.test.client import RequestFactory
from mock import Mock
from unittest2 import TestCase
from .helpers import RequestPatchMixin
from .test_views import TestProxy
class ResponseConstructionTest(TestCase, RequestPatchMixin):
def setUp(self):
self.proxy = TestProxy.as_view()
self.browser_r... | from django.test.client import RequestFactory
from mock import Mock
from unittest2 import TestCase
from .helpers import RequestPatchMixin
from .test_views import TestProxy
class ResponseConstructionTest(TestCase, RequestPatchMixin):
def get_request(self):
return RequestFactory().get('/')
def setUp(s... |
Add new fragments to data.frag_index | import os
from django.shortcuts import render, redirect
from django.template import Context
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
from chemtools.extractor import CORES, RGROUPS, ARYL
from data.models import JobTemplate
def frag_index(request):
xrnames = ["H", "... | import os
from django.shortcuts import render, redirect
from django.template import Context
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
from chemtools.extractor import CORES, RGROUPS, ARYL
from data.models import JobTemplate
def frag_index(request):
xrnames = ["H", "... |
Improve list display of events | from django.contrib import admin
from django.contrib.admin import register
from falmer.events.models import Event
@register(Event)
class EventModelAdmin(admin.ModelAdmin):
pass
| from django.contrib import admin
from django.contrib.admin import register
from falmer.events.models import Event, MSLEvent
@register(Event)
class EventModelAdmin(admin.ModelAdmin):
list_display = ('title', 'start_time', 'end_time', )
@register(MSLEvent)
class MSLEventModelAdmin(admin.ModelAdmin):
pass
|
Add continue when no extension ".jpg" nor ".png" is found in URL | import urllib
import os
import hashlib
with open('media_urls.txt','r') as f:
for url in f:
imagename = os.path.basename(url)
m = hashlib.md5(url).hexdigest()
if '.jpg' in url:
shortname = m + '.jpg'
elif '.png' in url:
shortname = m + '.png'
else:
print ... | import urllib
import os
import hashlib
with open('media_urls.txt','r') as f:
for url in f:
imagename = os.path.basename(url)
m = hashlib.md5(url).hexdigest()
if '.jpg' in url:
shortname = m + '.jpg'
elif '.png' in url:
shortname = m + '.png'
else:
print ... |
Fix another situation where targets didn't get rebuilt | import os
from ..target import Target
class LocalFile(Target):
def __init__(self, path):
self._path = path
super(LocalFile, self).__init__()
if self.exists():
self._memory['timestamp'] = os.path.getmtime(self._path)
else:
self._memory['timestamp'] = 0
de... | import os
from ..target import Target
class LocalFile(Target):
def __init__(self, path):
self._path = path
super(LocalFile, self).__init__()
if self.exists():
self._memory['timestamp'] = os.path.getmtime(self._path)
else:
self._memory['timestamp'] = 0
de... |
Add extra DotDict subscriptability test | from piper.utils import DotDict
from piper.utils import dynamic_load
import pytest
class TestDotDict(object):
def test_get_nonexistant_raises_keyerror(self):
with pytest.raises(KeyError):
dd = DotDict({})
dd.does_not_exist
def test_get_item(self):
dd = DotDict({'dange... | from piper.utils import DotDict
from piper.utils import dynamic_load
import pytest
class TestDotDict(object):
def test_get_nonexistant_raises_keyerror(self):
with pytest.raises(KeyError):
dd = DotDict({})
dd.does_not_exist
def test_get_item(self):
dd = DotDict({'dange... |
Add path in test to src | import unittest
import NGrams
class TestNGrams(unittest.TestCase):
def test_unigrams(self):
sentence = 'this is a random piece of text'
ngram_list = NGrams.generate_ngrams(sentence, 1)
self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'],
... | import unittest
import sys
sys.path.append('../src')
import NGrams
class TestNGrams(unittest.TestCase):
def test_unigrams(self):
sentence = 'this is a random piece of text'
ngram_list = NGrams.generate_ngrams(sentence, 1)
self.assertEqual(ngram_list, [['this'], ['is'], ['a'], ['random'],
... |
Change class name to DuplicateScripts | """This module provides plugins for basic duplicate code detection."""
from hairball.plugins import HairballPlugin
class DuplicateChecks(HairballPlugin):
"""Plugin that keeps track of which scripts have been
used more than once whithin a project."""
def __init__(self):
super(DuplicateChecks, se... | """This module provides plugins for basic duplicate code detection."""
from hairball.plugins import HairballPlugin
class DuplicateScripts(HairballPlugin):
"""Plugin that keeps track of which scripts have been
used more than once whithin a project."""
def __init__(self):
super(DuplicateScripts, ... |
Return validation error messages to client | from flask import request, make_response
import json
from themint import app
from themint.service import message_service
@app.route('/', methods=['GET'])
def index():
return "Mint OK"
# TODO remove <title_number> below, as it is not used.
@app.route('/titles/<title_number>', methods=['POST'])
def post(title_num... | from flask import request, make_response
import json
from themint import app
from themint.service import message_service
from datatypes.exceptions import DataDoesNotMatchSchemaException
@app.route('/', methods=['GET'])
def index():
return "Mint OK"
# TODO remove <title_number> below, as it is not used.
@app.ro... |
Validate user password on creation | from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name', 'email', 'password']
class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['na... | from django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name', 'email', 'pas... |
Make resource type list static | import json
from rest_framework.test import APIClient
from rest_framework import status
from rest_framework.test import APITestCase
from hs_core.hydroshare.utils import get_resource_types
class TestResourceTypes(APITestCase):
def setUp(self):
self.client = APIClient()
def test_resource_typelist(se... | import json
from rest_framework.test import APIClient
from rest_framework import status
from rest_framework.test import APITestCase
class TestResourceTypes(APITestCase):
def setUp(self):
self.client = APIClient()
# Use a static list so that this test breaks when a resource type is
# add... |
Remove robots from pytest path ignore, as requested by @gonzalocasas. | import pytest
import compas
import math
import numpy
def pytest_ignore_collect(path):
if "rhino" in str(path):
return True
if "blender" in str(path):
return True
if "ghpython" in str(path):
return True
if "matlab" in str(path):
return True
if "robots" in str(pat... | import pytest
import compas
import math
import numpy
def pytest_ignore_collect(path):
if "rhino" in str(path):
return True
if "blender" in str(path):
return True
if "ghpython" in str(path):
return True
if "matlab" in str(path):
return True
if str(path).endswith(... |
Fix end of line format | #!/usr/bin/python
# coding: utf-8
import sys
import signal
import logging
import argparse
from lib.DbConnector import DbConnector
from lib.Acquisition import Acquisition
from lib.SystemMonitor import SystemMonitor
acq = Acquisition()
sm = SystemMonitor()
def signalHandler(signal, frame):
logging... | #!/usr/bin/python
# coding: utf-8
import sys
import signal
import logging
import argparse
from lib.DbConnector import DbConnector
from lib.Acquisition import Acquisition
from lib.SystemMonitor import SystemMonitor
acq = Acquisition()
sm = SystemMonitor()
def signalHandler(signal, frame):
logging.warning("Caught... |
Use zip for a shorter solution | class Matrix(object):
def __init__(self, s):
self.rows = [list(map(int, row.split()))
for row in s.split("\n")]
@property
def columns(self):
return [[row[i] for row in self.rows]
for i in range(len(self.rows[0]))]
| class Matrix(object):
def __init__(self, s):
self.rows = [list(map(int, row.split()))
for row in s.split("\n")]
@property
def columns(self):
return [list(col) for col in zip(*self.rows)]
|
Add commented out top-level imports | from __future__ import print_function, unicode_literals
import logging
__version__ = '1.3.0'
logging.basicConfig(format='%(levelname)s: indra/%(name)s - %(message)s',
level=logging.INFO)
logging.getLogger('requests').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
logg... | from __future__ import print_function, unicode_literals
import logging
__version__ = '1.3.0'
__all__ = ['bel', 'biopax', 'trips', 'reach', 'index_cards', 'sparser',
'databases', 'literature',
'preassembler', 'assemblers', 'mechlinker', 'belief',
'tools', 'util']
'''
#############
# For... |
Refactor populate_db pyinvoke task to use it in tests | import json
from pathlib import Path
import sys
import sqlalchemy as sa
from invoke import task
FANTASY_DB_SQL = Path.cwd() / 'fantasy-database' / 'schema.sql'
FANTASY_DB_DATA = Path.cwd() / 'fantasy-database' / 'data.json'
@task
def populate_db(ctx, data_file=FANTASY_DB_DATA):
from examples.fantasy import tabl... | import json
from pathlib import Path
import sys
import sqlalchemy as sa
from invoke import task
FANTASY_DATA_FOLDER = Path(__file__).parent / 'fantasy-database'
@task
def populate_db(ctx, data_folder=FANTASY_DATA_FOLDER, dsn=None):
from examples.fantasy import tables
data_file = data_folder / 'data.json'
... |
Update knowledge provider to work with API changes. | """
Knowledge provider that will respond to requests made by the rdf publisher or another bot.
"""
from sleekxmpp.plugins.base import base_plugin
from rhobot.components.storage.client import StoragePayload
from rdflib.namespace import FOAF
from rhobot.namespace import RHO
import logging
logger = logging.getLogger(__na... | """
Knowledge provider that will respond to requests made by the rdf publisher or another bot.
"""
from sleekxmpp.plugins.base import base_plugin
from rhobot.components.storage.client import StoragePayload
from rdflib.namespace import FOAF
from rhobot.namespace import RHO
import logging
logger = logging.getLogger(__na... |
Add missing return types to scope factory methods | """
byceps.services.snippet.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from enum import Enum
from typing import NewType
from uuid import UUID
from attr import attrib, attrs
from ...site.transfer.models impor... | """
byceps.services.snippet.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from enum import Enum
from typing import NewType
from uuid import UUID
from attr import attrib, attrs
from ...site.transfer.models impor... |
Add satan sha to glockfile script | #!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
for path in paths:
print "{repo} {sha}".format(
repo = path[7:],
sha = path_sha1(path)
)
def path_sha1(path):
cmd = "cd {} ... | #!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
print "github.com/localhots/satan {}".format(path_sha1("."))
for path in paths:
print "{repo} {sha}".format(
repo = path[7:],
sha = ... |
Remove glob imports from sympy.geometry. | """
A geometry module for the SymPy library. This module contains all of the
entities and functions needed to construct basic geometrical data and to
perform simple informational queries.
Usage:
======
Notes:
======
Currently the geometry module is restricted to the 2-dimensional
Euclidean space.
Examples
=... | """
A geometry module for the SymPy library. This module contains all of the
entities and functions needed to construct basic geometrical data and to
perform simple informational queries.
Usage:
======
Notes:
======
Currently the geometry module is restricted to the 2-dimensional
Euclidean space.
Examples
=... |
Use accessor to use in sort. | # -*- coding: utf-8 -*-
import re
from . import export
@export
def fuzzyfinder(input, collection, accessor=lambda x: x):
"""
Args:
input (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
... | # -*- coding: utf-8 -*-
import re
from . import export
@export
def fuzzyfinder(input, collection, accessor=lambda x: x):
"""
Args:
input (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
... |
Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx. | from getpass import getpass
from netmiko import ConnectHandler
def main():
password = getpass()
pynet_rtr1 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': password, 'port': 22}
pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'pa... | # Use Netmiko to execute 'show arp' on pynet-rtr1, pynet-rtr2, and juniper-srx.
from getpass import getpass
from netmiko import ConnectHandler
def main():
password = getpass()
pynet_rtr1 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': password, 'port': 22}
pynet_rtr... |
Add alt-f binding for auto-suggestion. | """
Key bindings for auto suggestion (for fish-style auto suggestion).
"""
from __future__ import unicode_literals
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.filters import Condition
__all__ = [
'load_auto_suggest_bindi... | """
Key bindings for auto suggestion (for fish-style auto suggestion).
"""
from __future__ import unicode_literals
import re
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.filters import Condition, emacs_mode
__all__ = [
'l... |
Revert "use pop instead of get because it doens't cause uncaught exceptions." | from core.build.subnet import build_subnet
from core.network.models import Network
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse
import pdb
def build_network(request, network_pk):
network = get_object_or_404(Network, pk=network_pk)
if request.GET.pop(... | from core.build.subnet import build_subnet
from core.network.models import Network
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse
import pdb
def build_network(request, network_pk):
network = get_object_or_404(Network, pk=network_pk)
if request.GET.get(... |
Update the knowledge base according to the emotion | import logging; logger = logging.getLogger("robot." + __name__)
from robots.exception import RobotError
from robots.actions.look_at import sweep
from robots.action import *
###############################################################################
@action
def sorry(robot, speed = 0.5):
return sweep(robot,... | import logging; logger = logging.getLogger("robot." + __name__)
import random
from robots.exception import RobotError
from robots.lowlevel import *
from robots.actions.look_at import sweep
from robots.action import *
###############################################################################
@action
@workswit... |
Use urn from certificate to create username | '''
Created on Aug 12, 2010
@author: jnaous
'''
import logging
import re
from django.contrib.auth.backends import RemoteUserBackend
from django.conf import settings
from expedient.common.permissions.shortcuts import give_permission_to
from django.contrib.auth.models import User
logger = logging.getLogger("expedient_g... | '''
Created on Aug 12, 2010
@author: jnaous
'''
import logging
import traceback
from django.contrib.auth.backends import RemoteUserBackend
from sfa.trust.gid import GID
from expedient_geni.utils import get_user_urn, urn_to_username
from geni.util.urn_util import URN
logger = logging.getLogger("expedient_geni.backends... |
Add a test for Twitter accounts with long identifier. | from __future__ import print_function, unicode_literals
from gittip.elsewhere import twitter
from gittip.testing import Harness
class TestElsewhereTwitter(Harness):
def test_get_user_info_gets_user_info(self):
twitter.TwitterAccount(self.db, "1", {'screen_name': 'alice'}).opt_in('alice')
expecte... | from __future__ import print_function, unicode_literals
from gittip.elsewhere import twitter
from gittip.testing import Harness
class TestElsewhereTwitter(Harness):
def test_get_user_info_gets_user_info(self):
twitter.TwitterAccount(self.db, "1", {'screen_name': 'alice'}).opt_in('alice')
expecte... |
Add support for returning the uuids for a profile query | # Standard imports
import json
import logging
import uuid
# Our imports
import emission.core.get_database as edb
def get_platform_query(platform):
return {"curr_platform": platform}
def get_sync_interval_query(interval):
return {"curr_sync_interval": interval}
def get_user_query(user_id_list):
return {"... | # Standard imports
import json
import logging
import uuid
# Our imports
import emission.core.get_database as edb
def get_platform_query(platform):
return {"curr_platform": platform}
def get_sync_interval_query(interval):
return {"curr_sync_interval": interval}
def get_user_query(user_id_list):
return {"... |
Use two return statements and remove printing | """A module to demonstrate exceptions."""
import sys
def convert(item):
'''
Convert to an integer.
Args:
item: some object
Returns:
an integer representation of the object
Throws:
a ValueException
'''
try:
x = int(item)
print(str.format('Conversio... | """A module to demonstrate exceptions."""
import sys
def convert(item):
"""
Convert to an integer.
Args:
item: some object
Returns:
an integer representation of the object
Throws:
a ValueException
"""
try:
return int(item)
except (ValueError, TypeErro... |
Add test for offline compression using django_compressor | import os
import shutil
import tempfile
from django.test import TestCase
from django.core.management import call_command
from django.test.utils import override_settings
TMP_STATIC_DIR = tempfile.mkdtemp()
@override_settings(
COMPRESS_ENABLED=True,
COMPRESS_OFFLINE=True,
COMPRESS_ROOT=TMP_STATIC_DIR
)
c... | import os
import shutil
import tempfile
from django.test import TestCase
from django.core.management import call_command
from django.test.utils import override_settings
TMP_STATIC_DIR = tempfile.mkdtemp()
@override_settings(
COMPRESS_ENABLED=True,
COMPRESS_OFFLINE=True,
COMPRESS_ROOT=TMP_STATIC_DIR
)
c... |
Change calendar JSON view url | from django.conf.urls import patterns, url
from swingtime import views
urlpatterns = patterns('',
url(
r'^(?:calendar/)?$',
views.CalendarView.as_view(),
name='swingtime-calendar'
),
url(
r'^calendar/json/$',
views.CalendarJSONView.as_view(),
name='swingtime... | from django.conf.urls import patterns, url
from swingtime import views
urlpatterns = patterns('',
url(
r'^(?:calendar/)?$',
views.CalendarView.as_view(),
name='swingtime-calendar'
),
url(
r'^calendar.json$',
views.CalendarJSONView.as_view(),
name='swingtime-... |
Add versioning to api routes | from flask import Blueprint
from unbound_legacy_api.utils.response import create_response
stats_bp = Blueprint('stats', __name__, url_prefix='/stats')
@stats_bp.route('/ping')
def ping():
"""Generic ping route to check if api is up"""
return create_response(status='success')
| from flask import Blueprint
from unbound_legacy_api.utils.response import create_response
stats_bp = Blueprint('stats', __name__, url_prefix='/v1/stats')
@stats_bp.route('/ping')
def ping():
"""Generic ping route to check if api is up"""
return create_response(status='success')
|
Update title of 'Wumo' crawlers, part two | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = 'Wulffmorgenthaler (vg.no)'
language = 'no'
url = 'http://heltnormalt.no/wumo'
rights = 'Mikael Wulff & Anders Morgenthaler'
class Crawler(CrawlerBa... | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = 'Wumo (vg.no)'
language = 'no'
url = 'http://heltnormalt.no/wumo'
rights = 'Mikael Wulff & Anders Morgenthaler'
class Crawler(CrawlerBase):
hist... |
Fix to make sure we dont get errors in gevent socket write call when we are writing the policy file back | from gevent.server import StreamServer
__all__ = ['FlashPolicyServer']
class FlashPolicyServer(StreamServer):
policy = """<?xml version="1.0"?><!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cros... | from gevent.server import StreamServer
__all__ = ['FlashPolicyServer']
class FlashPolicyServer(StreamServer):
policy = """<?xml version="1.0"?><!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy><allow-access-from domain="*" to-ports="*"/></cros... |
Revert "Made BaseInput inherit from forms.Field so inputs can be used in layouts. Added a SubmitButtonWidget." | from django import forms
from django.forms.widgets import Input
class SubmitButtonWidget(Input):
"""
A widget that handles a submit button.
"""
input_type = 'submit'
def render(self, name, value, attrs=None):
return super(SubmitButtonWidget, self).render(name,
self.attrs['value... | class BaseInput(object):
"""
An base Input class to reduce the amount of code in the Input classes.
"""
def __init__(self,name,value):
self.name = name
self.value = value
class Toggle(object):
"""
A container for holder toggled items such as fields and butt... |
Make the 2 mandatory parameters mandatory. Make the help message a bit clearer and provides an example. | #!/usr/bin/env python3
# https://faq.i3wm.org/question/3699/how-can-i-open-an-application-when-i-open-a-certain-workspace-for-the-first-time/
from argparse import ArgumentParser
import i3ipc
i3 = i3ipc.Connection()
parser = ArgumentParser(description='Open an application on a given workspace when it is initialized'... | #!/usr/bin/env python3
# https://faq.i3wm.org/question/3699/how-can-i-open-an-application-when-i-open-a-certain-workspace-for-the-first-time/
from argparse import ArgumentParser
import i3ipc
i3 = i3ipc.Connection()
parser = ArgumentParser(description="""Open the given application each time the
given workspace i... |
Add tests for feedback submission view. | import mock
from ...helpers import BaseApplicationTest
class TestFeedbackForm(BaseApplicationTest):
def _post(self):
return self.client.post('/feedback', data={
'uri': 'test:some-uri',
'what_doing': 'test: what doing text',
'what_happened': 'test: what happened text'})
... | |
Add bidi (right-to-left layout) attr to locale resource | # Copyright (C) 2015 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2015 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2015 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the F... | # Copyright (C) 2015 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2015 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2015 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the F... |
Test builds a number of schools, each of which has a number of subject areas. | from django.test import TestCase
from competencies.models import *
import testing_utilities as tu
class TestForkSchools(TestCase):
def setUp(self):
# Create a school.
self.school_0 = tu.create_school(name="School 0")
def test_fork_school(self):
# Make a new school, and fork school_o'... | from django.test import TestCase
from competencies.models import *
import testing_utilities as tu
class TestForkSchools(TestCase):
def setUp(self):
num_schools = 3
num_subject_areas = 5
# Create some schools.
self.schools = []
for school_num in range(0, num_schools):
... |
Fix dict argument not hashable | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from __future__ import print_function
ADD_OP = '+'
MULTIPLY_OP = '*'
OPERATORS = [ADD_OP, MULTIPLY_OP]
_cache_map = dict()
def cached(f):
def decorated(*args, **kwargs):
key = (f, tuple(args), tuple(kwargs.items()))
if key in _cache_map:... | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from __future__ import print_function
ADD_OP = '+'
MULTIPLY_OP = '*'
OPERATORS = [ADD_OP, MULTIPLY_OP]
def to_immutable(*m):
def r(d):
if isinstance(d, dict):
return tuple((e, to_immutable(v)) for e, v in d.iteritems())
if isin... |
Make agents able to see each other. | """
Module that holds classes that represent an agent's perception handler.
"""
import abc
import world
import structure
class PerceptionHandler(object):
"""
Abstract perception handler class.
"""
@abc.abstractmethod
def perceive(self, agent, world):
"""
Generates a percept given ... | """
Module that holds classes that represent an agent's perception handler.
"""
import abc
import world
import agent
import structure
class PerceptionHandler(object):
"""
Abstract perception handler class.
"""
@abc.abstractmethod
def perceive(self, agent, world):
"""
Generates a p... |
Remove -d command line argument in favour of __debug__. | import argparse
import sys
from os import path
def parse_arguments():
parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave')
parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)')
parse... | import argparse
import sys
from os import path
def parse_arguments():
parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave')
parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)')
parse... |
Add download to snappy bouncer | from django.contrib import admin
from snappybouncer.models import Conversation, UserAccount, Ticket
admin.site.register(Conversation)
admin.site.register(UserAccount)
admin.site.register(Ticket)
| from django.contrib import admin
from snappybouncer.models import Conversation, UserAccount, Ticket
from control.actions import export_select_fields_csv_action
class TicketAdmin(admin.ModelAdmin):
actions = [export_select_fields_csv_action(
"Export selected objects as CSV file",
fields = [
... |
Move .lower() method call for readability | def word_count(s):
words = strip_punc(s.lower()).split()
return {word: words.count(word) for word in set(words)}
def strip_punc(s):
return "".join(ch if ch.isalnum() else " " for ch in s)
| def word_count(s):
words = strip_punc(s).lower().split()
return {word: words.count(word) for word in set(words)}
def strip_punc(s):
return "".join(ch if ch.isalnum() else " " for ch in s)
|
Change package name to sphinxcontrib-mscgen | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='mscgen',
version='0.3'... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen Sphinx extension.
Allow mscgen-formatted Message Sequence Chart graphs to be included in
Sphinx-generated documents inline.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-mscgen',
... |
Add description of assertions raised | #!/usr/bin/python -tt
"""Solves problem B from Google Code Jam Qualification Round Africa 2010
(https://code.google.com/codejam/contest/351101/dashboard#s=p1)
"Reverse Words"
"""
import sys
def main():
"""Reads problem data from stdin and prints answers to stdout.
Args:
None
Returns:
No... | #!/usr/bin/python -tt
"""Solves problem B from Google Code Jam Qualification Round Africa 2010
(https://code.google.com/codejam/contest/351101/dashboard#s=p1)
"Reverse Words"
"""
import sys
def main():
"""Reads problem data from stdin and prints answers to stdout.
Args:
None
Returns:
No... |
Return returncode from shell command. | # encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""... | # encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""... |
Fix code style issues with Black | # -*- coding: utf-8 -*-
import os
from scout.demo import coverage_qc_report
from scout.commands import cli
def test_load_coverage_qc_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(coverage_qc_r... | # -*- coding: utf-8 -*-
import os
from scout.demo import coverage_qc_report
from scout.commands import cli
def test_load_coverage_qc_report(mock_app, case_obj):
"""Testing the load delivery report cli command"""
# Make sure the path to delivery report is a valid path
assert os.path.isfile(coverage_qc_re... |
Add sleep to simulate work | from __future__ import absolute_import
from ddsc_worker.celery import celery
@celery.task
def add(x, y):
return x + y
@celery.task
def mul(x, y):
return x + y
| from __future__ import absolute_import
from ddsc_worker.celery import celery
import time
@celery.task
def add(x, y):
time.sleep(10)
return x + y
@celery.task
def mul(x, y):
time.sleep(2)
return x * y
|
Add PDFDisplay view to the test app | """testapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | """testapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... |
Print additional stats for each projects | from django.core.management.base import BaseCommand
from xbrowse_server.base.models import Project
class Command(BaseCommand):
"""Command to generate a ped file for a given project"""
def handle(self, *args, **options):
projects = Project.objects.all()
for project in projects:
ind... | from django.core.management.base import BaseCommand
from xbrowse_server.base.models import Project
class Command(BaseCommand):
"""Command to print out basic stats on some or all projects. Optionally takes a list of project_ids. """
def handle(self, *args, **options):
if args:
projects = [... |
Fix bug in action serializer | from rest_framework import serializers
from editorsnotes.main.models.auth import (LogActivity, ADDITION, CHANGE,
DELETION)
VERSION_ACTIONS = {
ADDITION: 'added',
CHANGE: 'changed',
DELETION: 'deleted'
}
# TODO: make these fields nested, maybe
class ActivitySeria... | from rest_framework import serializers
from editorsnotes.main.models.auth import (LogActivity, ADDITION, CHANGE,
DELETION)
VERSION_ACTIONS = {
ADDITION: 'added',
CHANGE: 'changed',
DELETION: 'deleted'
}
# TODO: make these fields nested, maybe
class ActivitySeria... |
Fix mismatched logic error in compatibility check | """
Detect incompatible version of OpenPyXL
GH7169
"""
from distutils.version import LooseVersion
start_ver = '1.6.1'
stop_ver = '2.0.0'
def is_compat():
"""Detect whether the installed version of openpyxl is supported.
Returns
-------
compat : bool
``True`` if openpyxl is installed and is... | """
Detect incompatible version of OpenPyXL
GH7169
"""
from distutils.version import LooseVersion
start_ver = '1.6.1'
stop_ver = '2.0.0'
def is_compat():
"""Detect whether the installed version of openpyxl is supported.
Returns
-------
compat : bool
``True`` if openpyxl is installed and is... |
Read input file from stdin. | import argparse
import yaml
from .bocca import make_project, ProjectExistsError
def main():
parser = argparse.ArgumentParser()
parser.add_argument('file', help='Project description file')
args = parser.parse_args()
try:
with open(args.file, 'r') as fp:
make_project(yaml.load(fp... | import argparse
import yaml
from .bocca import make_project, ProjectExistsError
def main():
parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'),
help='Project description file')
args = parser.parse_args()
try:
make_project(yaml... |
Remove useless mock side effect | import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.publicip
def build_module():
config = core.config.Config([])
return modules.contrib.publicip.Module(config=config, theme=None)
def widget(module):
return module.widgets()[0]
class PublicIPTest... | import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.publicip
def build_module():
config = core.config.Config([])
return modules.contrib.publicip.Module(config=config, theme=None)
def widget(module):
return module.widgets()[0]
class PublicIPTest... |
Use plugin_dir as base for script_path | #!/usr/bin/env python
import sys
from bashscriptrunner import BashScriptRunner
name = "chef"
script = BashScriptRunner(script_path=["roushagent/plugins/lib/%s" % name])
def setup(config):
LOG.debug('Doing setup in test.py')
register_action('install_chef', install_chef)
register_action('run_chef', run_ch... | #!/usr/bin/env python
import sys
import os
from bashscriptrunner import BashScriptRunner
name = "chef"
def setup(config={}):
LOG.debug('Doing setup in test.py')
plugin_dir = config.get("plugin_dir", "roushagent/plugins")
script_path = [os.path.join(plugin_dir, "lib", name)]
script = BashScriptRunner(... |
Use more readable version comparision | import sys
import pstats
import cProfile
import unittest
from django.test.simple import DjangoTestSuiteRunner
class ProfilingTestRunner(DjangoTestSuiteRunner):
def run_suite(self, suite, **kwargs):
stream = open('profiled_tests.txt', 'w')
# failfast keyword was added in Python 2.7 so we n... | import sys
import pstats
import cProfile
import unittest
from django.test.simple import DjangoTestSuiteRunner
class ProfilingTestRunner(DjangoTestSuiteRunner):
def run_suite(self, suite, **kwargs):
stream = open('profiled_tests.txt', 'w')
# failfast keyword was added in Python 2.7 so we n... |
Add S3 Generator to generators module | from .databricks_generator import DatabricksTableGenerator
from .glob_reader_generator import GlobReaderGenerator
from .subdir_reader_generator import SubdirReaderGenerator
from .in_memory_generator import InMemoryGenerator
from .query_generator import QueryGenerator
from .table_generator import TableGenerator | from .databricks_generator import DatabricksTableGenerator
from .glob_reader_generator import GlobReaderGenerator
from .subdir_reader_generator import SubdirReaderGenerator
from .in_memory_generator import InMemoryGenerator
from .query_generator import QueryGenerator
from .table_generator import TableGenerator
from .s3... |
Add assert to validator test cases | import unittest
import quantities as pq
class ValidatorTestCase(unittest.TestCase):
def register_test(self):
class TestClass():
intValue = 0
def getIntValue(self):
return self.intValue
from sciunit.validators import register_quantity, register_type
reg... | import unittest
import quantities as pq
class ValidatorTestCase(unittest.TestCase):
def test1(self):
self.assertEqual(1, 1)
def register_test(self):
class TestClass():
intValue = 0
def getIntValue(self):
return self.intValue
from sciunit.valid... |
Fix if encoding is not utf-8 | import setuptools
setuptools.setup(
name='mailcap-fix',
version='0.1.1',
description='A patched mailcap module that conforms to RFC 1524',
long_description=open('README.rst').read(),
url='https://github.com/michael-lazar/mailcap_fix',
author='Michael Lazar',
author_email='lazar.michael22@gm... | import setuptools
setuptools.setup(
name='mailcap-fix',
version='0.1.1',
description='A patched mailcap module that conforms to RFC 1524',
long_description=open('README.rst', encoding='utf-8').read(),
url='https://github.com/michael-lazar/mailcap_fix',
author='Michael Lazar',
author_email='... |
Update PyPI status to alpha | from setuptools import setup, find_packages
with open('README.rst') as readme:
next(readme)
long_description = ''.join(readme).strip()
setup(
name='pytest-xpara',
version='0.0.0',
description='An extended parametrizing plugin of pytest.',
url='https://github.com/tonyseek/pytest-xpara',
lon... | from setuptools import setup, find_packages
with open('README.rst') as readme:
next(readme)
long_description = ''.join(readme).strip()
setup(
name='pytest-xpara',
version='0.0.0',
description='An extended parametrizing plugin of pytest.',
url='https://github.com/tonyseek/pytest-xpara',
lon... |
Increment version number for updated pypi package | from setuptools import setup, find_packages
import os
version = '0.1.1'
LONG_DESCRIPTION = """
===============
django-helpdesk
===============
This is a Django-powered helpdesk ticket tracker, designed to
plug into an existing Django website and provide you with
internal (or, perhaps, external) helpdesk management.... | from setuptools import setup, find_packages
import os
version = '0.1.2'
LONG_DESCRIPTION = """
===============
django-helpdesk
===============
This is a Django-powered helpdesk ticket tracker, designed to
plug into an existing Django website and provide you with
internal (or, perhaps, external) helpdesk management.... |
Switch use of getattr to getattribute. | from collections import OrderedDict
class AttrDict(OrderedDict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
def __getattr__(self, attr):
if attr not in self:
raise AttributeError(attr)
else:
return self[attr]
def _... | from collections import OrderedDict
class AttrDict(OrderedDict):
def __init__(self, *args, **kwargs):
super(OrderedDict, self).__init__(*args, **kwargs)
def __getattribute__(self, attr):
if attr in self:
return self[attr]
else:
return super(OrderedDict, self)._... |
Remove the unused unicode module. | from setuptools import setup
setup(
name="hashi",
packages=["hashi"],
version="0.0",
description="Web centric IRC client.",
author="Nell Hardcastle",
author_email="chizu@spicious.com",
install_requires=["pyzmq>=2.1.7",
"txzmq",
"txWebSocket",
... | from setuptools import setup
setup(
name="hashi",
packages=["hashi"],
version="0.0",
description="Web centric IRC client.",
author="Nell Hardcastle",
author_email="chizu@spicious.com",
install_requires=["pyzmq>=2.1.7",
"txzmq",
"txWebSocket",
... |
Use codecs.open for py2/py3-compatible utf8 reading | from setuptools import setup, find_packages
import sys
import os.path
import numpy as np
# Must be one line or PyPI will cut it off
DESC = ("A powerful, accurate, and easy-to-use Python library for "
"doing colorspace conversions")
LONG_DESC = open("README.rst").read()
# defines __version__
exec(open("color... | from setuptools import setup, find_packages
import sys
import os.path
import numpy as np
# Must be one line or PyPI will cut it off
DESC = ("A powerful, accurate, and easy-to-use Python library for "
"doing colorspace conversions")
import codecs
LONG_DESC = codecs.open("README.rst", encoding="utf-8").read()
... |
Add templates, bump version number | from setuptools import setup, find_packages
setup(
name='icecake',
version='0.1.0',
py_modules=['icecake'],
url="https://github.com/cbednarski/icecake",
author="Chris Bednarski",
author_email="banzaimonkey@gmail.com",
description="An easy and cool static site generator",
license="MIT",
... | from setuptools import setup, find_packages
setup(
name='icecake',
version='0.2.0',
py_modules=['icecake', 'templates'],
url="https://github.com/cbednarski/icecake",
author="Chris Bednarski",
author_email="banzaimonkey@gmail.com",
description="An easy and cool static site generator",
li... |
Fix for matrixmultiply != dot on Numeric < 23.4 |
from info_scipy_base import __doc__
from scipy_base_version import scipy_base_version as __version__
from ppimport import ppimport, ppimport_attr
# The following statement is equivalent to
#
# from Matrix import Matrix as mat
#
# but avoids expensive LinearAlgebra import when
# Matrix is not used.
mat = ppimport_a... |
from info_scipy_base import __doc__
from scipy_base_version import scipy_base_version as __version__
from ppimport import ppimport, ppimport_attr
# The following statement is equivalent to
#
# from Matrix import Matrix as mat
#
# but avoids expensive LinearAlgebra import when
# Matrix is not used.
mat = ppimport_a... |
Fix two failing typing tests | import numpy as np
a: np.ndarray
generator = (i for i in range(10))
np.require(a, requirements=1) # E: No overload variant
np.require(a, requirements="TEST") # E: incompatible type
np.zeros("test") # E: incompatible type
np.zeros() # E: Too few arguments
np.ones("test") # E: incompatible type
np.ones() # E: T... | import numpy as np
a: np.ndarray
generator = (i for i in range(10))
np.require(a, requirements=1) # E: No overload variant
np.require(a, requirements="TEST") # E: incompatible type
np.zeros("test") # E: incompatible type
np.zeros() # E: Missing positional argument
np.ones("test") # E: incompatible type
np.ones... |
Drop another Python 2 shim | from unittest.mock import patch
import pytest
from .core import PostmarkClient, requests
@pytest.yield_fixture
def postmark_request():
"""Mocks network requests to Postmark API."""
if patch is None:
raise AssertionError('To use pytest fixtures on Python 2, please, install postmarker["tests"]')
w... | from unittest.mock import patch
import pytest
from .core import PostmarkClient, requests
@pytest.yield_fixture
def postmark_request():
"""Mocks network requests to Postmark API."""
with patch("postmarker.core.requests.Session.request", wraps=requests.Session().request) as patched:
with patch("postma... |
Revise tower of hanoi alg from Yuanlin | """The tower of Hanoi."""
from __future__ import print_function
def move_towers(height, from_pole, to_pole, with_pole):
if height == 1:
print('Moving disk from {0} to {1}'.format(from_pole, to_pole))
else:
move_towers(height - 1, from_pole, with_pole, to_pole)
move_towers(1, from_pole,... | """The tower of Hanoi."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def tower_of_hanoi(height, from_pole, to_pole, with_pole, counter):
if height == 1:
counter[0] += 1
print('{0} -> {1}'.format(from_pole, to_pole))
else:
... |
Add SecureModeNeeded property to PayInExecutionDetailsDirect | 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
self.SecureMod... |
Clean up python script and make it run in linear time. | #!/usr/bin/python
import argparse
import re
format = list('''
-- --
-----------
-----------
----------
--------
-------
-- --
-----------
'''[1:-1])
def setFormatString(index, value):
position = -1
for i in range(len(format)):
if not format[i].isspace():
position += 1
if position == index:
format[i... | #!/usr/bin/python
import argparse
import ast
format = list('''
-- --
-----------
-----------
----------
--------
-------
-- --
-----------
'''[1:-1])
# Print the given labels using the whitespace of format.
def printFormatted(labels):
i = 0
for c in format:
if c.isspace():
print(c, end='')
else:
pr... |
Use contents of README as long_description | #!/usr/bin/env python3
from setuptools import setup
from ipyrmd import __version__
setup(name="ipyrmd",
version=__version__,
description="Convert between IPython/Jupyter notebooks and RMarkdown",
author="Gordon Ball",
author_email="gordon@chronitis.net",
url="https://github.com/chronitis... | #!/usr/bin/env python3
from setuptools import setup
from ipyrmd import __version__
with open("README.md") as f:
long_desc = f.read()
setup(name="ipyrmd",
version=__version__,
description="Convert between IPython/Jupyter notebooks and RMarkdown",
long_description=long_desc,
author="Gordon ... |
Use pip version of python-payer-api instead. | import os
from distutils.core import setup
from setuptools import find_packages
VERSION = __import__("django_shop_payer_backend").VERSION
CLASSIFIERS = [
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development',... | import os
from distutils.core import setup
from setuptools import find_packages
VERSION = __import__("django_shop_payer_backend").VERSION
CLASSIFIERS = [
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development',... |
Change relative imports to absolute. | from django.contrib import admin
from .filters import ResourceTypeFilter
from .mixins import LogEntryAdminMixin
from .models import LogEntry
class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin):
list_display = ["created", "resource_url", "action", "msg_short", "user_url"]
search_fields = [
"time... | from django.contrib import admin
from auditlog.filters import ResourceTypeFilter
from auditlog.mixins import LogEntryAdminMixin
from auditlog.models import LogEntry
class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin):
list_display = ["created", "resource_url", "action", "msg_short", "user_url"]
search_... |
Refactor - Simplify the call to api | # Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui.back import http, api_query
from swh.core.json import SW... | # Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui.back import http, api_query
from swh.core.json import SW... |
Return serializable string from base64encode. | from __future__ import print_function
import sys
import hashlib
import base64
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def to_unicode(content):
# TODO: considering using the 'six' library for this, for now just do something simple.
if sys.version_info >= (3,0):
ret... | from __future__ import print_function
import sys
import hashlib
import base64
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def to_unicode(content):
# TODO: considering using the 'six' library for this, for now just do something simple.
if sys.version_info >= (3,0):
ret... |
Add delete_min() and its helper func’s | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class BinaryHeap(object):
def __init__(self):
# Put single zero as the 1st element, so that
# integer division can be used in later methods.
self.heap_ls = [0]
self.current_... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class BinaryHeap(object):
def __init__(self):
# Put single zero as the 1st element, so that
# integer division can be used in later methods.
self.heap_ls = [0]
self.current_... |
Add test for mp3, ogg and flac support in gstreamer backend | import unittest
import os
from mopidy.models import Playlist, Track
from mopidy.backends.gstreamer import GStreamerBackend
from tests.backends.base import (BasePlaybackControllerTest,
BaseCurrentPlaylistControllerTest)
folder = os.path.dirname(__file__)
folder = os.path.join(folder, ... | import unittest
import os
from mopidy.models import Playlist, Track
from mopidy.backends.gstreamer import GStreamerBackend
from tests.backends.base import (BasePlaybackControllerTest,
BaseCurrentPlaylistControllerTest)
folder = os.path.dirname(__file__)
folder = os.path.join(folder, ... |
Revert "migrations: Replace special chars in stream & user names with space." | # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
from typing import Text
def remove_special_chars_from_streamname(apps, schema_editor):
# type: (StateApps, DatabaseSchemaE... | # -*- coding: utf-8 -*-
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0126_prereg_remove_users_without_realm'),
]
operations = [
# There was a migration here, which wasn't ready for wide deployment
# and was backed out. This ... |
Add debug log output to `cob testserver` | import click
import logbook
from ..app import build_app
from ..bootstrapping import ensure_project_bootstrapped
_logger = logbook.Logger(__name__)
@click.command()
@click.option('-p', '--port', type=int, default=5000)
@click.option('--debug/--no-debug', is_flag=True, default=True)
def testserver(port, debug):
e... | import click
import logbook
from ..app import build_app
from ..bootstrapping import ensure_project_bootstrapped
_logger = logbook.Logger(__name__)
@click.command()
@click.option('-p', '--port', type=int, default=5000)
@click.option('--debug/--no-debug', is_flag=True, default=True)
def testserver(port, debug):
e... |
Change subject and content of registration email. | from celery import task
from django.core.mail import EmailMessage
from webparticipation.apps.ureporter.models import delete_user_from_rapidpro as delete_from
@task()
def send_verification_token(ureporter):
if ureporter.token:
subject = 'Hello'
body = 'Welcome to ureport. To complete the registrati... | from celery import task
from django.core.mail import EmailMessage
from webparticipation.apps.ureporter.models import delete_user_from_rapidpro as delete_from
@task()
def send_verification_token(ureporter):
if ureporter.token:
subject = 'U-Report Registration'
body = 'Thank you for registering with... |
ADD test to test iterative fit sparse | import unittest
from autosklearn.pipeline.components.regression.random_forest import RandomForest
from autosklearn.pipeline.util import _test_regressor, _test_regressor_iterative_fit
import sklearn.metrics
class RandomForestComponentTest(unittest.TestCase):
def test_default_configuration(self):
for i in... | import unittest
from autosklearn.pipeline.components.regression.random_forest import RandomForest
from autosklearn.pipeline.util import _test_regressor, _test_regressor_iterative_fit
import sklearn.metrics
class RandomForestComponentTest(unittest.TestCase):
def test_default_configuration(self):
for i in... |
Store magic test. On MacOSX the temp dir in /var is symlinked into /private/var thus making this comparison fail. This is solved by using os.path.realpath to expand the tempdir into is's real directory. | import tempfile, os
import nose.tools as nt
ip = get_ipython()
ip.magic('load_ext storemagic')
def test_store_restore():
ip.user_ns['foo'] = 78
ip.magic('alias bar echo "hello"')
tmpd = tempfile.mkdtemp()
ip.magic('cd ' + tmpd)
ip.magic('store foo')
ip.magic('store bar')
# Check stor... | import tempfile, os
import nose.tools as nt
ip = get_ipython()
ip.magic('load_ext storemagic')
def test_store_restore():
ip.user_ns['foo'] = 78
ip.magic('alias bar echo "hello"')
tmpd = tempfile.mkdtemp()
ip.magic('cd ' + tmpd)
ip.magic('store foo')
ip.magic('store bar')
# Check stor... |
Add aliases for MFR-related utilites | from .views import node
# Alias the project serializer
serialize_node = node._view_project
| # -*- coding: utf-8 -*-
"""Various node-related utilities."""
from website.project.views import node
from website.project.views import file as file_views
# Alias the project serializer
serialize_node = node._view_project
# File rendering utils
get_cache_content = file_views.get_cache_content
get_cache_path = file_vi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.