Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
2,600 | def do_remove_data(self, data, distance, mtree):
for child in self.children.itervalues():
if abs(distance - child.distance_to_parent) <= child.radius: # TODO: confirm
distance_to_child = mtree.distance_function(data, child.data)
if distance_to_child <= child.radius:
try:
child.remove_data(data... | KeyError | dataset/ETHPy150Open erdavila/M-Tree/py/mtree/__init__.py/_NonLeafNodeTrait.do_remove_data |
2,601 | def __getattribute__(self, name):
try:
return WebObRequest.__getattribute__(self, name)
except __HOLE__ as e:
logger.exception(e)
abort(400) | UnicodeDecodeError | dataset/ETHPy150Open pecan/pecan/pecan/core.py/Request.__getattribute__ |
2,602 | def proxy(key):
class ObjectProxy(object):
explanation_ = AttributeError(
"`pecan.state` is not bound to a context-local context.\n"
"Ensure that you're accessing `pecan.request` or `pecan.response` "
"from within the context of a WSGI `__call__` and that "
"... | AttributeError | dataset/ETHPy150Open pecan/pecan/pecan/core.py/proxy |
2,603 | def find_controller(self, state):
'''
The main request handler for Pecan applications.
'''
# get a sorted list of hooks, by priority (no controller hooks yet)
req = state.request
pecan_state = req.pecan
# store the routing path for the current application to allo... | TypeError | dataset/ETHPy150Open pecan/pecan/pecan/core.py/PecanBase.find_controller |
2,604 | def _handle_empty_response_body(self, state):
# Enforce HTTP 204 for responses which contain no body
if state.response.status_int == 200:
# If the response is a generator...
if isinstance(state.response.app_iter, types.GeneratorType):
# Split the generator into tw... | UnicodeDecodeError | dataset/ETHPy150Open pecan/pecan/pecan/core.py/PecanBase._handle_empty_response_body |
2,605 | def get_args(self, state, all_params, remainder, argspec, im_self):
# When comparing the argspec of the method to GET/POST params,
# ignore the implicit (req, resp) at the beginning of the function
# signature
if hasattr(state.controller, '__self__'):
_repr = '.'.join((
... | IndexError | dataset/ETHPy150Open pecan/pecan/pecan/core.py/ExplicitPecan.get_args |
2,606 | @cached
@gen.coroutine
def get(self, secure, netloc, url):
proto = 'http' + secure
netloc = url_unescape(netloc)
if '/?' in url:
url, query = url.rsplit('/?', 1)
else:
query = None
remote_url = u"{}://{}/{}".format(proto, netloc, quote(url))
... | UnicodeDecodeError | dataset/ETHPy150Open jupyter/nbviewer/nbviewer/providers/url/handlers.py/URLHandler.get |
2,607 | def parse(self, stream):
""" parse unified diff
return True on success
"""
lineends = dict(lf=0, crlf=0, cr=0)
nexthunkno = 0 #: even if index starts with 0 user messages number hunks from 1
p = None
hunk = None
# hunkactual variable is used to calculate hun... | StopIteration | dataset/ETHPy150Open ensime/ensime-sublime/patch.py/PatchSet.parse |
2,608 | def apply(self, strip=0, root=None):
""" Apply parsed patch, optionally stripping leading components
from file paths. `root` parameter specifies working dir.
return True on success
"""
if root:
prevdir = os.getcwd()
os.chdir(root)
total = len(self.ite... | ValueError | dataset/ETHPy150Open ensime/ensime-sublime/patch.py/PatchSet.apply |
2,609 | def get_console(request, console_type, instance):
"""Get a console url based on console type."""
if console_type == 'AUTO':
check_consoles = CONSOLES
else:
try:
check_consoles = {'console_type': CONSOLES[console_type]}
except KeyError:
msg = _('Console type "%... | AttributeError | dataset/ETHPy150Open CiscoSystems/avos/openstack_dashboard/dashboards/project/instances/console.py/get_console |
2,610 | def _process_data(self):
# Process all incoming data until there are no more complete packets.
while len(self._buffer):
if self._expecting_ack:
self._expecting_ack = False
self._check_expected_ack()
# Check for a ctrl-c.
if len(self._b... | ValueError | dataset/ETHPy150Open mbedmicro/pyOCD/pyOCD/gdbserver/gdbserver.py/GDBServerPacketIOThread._process_data |
2,611 | @classmethod
def cache_distribution(cls, zf, source, target_dir):
"""Possibly cache an egg from within a zipfile into target_cache.
Given a zipfile handle and a filename corresponding to an egg distribution within
that zip, maybe write to the target cache and return a Distribution."""
dependenc... | OSError | dataset/ETHPy150Open pantsbuild/pex/pex/util.py/CacheHelper.cache_distribution |
2,612 | def open(self, desktop=None):
"""
Open a dialogue box (dialog) using a program appropriate to the desktop
environment in use.
If the optional 'desktop' parameter is specified then attempt to use
that particular desktop environment's mechanisms to open the dialog
instead... | KeyError | dataset/ETHPy150Open JT5D/Alfred-Popclip-Sublime/Sublime Text 2/SideBarEnhancements/sidebar/desktop/dialog.py/Dialogue.open |
2,613 | def _getBuiltinExceptionNames():
def isExceptionName(builtin_name):
if builtin_name.endswith("Error") or \
builtin_name.endswith("Exception"):
return True
elif builtin_name in ("StopIteration", "GeneratorExit", "SystemExit",
"NotImplemented", "Key... | ImportError | dataset/ETHPy150Open kayhayen/Nuitka/nuitka/Builtins.py/_getBuiltinExceptionNames |
2,614 | def Add(self, ports, kind, allow_privileged=False, prohibited_host_ports=()):
"""Load port configurations and adds them to an internal dict.
Args:
ports: A list of strings or a CSV representing port forwarding.
kind: what kind of port configuration this is, only used for error
reporting.
... | ValueError | dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/client/services/port_manager.py/PortManager.Add |
2,615 | def moderation_queue(request):
"""
Displays a list of unapproved comments to be approved.
Templates: `comments/moderation_queue.html`
Context:
comments
Comments to be approved (paginated).
empty
Is the comment list empty?
is_paginated
Is there... | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/contrib/comments/views/moderation.py/moderation_queue |
2,616 | @staticmethod
def find_file(names, tail):
try:
return next(n for n in names if n.endswith(tail))
except __HOLE__:
return None | StopIteration | dataset/ETHPy150Open SMFOSS/CheesePrism/cheeseprism/pipext.py/RequirementDownloader.find_file |
2,617 | def handle_requirement(self, req, finder):
"""
Download requirement, return a new requirement set of
requirements dependencies.
"""
if req.editable:
msg = "Editables not supported: %s" %req
logger.warn(msg)
self.errors.append("%s: %s" %(req, ms... | HTTPError | dataset/ETHPy150Open SMFOSS/CheesePrism/cheeseprism/pipext.py/RequirementDownloader.handle_requirement |
2,618 | def accept(self, match, include_rejected=False, include_denied=False):
'''
Accept the keys matched
:param str match: A string to match against. i.e. 'web*'
:param bool include_rejected: Whether or not to accept a matched key that was formerly rejected
:param bool include_denied:... | KeyboardInterrupt | dataset/ETHPy150Open saltstack/salt/salt/key.py/KeyCLI.accept |
2,619 | def delete(self, match):
'''
Delete the matched keys
:param str match: A string to match against. i.e. 'web*'
'''
def _print_deleted(matches, after_match):
deleted = []
for keydir in (self.key.ACC, self.key.PEND, self.key.REJ):
deleted.ext... | KeyboardInterrupt | dataset/ETHPy150Open saltstack/salt/salt/key.py/KeyCLI.delete |
2,620 | def list_keys(self):
'''
Return a dict of managed keys and what the key status are
'''
key_dirs = []
# We have to differentiate between RaetKey._check_minions_directories
# and Zeromq-Keys. Raet-Keys only have three states while ZeroMQ-keys
# havd an additional ... | IOError | dataset/ETHPy150Open saltstack/salt/salt/key.py/Key.list_keys |
2,621 | def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.nam... | IOError | dataset/ETHPy150Open saltstack/salt/salt/key.py/Key.accept |
2,622 | def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
... | IOError | dataset/ETHPy150Open saltstack/salt/salt/key.py/Key.accept_all |
2,623 | def delete_key(self,
match=None,
match_dict=None,
preserve_minions=False,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "matc... | IOError | dataset/ETHPy150Open saltstack/salt/salt/key.py/Key.delete_key |
2,624 | def delete_den(self):
'''
Delete all denied keys
'''
keys = self.list_keys()
for status, keys in six.iteritems(self.list_keys()):
for key in keys[self.DEN]:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
... | OSError | dataset/ETHPy150Open saltstack/salt/salt/key.py/Key.delete_den |
2,625 | def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
eload = {'result': True,
... | OSError | dataset/ETHPy150Open saltstack/salt/salt/key.py/Key.delete_all |
2,626 | def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.nam... | OSError | dataset/ETHPy150Open saltstack/salt/salt/key.py/Key.reject |
2,627 | def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
... | OSError | dataset/ETHPy150Open saltstack/salt/salt/key.py/Key.reject_all |
2,628 | def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
'''
Accept public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.nam... | IOError | dataset/ETHPy150Open saltstack/salt/salt/key.py/RaetKey.accept |
2,629 | def accept_all(self):
'''
Accept all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
... | IOError | dataset/ETHPy150Open saltstack/salt/salt/key.py/RaetKey.accept_all |
2,630 | def delete_key(self,
match=None,
match_dict=None,
preserve_minions=False,
revoke_auth=False):
'''
Delete public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_di... | OSError | dataset/ETHPy150Open saltstack/salt/salt/key.py/RaetKey.delete_key |
2,631 | def delete_all(self):
'''
Delete all keys
'''
for status, keys in six.iteritems(self.list_keys()):
for key in keys:
try:
os.remove(os.path.join(self.opts['pki_dir'], status, key))
except (__HOLE__, IOError):
... | OSError | dataset/ETHPy150Open saltstack/salt/salt/key.py/RaetKey.delete_all |
2,632 | def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
'''
Reject public keys. If "match" is passed, it is evaluated as a glob.
Pre-gathered matches can also be passed via "match_dict".
'''
if match is not None:
matches = self.nam... | IOError | dataset/ETHPy150Open saltstack/salt/salt/key.py/RaetKey.reject |
2,633 | def reject_all(self):
'''
Reject all keys in pre
'''
keys = self.list_keys()
for key in keys[self.PEND]:
try:
shutil.move(
os.path.join(
self.opts['pki_dir'],
self.PEND,
... | IOError | dataset/ETHPy150Open saltstack/salt/salt/key.py/RaetKey.reject_all |
2,634 | def run(self):
# determine the sender's ip address from the email headers
ip_address = None
try:
headers = self.email_dict['headers']
for hdr in ['X-Originating-IP', # preferred header order to use
'X-Source-IP',
'X-Source',... | KeyError | dataset/ETHPy150Open dpapathanasiou/intelligent-smtp-responder/agents/weather_response_example.py/reply_weather.run |
2,635 | def unpack(*arguments):
"""
Unpack arguments to be used in methods wrapped
"""
def decorator(func):
def wrapper(_self, data, **kwargs):
data = smart_parse(data)
try:
args = [data[item] for item in arguments]
except __HOLE__:
rai... | KeyError | dataset/ETHPy150Open sihrc/tornado-boilerplate/indico/utils/__init__.py/unpack |
2,636 | def form_urlencoded_parse(body):
"""
Parse x-www-form-url encoded data
"""
try:
data = urlparse.parse_qs(body, strict_parsing=True)
for key in data:
data[key] = data[key][0]
return data
except __HOLE__:
raise InvalidJSON() | ValueError | dataset/ETHPy150Open sihrc/tornado-boilerplate/indico/utils/__init__.py/form_urlencoded_parse |
2,637 | def smart_parse(body):
"""
Handle json, fall back to x-www-form-urlencoded
"""
try:
data_dict = json.loads(body)
except __HOLE__:
return form_urlencoded_parse(body)
return data_dict | ValueError | dataset/ETHPy150Open sihrc/tornado-boilerplate/indico/utils/__init__.py/smart_parse |
2,638 | def config(settings):
"""
Template for Washington Common Operating Picture (WA-COP)
http://psmcop.org
"""
T = current.T
s3 = current.response.s3
# -----------------------------------------------------------------------------
# Pre-Populate
settings.base.prepopulate += ("MC... | IOError | dataset/ETHPy150Open sahana/eden/modules/templates/MCOP/config.py/config |
2,639 | def _register_patched_dtype_reduce():
"""
Numpy < 1.7 has a bug when copying/pickling dtype objects with a
zero-width void type--i.e. ``np.dtype('V0')``. Specifically, although
creating a void type is perfectly valid, it crashes when instantiating
a dtype using a format string of 'V0', which is wha... | ImportError | dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/_compat/__init__.py/_register_patched_dtype_reduce |
2,640 | def test_invalid_option(runner):
try:
@click.command()
@click.option('foo')
def cli(foo):
pass
except __HOLE__ as e:
assert 'No options defined but a name was passed (foo).' \
in str(e)
else:
assert False, 'Expected a type error because of an i... | TypeError | dataset/ETHPy150Open pallets/click/tests/test_options.py/test_invalid_option |
2,641 | def test_invalid_nargs(runner):
try:
@click.command()
@click.option('--foo', nargs=-1)
def cli(foo):
pass
except __HOLE__ as e:
assert 'Options cannot have nargs < 0' in str(e)
else:
assert False, 'Expected a type error because of an invalid option.' | TypeError | dataset/ETHPy150Open pallets/click/tests/test_options.py/test_invalid_nargs |
2,642 | def formfield_for_dbfield(self, db_field, **kwargs):
# Allow to use formfield_overrides using a fieldname too.
# Avoids the major need to reroute formfield_for_dbfield() via the plugin.
try:
attrs = self.formfield_overrides[db_field.name]
kwargs = dict(attrs, **kwargs)
... | KeyError | dataset/ETHPy150Open edoburu/django-fluent-contents/fluent_contents/admin/contentitems.py/BaseContentItemInline.formfield_for_dbfield |
2,643 | def reserveConfirmed(self, nsi_header, connection_id, global_reservation_id, description, service_parameters):
try:
nsi_header = self.notifications.pop( (connection_id, RESERVE_RESPONSE) )
d = self.provider_client.reserveConfirmed(nsi_header, connection_id, global_reservation_id, descrip... | KeyError | dataset/ETHPy150Open NORDUnet/opennsa/opennsa/protocols/nsi2/provider.py/Provider.reserveConfirmed |
2,644 | def reserveFailed(self, nsi_header, connection_id, connection_states, err):
try:
nsi_header = self.notifications.pop( (connection_id, RESERVE_RESPONSE) )
d = self.provider_client.reserveFailed(nsi_header, connection_id, connection_states, err)
d.addErrback(logError, 'reserveF... | KeyError | dataset/ETHPy150Open NORDUnet/opennsa/opennsa/protocols/nsi2/provider.py/Provider.reserveFailed |
2,645 | def reserveCommitConfirmed(self, header, connection_id):
try:
org_header = self.notifications.pop( (connection_id, RESERVE_COMMIT_RESPONSE) )
d = self.provider_client.reserveCommitConfirmed(org_header.reply_to, org_header.requester_nsa, org_header.provider_nsa, org_header.correlation_id... | KeyError | dataset/ETHPy150Open NORDUnet/opennsa/opennsa/protocols/nsi2/provider.py/Provider.reserveCommitConfirmed |
2,646 | def reserveAbortConfirmed(self, header, connection_id):
try:
org_header = self.notifications.pop( (connection_id, RESERVE_ABORT_RESPONSE) )
d = self.provider_client.reserveAbortConfirmed(org_header.reply_to, org_header.requester_nsa, org_header.provider_nsa, org_header.correlation_id, c... | KeyError | dataset/ETHPy150Open NORDUnet/opennsa/opennsa/protocols/nsi2/provider.py/Provider.reserveAbortConfirmed |
2,647 | def provisionConfirmed(self, header, connection_id):
try:
org_header = self.notifications.pop( (connection_id, PROVISION_RESPONSE) )
d = self.provider_client.provisionConfirmed(org_header.reply_to, org_header.correlation_id, org_header.requester_nsa, org_header.provider_nsa, connection_... | KeyError | dataset/ETHPy150Open NORDUnet/opennsa/opennsa/protocols/nsi2/provider.py/Provider.provisionConfirmed |
2,648 | def releaseConfirmed(self, header, connection_id):
try:
org_header = self.notifications.pop( (connection_id, RELEASE_RESPONSE) )
d = self.provider_client.releaseConfirmed(org_header.reply_to, org_header.correlation_id, org_header.requester_nsa, org_header.provider_nsa, connection_id)
... | KeyError | dataset/ETHPy150Open NORDUnet/opennsa/opennsa/protocols/nsi2/provider.py/Provider.releaseConfirmed |
2,649 | def terminateConfirmed(self, header, connection_id):
try:
org_header = self.notifications.pop( (connection_id, TERMINATE_RESPONSE) )
return self.provider_client.terminateConfirmed(org_header.reply_to, org_header.correlation_id, org_header.requester_nsa, org_header.provider_nsa, connecti... | KeyError | dataset/ETHPy150Open NORDUnet/opennsa/opennsa/protocols/nsi2/provider.py/Provider.terminateConfirmed |
2,650 | def get_by_id(self, styleId):
"""
Return the ``<w:style>`` child element having ``styleId`` attribute
matching *styleId*, or |None| if not found.
"""
xpath = 'w:style[@w:styleId="%s"]' % styleId
try:
return self.xpath(xpath)[0]
except __HOLE__:
... | IndexError | dataset/ETHPy150Open python-openxml/python-docx/docx/oxml/styles.py/CT_Styles.get_by_id |
2,651 | def get_by_name(self, name):
"""
Return the ``<w:style>`` child element having ``<w:name>`` child
element with value *name*, or |None| if not found.
"""
xpath = 'w:style[w:name/@w:val="%s"]' % name
try:
return self.xpath(xpath)[0]
except __HOLE__:
... | IndexError | dataset/ETHPy150Open python-openxml/python-docx/docx/oxml/styles.py/CT_Styles.get_by_name |
2,652 | def test_invalid_server_name():
ips = ["1.1.1.1"]
bad_server = "garbage.invalid"
bw = setup_server()
bw.server = bad_server
try:
bw.lookup_ips(ips)
except __HOLE__ as e:
print e
assert str(e) == "Couldn't connect to %s:%s" % (bad_server, bw.port), e
except Exception a... | IOError | dataset/ETHPy150Open csirtfoundry/BulkWhois/tests/bulkwhois_tests.py/test_invalid_server_name |
2,653 | def get_storage(path, *args, **kwargs):
i = path.rfind('.')
module, attr = path[:i], path[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise MissingStorageModule(
'Error loading storage %s: "%s"' % (module, e))
try:
storage_class = getattr(mod, at... | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/formtools/wizard/storage/__init__.py/get_storage |
2,654 | def find_filegroups(paths, substring='', extensions=None, validity_check=True,
ignore_invisible=True, rstrip='', ignore_substring=None):
"""Find and collect files from different directories in a python dictionary.
Parameters
----------
paths : `list`
Paths of the directories... | KeyError | dataset/ETHPy150Open rasbt/mlxtend/mlxtend/file_io/find_filegroups.py/find_filegroups |
2,655 | def __setattr__(self, key, value):
if key == '_attributes':
super(Fluent, self).__setattr__(key, value)
try:
super(Fluent, self).__getattribute__(key)
return super(Fluent, self).__setattr__(key, value)
except __HOLE__:
pass
self._attribu... | AttributeError | dataset/ETHPy150Open sdispater/orator/orator/support/fluent.py/Fluent.__setattr__ |
2,656 | def importMACS( infile, outfile, suffix = ".norm.bam" ):
'''import MACS results.
Imports only positive peaks. It filters peaks by p-value,
q-value and fold change and imports the diagnostic data.
Does re-counting of peakcenter, peakval, ... using
the normalized tag counts.
'''
track = inf... | OSError | dataset/ETHPy150Open CGATOxford/cgat/obsolete/pipeline_vitaminD_intervals.py/importMACS |
2,657 | def makeIntervalCorrelation( infiles, outfile, field ):
'''compute correlation of interval properties between sets
'''
dbhandle = sqlite3.connect( PARAMS["database"] )
tracks, idx = [], []
for infile in infiles:
track = infile[:-len(".bed")]
cc = dbhandle.cursor()
statement... | KeyError | dataset/ETHPy150Open CGATOxford/cgat/obsolete/pipeline_vitaminD_intervals.py/makeIntervalCorrelation |
2,658 | def listclasses(self):
dir, file = os.path.split(self.file)
name, ext = os.path.splitext(file)
if os.path.normcase(ext) != ".py":
return []
try:
dict = pyclbr.readmodule_ex(name, [dir] + sys.path)
except __HOLE__:
return []
items = []
... | ImportError | dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/idlelib/ClassBrowser.py/ModuleBrowserTreeItem.listclasses |
2,659 | def __init__(self, name, classes, file):
self.name = name
self.classes = classes
self.file = file
try:
self.cl = self.classes[self.name]
except (__HOLE__, KeyError):
self.cl = None
self.isfunction = isinstance(self.cl, pyclbr.Function) | IndexError | dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/idlelib/ClassBrowser.py/ClassBrowserTreeItem.__init__ |
2,660 | def IsExpandable(self):
if self.cl:
try:
return not not self.cl.methods
except __HOLE__:
return False | AttributeError | dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/idlelib/ClassBrowser.py/ClassBrowserTreeItem.IsExpandable |
2,661 | def _class_browser(parent): #Wrapper for htest
try:
file = __file__
except __HOLE__:
file = sys.argv[0]
if sys.argv[1:]:
file = sys.argv[1]
else:
file = sys.argv[0]
dir, file = os.path.split(file)
name = os.path.splitext(file)[0]
flist = PyShel... | NameError | dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/idlelib/ClassBrowser.py/_class_browser |
2,662 | def _address_to_hosts(self, addresses):
"""Iterate over hosts within an address range.
If an explicit range specifier is missing, the parameter is
interpreted as a specific individual address.
"""
try:
return [netaddr.IPAddress(addresses)]
except __HOLE__:
... | ValueError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/floating_ips_bulk.py/FloatingIPBulkController._address_to_hosts |
2,663 | def get_height(self):
try:
return os.path.getsize(self.path)/80 - 1
except __HOLE__, e:
return 0 | OSError | dataset/ETHPy150Open chromaway/ngcccbase/ngcccbase/blockchain.py/FileStore.get_height |
2,664 | def read_raw_header(self, height):
try:
with open(self.path, 'rb') as store:
store.seek(height*80)
data = store.read(80)
assert len(data) == 80
return data
except (OSError, __HOLE__), e:
return None | AssertionError | dataset/ETHPy150Open chromaway/ngcccbase/ngcccbase/blockchain.py/FileStore.read_raw_header |
2,665 | def verify_chunk(self, index, chunk):
height = index*2016
num = len(chunk)/80
if index == 0:
prev_hash = ("0"*64)
else:
prev_header = self.store.read_header(index*2016-1)
if prev_header is None:
raise
prev_hash = self.has... | AssertionError | dataset/ETHPy150Open chromaway/ngcccbase/ngcccbase/blockchain.py/BlockHashingAlgorithm.verify_chunk |
2,666 | def verify_chain(self, chain):
prev_header = self.store.read_header(chain[0].get('block_height')-1)
prev_hash = self.hash_header(self.store.header_to_raw(prev_header))
for header in chain:
bits, target = self.get_target(header.get('block_height')/2016, chain)
_hash = sel... | AssertionError | dataset/ETHPy150Open chromaway/ngcccbase/ngcccbase/blockchain.py/BlockHashingAlgorithm.verify_chain |
2,667 | def testGraphDisplay(self):
try:
import networkx
import matplotlib
except __HOLE__ as error:
logging.debug(error)
return
#Show
numFeatures = 1
numVertices = 20
vList = VertexList(numVertices, numFeatures)
graph = ... | ImportError | dataset/ETHPy150Open charanpald/APGL/apgl/generator/test/BarabasiAlbertGeneratorTest.py/BarabasiAlbertGeneratorTest.testGraphDisplay |
2,668 | def import_string(import_name, silent=False):
"""Imports an object based on a string. This use useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sa... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/utils.py/import_string |
2,669 | def open_if_exists(filename, mode='rb'):
"""Returns a file descriptor for the filename if that file exists,
otherwise `None`.
"""
try:
return open(filename, mode)
except __HOLE__, e:
if e.errno not in (errno.ENOENT, errno.EISDIR):
raise | IOError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/utils.py/open_if_exists |
2,670 | def pformat(obj, verbose=False):
"""Prettyprint an object. Either use the `pretty` library or the
builtin `pprint`.
"""
try:
from pretty import pretty
return pretty(obj, verbose=verbose)
except __HOLE__:
from pprint import pformat
return pformat(obj) | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/utils.py/pformat |
2,671 | def get(self, key, default=None):
"""Return an item from the cache dict or `default`"""
try:
return self[key]
except __HOLE__:
return default | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/utils.py/LRUCache.get |
2,672 | def setdefault(self, key, default=None):
"""Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key.
"""
try:
return self[key]
except __HOLE__:
self[key] = default
return default | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/utils.py/LRUCache.setdefault |
2,673 | def __getitem__(self, key):
"""Get an item from the cache. Moves the item up so that it has the
highest priority then.
Raise an `KeyError` if it does not exist.
"""
rv = self._mapping[key]
if self._queue[-1] != key:
try:
self._remove(key)
... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/utils.py/LRUCache.__getitem__ |
2,674 | def __setitem__(self, key, value):
"""Sets the value for an item. Moves the item up so that it
has the highest priority then.
"""
self._wlock.acquire()
try:
if key in self._mapping:
try:
self._remove(key)
except __HO... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/utils.py/LRUCache.__setitem__ |
2,675 | def __delitem__(self, key):
"""Remove an item from the cache dict.
Raise an `KeyError` if it does not exist.
"""
self._wlock.acquire()
try:
del self._mapping[key]
try:
self._remove(key)
except __HOLE__:
# __getit... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/utils.py/LRUCache.__delitem__ |
2,676 | def acquire_lock(self, name):
"""
Wait for a lock with name.
This will prevent other processes from acquiring the lock with the name while it is held.
Thus they will wait in the position where they are acquiring the lock until the process
that has it releases it.
"""
... | RuntimeError | dataset/ETHPy150Open mkorpela/pabot/pabot/PabotLib.py/PabotLib.acquire_lock |
2,677 | def acquire_value_set(self):
"""
Reserve a set of values for this execution.
No other process can reserve the same set of values while the set is reserved.
Acquired value set needs to be released after use to allow other processes
to access it.
"""
if self._remote... | RuntimeError | dataset/ETHPy150Open mkorpela/pabot/pabot/PabotLib.py/PabotLib.acquire_value_set |
2,678 | def get_objects_name(self):
try:
profile = self.profile_list
return "User: %s" % profile.username
except ObjectDoesNotExist:
pass
try:
book = self.book_list
return "Book: \"%s\", author: %s" % (book.name, book.default_author.username)
... | ObjectDoesNotExist | dataset/ETHPy150Open ProstoKSI/django-voter/voter/models.py/Rating.get_objects_name |
2,679 | def action_shell(params):
from nailgun.db import db
from nailgun.settings import settings
if params.config_file:
settings.update_from_file(params.config_file)
try:
from IPython import embed
embed()
except __HOLE__:
code.interact(local={'db': db, 'settings': settings}... | ImportError | dataset/ETHPy150Open openstack/fuel-web/nailgun/manage.py/action_shell |
2,680 | def __init__(self, params, offset=0):
agents.Agent.__init__(self, params, offset)
try:
self.maxprice = self.args[0]
except (AttributeError, IndexError):
raise MissingParameter, 'maxprice'
try:
self.maxbuy = self.args[1]
except __HOLE__:
... | IndexError | dataset/ETHPy150Open jcbagneris/fms/fms/contrib/coleman/agents/smartmem5trader.py/SmartMem5Trader.__init__ |
2,681 | def act(self, world=None, market=None):
"""
Return order as a dict with keys in (direction, price, quantity).
If SELL, pick price between highest success, next highest bid.
If BUY, pick price between lowest success, next lowest bid.
Avoid short selling and levering up (borrowing... | ValueError | dataset/ETHPy150Open jcbagneris/fms/fms/contrib/coleman/agents/smartmem5trader.py/SmartMem5Trader.act |
2,682 | def wantMethod(self, method):
# only works with unittest compatible functions currently
method = getattr(sys.modules[method.im_class.__module__], method.im_class.__name__)
try:
# check if this test was modified (e.g. added/changed)
filename = inspect.getfile(method)
... | TypeError | dataset/ETHPy150Open dcramer/quickunit/quickunit/plugin.py/QuickUnitPlugin.wantMethod |
2,683 | def analyze(self, opts, cluster_stats):
try:
warning = int(opts.warning)
critical = int(opts.critical)
except (__HOLE__, ValueError):
print >>sys.stderr, 'Invalid values for "warning" and "critical".'
return 2
if opts.key is None:
pri... | TypeError | dataset/ETHPy150Open andreisavu/zookeeper-monitoring/check_zookeeper.py/NagiosHandler.analyze |
2,684 | def analyze(self, opts, cluster_stats):
if opts.key is None:
print >>sys.stderr, 'The key name is mandatory.'
return 1
if opts.leader is True:
try:
leader = [x for x in cluster_stats.values() \
if x.get('zk_server_state', '') == 'l... | IndexError | dataset/ETHPy150Open andreisavu/zookeeper-monitoring/check_zookeeper.py/CactiHandler.analyze |
2,685 | def analyze(self, opts, cluster_stats):
if len(cluster_stats) != 1:
print >>sys.stderr, 'Only allowed to monitor a single node.'
return 1
for host, stats in cluster_stats.items():
for k, v in stats.items():
try:
self.call([opts.gme... | TypeError | dataset/ETHPy150Open andreisavu/zookeeper-monitoring/check_zookeeper.py/GangliaHandler.analyze |
2,686 | def _parse(self, data):
""" Parse the output from the 'mntr' 4letter word command """
h = StringIO(data)
result = {}
for line in h.readlines():
try:
key, value = self._parse_line(line)
result[key] = value
except __HOLE__:
... | ValueError | dataset/ETHPy150Open andreisavu/zookeeper-monitoring/check_zookeeper.py/ZooKeeperServer._parse |
2,687 | def _parse_line(self, line):
try:
key, value = map(str.strip, line.split('\t'))
except ValueError:
raise ValueError('Found invalid line: %s' % line)
if not key:
raise ValueError('The key is mandatory and should not be empty')
try:
value =... | TypeError | dataset/ETHPy150Open andreisavu/zookeeper-monitoring/check_zookeeper.py/ZooKeeperServer._parse_line |
2,688 | def create_handler(name):
""" Return an instance of a platform specific analyzer """
try:
return globals()['%sHandler' % name.capitalize()]()
except __HOLE__:
return None | KeyError | dataset/ETHPy150Open andreisavu/zookeeper-monitoring/check_zookeeper.py/create_handler |
2,689 | def _solve_n_slack_qp(self, constraints, n_samples):
C = self.C
joint_features = [c[1] for sample in constraints for c in sample]
losses = [c[2] for sample in constraints for c in sample]
joint_feature_matrix = np.vstack(joint_features).astype(np.float)
n_constraints = len(joint... | ValueError | dataset/ETHPy150Open pystruct/pystruct/pystruct/learners/n_slack_ssvm.py/NSlackSSVM._solve_n_slack_qp |
2,690 | def fit(self, X, Y, constraints=None, warm_start=None, initialize=True):
"""Learn parameters using cutting plane method.
Parameters
----------
X : iterable
Traing instances. Contains the structured input objects.
No requirement on the particular form of entries o... | KeyboardInterrupt | dataset/ETHPy150Open pystruct/pystruct/pystruct/learners/n_slack_ssvm.py/NSlackSSVM.fit |
2,691 | def main(opt):
from aero_kernels import dirichlet, dotPV, dotR, init_cg, res_calc, spMV, \
update, updateP, updateUR
try:
with h5py.File(opt['mesh'], 'r') as f:
# sets
nodes = op2.Set.fromhdf5(f, 'nodes')
bnodes = op2.Set.fromhdf5(f, 'bedges')
cell... | IOError | dataset/ETHPy150Open OP2/PyOP2/demo/aero.py/main |
2,692 | def get_serializer(alias):
alias = alias or MOMENT_SERIALIZER
if hasattr(alias, 'loads'):
return alias
try:
return _serializers[alias]
except __HOLE__:
raise LookupError("Serializer `{}` not configured.".format(alias)) | KeyError | dataset/ETHPy150Open caxap/redis-moment/moment/conf.py/get_serializer |
2,693 | def get_connection(alias='default'):
global _connections
if isinstance(alias, redis.StrictRedis):
return alias
try:
return _connections[alias]
except __HOLE__:
raise LookupError("Connection `{}` not configured.".format(alias)) | KeyError | dataset/ETHPy150Open caxap/redis-moment/moment/conf.py/get_connection |
2,694 | def _get_schema(self):
time_now = int(datetime.datetime.utcnow().strftime('%s'))
if ((self.column_families is None or
(time_now - self.last_schema_sync_time < 3600))):
return False
url = 'http://%s:%i/%s/keyspaces' % (self.config['host'],
... | ValueError | dataset/ETHPy150Open python-diamond/Diamond/src/collectors/dseopscenter/dseopscenter.py/DseOpsCenterCollector._get_schema |
2,695 | def _get(self, start, end, step=60):
self._get_schema()
url = ('http://%s:%i/%s/new-metrics?node_group=%s&columnfamilies=%s'
'&metrics=%s&start=%i&end=%i&step=%i%s') % (
self.config['host'],
int(self.config['port']),
self.config['cluster_id'],
... | TypeError | dataset/ETHPy150Open python-diamond/Diamond/src/collectors/dseopscenter/dseopscenter.py/DseOpsCenterCollector._get |
2,696 | def item_link(self, item):
try:
return item.get_absolute_url()
except __HOLE__:
raise ImproperlyConfigured, "Give your %s class a get_absolute_url() method, or define an item_link() method in your Feed class." % item.__class__.__name__ | AttributeError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/contrib/syndication/feeds.py/Feed.item_link |
2,697 | def __get_dynamic_attr(self, attname, obj, default=None):
try:
attr = getattr(self, attname)
except __HOLE__:
return default
if callable(attr):
# Check func_code.co_argcount rather than try/excepting the
# function and catching the TypeError, becau... | AttributeError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/contrib/syndication/feeds.py/Feed.__get_dynamic_attr |
2,698 | def get_feed(self, url=None):
"""
Returns a feedgenerator.DefaultFeed object, fully populated, for
this feed. Raises FeedDoesNotExist for invalid parameters.
"""
if url:
bits = url.split('/')
else:
bits = []
try:
obj = self.get... | ObjectDoesNotExist | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/contrib/syndication/feeds.py/Feed.get_feed |
2,699 | def collect(self, device, ip, user, password):
"""
This function collects the metrics for one filer.
"""
sys.path.append(self.config['netappsdkpath'])
try:
import NaServer
except __HOLE__:
self.log.error("Unable to load NetApp SDK from %s" % (
... | ImportError | dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/netapp/netapp.py/NetAppCollector.collect |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.