Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
6,000 | def add_layer(self, layer=None, is_output=False, **kwargs):
'''Add a :ref:`layer <layers>` to our network graph.
Parameters
----------
layer : int, tuple, dict, or :class:`Layer <theanets.layers.base.Layer>`
A value specifying the layer to add. For more information, please
... | TypeError | dataset/ETHPy150Open lmjohns3/theanets/theanets/graph.py/Network.add_layer |
6,001 | def __new__(cls, name, bases, attrs):
attrs['base_fields'] = {}
declared_fields = {}
# Inherit any fields from parent(s).
try:
parents = [b for b in bases if issubclass(b, Resource)]
# Simulate the MRO.
parents.reverse()
for p in parents:... | NameError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/DeclarativeMetaclass.__new__ |
6,002 | def wrap_view(self, view):
"""
Wraps methods so they can be called in a more functional way as well
as handling exceptions better.
Note that if ``BadRequest`` or an exception with a ``response`` attr
are seen, there is special handling to either present a message back
to... | ValidationError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.wrap_view |
6,003 | def remove_api_resource_names(self, url_dict):
"""
Given a dictionary of regex matches from a URLconf, removes
``api_name`` and/or ``resource_name`` if found.
This is useful for converting URLconf matches into something suitable
for data lookup. For example::
Model.... | KeyError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.remove_api_resource_names |
6,004 | def dehydrate_resource_uri(self, bundle):
"""
For the automatically included ``resource_uri`` field, dehydrate
the URI for the given bundle.
Returns empty string if no URI can be generated.
"""
try:
return self.get_resource_uri(bundle)
except __HOLE__... | NotImplementedError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.dehydrate_resource_uri |
6,005 | def get_detail(self, request, **kwargs):
"""
Returns a single serialized resource.
Calls ``cached_obj_get/obj_get`` to provide the data, then handles that result
set and serializes it.
Should return a HttpResponse (200 OK).
"""
try:
obj = self.cached... | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.get_detail |
6,006 | def patch_list(self, request, **kwargs):
"""
Updates a collection in-place.
The exact behavior of ``PATCH`` to a list resource is still the matter of
some debate in REST circles, and the ``PATCH`` RFC isn't standard. So the
behavior this method implements (described below) is so... | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.patch_list |
6,007 | def patch_detail(self, request, **kwargs):
"""
Updates a resource in-place.
Calls ``obj_update``.
If the resource is updated, return ``HttpAccepted`` (202 Accepted).
If the resource did not exist, return ``HttpNotFound`` (404 Not Found).
"""
request = convert_po... | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.patch_detail |
6,008 | def get_multiple(self, request, **kwargs):
"""
Returns a serialized list of resources based on the identifiers
from the URL.
Calls ``obj_get`` to fetch only the objects requested. This method
only responds to HTTP GET.
Should return a HttpResponse (200 OK).
"""
... | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.get_multiple |
6,009 | def obj_get_list(self, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_get_list``.
Takes an optional ``request`` object, whose ``GET`` dictionary can be
used to narrow the query.
"""
filters = {}
if hasattr(request, 'GET'):
# Grab... | ValueError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/ModelResource.obj_get_list |
6,010 | def obj_get(self, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_get``.
Takes optional ``kwargs``, which are used to narrow the query to find
the instance.
"""
try:
base_object_list = self.get_object_list(request).filter(**kwargs)
... | ValueError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/ModelResource.obj_get |
6,011 | def obj_update(self, bundle, request=None, skip_errors=False, **kwargs):
"""
A ORM-specific implementation of ``obj_update``.
"""
if not bundle.obj or not self.get_bundle_detail_data(bundle):
# Attempt to hydrate data from kwargs before doing a lookup for the object.
... | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/ModelResource.obj_update |
6,012 | def obj_delete(self, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_delete``.
Takes optional ``kwargs``, which are used to narrow the query to find
the instance.
"""
obj = kwargs.pop('_obj', None)
if not hasattr(obj, 'delete'):
t... | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/ModelResource.obj_delete |
6,013 | def save_related(self, bundle):
"""
Handles the saving of related non-M2M data.
Calling assigning ``child.parent = parent`` & then calling
``Child.save`` isn't good enough to make sure the ``parent``
is saved.
To get around this, we go through all our related fields &
... | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/ModelResource.save_related |
6,014 | def convert_post_to_VERB(request, verb):
"""
Force Django to process the VERB.
"""
if request.method == verb:
if hasattr(request, '_post'):
del(request._post)
del(request._files)
try:
request.method = "POST"
request._load_post_and_files()
... | AttributeError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/convert_post_to_VERB |
6,015 | def run(self, fake=False, *args, **kwargs):
"""
Execute import.
"""
from panda.models import DataUpload, RelatedUpload
log = logging.getLogger(self.name)
log.info('Purging orphaned uploads')
local_files = os.listdir(settings.MEDIA_ROOT)
data_uploads = Da... | ValueError | dataset/ETHPy150Open pandaproject/panda/panda/tasks/purge_orphaned_uploads.py/PurgeOrphanedUploadsTask.run |
6,016 | @classmethod
def get_build_step_for_job(cls, job_id):
jobplan = cls.query.filter(
cls.job_id == job_id,
).first()
if jobplan is None:
return None, None
steps = jobplan.get_steps()
try:
step = steps[0]
except __HOLE__:
r... | IndexError | dataset/ETHPy150Open dropbox/changes/changes/models/jobplan.py/JobPlan.get_build_step_for_job |
6,017 | def remove_chartjunk(ax, spines, grid=None, ticklabels=None, show_ticks=False,
xkcd=False):
'''
Removes "chartjunk", such as extra lines of axes and tick marks.
If grid="y" or "x", will add a white grid at the "y" or "x" axes,
respectively
If ticklabels="y" or "x", or ['x', 'y... | KeyError | dataset/ETHPy150Open olgabot/prettyplotlib/prettyplotlib/utils.py/remove_chartjunk |
6,018 | def maybe_get_linewidth(**kwargs):
try:
key = (set(["lw", "linewidth", 'linewidths']) & set(kwargs)).pop()
lw = kwargs[key]
except __HOLE__:
lw = 0.15
return lw | KeyError | dataset/ETHPy150Open olgabot/prettyplotlib/prettyplotlib/utils.py/maybe_get_linewidth |
6,019 | def has(data, sub_data):
# Recursive approach to look for a subset of data in data.
# WARNING: Don't use on huge structures
# :param data: Data structure
# :param sub_data: subset being checked for
# :return: True or False
try:
(item for item in data if item == sub_data).next()
r... | StopIteration | dataset/ETHPy150Open CenterForOpenScience/osf.io/tests/test_notifications.py/has |
6,020 | def open_sysfs_numa_stats():
"""Returns a possibly empty list of opened files."""
try:
nodes = os.listdir(NUMADIR)
except __HOLE__, (errno, msg):
if errno == 2: # No such file or directory
return [] # We don't have NUMA stats.
raise
nodes = [node for node in nodes... | OSError | dataset/ETHPy150Open scalyr/scalyr-agent-2/scalyr_agent/third_party/tcollector/collectors/0/procstats.py/open_sysfs_numa_stats |
6,021 | @register_test(tier=2)
def test_packed_packages(err, package=None):
if not package:
return
processed_files = 0
garbage_files = 0
# Iterate each item in the package.
for name in package:
file_info = package.info(name)
file_name = file_info["name_lower"]
file_size = ... | KeyError | dataset/ETHPy150Open mozilla/app-validator/appvalidator/testcases/content.py/test_packed_packages |
6,022 | def apiDecorator(api_type):
def _apiDecorator(func):
lines = ['']
marked = False
if not func.__doc__:
func.__doc__ = func.__name__
lines = func.__doc__.split('\n')
for idx, line in enumerate(lines):
if '@' in line:
l = line.replace('\t'... | TypeError | dataset/ETHPy150Open sassoftware/conary/conary/lib/api.py/apiDecorator |
6,023 | def split_string(self, string):
""" Yields substrings for which the same escape code applies.
"""
self.actions = []
start = 0
for match in ANSI_PATTERN.finditer(string):
raw = string[start:match.start()]
substring = SPECIAL_PATTERN.sub(self._replace_speci... | ValueError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/frontend/qt/console/ansi_code_processor.py/AnsiCodeProcessor.split_string |
6,024 | def set_osc_code(self, params):
""" Set attributes based on OSC (Operating System Command) parameters.
Parameters
----------
params : sequence of str
The parameters for the command.
"""
try:
command = int(params.pop(0))
except (Ind... | ValueError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/frontend/qt/console/ansi_code_processor.py/AnsiCodeProcessor.set_osc_code |
6,025 | def setUp(self):
try:
from pikos.cymonitors.focused_function_monitor import (
FocusedFunctionMonitor)
except __HOLE__:
self.skipTest('Cython FocusedFunctionMonitor is not available')
self.maxDiff = None
self.stream = StringIO.StringIO()
de... | ImportError | dataset/ETHPy150Open enthought/pikos/pikos/tests/test_focused_cfunction_monitor.py/TestFocusedCFunctionMonitor.setUp |
6,026 | @classmethod
def mr_job_script(cls):
"""Path of this script. This returns the file containing
this class, or ``None`` if there isn't any (e.g. it was
defined from the command line interface.)"""
try:
return inspect.getsourcefile(cls)
except __HOLE__:
r... | TypeError | dataset/ETHPy150Open Yelp/mrjob/mrjob/job.py/MRJob.mr_job_script |
6,027 | def MVgammaln(x, D):
''' Compute log of the D-dimensional multivariate Gamma func. for input x
Notes: Caching gives big speedup!
-------
caching : 208 sec for 5 iters of CGS on K=50, D=2 problem with N=10000
no cache : 300 sec
'''
try:
return MVgCache[D][x]
except __HOLE_... | KeyError | dataset/ETHPy150Open daeilkim/refinery/refinery/bnpy/bnpy-dev/bnpy/util/SpecialFuncUtil.py/MVgammaln |
6,028 | def test_server(self):
logging.debug('')
logging.debug('test_server')
testdir = 'test_server'
if os.path.exists(testdir):
shutil.rmtree(testdir, onerror=onerror)
os.mkdir(testdir)
os.chdir(testdir)
try:
# Create a server.
serv... | TypeError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/test/test_objserverfactory.py/TestCase.test_server |
6,029 | def _setup_pre_commit_hook(self):
"""
Copy the pre-commit hook found at config.pre_commit_hook to the
closest .git directory. If no .git directory exists, throw an
exception.
"""
if self.config.get('pre_commit_hook') is None:
return
check_dir = os.ge... | OSError | dataset/ETHPy150Open appnexus/schema-tool/schematool/command/init.py/InitCommand._setup_pre_commit_hook |
6,030 | def quoted_string_literal(s, d):
"""
SOQL requires single quotes to be escaped.
http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_soql_select_quotedstringescapes.htm
"""
try:
return "'%s'" % (s.replace("\\", "\\\\").replace("'", "\\'"),)
except __HOLE__ as e:... | TypeError | dataset/ETHPy150Open django-salesforce/django-salesforce/salesforce/backend/query.py/quoted_string_literal |
6,031 | def iterator(self):
"""
An iterator over the results from applying this QuerySet to the
remote web service.
"""
try:
sql, params = SQLCompiler(self.query, connections[self.db], None).as_sql()
except EmptyResultSet:
raise StopIteration
curso... | KeyError | dataset/ETHPy150Open django-salesforce/django-salesforce/salesforce/backend/query.py/SalesforceQuerySet.iterator |
6,032 | def execute_delete(self, query):
table = query.model._meta.db_table
## the root where node's children may itself have children..
def recurse_for_pk(children):
for node in children:
if hasattr(node, 'rhs'):
pk = node.rhs[0]
else:
... | TypeError | dataset/ETHPy150Open django-salesforce/django-salesforce/salesforce/backend/query.py/CursorWrapper.execute_delete |
6,033 | def fetchone(self):
"""
Fetch a single result from a previously executed query.
"""
try:
return next(self.results)
except __HOLE__:
return None | StopIteration | dataset/ETHPy150Open django-salesforce/django-salesforce/salesforce/backend/query.py/CursorWrapper.fetchone |
6,034 | def test_maybeDeferredSyncError(self):
"""
L{defer.maybeDeferred} should catch exception raised by a synchronous
function and errback its resulting L{defer.Deferred} with it.
"""
S, E = [], []
try:
'10' + 5
except __HOLE__, e:
expected = st... | TypeError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/test/test_defer.py/DeferredTestCase.test_maybeDeferredSyncError |
6,035 | def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
self.active = kwargs.pop('active', None)
initial = kwargs.get('initial', {})
default_loc = utils.get_setting('TIMEPIECE_DEFAULT_LOCATION_SLUG')
if default_loc:
try:
loc = Location.obj... | IndexError | dataset/ETHPy150Open caktus/django-timepiece/timepiece/entries/forms.py/ClockInForm.__init__ |
6,036 | def test_loadTestsFromTestCase__TestSuite_subclass(self):
class NotATestCase(unittest.TestSuite):
pass
loader = unittest.TestLoader()
try:
loader.loadTestsFromTestCase(NotATestCase)
except __HOLE__:
pass
else:
self.fail('Should rai... | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromTestCase__TestSuite_subclass |
6,037 | def test_loadTestsFromName__empty_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('')
except __HOLE__ as e:
self.assertEqual(str(e), "Empty module name")
else:
self.fail("TestLoader.loadTestsFromName failed to raise ValueError... | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__empty_name |
6,038 | def test_loadTestsFromName__malformed_name(self):
loader = unittest.TestLoader()
# XXX Should this raise ValueError or ImportError?
try:
loader.loadTestsFromName('abc () //')
except __HOLE__:
pass
except ImportError:
pass
else:
... | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__malformed_name |
6,039 | def test_loadTestsFromName__unknown_module_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('sdasfasfasdf')
except __HOLE__ as e:
self.assertEqual(str(e), "No module named 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsF... | ImportError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__unknown_module_name |
6,040 | def test_loadTestsFromName__unknown_attr_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('unittest.sdasfasfasdf')
except __HOLE__ as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
self.fai... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__unknown_attr_name |
6,041 | def test_loadTestsFromName__relative_unknown_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('sdasfasfasdf', unittest)
except __HOLE__ as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
sel... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__relative_unknown_name |
6,042 | def test_loadTestsFromName__relative_empty_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('', unittest)
except __HOLE__ as e:
pass
else:
self.fail("Failed to raise AttributeError")
# "The specifier name is a ``dotted nam... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__relative_empty_name |
6,043 | def test_loadTestsFromName__relative_malformed_name(self):
loader = unittest.TestLoader()
# XXX Should this raise AttributeError or ValueError?
try:
loader.loadTestsFromName('abc () //', unittest)
except __HOLE__:
pass
except AttributeError:
p... | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__relative_malformed_name |
6,044 | def test_loadTestsFromName__relative_bad_object(self):
m = types.ModuleType('m')
m.testcase_1 = object()
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('testcase_1', m)
except __HOLE__:
pass
else:
self.fail("Should have r... | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__relative_bad_object |
6,045 | def test_loadTestsFromName__relative_invalid_testmethod(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('test... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__relative_invalid_testmethod |
6,046 | def test_loadTestsFromName__callable__wrong_type(self):
m = types.ModuleType('m')
def return_wrong():
return 6
m.return_wrong = return_wrong
loader = unittest.TestLoader()
try:
suite = loader.loadTestsFromName('return_wrong', m)
except __HOLE__:
... | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__callable__wrong_type |
6,047 | def test_loadTestsFromNames__empty_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames([''])
except __HOLE__ as e:
self.assertEqual(str(e), "Empty module name")
else:
self.fail("TestLoader.loadTestsFromNames failed to raise Value... | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__empty_name |
6,048 | def test_loadTestsFromNames__malformed_name(self):
loader = unittest.TestLoader()
# XXX Should this raise ValueError or ImportError?
try:
loader.loadTestsFromNames(['abc () //'])
except ValueError:
pass
except __HOLE__:
pass
else:
... | ImportError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__malformed_name |
6,049 | def test_loadTestsFromNames__unknown_module_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['sdasfasfasdf'])
except __HOLE__ as e:
self.assertEqual(str(e), "No module named 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTe... | ImportError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__unknown_module_name |
6,050 | def test_loadTestsFromNames__unknown_attr_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
except __HOLE__ as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__unknown_attr_name |
6,051 | def test_loadTestsFromNames__unknown_name_relative_1(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
except __HOLE__ as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__unknown_name_relative_1 |
6,052 | def test_loadTestsFromNames__unknown_name_relative_2(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
except __HOLE__ as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
els... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__unknown_name_relative_2 |
6,053 | def test_loadTestsFromNames__relative_empty_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames([''], unittest)
except __HOLE__:
pass
else:
self.fail("Failed to raise ValueError")
# "The specifier name is a ``dotted name'' t... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__relative_empty_name |
6,054 | def test_loadTestsFromNames__relative_malformed_name(self):
loader = unittest.TestLoader()
# XXX Should this raise AttributeError or ValueError?
try:
loader.loadTestsFromNames(['abc () //'], unittest)
except __HOLE__:
pass
except ValueError:
p... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__relative_malformed_name |
6,055 | def test_loadTestsFromNames__relative_bad_object(self):
m = types.ModuleType('m')
m.testcase_1 = object()
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['testcase_1'], m)
except __HOLE__:
pass
else:
self.fail("Should ha... | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__relative_bad_object |
6,056 | def test_loadTestsFromNames__relative_invalid_testmethod(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['t... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__relative_invalid_testmethod |
6,057 | def test_loadTestsFromNames__callable__wrong_type(self):
m = types.ModuleType('m')
def return_wrong():
return 6
m.return_wrong = return_wrong
loader = unittest.TestLoader()
try:
suite = loader.loadTestsFromNames(['return_wrong'], m)
except __HOLE_... | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__callable__wrong_type |
6,058 | def normalize_scopes(scopes):
"""
Given a list of public-facing scope names from a CAS token, return the list of internal scopes
This is useful for converting a single broad scope name (from CAS) into the small constituent parts
(as used by views)
:param list scopes: a list public facing scope... | KeyError | dataset/ETHPy150Open CenterForOpenScience/osf.io/framework/auth/oauth_scopes.py/normalize_scopes |
6,059 | def find(self, **kwargs):
"""
Find a single item with attributes matching ``**kwargs``.
This isn't very efficient: it loads the entire list then filters on
the Python side.
"""
rl = self.findall(**kwargs)
try:
return rl[0]
except __HOL... | IndexError | dataset/ETHPy150Open jacobian-archive/openstack.compute/openstack/compute/base.py/ManagerWithFind.find |
6,060 | def findall(self, **kwargs):
"""
Find all items with attributes matching ``**kwargs``.
This isn't very efficient: it loads the entire list then filters on
the Python side.
"""
found = []
searches = kwargs.items()
for obj in self.list():
... | AttributeError | dataset/ETHPy150Open jacobian-archive/openstack.compute/openstack/compute/base.py/ManagerWithFind.findall |
6,061 | def getid(obj):
"""
Abstracts the common pattern of allowing both an object or an object's ID
(integer) as a parameter when dealing with relationships.
"""
try:
return obj.id
except __HOLE__:
return int(obj) | AttributeError | dataset/ETHPy150Open jacobian-archive/openstack.compute/openstack/compute/base.py/getid |
6,062 | def bdecode(x):
try:
r, l = decode_func[six.indexbytes(x, 0)](x, 0)
except (IndexError, KeyError, __HOLE__):
raise
raise BTFailure("not a valid bencoded string")
if l != len(x):
raise BTFailure("invalid bencoded value (data after valid prefix)")
return r | ValueError | dataset/ETHPy150Open JohnDoee/autotorrent/autotorrent/bencode.py/bdecode |
6,063 | @csrf_exempt
def rest(request, *pargs):
"""
Calls python function corresponding with HTTP METHOD name.
Calls with incomplete arguments will return HTTP 400
"""
if request.method == 'GET':
rest_function = get
elif request.method == 'POST':
rest_function = post
elif request.me... | TypeError | dataset/ETHPy150Open emccode/heliosburn/heliosburn/django/hbproject/api/views/testplan.py/rest |
6,064 | @RequireLogin()
def post(request):
"""
Create new test plan.
"""
try:
new = json.loads(request.body)
assert "name" in new
except __HOLE__:
return HttpResponseBadRequest("invalid JSON")
except AssertionError:
return HttpResponseBadRequest("argument mismatch")
... | ValueError | dataset/ETHPy150Open emccode/heliosburn/heliosburn/django/hbproject/api/views/testplan.py/post |
6,065 | @RequireLogin()
def put(request, testplan_id):
"""
Update existing test plan based on testplan_id.
"""
try:
in_json = json.loads(request.body)
except __HOLE__:
return HttpResponseBadRequest("invalid JSON")
dbc = db_model.connect()
try:
testplan = dbc.testplan.find_on... | ValueError | dataset/ETHPy150Open emccode/heliosburn/heliosburn/django/hbproject/api/views/testplan.py/put |
6,066 | def prep_trans_tar(file_client, chunks, file_refs, pillar=None, id_=None):
'''
Generate the execution package from the saltenv file refs and a low state
data structure
'''
gendir = tempfile.mkdtemp()
trans_tar = salt.utils.mkstemp()
lowfn = os.path.join(gendir, 'lowstate.json')
pillarfn ... | OSError | dataset/ETHPy150Open saltstack/salt/salt/client/ssh/state.py/prep_trans_tar |
6,067 | def _get_http(timeout):
try:
http = Http(timeout=timeout)
except __HOLE__:
# The user's version of http2lib is old. Omit the timeout.
http = Http()
return http | TypeError | dataset/ETHPy150Open njr0/fish/fish/fishlib.py/_get_http |
6,068 | def get_values_by_query(self, query, tags):
"""
Gets the values of a set of tags satisfying a given query.
Returns them as a dictionary (hash) keyed on object ID.
The values in the dictionary are simple objects with each tag
value in the object's dictionary (__dict__).
q... | KeyError | dataset/ETHPy150Open njr0/fish/fish/fishlib.py/Fluidinfo.get_values_by_query |
6,069 | def get_typed_tag_value(v):
"""Uses some simple rules to extract simple typed values from strings.
Specifically:
true and t (any case) return True (boolean)
false and f (any case) return False (boolean)
simple integers (possibly signed) are returned as ints
simple... | ValueError | dataset/ETHPy150Open njr0/fish/fish/fishlib.py/get_typed_tag_value |
6,070 | def get_typed_tag_value_from_file(path, options):
path = expandpath(path)
mime = options.mime[0] if options.mime else None
if os.path.exists(path):
v = Dummy()
stem, ext = os.path.splitext(path)
ext = ext[1:].lower()
if (mime and mime in TEXTUAL_MIMES.values()) or ext in TEXT... | UnicodeDecodeError | dataset/ETHPy150Open njr0/fish/fish/fishlib.py/get_typed_tag_value_from_file |
6,071 | def to_typed(v):
"""
Turns json-formatted string into python value.
Unicode.
"""
L = v.lower()
if v.startswith(u'"') and v.startswith(u'"') and len(v) >= 2:
return v[1:-1]
elif v.startswith(u"'") and v.startswith(u"'") and len(v) >= 2:
return v[1:-1]
elif L == u'true':
... | ValueError | dataset/ETHPy150Open njr0/fish/fish/fishlib.py/to_typed |
6,072 | def number_try_parse(str):
for func in (int, float):
try:
return func(str)
except __HOLE__:
pass
return str | ValueError | dataset/ETHPy150Open membase/membase-cli/pump_csv.py/number_try_parse |
6,073 | def provide_batch(self):
if self.done:
return 0, None
if not self.r:
try:
self.r = csv.reader(open(self.spec, 'rU'))
self.fields = self.r.next()
if not 'id' in self.fields:
return ("error: no 'id' field in 1st l... | StopIteration | dataset/ETHPy150Open membase/membase-cli/pump_csv.py/CSVSource.provide_batch |
6,074 | def consume_batch_async(self, batch):
if not self.writer:
self.writer = csv.writer(sys.stdout)
self.writer.writerow(['id', 'flags', 'expiration', 'cas', 'value'])
for msg in batch.msgs:
cmd, vbucket_id, key, flg, exp, cas, meta, val = msg
if self.skip(key... | IOError | dataset/ETHPy150Open membase/membase-cli/pump_csv.py/CSVSink.consume_batch_async |
6,075 | def test_constructor(self):
pi = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')
assert_equal(len(pi), 9)
pi = PeriodIndex(freq='Q', start='1/1/2001', end='12/1/2009')
assert_equal(len(pi), 4 * 9)
pi = PeriodIndex(freq='M', start='1/1/2001', end='12/1/2009')
as... | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/tseries/tests/test_period.py/TestPeriodIndex.test_constructor |
6,076 | def test_period_index_length(self):
pi = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')
assert_equal(len(pi), 9)
pi = PeriodIndex(freq='Q', start='1/1/2001', end='12/1/2009')
assert_equal(len(pi), 4 * 9)
pi = PeriodIndex(freq='M', start='1/1/2001', end='12/1/2009')
... | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/tseries/tests/test_period.py/TestPeriodIndex.test_period_index_length |
6,077 | def test_get_loc_msg(self):
idx = period_range('2000-1-1', freq='A', periods=10)
bad_period = Period('2012', 'A')
self.assertRaises(KeyError, idx.get_loc, bad_period)
try:
idx.get_loc(bad_period)
except __HOLE__ as inst:
self.assertEqual(inst.args[0], bad... | KeyError | dataset/ETHPy150Open pydata/pandas/pandas/tseries/tests/test_period.py/TestPeriodIndex.test_get_loc_msg |
6,078 | def scan(build, root, desc, **custom_vars ):
global numStamped
numStamped = 0
try:
build = string.atoi(build)
except __HOLE__:
print 'ERROR: build number is not a number: %s' % build
sys.exit(1)
debug = 0 ### maybe fix this one day
varList = ['major', 'minor', 'sub', 'company', 'cop... | ValueError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/scripts/VersionStamp/bulkstamp.py/scan |
6,079 | def getDecodableAttributes(self, obj, attrs, codec=None):
"""
Returns a dictionary of attributes for C{obj} that has been filtered,
based on the supplied C{attrs}. This allows for fine grain control
over what will finally end up on the object or not.
@param obj: The object that ... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/alias.py/ClassAlias.getDecodableAttributes |
6,080 | def parse_json(self, json):
self.doi = DOI(json.get('URL', None))
self.score = float(json.get('score', 0.))
try:
self.title = self.format_title(json['title'][0])
except (IndexError, KeyError):
self.title = self.UNKNOWN_TITLE
#self.timestamp = float(json['... | KeyError | dataset/ETHPy150Open dotcs/doimgr/lib/search/result.py/SearchResult.parse_json |
6,081 | def endElement(self, name, value, connection):
if name == 'InstanceType':
self.instance_type = value
elif name == 'LaunchConfigurationName':
self.name = value
elif name == 'KeyName':
self.key_name = value
elif name == 'ImageId':
self.image_... | ValueError | dataset/ETHPy150Open radlab/sparrow/deploy/third_party/boto-2.1.1/boto/ec2/autoscale/launchconfig.py/LaunchConfiguration.endElement |
6,082 | def _volume_type_and_iops_for_profile_name(profile_name, size):
"""
Determines and returns the volume_type and iops for a boto create_volume
call for a given profile_name.
:param profile_name: The name of the profile.
:param size: The size of the volume to create in GiB.
:returns: A tuple of ... | ValueError | dataset/ETHPy150Open ClusterHQ/flocker/flocker/node/agents/ebs.py/_volume_type_and_iops_for_profile_name |
6,083 | def _set_environ(self, env, name, value):
if value is self.Unset:
try:
del env[name]
except __HOLE__:
pass
else:
env[name] = value | KeyError | dataset/ETHPy150Open Masood-M/yalih/mechanize/_testcase.py/MonkeyPatcher._set_environ |
6,084 | def instart(cls, name, display_name=None, stay_alive=True):
'''Install and Start (auto) a Service
cls : the class (derived from Service) that implement the Service
name : Service name
display_name : the name displayed in the service manager
stay_alive : Service will stop on logout if False
'''... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/utils/winservice.py/instart |
6,085 | def get_connection(path=None, fail_silently=False, **kwargs):
"""
Load an sms backend and return an instance of it.
:param string path: backend python path. Default: sendsms.backends.console.SmsBackend
:param bool fail_silently: Flag to not throw exceptions on error. Default: False
:returns: backen... | AttributeError | dataset/ETHPy150Open stefanfoulis/django-sendsms/sendsms/api.py/get_connection |
6,086 | @classmethod
def callable_info(cls, f):
'''Info about a callable.
The results are cached for efficiency.
:param f:
:type f: callable
:rtype: frozendict
'''
if not callable(f):
return None
if isinstance(f, FunctionType):
# in case of ensure_va_kwa
try:
... | AttributeError | dataset/ETHPy150Open rsms/smisk/lib/smisk/util/introspect.py/introspect.callable_info |
6,087 | @classmethod
def ensure_va_kwa(cls, f, parent=None):
'''Ensures `f` accepts both ``*varargs`` and ``**kwargs``.
If `f` does not support ``*args``, it will be wrapped with a
function which cuts away extra arguments in ``*args``.
If `f` does not support ``*args``, it will be wrapped with a
... | AttributeError | dataset/ETHPy150Open rsms/smisk/lib/smisk/util/introspect.py/introspect.ensure_va_kwa |
6,088 | def _mk_exception(exception, name=None):
# Create an exception inheriting from both JoblibException
# and that exception
if name is None:
name = exception.__name__
this_name = 'Joblib%s' % name
if this_name in _exception_mapping:
# Avoid creating twice the same exception
this... | TypeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/externals/joblib/my_exceptions.py/_mk_exception |
6,089 | def openfile(path, mode="r", *args, **kw):
"""Open file
Aside from the normal modes accepted by `open()`, this function
accepts an `x` mode that causes the file to be opened for exclusive-
write, which means that an exception (`FileExists`) will be raised
if the file being opened already exists.
... | OSError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/blobs/fsdb.py/openfile |
6,090 | @staticmethod
def parser(config_file):
if not ConfigParser.result:
try:
with open(config_file, 'r') as stream:
cfg = yaml.load(stream)
except __HOLE__:
raise FlashLightExceptions("{0} cannot be opened !!!".format(config_file))
except Exception, err:
raise FlashLightExceptions... | IOError | dataset/ETHPy150Open galkan/flashlight/lib/core/config_parser.py/ConfigParser.parser |
6,091 | @staticmethod
def get_screen_ports(config_file):
cfg = ConfigParser.parser if ConfigParser.result else ConfigParser.parser(config_file)
try:
return cfg["screen_ports"]
except __HOLE__:
return ConfigParser.default_port... | KeyError | dataset/ETHPy150Open galkan/flashlight/lib/core/config_parser.py/ConfigParser.get_screen_ports |
6,092 | def open(self, path, flags, attr):
path = self.files.normalize(path)
try:
fobj = self.files[path]
except __HOLE__:
if flags & os.O_WRONLY:
# Only allow writes to files in existing directories.
if os.path.dirname(path) not in self.files:
... | KeyError | dataset/ETHPy150Open fabric/fabric/tests/server.py/FakeSFTPServer.open |
6,093 | def stat(self, path):
path = self.files.normalize(path)
try:
fobj = self.files[path]
except __HOLE__:
return ssh.SFTP_NO_SUCH_FILE
return fobj.attributes
# Don't care about links right now | KeyError | dataset/ETHPy150Open fabric/fabric/tests/server.py/FakeSFTPServer.stat |
6,094 | def logEI_gaussian(mean, var, thresh):
"""Return log(EI(mean, var, thresh))
This formula avoids underflow in cdf for
thresh >= mean + 37 * sqrt(var)
"""
assert np.asarray(var).min() >= 0
sigma = np.sqrt(var)
score = (mean - thresh) / sigma
n = scipy.stats.norm
try:
floa... | TypeError | dataset/ETHPy150Open hyperopt/hyperopt/hyperopt/criteria.py/logEI_gaussian |
6,095 | def _validate_property_values(self, properties):
"""Check if the input of local_gb, cpus and memory_mb are valid.
:param properties: a dict contains the node's information.
"""
if not properties:
return
invalid_msgs_list = []
for param in REQUIRED_INT_PROPERT... | AssertionError | dataset/ETHPy150Open openstack/ironic/ironic/objects/node.py/Node._validate_property_values |
6,096 | @utils.synchronized('connect_volume')
def connect_volume(self, connection_info, disk_info):
"""Connect the volume."""
data = connection_info['data']
quobyte_volume = self._normalize_export(data['export'])
mount_path = self._get_mount_path(connection_info)
mounted = libvirt_ut... | OSError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/libvirt/volume/quobyte.py/LibvirtQuobyteVolumeDriver.connect_volume |
6,097 | def short(self, url):
params = json.dumps({'longUrl': url})
headers = {'content-type': 'application/json'}
url = '{0}?key={1}'.format(self.api_url, self.api_key)
response = self._post(url, data=params, headers=headers)
if response.ok:
try:
data = respo... | ValueError | dataset/ETHPy150Open ellisonleao/pyshorteners/pyshorteners/shorteners/googl.py/Google.short |
6,098 | def expand(self, url):
params = {'shortUrl': url}
url = '{0}?key={1}'.format(self.api_url, self.api_key)
response = self._get(url, params=params)
if response.ok:
try:
data = response.json()
except __HOLE__:
raise ExpandingErrorExce... | ValueError | dataset/ETHPy150Open ellisonleao/pyshorteners/pyshorteners/shorteners/googl.py/Google.expand |
6,099 | def get_cache_stats():
"""Return a dictionary containing information on the current cache stats.
This only supports memcache.
"""
hostnames = get_memcached_hosts()
if not hostnames:
return None
all_stats = []
for hostname in hostnames:
try:
host, port = hostna... | ValueError | dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/admin/cache_stats.py/get_cache_stats |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.