commit stringlengths 40 40 | subject stringlengths 1 1.49k | old_file stringlengths 4 311 | new_file stringlengths 4 311 | new_contents stringlengths 1 29.8k | old_contents stringlengths 0 9.9k | lang stringclasses 3
values | proba float64 0 1 |
|---|---|---|---|---|---|---|---|
788cc159e4d734b972e22ccf06dbcd8ed8f94885 | Update DictStack implementation from jaraco.collections 3.5.1 | distutils/_collections.py | distutils/_collections.py | import collections
import itertools
# from jaraco.collections 3.5.1
class DictStack(list, collections.abc.Mapping):
"""
A stack of dictionaries that behaves as a view on those dictionaries,
giving preference to the last.
>>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)])
>>> stack['a']
2... | import collections
import itertools
# from jaraco.collections 3.5
class DictStack(list, collections.abc.Mapping):
"""
A stack of dictionaries that behaves as a view on those dictionaries,
giving preference to the last.
>>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)])
>>> stack['a']
2
... | Python | 0 |
3ff2ecfd26097b37832a397a43db6121a0bc3627 | Remove superfluous comment. | djadyen/management/commands/adyen_maintenance.py | djadyen/management/commands/adyen_maintenance.py | from datetime import timedelta
from django.apps import apps
from django.core.management.base import BaseCommand
from django.utils import timezone
from djadyen import settings
from djadyen.choices import Status
from djadyen.models import AdyenNotification
class Command(BaseCommand):
help = "Process the adyen not... | from datetime import timedelta
from django.apps import apps
from django.core.management.base import BaseCommand
from django.utils import timezone
from djadyen import settings
from djadyen.choices import Status
from djadyen.models import AdyenNotification
class Command(BaseCommand):
help = "Process the adyen not... | Python | 0.000001 |
32eba84ec5527f1afc82998e98f5d15035e311c1 | Allow forced loading. Contemplating changing the default too. | chef/base.py | chef/base.py | from chef.api import ChefAPI
class DelayedAttribute(object):
"""Descriptor that calls ._populate() before access to implement lazy loading."""
def __init__(self, attr):
self.attr = attr
def __get__(self, instance, owner):
if instance is None:
return self
if not getattr... | from chef.api import ChefAPI
class DelayedAttribute(object):
"""Descriptor that calls ._populate() before access to implement lazy loading."""
def __init__(self, attr):
self.attr = attr
def __get__(self, instance, owner):
if instance is None:
return self
if not getattr... | Python | 0 |
6ba2dc8cf06efd74cae941c370e75ccddcf1d25c | fix broken arg of DnnL2Pool2DNode | treeano/sandbox/nodes/l2_pool.py | treeano/sandbox/nodes/l2_pool.py | import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
fX = theano.config.floatX
@treeano.register_node("l2_pool")
class L2PoolNode(treeano.Wrapper1NodeImpl):
"""
node that takes the L2 norm of the pooled over region
"""
hyperparameter_names = ("pool_s... | import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
fX = theano.config.floatX
@treeano.register_node("l2_pool")
class L2PoolNode(treeano.Wrapper1NodeImpl):
"""
node that takes the L2 norm of the pooled over region
"""
hyperparameter_names = ("pool_s... | Python | 0.000004 |
7967d5fb49cd1bb0b1ed8d2417c3ace36f47600d | Refactor denoise tests and add tests for bilateral filter | skimage/filter/tests/test_denoise.py | skimage/filter/tests/test_denoise.py | import numpy as np
from numpy.testing import run_module_suite, assert_raises
from skimage import filter, data, color, img_as_float
lena = img_as_float(data.lena()[:256, :256])
lena_gray = color.rgb2gray(lena)
def test_tv_denoise_2d():
# lena image
img = lena_gray
# add noise to lena
img += 0.5 * im... | import numpy as np
from numpy.testing import run_module_suite
from skimage import filter, data, color
class TestTvDenoise():
def test_tv_denoise_2d(self):
"""
Apply the TV denoising algorithm on the lena image provided
by scipy
"""
# lena image
lena = color.rgb2gr... | Python | 0 |
539038ba1135b68786adb44d7660c82a96794971 | Remove logging | imgproc.py | imgproc.py | from SimpleCV import *
import numpy
import cv2
def process_image(obj, img, config, each_blob=None):
"""
:param obj: Object we're tracking
:param img: Input image
:param config: Controls
:param each_blob: function, taking a SimpleCV.Blob as an argument, that is called for every candidate blob
:... | from SimpleCV import *
import numpy
import cv2
def process_image(obj, img, config, each_blob=None):
"""
:param obj: Object we're tracking
:param img: Input image
:param config: Controls
:param each_blob: function, taking a SimpleCV.Blob as an argument, that is called for every candidate blob
:... | Python | 0.000001 |
5fb74f09f4a1ee883b6cea5b8f531d8ef01e61f7 | Update Lexer | lexer.py | lexer.py | import ply.lex as lex
class Lexer(object):
reserved = {
'and' : 'AND',
'do' : 'DO',
'else' : 'ELSE',
'while' : 'WHILE',
'then' : 'THEN',
'end' : 'END',
'for' : 'FOR',
'if' : 'IF',
'var' : 'VAR',
'or' : 'OR'
}
# List of token names
tokens = [
'ID' ... | import ply.lex as lex
class Lexer(object):
reserved = {
'and' : 'AND',
'break' : 'BREAK',
'do' : 'DO',
'else' : 'ELSE',
'elseif' : 'ELSEIF',
'end' : 'END',
'false' : 'FALSE',
'for' : 'FOR',
'function': 'FUNCTION',
'if' : 'IF',
'in' : 'IN... | Python | 0.000001 |
372ce38d1ddcf2fd65d83df2499d97d4fc2128e6 | Fix issue in cbb.py | ed2d/physics/cbb.py | ed2d/physics/cbb.py | from ed2d.physics.collisiondata import*
from ed2d.glmath import vector
# Circle Bounding Box
class CBB(object):
def __init__(self, radius, center):
'''Creates a circle bounding box object to be used with the physics engine. Takes in a float for the radius and an array for the center.'''
self.radius =... | from ed2d.physics.collisiondata import*
from ed2d.glmath import vector
# Circle Bounding Box
class CBB(object):
def __init__(self, radius, center):
'''Creates a circle bounding box object to be used with the physics engine. Takes in a float for the radius and an array for the center.'''
self.radius =... | Python | 0.000001 |
1451d199833b405929105f939f57b4d4faf50fa2 | Use new py.test to generate vector-vs-scalar tests | skyfield/tests/test_vectorization.py | skyfield/tests/test_vectorization.py | """Determine whether arrays work as well as individual inputs."""
from itertools import izip
from numpy import array
from ..constants import T0
from ..planets import earth, mars
from ..timescales import JulianDate, julian_date
dates = array([
julian_date(1969, 7, 20, 20. + 18. / 60.),
T0,
julian_date(2012... | """Determine whether arrays work as well as individual inputs."""
import pytest
from numpy import array
from ..constants import T0
from ..planets import earth, mars
from ..timescales import JulianDate, julian_date
dates = array([
julian_date(1969, 7, 20, 20. + 18. / 60.),
T0,
julian_date(2012, 12, 21),
... | Python | 0 |
0ea687403b01dbc6268c15550f0caf45a54e9106 | Fix Joust picking with multiple minions in the deck | fireplace/cards/utils.py | fireplace/cards/utils.py | import random
from hearthstone.enums import CardClass, CardType, GameTag, Race, Rarity
from ..actions import *
from ..aura import Refresh
from ..dsl import *
from ..events import *
from ..utils import custom_card
# For buffs which are removed when the card is moved to play (eg. cost buffs)
# This needs to be Summon, ... | import random
from hearthstone.enums import CardClass, CardType, GameTag, Race, Rarity
from ..actions import *
from ..aura import Refresh
from ..dsl import *
from ..events import *
from ..utils import custom_card
# For buffs which are removed when the card is moved to play (eg. cost buffs)
# This needs to be Summon, ... | Python | 0 |
42462135cec040d17f8ce4488c1ee6bb3b59f406 | Bump mono-basic to @mono/mono-basic/b8011b2f274606323da0927214ed98336465f467 | packages/mono-basic.py | packages/mono-basic.py | GitHubTarballPackage ('mono', 'mono-basic', '4.0.1', 'b8011b2f274606323da0927214ed98336465f467',
configure = './configure --prefix="%{prefix}"',
override_properties = { 'make': 'make' }
)
| GitHubTarballPackage ('mono', 'mono-basic', '3.0', '0d0440feccf648759f7316f93ad09b1e992ea13a',
configure = './configure --prefix="%{prefix}"',
override_properties = { 'make': 'make' }
)
| Python | 0.000001 |
3ddddbd24bb37c30df80233ec4c70c38b6c29e82 | Update leaflet request to be over https | emstrack/forms.py | emstrack/forms.py | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... | Python | 0 |
612698f37ab726fb77aa1f284c97d01d1d726abf | Bump version | django_anyvcs/__init__.py | django_anyvcs/__init__.py | # Copyright (c) 2014-2016, Clemson University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditio... | # Copyright (c) 2014-2016, Clemson University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditio... | Python | 0 |
9674a0869c2a333f74178e305677259e7ac379c3 | Make the Websocket's connection header value case-insensitive | examples/ignore_websocket.py | examples/ignore_websocket.py | # This script makes mitmproxy switch to passthrough mode for all HTTP
# responses with "Connection: Upgrade" header. This is useful to make
# WebSockets work in untrusted environments.
#
# Note: Chrome (and possibly other browsers), when explicitly configured
# to use a proxy (i.e. mitmproxy's regular mode), send a CON... | # This script makes mitmproxy switch to passthrough mode for all HTTP
# responses with "Connection: Upgrade" header. This is useful to make
# WebSockets work in untrusted environments.
#
# Note: Chrome (and possibly other browsers), when explicitly configured
# to use a proxy (i.e. mitmproxy's regular mode), send a CON... | Python | 0.005274 |
7c90e73d3ffa2a8209a751b01c7cd8bd3122b13b | Use actual feature values instead of binary for making pivot predictions | scripts/build_pivot_training_data.py | scripts/build_pivot_training_data.py | #!/usr/bin/env python
from os.path import join, dirname
from sklearn.datasets import load_svmlight_file, dump_svmlight_file
import numpy as np
import scipy.sparse
import sys
from uda_common import read_feature_groups
def main(args):
if len(args) < 3:
sys.stderr.write("Three required arguments: <pivot file... | #!/usr/bin/env python
from os.path import join, dirname
from sklearn.datasets import load_svmlight_file, dump_svmlight_file
import numpy as np
import scipy.sparse
import sys
from uda_common import read_feature_groups
def main(args):
if len(args) < 3:
sys.stderr.write("Three required arguments: <pivot file... | Python | 0 |
d981caff4b6710a3779f25fd8955fd111d9ea0cf | fix export error in dj 19 | django_tablib/datasets.py | django_tablib/datasets.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from .base import BaseDataset
class SimpleDataset(BaseDataset):
def __init__(self, queryset, headers=None, encoding='utf-8'):
self.queryset = queryset
self.encoding = encoding
if headers is None:
... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from .base import BaseDataset
class SimpleDataset(BaseDataset):
def __init__(self, queryset, headers=None, encoding='utf-8'):
self.queryset = queryset
self.encoding = encoding
if headers is None:
... | Python | 0 |
a43b62c60b00233fa84c66bf4a332410903476eb | fix typo | django_fabric/fabfile.py | django_fabric/fabfile.py | # -*- coding: utf8 -*-
from fabric.api import local, run, cd
from fabric.operations import sudo
from fabric import colors
from fabric.context_managers import settings
from fabric.contrib.console import confirm
from fabric.contrib import django
from fabric.utils import abort
class App():
project_paths = {}
pro... | # -*- coding: utf8 -*-
from fabric.api import local, run, cd
from fabric.operations import sudo
from fabric import colors
from fabric.context_managers import settings
from fabric.contrib.console import confirm
from fabric.contrib import django
from fabric.utils import abort
class App():
project_paths = {}
pro... | Python | 0.999991 |
a5add45a7f4fb1f9651e49fb5f20fe1c9953c0b8 | Assert expected dates for A1 | esios/archives.py | esios/archives.py | # -*- coding: utf-8 -*-
from datetime import datetime
from dateutil import relativedelta
from libsaas import http, parsers, port
from libsaas.services import base
from esios.utils import translate_param, serialize_param
LIQUICOMUN_PRIORITY = [
'C7', 'A7', 'C6', 'A6', 'C5', 'A5', 'C4', 'A4', 'C3', 'A3', 'C2', 'A... | # -*- coding: utf-8 -*-
from datetime import datetime
from libsaas import http, parsers, port
from libsaas.services import base
from esios.utils import translate_param, serialize_param
LIQUICOMUN_PRIORITY = [
'C7', 'A7', 'C6', 'A6', 'C5', 'A5', 'C4', 'A4', 'C3', 'A3', 'C2', 'A2',
'C1', 'A1'
]
def parser_n... | Python | 0.999994 |
4c500ce1995da97861e37647b61efaf14c6b08d0 | Load saved RDD | code/main.py | code/main.py | from spark_model import SparkModel
import socket
from document import Document
from pyspark import SparkContext, SparkConf
from boto.s3.connection import S3Connection
from pyspark import SparkConf, SparkContext
import json
import sys
from datetime import datetime
def log_results(saved, model_type, start_time, end_time... | from spark_model import SparkModel
import socket
from document import Document
from pyspark import SparkContext, SparkConf
from boto.s3.connection import S3Connection
from pyspark import SparkConf, SparkContext
import json
import sys
from datetime import datetime
def log_results(model_type, start_time, end_time, score... | Python | 0.000001 |
9ec2382de5a3d5377fee03a6151e5afbf36f8e71 | add doc link | code/mode.py | code/mode.py | # an in-depth rundown of this program
# can be found at:
# https://github.com/joshhartigan/learn-programming/blob/master/Most%20Frequent%20Integer.md
def mode(array):
count = {}
for elem in array:
try:
count[elem] += 1
except (KeyError):
count[elem] = 1
# get max cou... | def mode(array):
count = {}
for elem in array:
try:
count[elem] += 1
except (KeyError):
count[elem] = 1
# get max count
maximum = 0
modeKey = 0
for key in count.keys():
if count[key] > maximum:
maximum = count[key]
modeKey =... | Python | 0 |
ae2284fa85e1ef7be43792b72480018729b1c2ba | Bump PEP version for __version__ comment | fluent_blogs/__init__.py | fluent_blogs/__init__.py | # following PEP 440
__version__ = "1.0"
# Fix for internal messy imports.
# When base_models is imported before models/__init__.py runs, there is a circular import:
# base_models -> models/managers.py -> invoking models/__init__.py -> models/db.py -> base_models.py
#
# This doesn't occur when the models are imported f... | # following PEP 386
__version__ = "1.0"
# Fix for internal messy imports.
# When base_models is imported before models/__init__.py runs, there is a circular import:
# base_models -> models/managers.py -> invoking models/__init__.py -> models/db.py -> base_models.py
#
# This doesn't occur when the models are imported f... | Python | 0.000001 |
ac249c24c2f72764a8618a0f2e9cd1909d50d1d5 | Allow to specify custom options for EscapeCode preprocessor. | foliant/backends/base.py | foliant/backends/base.py | from importlib import import_module
from shutil import copytree
from datetime import date
from logging import Logger
from foliant.utils import spinner
class BaseBackend(object):
'''Base backend. All backends must inherit from this one.'''
targets = ()
required_preprocessors_before = ()
required_prep... | from importlib import import_module
from shutil import copytree
from datetime import date
from logging import Logger
from foliant.utils import spinner
class BaseBackend(object):
'''Base backend. All backends must inherit from this one.'''
targets = ()
required_preprocessors_before = ()
required_prep... | Python | 0 |
ef9cd0033ccfd314592be7987c262a61d0ec2fba | fix thing I apparently never testedgit add light.py | light.py | light.py | import RPi.GPIO as GPIO
class Light:
def __init__(self, pin):
self.pin = pin
self.status = False
GPIO.setup(pin, GPIO.OUT)
def toggle(self):
self.status = not self.status
self.do()
def on(self):
self.status = True
self.do()
def off(self):
self.status = False
self.do()
... | import RPi.GPIO as GPIO
class Light:
def __init__(self, pin):
self.pin = pin
self.status = False
GPIO.setup(pin, GPIO.OUT)
def toggle(self):
self.status = not self.status
self.do()
def on(self):
self.status = True
self.do()
def off(self):
self.status = False
self.do()
... | Python | 0 |
f0d4b430b627fb9e2b18ba3f82c936698fac6430 | Update to version 1.3 | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Account Report CSV, for OpenERP
# Copyright (C) 2013 XCG Consulting (http://odoo.consulting)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Aff... | # -*- coding: utf-8 -*-
##############################################################################
#
# Account Report CSV, for OpenERP
# Copyright (C) 2013 XCG Consulting (http://odoo.consulting)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Aff... | Python | 0 |
7b176d1e775ddec384a76d6de9c121e114a8738e | load ACL | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Account Analytic Online, for OpenERP
# Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | # -*- coding: utf-8 -*-
##############################################################################
#
# Account Analytic Online, for OpenERP
# Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | Python | 0.000002 |
febfb4c9a5ec5ddfe1f13067c1bc63533e58b09b | DEBUG = False | elgassia/settings.py | elgassia/settings.py | """
Django settings for elgassia project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
i... | """
Django settings for elgassia project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
i... | Python | 0.000001 |
08fddbdc0ac70a549bac82131771218107186def | add discription | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
{
'name': "Account Discount",
'summary': """
Use Tax model for discounts as well""",
'description': """
Odoo OpenERP Account Discount from Tax
This module adds new concept to use tax model as discount model and print both taxes and discounts separetly.... | # -*- coding: utf-8 -*-
{
'name': "Account Discount",
'summary': """
Apply Discount model to taxes""",
'description': """
The purpose is to apply discount record for the same tax model
""",
'author': "Khaled Hamed",
'website': "http://www.grandtk.com",
# Categories can be... | Python | 0.000952 |
6d83f2150f7c6177385b9f2d8abbe48cd2979130 | Add staleness to MonthCache Admin display | events/admin.py | events/admin.py | from django.contrib import admin
from .models import Calendar,MonthCache
# Register your models here.
@admin.register(Calendar)
class CalendarAdmin(admin.ModelAdmin):
list_display = ('name','remote_id','css_class')
@admin.register(MonthCache)
class MonthCacheAdmin(admin.ModelAdmin):
list_display = ('calend... | from django.contrib import admin
from .models import Calendar,MonthCache
# Register your models here.
@admin.register(Calendar)
class CalendarAdmin(admin.ModelAdmin):
list_display = ('name','remote_id','css_class')
@admin.register(MonthCache)
class MonthCacheAdmin(admin.ModelAdmin):
list_display = ('calend... | Python | 0 |
d308bbd0200e1b4783bf63cafda03650579b9351 | change help text | ynr/apps/official_documents/models.py | ynr/apps/official_documents/models.py | import os
from django.db import models
from django.urls import reverse
from django_extensions.db.models import TimeStampedModel
DOCUMENT_UPLOADERS_GROUP_NAME = "Document Uploaders"
def document_file_name(instance, filename):
return os.path.join(
"official_documents", str(instance.ballot.ballot_paper_id)... | import os
from django.db import models
from django.urls import reverse
from django_extensions.db.models import TimeStampedModel
DOCUMENT_UPLOADERS_GROUP_NAME = "Document Uploaders"
def document_file_name(instance, filename):
return os.path.join(
"official_documents", str(instance.ballot.ballot_paper_id)... | Python | 0.000029 |
cedae39716587fcc0459a05e74acc43b190d7457 | split download | example-era5.py | example-era5.py | #!/usr/bin/env python
# (C) Copyright 2018 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status... | #!/usr/bin/env python
# (C) Copyright 2018 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status... | Python | 0.000005 |
cdf7dfc01cca8472c517d2a93d89e97e1f838103 | Add metanode to degree_df functionality | hetio/stats.py | hetio/stats.py | import pandas
import matplotlib
import matplotlib.backends.backend_pdf
import seaborn
def get_degrees_for_metanode(graph, metanode):
"""
Return a dataframe that reports the degree of each metaedge for
each node of kind metanode.
"""
metanode_to_nodes = graph.get_metanode_to_nodes()
nodes = meta... | import pandas
import matplotlib
import matplotlib.backends.backend_pdf
import seaborn
def get_degrees_for_metanode(graph, metanode):
"""
Return a dataframe that reports the degree of each metaedge for
each node of kind metanode.
"""
metanode_to_nodes = graph.get_metanode_to_nodes()
nodes = meta... | Python | 0 |
3846907435da720c075ab89579b970da5019b49f | Add Tapastic/AmpleTime | dosagelib/plugins/tapastic.py | dosagelib/plugins/tapastic.py | # SPDX-License-Identifier: MIT
# Copyright (C) 2019-2020 Tobias Gruetzmacher
# Copyright (C) 2019-2020 Daniel Ring
import json
import re
from ..scraper import _ParserScraper
from ..helpers import indirectStarter
class Tapastic(_ParserScraper):
baseUrl = 'https://tapas.io/'
imageSearch = '//article[contains(@... | # SPDX-License-Identifier: MIT
# Copyright (C) 2019-2020 Tobias Gruetzmacher
# Copyright (C) 2019-2020 Daniel Ring
import json
import re
from ..scraper import _ParserScraper
from ..helpers import indirectStarter
class Tapastic(_ParserScraper):
baseUrl = 'https://tapas.io/'
imageSearch = '//article[contains(@... | Python | 0.000001 |
62314491b148c51e7c27e13aded283a0622c47f4 | improve h5py config check | hpat/config.py | hpat/config.py | try:
from .io import _hdf5
import h5py
# TODO: make sure h5py/hdf5 supports parallel
except ImportError:
_has_h5py = False
else:
_has_h5py = True
try:
import pyarrow
except ImportError:
_has_pyarrow = False
else:
_has_pyarrow = True
try:
from . import ros_cpp
except ImportError:
... | try:
from .io import _hdf5
except ImportError:
_has_h5py = False
else:
_has_h5py = True
try:
import pyarrow
except ImportError:
_has_pyarrow = False
else:
_has_pyarrow = True
try:
from . import ros_cpp
except ImportError:
_has_ros = False
else:
_has_ros = True
try:
from . impo... | Python | 0 |
75729e3e06c560892f0bf285fdd8a15f9f58b7d5 | Delete local file with no signature, without trying reget | lib/oelite/fetch/url.py | lib/oelite/fetch/url.py | import oelite.fetch
import bb.utils
import os
import urlgrabber
import hashlib
class UrlFetcher():
SUPPORTED_SCHEMES = ("http", "https", "ftp")
def __init__(self, uri, d):
if not uri.scheme in self.SUPPORTED_SCHEMES:
raise Exception(
"Scheme %s not supported by oelite.fetc... | import oelite.fetch
import bb.utils
import os
import urlgrabber
import hashlib
class UrlFetcher():
SUPPORTED_SCHEMES = ("http", "https", "ftp")
def __init__(self, uri, d):
if not uri.scheme in self.SUPPORTED_SCHEMES:
raise Exception(
"Scheme %s not supported by oelite.fetc... | Python | 0 |
ae7a5bef1e3ee0216651dc4aeef3abcbab3cf76e | update code | Strings/alternating-characters.py | Strings/alternating-characters.py | # Alternating Characters
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/alternating-characters/problem
# Time complexity: O(n)
def alternatingCharacters(s):
sumChars = 0
for i in range(len(s)):
if i == 0 or tempChar != s[i]:
tempChar = s[i]
continue
... | # Alternating Characters
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/alternating-characters/problem
def alternatingCharacters(s):
sumChars = 0
for i in range(len(s)):
if i == 0 or tempChar != s[i]:
tempChar = s[i]
continue
if tempChar == s[... | Python | 0 |
44fbc835354b7612d5d203250255a323c8759b64 | fix log %(levelname)-8s to align | torequests/logs.py | torequests/logs.py | #! coding:utf-8
import logging
dummy_logger = logging.getLogger('torequests.dummy')
main_logger = logging.getLogger('torequests.main')
def init_logger(name='', handler_path_levels=None,
level=logging.INFO, formatter=None,
formatter_str=None, datefmt="%Y-%m-%d %H:%M:%S"):
"""Args:
... | #! coding:utf-8
import logging
dummy_logger = logging.getLogger('torequests.dummy')
main_logger = logging.getLogger('torequests.main')
def init_logger(name='', handler_path_levels=None,
level=logging.INFO, formatter=None,
formatter_str=None, datefmt="%Y-%m-%d %H:%M:%S"):
"""Args:
... | Python | 0.000001 |
db47a651e380709c33c54c86f9a3861187772406 | Add metrics to MNIST | eva/examples/mnist.py | eva/examples/mnist.py | #%% Setup.
from collections import namedtuple
import numpy as np
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import Nadam
from keras.layers.adva... | #%% Setup.
from collections import namedtuple
import numpy as np
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import Nadam
from keras.layers.adva... | Python | 0.000019 |
7dc20e510a1e8b93d470c8d26c530a0ce7affefb | format indent. (#3) | flasklogin.py | flasklogin.py | from flask import Flask , request , abort , redirect , Response ,url_for
from flask.ext.login import LoginManager , login_required , UserMixin , login_user
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_key'
login_manager = LoginManager()
login_manager.login_view = "login"
login_manager.init_app(app)
class ... | from flask import Flask , request , abort , redirect , Response ,url_for
from flask.ext.login import LoginManager , login_required , UserMixin , login_user
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_key'
login_manager = LoginManager()
login_manager.login_view = "login"
login_manager.init_app(app)
class ... | Python | 0.000001 |
df12bb251bbb6ab1b7efc1e955eb87faa73c6c15 | Add message for correct orfik answer | events/orfik/views.py | events/orfik/views.py | from django.shortcuts import render, redirect, get_object_or_404
from events.orfik import models
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from general import models as generalmodels
from django.contrib import messages
de... | from django.shortcuts import render, redirect, get_object_or_404
from events.orfik import models
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from general import models as generalmodels
from django.contrib import messages
de... | Python | 0.000093 |
f6672fd0074052ba71bc1266590f0ef0db8f14d0 | fix import. | blackgate/cli.py | blackgate/cli.py | # -*- coding: utf-8 -*-
import click
from blackgate.core import component
from blackgate.server import run
@click.group()
def main():
# README CONFIG
component.install_from_config(config)
@main.command()
def start():
run(config.get('port', 9654))
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
import click
from blackgate.core import component
from blackgate.server importrun
@click.group()
def main():
# README CONFIG
component.install_from_config(config)
@main.command()
def start():
run(config.get('port', 9654))
if __name__ == '__main__':
main()
| Python | 0 |
1c9a16a0896cd39aca2b44c0ef5c4eb155d1dab7 | Add a test for 2 framgnets case. | server/kcaa/manipulator_util_test.py | server/kcaa/manipulator_util_test.py | #!/usr/bin/env python
import pytest
import manipulator_util
class TestManipulatorManager(object):
def pytest_funcarg__manager(self, request):
return manipulator_util.ManipulatorManager(None, {}, 0)
def test_in_schedule_fragment(self):
in_schedule_fragment = (
manipulator_util.M... | #!/usr/bin/env python
import pytest
import manipulator_util
class TestManipulatorManager(object):
def pytest_funcarg__manager(self, request):
return manipulator_util.ManipulatorManager(None, {}, 0)
def test_in_schedule_fragment(self):
in_schedule_fragment = (
manipulator_util.M... | Python | 0.000001 |
3bd383a15902d8367097a4348de64c929732767b | Fix Test | tests/NewsParser_Test.py | tests/NewsParser_Test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: balicanta
# @Date: 2014-10-25 09:57:26
# @Last Modified by: balicanta
# @Last Modified time: 2014-10-27 23:44:57
from NewsParser import NewsParser
from requests.utils import get_encodings_from_content
test_fixtures = [
{"url": "http://udn.com/NEWS/NATIO... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: balicanta
# @Date: 2014-10-25 09:57:26
# @Last Modified by: bustta
# @Last Modified time: 2014-10-27 23:22:08
from NewsParser import NewsParser
from requests.utils import get_encodings_from_content
test_fixtures = [
{"url": "http://udn.com/NEWS/NATIONAL... | Python | 0.000001 |
97478d2bb38b94a5effbbc74db3ae1a0360f9a19 | remove vm.id usage in exeption message | vmpool/endpoint.py | vmpool/endpoint.py | # coding: utf-8
from core.utils import generator_wait_for
from core.logger import log_pool
from core.config import config
from core.exceptions import PlatformException, NoSuchEndpoint, \
CreationException
from vmpool.virtual_machines_pool import pool
from vmpool.platforms import Platforms
from vmpool.vmqueue impo... | # coding: utf-8
from core.utils import generator_wait_for
from core.logger import log_pool
from core.config import config
from core.exceptions import PlatformException, NoSuchEndpoint, \
CreationException
from vmpool.virtual_machines_pool import pool
from vmpool.platforms import Platforms
from vmpool.vmqueue impo... | Python | 0 |
01bb6723b2bc7ab7a7fb6629e304f5ed42f40af4 | Add GSM characters test case for a unicode message. | tests/clockwork_tests.py | tests/clockwork_tests.py | # -*- coding: utf-8 -*-
import unittest
import clockwork
import clockwork_exceptions
class ApiTests(unittest.TestCase):
api_key = "YOUR_API_KEY_HERE"
def test_should_send_single_message(self):
"""Sending a single SMS with the minimum detail and no errors should work"""
api = clockwork.API(self.api_key)
sms ... | import unittest
import clockwork
import clockwork_exceptions
class ApiTests(unittest.TestCase):
api_key = "YOUR_API_KEY_HERE"
def test_should_send_single_message(self):
"""Sending a single SMS with the minimum detail and no errors should work"""
api = clockwork.API(self.api_key)
sms = clockwork.SMS(to="44123... | Python | 0 |
4548b24c17caf6149b741c7f8a8f743f4ff431b4 | Remove partitions | 2011/candy_splitting.py | 2011/candy_splitting.py | #!/usr/bin/env python
from __future__ import print_function
from functools import reduce
def split_candies(candies):
assert isinstance(candies, list)
xor = reduce(lambda x, y: x ^ y, candies)
if xor == 0:
return sum(candies) - min(candies)
else:
return 0
if __name__ == '__main__':
... | #!/usr/bin/env python
from __future__ import print_function
from functools import reduce
def split_candies(candies):
assert isinstance(candies, list)
partitions = sorted_k_partitions(candies, 2)
print(partitions)
max_candy = 0
for partition in partitions:
xor0 = reduce(lambda x, y: x ^ y... | Python | 0.000011 |
08125322609e97e868c5c712df9e35e4c556434d | Use enumerate() instead of managing an index variable. | httparchive.py | httparchive.py | #!/usr/bin/env python
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | #!/usr/bin/env python
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | Python | 0.999997 |
d5482b10a712863c36a59d8ce82f3958ec41e78b | Add CORS on /swagger.json | APITaxi/api/__init__.py | APITaxi/api/__init__.py | # -*- coding: utf-8 -*-
from flask.ext.restplus import apidoc, Api
from flask import Blueprint, render_template
from flask_cors import cross_origin
api_blueprint = Blueprint('api', __name__)
api = Api(api_blueprint, doc=False, catch_all_404s=True,
title='API version 2.0')
ns_administrative = api.namespace('ad... | # -*- coding: utf-8 -*-
from flask.ext.restplus import apidoc, Api
from flask import Blueprint, render_template
api_blueprint = Blueprint('api', __name__)
api = Api(api_blueprint, doc=False, catch_all_404s=True,
title='API version 2.0')
ns_administrative = api.namespace('administrative',
description="... | Python | 0.000001 |
d16b57f3edca478622b84f56dfee7b2eea1f7498 | Add basic reporting | botbot/report.py | botbot/report.py | """Generate a report about file errors"""
import os
import sys
import math
from pkg_resources import resource_exists, resource_filename
from jinja2 import Environment, FileSystemLoader
from . import problems
_DEFAULT_RES_PATH = os.path.join('resources', 'templates')
_GENERIC_REPORT_NAME = 'generic.txt'
_ENV_REPORT_... | """Generate a report about file errors"""
import os
import sys
import math
from pkg_resources import resource_exists, resource_filename
from jinja2 import Environment, FileSystemLoader
from . import problems
_DEFAULT_RES_PATH = os.path.join('resources', 'templates')
_GENERIC_REPORT_NAME = 'generic.txt'
_ENV_REPORT_... | Python | 0 |
6e525872537cd31a80cb791d6594a1f6800c61b4 | add invers option, add args-parsing | i2c/PCF8574.py | i2c/PCF8574.py | #!/usr/bin/python
import sys
import smbus
import time
import argparse
# Reads data from PCF8574 and prints the state of each port
def readPCF8574(busnumber,address):
address = int(address,16)
busnumber = int(busnumber)
bus = smbus.SMBus(busnumber)
state = bus.read_byte(address);
for i in range(0,8)... | #!/usr/bin/python
import sys
import smbus
import time
# Reads data from PCF8574 and prints the state of each port
def readPCF8574(busnumber,address):
address = int(address,16)
busnumber = int(1)
bus = smbus.SMBus(busnumber)
state = bus.read_byte(address);
for i in range(0,8):
port = "port... | Python | 0.000002 |
7cca2fab9fe697fe0e31be0ea6dcd43e29028bfb | better example output | example/shapes.py | example/shapes.py | import pprint
from rdc.etl.transform.util import Log
from rdc.etl.transform.extract import Extract
from rdc.etl.harness.threaded2 import ThreadedHarness as ThreadedHarness2
from rdc.etl.harness.threaded import ThreadedHarness
def build_producer(name):
return Extract(({'producer': name, 'id': 1}, {'producer': name,... | from rdc.etl.status.console import ConsoleStatus
from rdc.etl.transform.util import Log
from rdc.etl.transform.extract import Extract
from rdc.etl.harness.threaded2 import ThreadedHarness as ThreadedHarness2
from rdc.etl.harness.threaded import ThreadedHarness
def build_producer(name):
return Extract(({'producer':... | Python | 0.999999 |
229a0db6574f75acf94cad6612dd39351fa6656a | Use absolute import. (Should this go into 2.5?) | Lib/test/test_cpickle.py | Lib/test/test_cpickle.py | import cPickle
import unittest
from cStringIO import StringIO
from test.pickletester import AbstractPickleTests, AbstractPickleModuleTests
from test import test_support
class cPickleTests(AbstractPickleTests, AbstractPickleModuleTests):
def setUp(self):
self.dumps = cPickle.dumps
self.loads = cPic... | import cPickle
import unittest
from cStringIO import StringIO
from pickletester import AbstractPickleTests, AbstractPickleModuleTests
from test import test_support
class cPickleTests(AbstractPickleTests, AbstractPickleModuleTests):
def setUp(self):
self.dumps = cPickle.dumps
self.loads = cPickle.l... | Python | 0 |
c888e52788ec37641f97f761d2052902db20582a | Add missing dates | erpnext/accounts/dashboard.py | erpnext/accounts/dashboard.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
from itertools import groupby
from operator import itemgetter
import frappe
from frappe.utils import add_to_date, date_diff, getdate, nowdate
from erpne... | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
from itertools import groupby
from operator import itemgetter
import frappe
from frappe.utils import add_to_date
from erpnext.accounts.report.general_le... | Python | 0.000043 |
dca8dce24e0bea671b52d456909c35e43c4f5929 | move exchange endpoint into consumer urlspace | example/urls.py | example/urls.py | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from django.contrib import admin
from .views import ConsumerView, ConsumerExchangeView
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', TemplateView.as_view(template_name='example/home.html'), name=... | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from django.contrib import admin
from .views import ConsumerView, ConsumerExchangeView
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', TemplateView.as_view(template_name='example/home.html'), name='ho... | Python | 0.000002 |
dcc472a6c8e15e7fc105277332681b38e40640df | Revert open_file_dialog example | examples/open_file_dialog.py | examples/open_file_dialog.py | import webview
import threading
"""
This example demonstrates creating an open file dialog.
"""
def open_file_dialog():
import time
time.sleep(5)
print(webview.create_file_dialog(webview.OPEN_DIALOG, allow_multiple=True))
if __name__ == '__main__':
t = threading.Thread(target=open_file_dialog)
t... | import webview
import threading
"""
This example demonstrates creating an open file dialog.
"""
def open_file_dialog():
import time
time.sleep(5)
print(webview.create_file_dialog(webview.OPEN_DIALOG, allow_multiple=False))
if __name__ == '__main__':
t = threading.Thread(target=open_file_dialog)
... | Python | 0 |
ef0e9f59ee1df18a5c37a559e78d0350d9e0a624 | Use `import_by_path`/`import_string` instead of manually `__import__`ing things | enumfields/fields.py | enumfields/fields.py | from django.core.exceptions import ValidationError
from django.db import models
from enum import Enum
import six
from django.db.models.fields import NOT_PROVIDED
try:
from django.utils.module_loading import import_string
except ImportError:
from django.utils.module_loading import import_by_path as import_strin... | from django.core.exceptions import ValidationError
from django.db import models
from enum import Enum
import six
from django.db.models.fields import NOT_PROVIDED
class EnumFieldMixin(six.with_metaclass(models.SubfieldBase)):
def __init__(self, enum, **options):
if isinstance(enum, six.string_types):
... | Python | 0.000003 |
965236870ce5bf6dcbe9398b444b977c796b096e | set the right keyword to the close function | simphony_paraview/tests/test_show.py | simphony_paraview/tests/test_show.py | import unittest
from hypothesis import given
from paraview import servermanager
from paraview.simple import Disconnect
from simphony_paraview.show import show
from simphony_paraview.core.testing import cuds_containers
class TestShow(unittest.TestCase):
def setUp(self):
if servermanager.ActiveConnection... | import unittest
from hypothesis import given
from paraview import servermanager
from paraview.simple import Disconnect
from simphony_paraview.show import show
from simphony_paraview.core.testing import cuds_containers
class TestShow(unittest.TestCase):
def setUp(self):
if servermanager.ActiveConnection... | Python | 0.000021 |
c0358584f2b5a05947ebb558c6d10293cc969a1a | Fix tests | tests/test_dependenpy.py | tests/test_dependenpy.py | # -*- coding: utf-8 -*-
"""Main test script."""
from dependenpy.cli import main
def test_main():
"""Main test method."""
main(['-lm', 'dependenpy'])
| # -*- coding: utf-8 -*-
"""Main test script."""
from dependenpy.cli import main
def test_main():
"""Main test method."""
main('dependenpy')
| Python | 0.000003 |
f6debd39f929616ca72763682c25a52bc01b536b | Update test_filterbank.py | tests/test_filterbank.py | tests/test_filterbank.py | from blimpy import Filterbank, read_header, fix_header
import pylab as plt
import numpy as np
import os
from pprint import pprint
def test_voyager():
filename = '/workdata/bl/data/voyager_f1032192_t300_v2.fil'
fb = Filterbank(filename)
fb.info()
fb.plot_spectrum()
plt.show()
fb = Filterbank(f... | from blimpy import Filterbank, read_header, fix_header
import pylab as plt
import numpy as np
import os
from pprint import pprint
def test_voyager():
filename = '/workdata/bl/data/voyager_f1032192_t300_v2.fil'
fb = Filterbank(filename)
fb.info()
fb.plot_spectrum()
plt.show()
fb = Filterbank(f... | Python | 0.000001 |
dbf520bb4050c5e393a4de3be9c136fef1cd88f2 | break test | tests/test_functional.py | tests/test_functional.py | # -*- coding: utf-8 -*-
"""Functional tests using WebTest.
See: http://webtest.readthedocs.org/
"""
import pytest
from flask import url_for
from foobar.user.models import User
from .factories import UserFactory
class TestLoggingIn:
def test_can_log_in_returns_200(self, user, testapp):
# Goes to homepa... | # -*- coding: utf-8 -*-
"""Functional tests using WebTest.
See: http://webtest.readthedocs.org/
"""
import pytest
from flask import url_for
from foobar.user.models import User
from .factories import UserFactory
class TestLoggingIn:
def test_can_log_in_returns_200(self, user, testapp):
# Goes to homepa... | Python | 0.000005 |
a6435a8713985464b8c37a438ac035d65f66b4cd | Add more user mapfiles and validate | tests/test_large_file.py | tests/test_large_file.py | import logging
import os
import cProfile
import glob
import json
import mappyfile
from mappyfile.parser import Parser
from mappyfile.pprint import PrettyPrinter
from mappyfile.transformer import MapfileToDict
from mappyfile.validator import Validator
def output(fn):
"""
Parse, transform, and pretty print
... | import logging
import cProfile
from mappyfile.parser import Parser
from mappyfile.pprint import PrettyPrinter
from mappyfile.transformer import MapfileToDict
def output(fn):
"""
Parse, transform, and pretty print
the result
"""
p = Parser()
m = MapfileToDict()
ast = p.parse_file(fn)
... | Python | 0 |
2a816cbb29488861fe8897a6af9359db254018c1 | Fix up test_paraboloid accuracy | tests/test_paraboloid.py | tests/test_paraboloid.py | import jtrace
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def test_properties():
import random
for i in range(100):
A = random.gauss(0.7, 0.8)
B = random.gauss(0.8, 1.2)
para = jtrace.Paraboloid(A, B)
asser... | import jtrace
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def test_properties():
import random
for i in range(100):
A = random.gauss(0.7, 0.8)
B = random.gauss(0.8, 1.2)
para = jtrace.Paraboloid(A, B)
asser... | Python | 0.999279 |
5e642c912ff7be5424e78e3dfe356c9579a39320 | fix typo in get_networks function | web_frontend/cloudscheduler/csv2/utils.py | web_frontend/cloudscheduler/csv2/utils.py | from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
import config
'''
dev code
= db_session.query(Cloud).filter(Cloud.cloud_type=="openstack")
db_session.merge(new_flav)
db_session.commit()
'''
def get_quotas(filter=None):
engine = create_engi... | from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
import config
'''
dev code
= db_session.query(Cloud).filter(Cloud.cloud_type=="openstack")
db_session.merge(new_flav)
db_session.commit()
'''
def get_quotas(filter=None):
engine = create_engi... | Python | 0.000948 |
ddf311b4dc7c08f3f08516c702531053f8919720 | Tidy imports | tests/test_validation.py | tests/test_validation.py | import json
from django.test import TestCase
from django_slack.exceptions import ChannelNotFound, MsgTooLong
from django_slack.backends import Backend
class TestOverride(TestCase):
def test_ok_result(self):
backend = Backend()
backend.validate('application/json', json.dumps({'ok': True}), {})
... | import json
from django.conf import settings
from django.test import TestCase, override_settings
from django_slack.exceptions import ChannelNotFound, MsgTooLong
from django_slack.backends import Backend
class TestOverride(TestCase):
def test_ok_result(self):
backend = Backend()
backend.validate('... | Python | 0 |
1ee39cd3174b487038b62a3a6a66bac46571775a | Test that symlinks are properly created in bin_dir | tests/test_virtualenv.py | tests/test_virtualenv.py | import virtualenv
import optparse
import os
import shutil
import sys
import tempfile
from mock import patch, Mock
def test_version():
"""Should have a version string"""
assert virtualenv.virtualenv_version, "Should have version"
@patch('os.path.exists')
def test_resolve_interpreter_with_absolute_path(mock_e... | import virtualenv
import optparse
from mock import patch, Mock
def test_version():
"""Should have a version string"""
assert virtualenv.virtualenv_version, "Should have version"
@patch('os.path.exists')
def test_resolve_interpreter_with_absolute_path(mock_exists):
"""Should return absolute path if given... | Python | 0.000001 |
50b6c9a9e55a22dc1893fcaf6f8800015992d41d | Make import more specific | iatidq/util.py | iatidq/util.py |
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3... |
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3... | Python | 0 |
a8389e913b417dc37e23f9cfc1f52ab63802c8a4 | movie title encode to support multiple language | demo/indexMlTmdb.py | demo/indexMlTmdb.py | import json
def enrich(movie):
""" Enrich for search purposes """
if 'title' in movie:
movie['title_sent'] = 'SENTINEL_BEGIN ' + movie['title']
def reindex(es, analysisSettings={}, mappingSettings={}, movieDict={}, index='tmdb'):
import elasticsearch.helpers
settings = {
"settings": {
... | import json
def enrich(movie):
""" Enrich for search purposes """
if 'title' in movie:
movie['title_sent'] = 'SENTINEL_BEGIN ' + movie['title']
def reindex(es, analysisSettings={}, mappingSettings={}, movieDict={}, index='tmdb'):
import elasticsearch.helpers
settings = {
"settings": {
... | Python | 0.999999 |
e4c92b7d8cdd808b2415c2edf11576a87264f7f3 | Remove context_stack_on_request_context() | frasco/ctx.py | frasco/ctx.py | from flask import has_request_context, _request_ctx_stack
from frasco.utils import unknown_value
from werkzeug.local import LocalProxy, LocalStack
from contextlib import contextmanager
import functools
class ContextStack(LocalStack):
def __init__(self, top=None, default_item=None, allow_nested=True, ignore_nested... | from flask import has_request_context, _request_ctx_stack
from frasco.utils import unknown_value
from werkzeug.local import LocalProxy, LocalStack
from contextlib import contextmanager
import functools
class ContextStack(LocalStack):
def __init__(self, top=None, default_item=None, allow_nested=True, ignore_nested... | Python | 0.000001 |
1c116355e91ebed668620f8f84d9d4331de4adab | include first 3 sentences only | cogs/wiki.py | cogs/wiki.py | import discord
from discord.ext import commands
from bs4 import BeautifulSoup
from urllib.parse import quote_plus
from dateutil.parser import isoparse
from utils import aiohttp_wrap as aw
class Wiki(commands.Cog):
SUMMARY_URI = "https://en.wikipedia.org/api/rest_v1/page/summary/{}?redirect=true"
SEARCH_URI ... | import discord
from discord.ext import commands
from bs4 import BeautifulSoup
from urllib.parse import quote_plus
from dateutil.parser import isoparse
from utils import aiohttp_wrap as aw
class Wiki(commands.Cog):
SUMMARY_URI = "https://en.wikipedia.org/api/rest_v1/page/summary/{}?redirect=true"
SEARCH_URI ... | Python | 0.000072 |
4f8429e9cd17f207ef429bdf21508cfac4200c4c | improve display | examples/admin.py | examples/admin.py | # -*- coding: utf-8 -*-
#
# django-granadilla
# Copyright (C) 2009 Bolloré telecom
# See AUTHORS file for a full list of contributors.
#
# 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 ... | # -*- coding: utf-8 -*-
#
# django-granadilla
# Copyright (C) 2009 Bolloré telecom
# See AUTHORS file for a full list of contributors.
#
# 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 ... | Python | 0.000001 |
47f8458553d42adbc9aa2c78bfdf002ed26d582a | update tests to support latest google-cloud-core (#23) | tests/unit/test__http.py | tests/unit/test__http.py | # Copyright 2015 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | # Copyright 2015 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | Python | 0 |
cbc8632a74f32415b2819b678340b6e4f0944dba | Use build_context factory | tests/unit/tools/list.py | tests/unit/tools/list.py | # encoding: UTF-8
import unittest
from tml.tools.list import List
from tml.tools.template import Template
from tests.mock import Client
from tml import build_context
class ListTest(unittest.TestCase):
def setUp(self):
self.context = build_context(client = Client.read_all(), locale = 'ru')
def test_... | # encoding: UTF-8
import unittest
from tml.tools.list import List
from tml.tools.template import Template
from tests.mock import Client
from tml import Context
class list(unittest.TestCase):
def setUp(self):
self.context = Context(client = Client.read_all(), locale = 'ru')
def test_render(self):
... | Python | 0.000001 |
dbce79102efa8fee233af95939f1ff0b9d060b00 | Update example workflow to show you can use classes | examples/basic.py | examples/basic.py | import time
from simpleflow import (
activity,
Workflow,
futures,
)
@activity.with_attributes(task_list='quickstart', version='example')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart', version='example')
def double(x):
return x * 2
# A simpleflow activity can b... | import time
from simpleflow import (
activity,
Workflow,
futures,
)
@activity.with_attributes(task_list='quickstart', version='example')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart', version='example')
def double(x):
return x * 2
@activity.with_attributes(ta... | Python | 0 |
9308152c67bc2ad2150a76e7897c8fd2568bf590 | Bump version: 0.0.4 -> 0.0.5 | conanfile.py | conanfile.py | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.5"
class IWYUCTargetCmakeConan(ConanFile):
name = "iwyu-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake... | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.4"
class IWYUCTargetCmakeConan(ConanFile):
name = "iwyu-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake... | Python | 0 |
487752f542880aa62d472734d88e00f29c9c5cae | make data a complete stub file | fabfile/data.py | fabfile/data.py | #!/usr/bin/env python
"""
Commands that update or process the application data.
"""
from fabric.api import task
@task(default=True)
def update():
"""
Stub function for updating app-specific data.
"""
pass
| #!/usr/bin/env python
"""
Commands that update or process the application data.
"""
from datetime import datetime
import json
from fabric.api import task
from facebook import GraphAPI
from twitter import Twitter, OAuth
import app_config
import copytext
@task(default=True)
def update():
"""
Stub function for... | Python | 0.000003 |
09ab8f6290e3c5bf33e01857d11b124444a4c990 | add sendaddr support to isotp | examples/isotp.py | examples/isotp.py | DEBUG = False
def msg(x):
if DEBUG:
print "S:",x.encode("hex")
if len(x) <= 7:
ret = chr(len(x)) + x
else:
assert False
return ret.ljust(8, "\x00")
def isotp_send(panda, x, addr, bus=0):
if len(x) <= 7:
panda.can_send(addr, msg(x), bus)
else:
ss = chr(0x10 + (len(x)>>8)) + chr(len(x)&0... | DEBUG = False
def msg(x):
if DEBUG:
print "S:",x.encode("hex")
if len(x) <= 7:
ret = chr(len(x)) + x
else:
assert False
return ret.ljust(8, "\x00")
def isotp_send(panda, x, addr, bus=0):
if len(x) <= 7:
panda.can_send(addr, msg(x), bus)
else:
ss = chr(0x10 + (len(x)>>8)) + chr(len(x)&0... | Python | 0 |
ba1186c47e5f3466faeea9f2d5bf96948d5f7183 | Add --strict flag to raise exception on undefined variables | confuzzle.py | confuzzle.py | import sys
import argparse
import yaml
import jinja2
def render(template_string, context_dict, strict=False):
template = jinja2.Template(template_string)
if strict:
template.environment.undefined = jinja2.StrictUndefined
return template.render(**context_dict)
def main():
parser = argparse.A... | import sys
import argparse
import yaml
from jinja2 import Template
def render(template_string, context_dict):
template = Template(template_string)
return template.render(**context_dict)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('template', nargs='?', type=argparse.FileType(... | Python | 0 |
bfd1e90365446fe1a7c1e5ae710dbf497cc405fb | Fix test with newline problems in Windows | utest/writer/test_filewriters.py | utest/writer/test_filewriters.py | from __future__ import with_statement
import unittest
from StringIO import StringIO
from robot.parsing import TestCaseFile
from robot.parsing.model import TestCaseTable
from robot.utils.asserts import assert_equals
from robot.utils import ET, ETSource
def create_test_case_file():
data = TestCaseFile(source='foo.... | from __future__ import with_statement
import unittest
from StringIO import StringIO
from robot.parsing import TestCaseFile
from robot.parsing.model import TestCaseTable
from robot.utils.asserts import assert_equals
from robot.utils import ET, ETSource
def create_test_case_file():
data = TestCaseFile(source='foo.... | Python | 0.000001 |
b336e83a63722b3a3e4d3f1779686149d5cef8d1 | Add compatibility for Python 2 | setuptools/tests/test_setopt.py | setuptools/tests/test_setopt.py | # coding: utf-8
from __future__ import unicode_literals
import io
import six
from setuptools.command import setopt
from setuptools.extern.six.moves import configparser
class TestEdit:
@staticmethod
def parse_config(filename):
parser = configparser.ConfigParser()
with io.open(filename, enco... | # coding: utf-8
from __future__ import unicode_literals
import io
import six
from setuptools.command import setopt
from setuptools.extern.six.moves import configparser
class TestEdit:
@staticmethod
def parse_config(filename):
parser = configparser.ConfigParser()
with io.open(filename, enco... | Python | 0.00002 |
70ccca895892fc81eb07c4d0b4b7cefe17554b77 | Fix typo | src/checker/plugin/links_finder_plugin.py | src/checker/plugin/links_finder_plugin.py | from bs4 import BeautifulSoup
from yapsy.IPlugin import IPlugin
from requests.exceptions import InvalidSchema
from requests.exceptions import ConnectionError
from requests.exceptions import MissingSchema
import requests
import urlparse
import urllib
import marisa_trie
class LinksFinder(IPlugin):
def __init__(self... | from bs4 import BeautifulSoup
from yapsy.IPlugin import IPlugin
from requests.exceptions import InvalidSchema
from requests.exceptions import ConnectionError
from requests.exceptions import MissingSchema
import requests
import urlparse
import urllib
import marisa_trie
class LinksFinder(IPlugin):
def __init__(self... | Python | 0.999999 |
71f67f02dd26e29002ced50298b245c6114ece3b | Update mathfunctions.py | Python/Math/mathfunctions.py | Python/Math/mathfunctions.py | # File with the functions which will be used in math script
# Number to the power of
def po (number, pof):
b = number
for _ in range(pof - 1):
b = int(b) * int(number)
return b
# Factors of a number
def factors (number):
current, ao, nums = 0, 0, []
while current < number:
ao = ao... | # File with the functions which will be used in math script
# Number to the power of
def po (number, pof):
b = number
for _ in range(pof - 1):
b = int(b) * int(number)
return b
# Factors of a number
def factors (number):
current, ao, nums = 0, 0, []
while current < number:
ao = ao... | Python | 0.000003 |
1d3eb0bafd46f3e9cfb7d6395ad1a100052ff821 | Clean up parameter types (#52527) | lib/ansible/plugins/doc_fragments/online.py | lib/ansible/plugins/doc_fragments/online.py | # -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# Standard documentation fragment
DOCUMENTATION = r'''
options:
api_token:
description:
- Online OAuth token.
type: str
aliases: [ oauth_t... | # -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# Standard documentation fragment
DOCUMENTATION = '''
options:
api_token:
description:
- Online OAuth token.
aliases: ['oauth_token']
api_url... | Python | 0 |
eb3f93ac64953eacecdd48e2cb8d5ca80554a95b | Update search-for-a-range.py | Python/search-for-a-range.py | Python/search-for-a-range.py | # Time: O(logn)
# Space: O(1)
#
# Given a sorted array of integers, find the starting and ending position of a given target value.
#
# Your algorithm's runtime complexity must be in the order of O(log n).
#
# If the target is not found in the array, return [-1, -1].
#
# For example,
# Given [5, 7, 7, 8, 8, 10] and ... | # Time: O(logn)
# Space: O(1)
#
# Given a sorted array of integers, find the starting and ending position of a given target value.
#
# Your algorithm's runtime complexity must be in the order of O(log n).
#
# If the target is not found in the array, return [-1, -1].
#
# For example,
# Given [5, 7, 7, 8, 8, 10] and ... | Python | 0 |
8831fb698e6ce4c263b1b3f02eba09744b46d64b | Remove unused variable (via yapf) | basis_set_exchange/curate/readers/cfour.py | basis_set_exchange/curate/readers/cfour.py | from ... import lut
from ..skel import create_skel
def read_cfour(basis_lines, fname):
'''Reads gbasis-formatted file data and converts it to a dictionary with the
usual BSE fields
Note that the gbasis format does not store all the fields we
have, so some fields are left blank
'''
s... | from ... import lut
from ..skel import create_skel
def read_cfour(basis_lines, fname):
'''Reads gbasis-formatted file data and converts it to a dictionary with the
usual BSE fields
Note that the gbasis format does not store all the fields we
have, so some fields are left blank
'''
s... | Python | 0 |
946b3867f464d96e85056b60d94593346a39cc51 | add map to tweet list | index.py | index.py | import os
import time
import TwitterAPI
import src.art.fluid
import src.art.gas
import src.art.map
# Configuration
twitterAPI = TwitterAPI.TwitterAPI(
consumer_key=os.environ["CONSUMER_KEY"],
consumer_secret=os.environ["CONSUMER_SECRET"],
access_token_key=os.environ["ACCESS_TOKEN_KEY"],
access_token_se... | import os
import time
import TwitterAPI
import src.art.fluid
import src.art.gas
# Configuration
twitterAPI = TwitterAPI.TwitterAPI(
consumer_key=os.environ["CONSUMER_KEY"],
consumer_secret=os.environ["CONSUMER_SECRET"],
access_token_key=os.environ["ACCESS_TOKEN_KEY"],
access_token_secret=os.environ["AC... | Python | 0.000002 |
34adb8bb30860eb7748188a7d1a9345a09c4519f | Implement punctuation filtering | index.py | index.py | from nltk.tokenize import word_tokenize, sent_tokenize
import getopt
import sys
import os
import io
import string
def build_dict(docs):
dictionary = set()
for doc_id, doc in docs.items():
dictionary.update(doc)
dictionary = list(dictionary)
dictionary.sort()
return dictionary
def build_postings(dictionary):
... | from nltk.tokenize import word_tokenize, sent_tokenize
import getopt
import sys
import os
import io
def build_dict(docs):
dictionary = set()
for doc_id, doc in docs.items():
dictionary.update(doc)
dictionary = list(dictionary)
dictionary.sort()
return dictionary
def build_postings(dictionary):
postings = {}... | Python | 0.999999 |
e320c8558646233b78760e1c84c5334a3a743d6d | Fix test_ensemble on Python 3.5 | tests/test_ensemble.py | tests/test_ensemble.py | import pytest
from rasa_core.policies import Policy
from rasa_core.policies.ensemble import PolicyEnsemble
class WorkingPolicy(Policy):
@classmethod
def load(cls, path):
return WorkingPolicy()
def persist(self, path):
pass
def train(self, training_trackers, domain, **kwargs):
... | import pytest
from rasa_core.policies import Policy
from rasa_core.policies.ensemble import PolicyEnsemble
class WorkingPolicy(Policy):
@classmethod
def load(cls, path):
return WorkingPolicy()
def persist(self, path):
pass
def train(self, training_trackers, domain, **kwargs):
... | Python | 0.998424 |
ed410e81af61699a16c34c1edbbaa18a80bcdcfe | use global DocSimServer instance in views | docsim/documents/views.py | docsim/documents/views.py | from ujson import dumps
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from rest_framework.generics import ListAPIView, RetrieveAPIView
from .docsimserver import DocSimServer
from .models import Cl... | from ujson import dumps
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from rest_framework.generics import ListAPIView, RetrieveAPIView
from .docsimserver import DocSimServer
from .models import Cl... | Python | 0 |
829d68f842c5076be7a8b2c3963c032977fe2f47 | Bump to 4.4-dp2. | pebble_tool/version.py | pebble_tool/version.py | version_base = (4, 4, 0)
version_suffix = 'dp2'
if version_suffix is None:
__version_info__ = version_base
else:
__version_info__ = version_base + (version_suffix,)
__version__ = '{}.{}'.format(*version_base)
if version_base[2] != 0:
__version__ += '.{}'.format(version_base[2])
if version_suffix is not N... | version_base = (4, 4, 0)
version_suffix = 'dp1'
if version_suffix is None:
__version_info__ = version_base
else:
__version_info__ = version_base + (version_suffix,)
__version__ = '{}.{}'.format(*version_base)
if version_base[2] != 0:
__version__ += '.{}'.format(version_base[2])
if version_suffix is not N... | Python | 0.000001 |
bc91c7abdc5754917642614930ad24d5db169c9a | simplify settings | shotglass/shotglass/settings.py | shotglass/shotglass/settings.py | import os
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles... | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the... | Python | 0.00049 |
752132f83cacb15273625f819eed1dab1d558e97 | Make sure all relevant fields are shown in the admin interface | dictionary/admin.py | dictionary/admin.py | from daisyproducer.dictionary.models import Word
from django.contrib import admin
class WordAdmin(admin.ModelAdmin):
list_display = ('untranslated', 'grade1', 'grade2', 'type', 'isConfirmed', 'isLocal')
ordering = ('untranslated',)
search_fields = ('untranslated',)
admin.site.register(Word, WordAdmin)
| from daisyproducer.dictionary.models import Word
from django.contrib import admin
class WordAdmin(admin.ModelAdmin):
list_display = ('untranslated', 'grade1', 'grade2', 'type', 'isConfirmed')
ordering = ('untranslated',)
search_fields = ('untranslated',)
admin.site.register(Word, WordAdmin)
| Python | 0 |
bda269c5b745703cf517222e004caf0233b40699 | refactor p4io to io | tests/test_get_data.py | tests/test_get_data.py | from planet4 import io
import datetime as dt
def test_get_numbers_from_date_from_fname():
fname1 = '/a/b/c/2014-06-02_some_name.h5'
assert io.split_date_from_fname(fname1) == [2014, 6, 2]
def test_get_datetime_object_from_fname():
fname1 = '/a/b/c/2014-06-02_some_name.h5'
dt_obj = dt.datetime(2014, ... | from planet4 import p4io
import datetime as dt
def test_get_numbers_from_date_from_fname():
fname1 = '/a/b/c/2014-06-02_some_name.h5'
assert p4io.split_date_from_fname(fname1) == [2014, 6, 2]
def test_get_datetime_object_from_fname():
fname1 = '/a/b/c/2014-06-02_some_name.h5'
dt_obj = dt.datetime(20... | Python | 0.999999 |
9b06a061a4bc439ea96761ead0a1397470cfff56 | update tests | tests/test_labeling.py | tests/test_labeling.py | from __future__ import print_function
from builtins import zip
from builtins import object
from usaddress import parse, GROUP_LABEL
from parserator.training import readTrainingData
import unittest
class TestSimpleAddresses(object) : # for test generators, must inherit from object
def test_simple_addresses(self):
... | from __future__ import print_function
from builtins import zip
from builtins import object
from usaddress import parse, GROUP_LABEL
from parserator.training import readTrainingData
import unittest
class TestSimpleAddresses(object) : # for test generators, must inherit from object
def test_simple_addresses(self):
... | Python | 0.000001 |
ab574b6c40b6e58f396c9522be864a78478617c1 | Remove TestMainLoop.test_concurrency | tests/test_mainloop.py | tests/test_mainloop.py | # -*- Mode: Python -*-
import os
import sys
import select
import signal
import time
import unittest
from gi.repository import GLib
from compathelper import _bytes
class TestMainLoop(unittest.TestCase):
@unittest.skipUnless(hasattr(os, "fork"), "no os.fork available")
def test_exception_handling(self):
... | # -*- Mode: Python -*-
import os
import sys
import select
import signal
import time
import unittest
try:
from _thread import start_new_thread
start_new_thread # pyflakes
except ImportError:
# Python 2
from thread import start_new_thread
from gi.repository import GLib
from compathelper import _bytes
... | Python | 0.013365 |
3cc7e0cebc8a7a7410ce6b239e55db0cf55b1dc8 | Fix broken tests in test_messages | tests/test_messages.py | tests/test_messages.py | from datetime import date
import unittest
from mock import patch
from six import u
from twilio.rest.resources import Messages
DEFAULT = {
'From': None,
'DateSent<': None,
'DateSent>': None,
'DateSent': None,
}
class MessageTest(unittest.TestCase):
def setUp(self):
self.resource = Messa... | from datetime import date
import unittest
from mock import patch
from six import u
from twilio.rest.resources import Messages
DEFAULT = {
'From': None,
'DateSent<': None,
'DateSent>': None,
'DateSent': None,
}
class MessageTest(unittest.TestCase):
def setUp(self):
self.resource = Messa... | Python | 0.000648 |
f6ecf6a45e2749261a20869aca5dfca6d7c03494 | Correct method doc. | qiprofile_rest_client/helpers/database.py | qiprofile_rest_client/helpers/database.py | """Mongo Engine interaction utilities."""
def get_or_create(klass, key=None, **non_key):
"""
This function stands in for the Mongo Engine ``get_or_create``
collection method which was deprecated in mongoengine v0.8.0
and dropped in mongoengine v0.10.0, since MongoDB does not
support transactions.
... | """Mongo Engine interaction utilities."""
def get_or_create(klass, pk, **non_pk):
"""
This function stands in for the Mongo Engine ``get_or_create``
collection method which was deprecated in mongoengine v0.8.0
and dropped in mongoengine v0.10.0, since MongoDB does not
support transactions.
... | Python | 0 |
c2df896183f80fe3ca0eab259874bc4385d399e9 | Clean up detrius in parallel test file | tests/test_parallel.py | tests/test_parallel.py | from __future__ import with_statement
from fabric.api import run, parallel, env, hide
from utils import FabricTest, eq_
from server import server, RESPONSES
class TestParallel(FabricTest):
@server()
@parallel
def test_parallel(self):
"""
Want to do a simple call and respond
"""
... | from __future__ import with_statement
from datetime import datetime
import copy
import getpass
import sys
import paramiko
from nose.tools import with_setup
from fudge import (Fake, clear_calls, clear_expectations, patch_object, verify,
with_patched_object, patched_context, with_fakes)
from fabric.context_manager... | Python | 0 |
8f86eacf1b85a0c497f9e8586a59cc19e6a0484f | Stop passing a recorder argument unecessarily in tests | tests/test_pipeline.py | tests/test_pipeline.py | from __future__ import print_function
import pytest
from plumbium.processresult import record, pipeline, call
class DummyRecorder(object):
def write(self, results):
self.results = results
@pytest.fixture
def simple_pipeline():
@record('an_output')
def recorded_function():
call(['echo', '... | from __future__ import print_function
import pytest
from plumbium.processresult import record, pipeline, call
class DummyRecorder(object):
def write(self, results):
self.results = results
@pytest.fixture
def simple_pipeline():
@record('an_output')
def recorded_function():
call(['echo', '... | Python | 0.000002 |
7b75f508bf651bdeb57bdc4d263ced26434054c8 | add pct test | tests/test_pvmodule.py | tests/test_pvmodule.py | """
Tests for pvmodules.
"""
from nose.tools import ok_
from pvmismatch.pvmismatch_lib.pvmodule import PVmodule, TCT96, PCT96
def test_calc_mod():
pvmod = PVmodule()
ok_(isinstance(pvmod, PVmodule))
return pvmod
def test_calc_TCT_mod():
pvmod = PVmodule(cell_pos=TCT96)
ok_(isinstance(pvmod, PVm... | """
Tests for pvmodules.
"""
from nose.tools import ok_
from pvmismatch.pvmismatch_lib.pvmodule import PVmodule, TCT96
def test_calc_mod():
pvmod = PVmodule()
ok_(isinstance(pvmod, PVmodule))
return pvmod
def test_calc_TCT_mod():
pvmod = PVmodule(cell_pos=TCT96)
ok_(isinstance(pvmod, PVmodule))... | Python | 0.000014 |
20d1ab60c718869d86deed5410d5aef428042195 | remove unused json import | tests/test_redirect.py | tests/test_redirect.py | import pytest
from urllib.parse import quote
from sanic.response import text, redirect
@pytest.fixture
def redirect_app(app):
@app.route('/redirect_init')
async def redirect_init(request):
return redirect("/redirect_target")
@app.route('/redirect_init_with_301')
async def redirect_init_with... | import pytest
import json
from urllib.parse import quote
from sanic.response import text, redirect
@pytest.fixture
def redirect_app(app):
@app.route('/redirect_init')
async def redirect_init(request):
return redirect("/redirect_target")
@app.route('/redirect_init_with_301')
async def redire... | Python | 0.000002 |
9744226621e27d4bd5d19a52b75b718e86bfef87 | Add extra filter for equipment | lims/equipment/views.py | lims/equipment/views.py |
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.exceptions import PermissionDenied
import django_filters
from lims.permissions.permissions import IsInAdminGroupOrRO
from .models import Equipment, EquipmentReservation
from .serializers import EquipmentSerializer, ... |
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.exceptions import PermissionDenied
import django_filters
from lims.permissions.permissions import IsInAdminGroupOrRO
from .models import Equipment, EquipmentReservation
from .serializers import EquipmentSerializer, ... | Python | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.