Unnamed: 0
int64 0
10k
| function
stringlengths 79
138k
| label
stringclasses 20
values | info
stringlengths 42
261
|
---|---|---|---|
3,300 |
def ancestor(self, n=1):
""" Retrieve an ancestor node from the internal stack.
Parameters
----------
n : int, optional
The depth of the target parent in the ancestry. The default
is 1 and indicates the parent of the active node.
Returns
-------
result : ASTNode or None
The desired ancestor node, or None if the index is out of
range.
"""
try:
# the -1 index is the current node
result = self._node_stack[-1 - n]
except __HOLE__:
result = None
return result
|
IndexError
|
dataset/ETHPy150Open nucleic/enaml/enaml/core/enaml_ast.py/ASTVisitor.ancestor
|
3,301 |
def get_all(self, cbobjects):
"""Retrieve a list of metadata objects associated with the specified
list of CoreBluetooth objects. If an object cannot be found then an
exception is thrown.
"""
try:
with self._lock:
return [self._metadata[x] for x in cbobjects]
except __HOLE__:
# Note that if this error gets thrown then the assumption that OSX
# will pass back to callbacks the exact CoreBluetooth objects that
# were used previously is broken! (i.e. the CoreBluetooth objects
# are not stateless)
raise RuntimeError('Failed to find expected metadata for CoreBluetooth object!')
|
KeyError
|
dataset/ETHPy150Open adafruit/Adafruit_Python_BluefruitLE/Adafruit_BluefruitLE/corebluetooth/metadata.py/CoreBluetoothMetadata.get_all
|
3,302 |
def callback_for(h, fd, flag, *default):
try:
if flag & READ:
return h.readers[fd]
if flag & WRITE:
if fd in h.consolidate:
return h.consolidate_callback
return h.writers[fd]
except __HOLE__:
if default:
return default[0]
raise
|
KeyError
|
dataset/ETHPy150Open celery/kombu/kombu/async/debug.py/callback_for
|
3,303 |
def assertValidUser(self, user):
"""Checks given asset for properties that should be present on all assets.
"""
self.assert_(isinstance(user, typepad.User),
'object %r is not a typepad.User' % user)
self.assert_(user.id)
self.assert_(user.url_id)
self.assert_(len(user.object_types) > 0)
self.assertEquals(user.object_types[0],
'tag:api.typepad.com,2009:User')
self.assertEquals(user.object_type, 'User')
# this asserts as false when the user's interests is empty
# self.assert_(user.interests)
self.assert_(user.make_self_link())
self.assert_(user.profile_page_url is not None)
self.assert_(user.avatar_link is not None)
try:
self.assert_(user.avatar_link.url_template is not None)
except __HOLE__:
self.assert_(user.avatar_link.url is not None)
self.assert_(user.avatar_link.width is not None)
self.assert_(user.avatar_link.height is not None)
|
AssertionError
|
dataset/ETHPy150Open typepad/python-typepad-api/tests/test_typepad.py/TestGroup.assertValidUser
|
3,304 |
def setUp(self):
super(TestBlog, self).setUp()
if not hasattr(self, 'blogger'):
self.credentials_for('blogger')
try:
typepad.client.batch_request()
try:
self.blogger = typepad.User.get_self()
self.blogs = self.blogger.blogs
finally:
typepad.client.complete_batch()
try:
self.blog = self.blogs[0]
except (IndexError, __HOLE__):
self.blog = None
finally:
self.clear_credentials()
|
AttributeError
|
dataset/ETHPy150Open typepad/python-typepad-api/tests/test_typepad.py/TestBlog.setUp
|
3,305 |
def __init__(self, **kwargs): # pylint: disable=W0231
try:
self.device_id = kwargs.pop('device_id') or self.default_device_id
self.v_range = float(kwargs.pop('v_range') or self.default_v_range)
self.dv_range = float(kwargs.pop('dv_range') or self.default_dv_range)
self.sampling_rate = int(kwargs.pop('sampling_rate') or self.default_sampling_rate)
self.resistor_values = kwargs.pop('resistor_values') or []
self.channel_map = kwargs.pop('channel_map') or self.default_channel_map
self.labels = (kwargs.pop('labels') or
['PORT_{}.csv'.format(i) for i in xrange(len(self.resistor_values))])
except __HOLE__, e:
raise ConfigurationError('Missing config: {}'.format(e.message))
if kwargs:
raise ConfigurationError('Unexpected config: {}'.format(kwargs))
|
KeyError
|
dataset/ETHPy150Open ARM-software/workload-automation/wlauto/external/daq_server/src/daqpower/config.py/DeviceConfiguration.__init__
|
3,306 |
def get_node(self, path):
"""
Returns node from within this particular ``DirNode``, so it is now
allowed to fetch, i.e. node located at 'docs/api/index.rst' from node
'docs'. In order to access deeper nodes one must fetch nodes between
them first - this would work::
docs = root.get_node('docs')
docs.get_node('api').get_node('index.rst')
:param: path - relative to the current node
.. note::
To access lazily (as in example above) node have to be initialized
with related changeset object - without it node is out of
context and may know nothing about anything else than nearest
(located at same level) nodes.
"""
try:
path = path.rstrip('/')
if path == '':
raise NodeError("Cannot retrieve node without path")
self.nodes # access nodes first in order to set _nodes_dict
paths = path.split('/')
if len(paths) == 1:
if not self.is_root():
path = '/'.join((self.path, paths[0]))
else:
path = paths[0]
return self._nodes_dict[path]
elif len(paths) > 1:
if self.changeset is None:
raise NodeError("Cannot access deeper "
"nodes without changeset")
else:
path1, path2 = paths[0], '/'.join(paths[1:])
return self.get_node(path1).get_node(path2)
else:
raise KeyError
except __HOLE__:
raise NodeError("Node does not exist at %s" % path)
|
KeyError
|
dataset/ETHPy150Open codeinn/vcs/vcs/nodes.py/DirNode.get_node
|
3,307 |
def _getUserId(self, irc, prefix):
try:
return ircdb.users.getUserId(prefix)
except __HOLE__:
irc.errorNotRegistered(Raise=True)
|
KeyError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/MoobotFactoids/plugin.py/MoobotFactoids._getUserId
|
3,308 |
def addFactoid(self, irc, msg, tokens):
# First, check and see if the entire message matches a factoid key
channel = plugins.getChannel(msg.args[0])
id = self._getUserId(irc, msg.prefix)
try:
(key, fact) = self._getKeyAndFactoid(tokens)
except __HOLE__ as e:
irc.error(str(e), Raise=True)
# Check and make sure it's not in the DB already
if self.db.getFactoid(channel, key):
irc.error(format(_('Factoid %q already exists.'), key), Raise=True)
self.db.addFactoid(channel, key, fact, id)
irc.replySuccess()
|
ValueError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/MoobotFactoids/plugin.py/MoobotFactoids.addFactoid
|
3,309 |
def changeFactoid(self, irc, msg, tokens):
id = self._getUserId(irc, msg.prefix)
(key, regexp) = list(map(' '.join,
utils.iter.split('=~'.__eq__, tokens, maxsplit=1)))
channel = plugins.getChannel(msg.args[0])
# Check and make sure it's in the DB
fact = self._getFactoid(irc, channel, key)
self._checkNotLocked(irc, channel, key)
# It's fair game if we get to here
try:
r = utils.str.perlReToReplacer(regexp)
except __HOLE__ as e:
irc.errorInvalid('regexp', regexp, Raise=True)
fact = fact[0]
new_fact = r(fact)
self.db.updateFactoid(channel, key, new_fact, id)
irc.replySuccess()
|
ValueError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/MoobotFactoids/plugin.py/MoobotFactoids.changeFactoid
|
3,310 |
def replaceFactoid(self, irc, msg, tokens):
# Must be registered!
channel = plugins.getChannel(msg.args[0])
id = self._getUserId(irc, msg.prefix)
del tokens[0] # remove the "no,"
try:
(key, fact) = self._getKeyAndFactoid(tokens)
except __HOLE__ as e:
irc.error(str(e), Raise=True)
_ = self._getFactoid(irc, channel, key)
self._checkNotLocked(irc, channel, key)
self.db.removeFactoid(channel, key)
self.db.addFactoid(channel, key, fact, id)
irc.replySuccess()
|
ValueError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/MoobotFactoids/plugin.py/MoobotFactoids.replaceFactoid
|
3,311 |
@internationalizeDocstring
def listauth(self, irc, msg, args, channel, author):
"""[<channel>] <author name>
Lists the keys of the factoids with the given author. Note that if an
author has an integer name, you'll have to use that author's id to use
this function (so don't use integer usernames!). <channel> is only
necessary if the message isn't sent in the channel itself.
"""
try:
id = ircdb.users.getUserId(author)
except __HOLE__:
irc.errorNoUser(name=author, Raise=True)
results = self.db.getKeysByAuthor(channel, id)
if not results:
irc.reply(format(_('No factoids by %q found.'), author))
return
keys = [format('%q', t[0]) for t in results]
s = format(_('Author search for %q (%i found): %L'),
author, len(keys), keys)
irc.reply(s)
|
KeyError
|
dataset/ETHPy150Open ProgVal/Limnoria/plugins/MoobotFactoids/plugin.py/MoobotFactoids.listauth
|
3,312 |
def run_web_hook(request, command, run):
"""
The web hook lets the message queue tell us how the command got on. It
accepts a JSON document with the status and the output from the command.
When we recieve it we also change the status.
"""
# we're dealing with a post request
if request.POST:
try:
# we try and get the run based on the url parameters
existing_run = Run.objects.get(id=run, command__slug=command)
# the web hook will only run against in progress tasks
# so in theory should only be run once.
if existing_run.status == "in_progress":
# sample json input
# json = """{
# "status": 0,
# "output": "bob2"
# }"""
# get json document from post body in request.POST
json = request.raw_post_data
# not try parse the JSON
try:
obj = simplejson.loads(json)
except __HOLE__, e:
# invalid input
return HttpResponseBadRequest()
# get the status code and convert it to our values
if obj['status'] == 0:
code = "succeeded"
else:
code = "failed"
# set the attributes on our run and save it
existing_run.status = code # succeeded failed in_progress
existing_run.output = obj['output']
existing_run.save()
# return a 200 code as everything went OK
return HttpResponse(
content_type = 'application/javascript; charset=utf8'
)
else:
# this run is not in progress, only the first response is recorded
# should be client error
return HttpResponseBadRequest()
except Run.DoesNotExist:
# we didn't find a run, so throw a 404
return HttpResponseNotFound()
else:
# should be method not allowed as we only respond to post
return HttpResponseNotAllowed(['POST'])
|
ValueError
|
dataset/ETHPy150Open garethr/Asteroid/asteroid/apps/runner/views.py/run_web_hook
|
3,313 |
def list_runs(request):
"list all the runs that have been made so far"
runs = get_list_or_404(Run)
paginator = Paginator(runs, 10) # Show 10 runs per page
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except __HOLE__:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
run_list = paginator.page(page)
except (EmptyPage, InvalidPage):
run_list = paginator.page(paginator.num_pages)
context = {
'runs': run_list,
}
return render_to_response('list_runs.html', context,
context_instance=RequestContext(request))
|
ValueError
|
dataset/ETHPy150Open garethr/Asteroid/asteroid/apps/runner/views.py/list_runs
|
3,314 |
def show_command(request, command):
"show an individual command, along with the last few runs"
# throw a 404 if we don't find anything
existing_command = get_object_or_404(Command, slug__iexact=command)
# get all runs
runs = Run.objects.filter(command=existing_command)
paginator = Paginator(runs, 10) # Show 10 runs per page
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except __HOLE__:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
run_list = paginator.page(page)
except (EmptyPage, InvalidPage):
run_list = paginator.page(paginator.num_pages)
context = {
'command': existing_command,
'runs': run_list,
}
return render_to_response('show_command.html', context,
context_instance=RequestContext(request))
|
ValueError
|
dataset/ETHPy150Open garethr/Asteroid/asteroid/apps/runner/views.py/show_command
|
3,315 |
def webpack_cfg_check(*args, **kwargs):
'''Test if config is compatible or not'''
from django.conf import settings
check_failed = False
user_config = getattr(settings, 'WEBPACK_LOADER', {})
try:
user_config = [dict({}, **cfg) for cfg in user_config.values()]
except __HOLE__:
check_failed = True
errors = []
if check_failed:
errors.append(BAD_CONFIG_ERROR)
return errors
|
TypeError
|
dataset/ETHPy150Open owais/django-webpack-loader/webpack_loader/apps.py/webpack_cfg_check
|
3,316 |
def valid_glob(ipglob):
"""
:param ipglob: An IP address range in a glob-style format.
:return: ``True`` if IP range glob is valid, ``False`` otherwise.
"""
#TODO: Add support for abbreviated ipglobs.
#TODO: e.g. 192.0.*.* == 192.0.*
#TODO: *.*.*.* == *
#TODO: Add strict flag to enable verbose ipglob checking.
if not _is_str(ipglob):
return False
seen_hyphen = False
seen_asterisk = False
octets = ipglob.split('.')
if len(octets) != 4:
return False
for octet in octets:
if '-' in octet:
if seen_hyphen:
return False
seen_hyphen = True
if seen_asterisk:
# Asterisks cannot precede hyphenated octets.
return False
try:
(octet1, octet2) = [int(i) for i in octet.split('-')]
except __HOLE__:
return False
if octet1 >= octet2:
return False
if not 0 <= octet1 <= 254:
return False
if not 1 <= octet2 <= 255:
return False
elif octet == '*':
seen_asterisk = True
else:
if seen_hyphen is True:
return False
if seen_asterisk is True:
return False
try:
if not 0 <= int(octet) <= 255:
return False
except ValueError:
return False
return True
|
ValueError
|
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/glob.py/valid_glob
|
3,317 |
def from_url(self, url):
"""extract host and port from an URL string"""
parts = urlparse.urlsplit(url)
if parts.scheme != 'spy':
raise serial.SerialException(
'expected a string in the form '
'"spy://port[?option[=value][&option[=value]]]": '
'not starting with spy:// (%r)' % (parts.scheme,))
# process options now, directly altering self
formatter = FormatHexdump
color = False
output = sys.stderr
try:
for option, values in urlparse.parse_qs(parts.query, True).items():
if option == 'file':
output = open(values[0], 'w')
elif option == 'color':
color = True
elif option == 'raw':
formatter = FormatRaw
elif option == 'all':
self.show_all = True
else:
raise ValueError('unknown option: %r' % (option,))
except __HOLE__ as e:
raise serial.SerialException(
'expected a string in the form '
'"spy://port[?option[=value][&option[=value]]]": %s' % e)
self.formatter = formatter(output, color)
return ''.join([parts.netloc, parts.path])
|
ValueError
|
dataset/ETHPy150Open pyserial/pyserial/serial/urlhandler/protocol_spy.py/Serial.from_url
|
3,318 |
def test_test_client_context_binding():
app = flask.Flask(__name__)
app.config['LOGGER_HANDLER_POLICY'] = 'never'
@app.route('/')
def index():
flask.g.value = 42
return 'Hello World!'
@app.route('/other')
def other():
1 // 0
with app.test_client() as c:
resp = c.get('/')
assert flask.g.value == 42
assert resp.data == b'Hello World!'
assert resp.status_code == 200
resp = c.get('/other')
assert not hasattr(flask.g, 'value')
assert b'Internal Server Error' in resp.data
assert resp.status_code == 500
flask.g.value = 23
try:
flask.g.value
except (AttributeError, __HOLE__):
pass
else:
raise AssertionError('some kind of exception expected')
|
RuntimeError
|
dataset/ETHPy150Open pallets/flask/tests/test_testing.py/test_test_client_context_binding
|
3,319 |
def tearDown(self):
try:
# We don't really care if this fails - some of the tests will set
# this in the course of their run.
transaction.managed(False)
transaction.leave_transaction_management()
self.new_connection.leave_transaction_management()
except transaction.TransactionManagementError:
pass
self.new_connection.close()
settings.DEBUG = self._old_debug
try:
self.end_blocking_transaction()
except (DatabaseError, __HOLE__):
pass
|
AttributeError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/modeltests/select_for_update/tests.py/SelectForUpdateTests.tearDown
|
3,320 |
def test_pickle_paths_as_pure_cleans_up_on_exception():
prev_reduce = Path.__reduce__
try:
with pickle_paths_as_pure():
raise ValueError()
except __HOLE__:
assert prev_reduce == Path.__reduce__ # ensure we clean up
|
ValueError
|
dataset/ETHPy150Open menpo/menpo/menpo/io/test/io_export_test.py/test_pickle_paths_as_pure_cleans_up_on_exception
|
3,321 |
def parse_unitname(unitname, fold_scale_prefix=True):
"""
Parse a unit term with at most two parts separated by / (a numerator and
denominator, or just a plain term). Returns a structure identical to that
returned by parse_simple_unitname(), but with extra fields for the
numerator and for the denominator, if one exists.
If there is a denominator, the 'base_unit', 'unit_class', 'primary_unit',
'multiplier', and 'scale_multiplier' fields will be returned as
combinations of the corresponding fields for the numerator and the
denominator.
>>> parse_unitname('GB/h') == {
... 'numer_multiplier': 1e9 * 9, 'denom_multiplier': 3600,
... 'multiplier': 1e9 * 8 / 3600,
... 'numer_unit_class': 'datasize', 'denom_unit_class': 'time',
... 'unit_class': 'datasize/time',
... 'numer_primary_unit': 'b', 'denom_primary_unit': 's',
... 'primary_unit': 'b/s',
... 'numer_base_unit': 'B', 'denom_base_unit': 'h',
... 'base_unit': 'B/h'}
True
"""
def copyfields(srcdict, nameprefix):
fields = ('multiplier', 'unit_class', 'primary_unit', 'base_unit', 'scale_multiplier')
for f in fields:
try:
unitstruct[nameprefix + f] = srcdict[f]
except __HOLE__:
pass
parts = unitname.split('/', 2)
if len(parts) > 2 or '' in parts:
# surrender pathetically and just return the original unit
return {'multiplier': 1, 'unit_class': None, 'primary_unit': unitname,
'base_unit': unitname}
unitstruct = parse_simple_unitname(parts[0], fold_scale_prefix=fold_scale_prefix)
copyfields(unitstruct, 'numer_')
if len(parts) == 2:
denominator = parse_simple_unitname(parts[1], fold_scale_prefix=fold_scale_prefix)
copyfields(denominator, 'denom_')
unitstruct['multiplier'] /= denominator['multiplier']
if unitstruct['unit_class'] is None or denominator['unit_class'] is None:
unitstruct['unit_class'] = None
else:
unitstruct['unit_class'] += '/' + denominator['unit_class']
unitstruct['primary_unit'] += '/' + denominator['primary_unit']
unitstruct['base_unit'] += '/' + denominator['base_unit']
if not fold_scale_prefix:
unitstruct['scale_multiplier'] /= denominator['scale_multiplier']
return unitstruct
|
KeyError
|
dataset/ETHPy150Open vimeo/graph-explorer/graph_explorer/unitconv.py/parse_unitname
|
3,322 |
def compat_simple_units_noprefix(unitclass, base_unit=None):
try:
return unit_classes_by_name[unitclass]
except __HOLE__:
return [(base_unit, 1)] if base_unit else []
|
KeyError
|
dataset/ETHPy150Open vimeo/graph-explorer/graph_explorer/unitconv.py/compat_simple_units_noprefix
|
3,323 |
def reload_request(self, locator, index=None):
try:
# element was found out via find_elements
if index is not None:
web_els = self.src_element.find_elements(*locator)
web_el = web_els[index]
else:
web_el = self.src_element.find_element(*locator)
except (exceptions.NoSuchElementException, __HOLE__):
return False
return web_el
|
IndexError
|
dataset/ETHPy150Open openstack/horizon/horizon/test/webdriver.py/WebElementWrapper.reload_request
|
3,324 |
def reload_request(self, locator, index):
try:
# element was found out via find_elements
if index is not None:
web_els = self.find_elements(*locator)
web_el = web_els[index]
else:
web_el = self.find_element(*locator)
return web_el
except (exceptions.NoSuchElementException, __HOLE__):
return False
|
IndexError
|
dataset/ETHPy150Open openstack/horizon/horizon/test/webdriver.py/WebDriverWrapper.reload_request
|
3,325 |
def __init__(self, parent):
parent.title = "Test AirwayModule Load and Save" # TODO make this more human readable by adding spaces
parent.categories = ["Testing.TestCases"]
parent.dependencies = []
parent.contributors = ["Demian Wassermann (Brigham and Women's Hospital)"] # replace with "Firstname Lastname (Org)"
parent.helpText = """
This is a scripted loadable module bundled in an extension.
"""
parent.acknowledgementText = """
This file was originally developed by Demian Wassermann
""" # replace with organization, grant and thanks.
self.parent = parent
# Add this test to the SelfTest module's list for discovery when the module
# is created. Since this module may be discovered before SelfTests itself,
# create the list if it doesn't already exist.
try:
slicer.selfTests
except __HOLE__:
slicer.selfTests = {}
slicer.selfTests['test_airwaymodule_loadsave'] = self.runTest
|
AttributeError
|
dataset/ETHPy150Open acil-bwh/SlicerCIP/Loadable/AirwayModule/Testing/Python/test_airwaymodule_loadsave.py/test_airwaymodule_loadsave.__init__
|
3,326 |
def update_from_console(self):
config = self.find_connection_info(self._host, self._port, self._db)
if config is None:
# the problem here is if VisTrails is being run through command
# line from LaTex, stdout is being redirected to a log file, so
# the user does not see the prompt in raw_input. getpass uses the
# controlling terminal so it works fine. Just to make sure he sees
# the first message prompt we will the controlling terminal
try:
f= open('/dev/tty', 'w')
f.write("\nConnect to db with username [%s]: "%self._user)
f.close()
user = raw_input()
except __HOLE__:
debug.warning("Couldn't write to terminal. Will try stdout")
user = raw_input("Connecting to db with username[%s]: "%self._user)
try:
if user != '':
self._user = user
passwd = getpass.getpass("password:")
self._passwd = passwd
config = {'host': self._host,
'port': int(self._port),
'user': self._user,
'passwd': self._passwd,
'db': self._db
}
test_db_connection(config)
config['succeeded'] = True
config['name'] = '%s@%s'%(self._user,self._host)
config['id'] = -1
except VistrailsDBException, e:
debug.critical('VisTrails DB Exception', e)
config['succeeded'] = False
except Exception, e2:
debug.critical('VisTrails Exception', e2)
config['succeeded'] = False
if config is not None:
if config['succeeded'] == False:
passwd = getpass.getpass("\nVisTrails DB password for user %s:"%config['user'])
self._user = config['user']
self._passwd = passwd
dbconfig = {'host': self._host,
'port': int(self._port),
'user': self._user,
'passwd': self._passwd,
'db': self._db
}
try:
test_db_connection(dbconfig)
config['succeeded'] = True
config['passwd'] = self._passwd
except VistrailsDBException, e:
debug.critical('VisTrails DB Exception', e)
config['succeeded'] = False
if config['succeeded'] == True:
self._host = config['host']
self._port = config['port']
self._db = config['db']
self._user = config['user']
self._passwd = config['passwd']
self.ext_connection_id = self.set_connection_info(**config)
return True
return False
return False
|
IOError
|
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/db/locator.py/DBLocator.update_from_console
|
3,327 |
@staticmethod
def from_link_file(filename):
"""from_link_file(filename: str) -> DBLocator
This will parse a '.vtl' file and will create a DBLocator. .vtl files
are vistrail link files and they are used to point vistrails to open
vistrails from the database on the web. """
def convert_from_str(value,type):
def bool_conv(x):
s = str(x).upper()
if s == 'TRUE':
return True
if s == 'FALSE':
return False
if value is not None:
if type == 'str':
return str(value)
elif value.strip() != '':
if type == 'long':
return long(value)
elif type == 'float':
return float(value)
elif type == 'int':
return int(value)
elif type == 'bool':
return bool_conv(value)
elif type == 'base64':
return base64.b64decode(value)
return None
def guess_extension_from_contents(contents):
if contents.startswith("<vistrail"):
return ".xml"
else:
return ".vt"
tree = ElementTree.parse(filename)
node = tree.getroot()
if node.tag != 'vtlink':
return None
#read attributes
data = node.get('host', None)
host = convert_from_str(data, 'str')
data = node.get('port', None)
port = convert_from_str(data,'int')
data = node.get('database', None)
database = convert_from_str(data,'str')
data = node.get('vtid')
vt_id = convert_from_str(data, 'int')
data = node.get('version')
version = convert_from_str(data, 'str')
data = node.get('tag')
tag = convert_from_str(data, 'str')
data = node.get('execute')
execute = convert_from_str(data, 'bool')
data = node.get('showSpreadsheetOnly')
showSpreadsheetOnly = convert_from_str(data, 'bool')
data = node.get('url', None)
url = convert_from_str(data,'str')
data = node.get('vtcontent', None)
vtcontent = convert_from_str(data,'base64')
data = node.get('filename', None)
vtname = convert_from_str(data, 'str')
data = node.get('forceDB',None)
forceDB = convert_from_str(data,'bool')
data = node.get('mashuptrail', None)
mashuptrail = convert_from_str(data, 'str')
data = node.get('mashupVersion', None)
mashupVersion = convert_from_str(data, 'int')
data = node.get('parameterExploration', None)
parameterExploration = convert_from_str(data, 'int')
#if execute is False, we will show the builder too
if showSpreadsheetOnly and not execute:
showSpreadsheetOnly = False
try:
version = int(version)
except (__HOLE__, TypeError):
pass
if tag is None:
tag = ''
## execute and showSpreadsheetOnly should be written to the current
## configuration
config = get_vistrails_configuration()
config.execute = execute
config.showWindow = not showSpreadsheetOnly
if not forceDB:
if vtcontent is not None:
if url is not None:
basename = url.split('/')[-1]
base,ext = os.path.splitext(basename)
dirname = os.path.dirname(filename)
fname = os.path.join(dirname,basename)
else:
basename = os.path.basename(filename)
base,ext = os.path.splitext(basename)
ext = guess_extension_from_contents(vtcontent)
dirname = os.path.dirname(filename)
fname = os.path.join(dirname,"%s%s"%(base,ext))
create_file = True
if os.path.exists(fname): #file was extracted before
create_file = False
oldf = open(fname)
oldcontents = oldf.read()
if oldcontents != vtcontent:
import vistrails.gui.extras.core.db.locator as db_gui
(overwrite, newname) = \
db_gui.ask_to_overwrite_file(None, 'vistrail')
create_file = True
if newname:
fname = newname
elif overwrite == False:
i=1
while os.path.exists(fname):
newbase = "%s_%s%s" % (base, i, ext)
fname = os.path.join(dirname,newbase)
i+=1
if create_file:
f = open(fname,'wb')
f.write(vtcontent)
f.close()
return FileLocator(fname, version_node=version, version_tag=tag,
mashuptrail=mashuptrail,
mashupVersion=mashupVersion,
parameterExploration=parameterExploration)
if host is not None:
user = ""
passwd = ""
return DBLocator(host, port, database,
user, passwd, None, obj_id=vt_id,
obj_type='vistrail',connection_id=None,
version_node=version, version_tag=tag,
mashuptrail=mashuptrail,
mashupVersion=mashupVersion,
parameterExploration=parameterExploration)
elif vtname is not None:
if os.path.dirname(vtname) == '':
#check if file exists in the same directory as the .vtl file
dirname = os.path.dirname(filename)
newvtname = os.path.join(dirname,vtname)
if os.path.exists(newvtname):
vtname = newvtname
#check for magic strings
if "@examples" in vtname:
vtname=vtname.replace("@examples", vistrails_examples_directory())
return FileLocator(vtname, version_node=version, version_tag=tag,
mashuptrail=mashuptrail,
mashupVersion=mashupVersion,
parameterExploration=parameterExploration)
|
ValueError
|
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/db/locator.py/FileLocator.from_link_file
|
3,328 |
def __init__(self, base_fd, pathspec=None, progress_callback=None,
full_pathspec=None):
"""Use TSK to read the pathspec.
Args:
base_fd: The file like object we read this component from.
pathspec: An optional pathspec to open directly.
progress_callback: A callback to indicate that the open call is still
working but needs more time.
full_pathspec: The full pathspec we are trying to open.
Raises:
IOError: If the file can not be opened.
"""
super(TSKFile, self).__init__(base_fd, pathspec=pathspec,
progress_callback=progress_callback,
full_pathspec=full_pathspec)
if self.base_fd is None:
raise IOError("TSK driver must have a file base.")
# If our base is another tsk driver - borrow the reference to the raw
# device, and replace the last pathspec component with this one after
# extending its path.
elif isinstance(base_fd, TSKFile) and self.base_fd.IsDirectory():
self.tsk_raw_device = self.base_fd.tsk_raw_device
last_path = utils.JoinPath(self.pathspec.last.path, pathspec.path)
# Replace the last component with this one.
self.pathspec.Pop(-1)
self.pathspec.Append(pathspec)
self.pathspec.last.path = last_path
# Use the base fd as a base to parse the filesystem only if its file like.
elif not self.base_fd.IsDirectory():
self.tsk_raw_device = self.base_fd
self.pathspec.Append(pathspec)
else:
# If we get here we have a directory from a non sleuthkit driver - dont
# know what to do with it.
raise IOError("Unable to parse base using Sleuthkit.")
# If we are successful in opening this path below the path casing is
# correct.
self.pathspec.last.path_options = rdf_paths.PathSpec.Options.CASE_LITERAL
fd_hash = self.tsk_raw_device.pathspec.SerializeToString()
# Cache the filesystem using the path of the raw device
try:
self.filesystem = vfs.DEVICE_CACHE.Get(fd_hash)
self.fs = self.filesystem.fs
except __HOLE__:
self.img = MyImgInfo(fd=self.tsk_raw_device,
progress_callback=progress_callback)
self.fs = pytsk3.FS_Info(self.img, 0)
self.filesystem = CachedFilesystem(self.fs, self.img)
vfs.DEVICE_CACHE.Put(fd_hash, self.filesystem)
# We prefer to open the file based on the inode because that is more
# efficient.
if pathspec.HasField("inode"):
self.fd = self.fs.open_meta(pathspec.inode)
self.tsk_attribute = self.GetAttribute(
pathspec.ntfs_type, pathspec.ntfs_id)
if self.tsk_attribute:
self.size = self.tsk_attribute.info.size
else:
self.size = self.fd.info.meta.size
else:
# Does the filename exist in the image?
self.fd = self.fs.open(utils.SmartStr(self.pathspec.last.path))
self.size = self.fd.info.meta.size
self.pathspec.last.inode = self.fd.info.meta.addr
|
KeyError
|
dataset/ETHPy150Open google/grr/grr/client/vfs_handlers/sleuthkit.py/TSKFile.__init__
|
3,329 |
def MakeStatResponse(self, tsk_file, tsk_attribute=None, append_name=False):
"""Given a TSK info object make a StatEntry.
Note that tsk uses two things to uniquely identify a data stream - the inode
object given in tsk_file and the attribute object which may correspond to an
ADS of this file for filesystems which support ADS. We store both of these
in the stat response.
Args:
tsk_file: A TSK File object for the specified inode.
tsk_attribute: A TSK Attribute object for the ADS. If None we use the main
stream.
append_name: If specified we append this name to the last element of the
pathspec.
Returns:
A StatEntry which can be used to re-open this exact VFS node.
"""
info = tsk_file.info
response = rdf_client.StatEntry()
meta = info.meta
if meta:
response.st_ino = meta.addr
for attribute in ["mode",
"nlink",
"uid",
"gid",
"size",
"atime",
"mtime",
"ctime",
"crtime"]:
try:
value = int(getattr(meta, attribute))
if value < 0: value &= 0xFFFFFFFF
setattr(response, "st_%s" % attribute, value)
except __HOLE__:
pass
name = info.name
child_pathspec = self.pathspec.Copy()
if append_name:
# Append the name to the most inner pathspec
child_pathspec.last.path = utils.JoinPath(child_pathspec.last.path,
utils.SmartUnicode(append_name))
child_pathspec.last.inode = meta.addr
if tsk_attribute is not None:
child_pathspec.last.ntfs_type = int(tsk_attribute.info.type)
child_pathspec.last.ntfs_id = int(tsk_attribute.info.id)
child_pathspec.last.stream_name = tsk_attribute.info.name
# Update the size with the attribute size.
response.st_size = tsk_attribute.info.size
default = rdf_paths.PathSpec.tsk_fs_attr_type.TSK_FS_ATTR_TYPE_DEFAULT
last = child_pathspec.last
if last.ntfs_type != default or last.ntfs_id:
# This is an ads and should be treated as a file.
# Clear all file type bits.
response.st_mode &= ~self.stat_type_mask
response.st_mode |= stat.S_IFREG
else:
child_pathspec.last.ntfs_type = None
child_pathspec.last.ntfs_id = None
child_pathspec.last.stream_name = None
if name:
# Encode the type onto the st_mode response
response.st_mode |= self.FILE_TYPE_LOOKUP.get(int(name.type), 0)
if meta:
# What if the types are different? What to do here?
response.st_mode |= self.META_TYPE_LOOKUP.get(int(meta.type), 0)
# Write the pathspec on the response.
response.pathspec = child_pathspec
return response
|
AttributeError
|
dataset/ETHPy150Open google/grr/grr/client/vfs_handlers/sleuthkit.py/TSKFile.MakeStatResponse
|
3,330 |
def Read(self, length):
"""Read from the file."""
if not self.IsFile():
raise IOError("%s is not a file." % self.pathspec.last.path)
available = min(self.size - self.offset, length)
if available > 0:
# This raises a RuntimeError in some situations.
try:
data = self.fd.read_random(self.offset, available,
self.pathspec.last.ntfs_type,
self.pathspec.last.ntfs_id)
except __HOLE__ as e:
raise IOError(e)
self.offset += len(data)
return data
return ""
|
RuntimeError
|
dataset/ETHPy150Open google/grr/grr/client/vfs_handlers/sleuthkit.py/TSKFile.Read
|
3,331 |
def ListFiles(self):
"""List all the files in the directory."""
if self.IsDirectory():
dir_fd = self.fd.as_directory()
for f in dir_fd:
try:
name = f.info.name.name
# Drop these useless entries.
if name in [".", ".."] or name in self.BLACKLIST_FILES:
continue
# First we yield a standard response using the default attributes.
yield self.MakeStatResponse(f, tsk_attribute=None, append_name=name)
# Now send back additional named attributes for the ADS.
for attribute in f:
if attribute.info.type in [pytsk3.TSK_FS_ATTR_TYPE_NTFS_DATA,
pytsk3.TSK_FS_ATTR_TYPE_DEFAULT]:
if attribute.info.name:
yield self.MakeStatResponse(f, append_name=name,
tsk_attribute=attribute)
except __HOLE__:
pass
else:
raise IOError("%s is not a directory" % self.pathspec.CollapsePath())
|
AttributeError
|
dataset/ETHPy150Open google/grr/grr/client/vfs_handlers/sleuthkit.py/TSKFile.ListFiles
|
3,332 |
def remez(numtaps, bands, desired, weight=None, Hz=1, type='bandpass',
maxiter=25, grid_density=16):
"""
Calculate the minimax optimal filter using the Remez exchange algorithm.
Calculate the filter-coefficients for the finite impulse response
(FIR) filter whose transfer function minimizes the maximum error
between the desired gain and the realized gain in the specified
frequency bands using the Remez exchange algorithm.
Parameters
----------
numtaps : int
The desired number of taps in the filter. The number of taps is
the number of terms in the filter, or the filter order plus one.
bands : array_like
A monotonic sequence containing the band edges in Hz.
All elements must be non-negative and less than half the sampling
frequency as given by `Hz`.
desired : array_like
A sequence half the size of bands containing the desired gain
in each of the specified bands.
weight : array_like, optional
A relative weighting to give to each band region. The length of
`weight` has to be half the length of `bands`.
Hz : scalar, optional
The sampling frequency in Hz. Default is 1.
type : {'bandpass', 'differentiator', 'hilbert'}, optional
The type of filter:
'bandpass' : flat response in bands. This is the default.
'differentiator' : frequency proportional response in bands.
'hilbert' : filter with odd symmetry, that is, type III
(for even order) or type IV (for odd order)
linear phase filters.
maxiter : int, optional
Maximum number of iterations of the algorithm. Default is 25.
grid_density : int, optional
Grid density. The dense grid used in `remez` is of size
``(numtaps + 1) * grid_density``. Default is 16.
Returns
-------
out : ndarray
A rank-1 array containing the coefficients of the optimal
(in a minimax sense) filter.
See Also
--------
freqz : Compute the frequency response of a digital filter.
References
----------
.. [1] J. H. McClellan and T. W. Parks, "A unified approach to the
design of optimum FIR linear phase digital filters",
IEEE Trans. Circuit Theory, vol. CT-20, pp. 697-701, 1973.
.. [2] J. H. McClellan, T. W. Parks and L. R. Rabiner, "A Computer
Program for Designing Optimum FIR Linear Phase Digital
Filters", IEEE Trans. Audio Electroacoust., vol. AU-21,
pp. 506-525, 1973.
Examples
--------
We want to construct a filter with a passband at 0.2-0.4 Hz, and
stop bands at 0-0.1 Hz and 0.45-0.5 Hz. Note that this means that the
behavior in the frequency ranges between those bands is unspecified and
may overshoot.
>>> from scipy import signal
>>> bpass = signal.remez(72, [0, 0.1, 0.2, 0.4, 0.45, 0.5], [0, 1, 0])
>>> freq, response = signal.freqz(bpass)
>>> ampl = np.abs(response)
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> ax1 = fig.add_subplot(111)
>>> ax1.semilogy(freq/(2*np.pi), ampl, 'b-') # freq in Hz
>>> plt.show()
"""
# Convert type
try:
tnum = {'bandpass': 1, 'differentiator': 2, 'hilbert': 3}[type]
except __HOLE__:
raise ValueError("Type must be 'bandpass', 'differentiator', "
"or 'hilbert'")
# Convert weight
if weight is None:
weight = [1] * len(desired)
bands = np.asarray(bands).copy()
return sigtools._remez(numtaps, bands, desired, weight, tnum, Hz,
maxiter, grid_density)
|
KeyError
|
dataset/ETHPy150Open scipy/scipy/scipy/signal/fir_filter_design.py/remez
|
3,333 |
def run(self):
"""Run the hight quarter, lunch the turrets and wait for results
"""
elapsed = 0
start_time = time.time()
self._publish({'command': 'start', 'msg': 'open fire'})
self.started = True
while elapsed <= (self.config['run_time']):
try:
self._run_loop_action()
self._print_status(elapsed)
elapsed = time.time() - start_time
except (Exception, __HOLE__):
print("\nStopping test, sending stop command to turrets")
self._publish({'command': 'stop', 'msg': 'premature stop'})
traceback.print_exc()
break
self._publish({'command': 'stop', 'msg': 'stopping fire'})
print("\n\nProcessing all remaining messages...")
self.result_collector.unbind(self.result_collector.LAST_ENDPOINT)
self._clean_queue()
|
KeyboardInterrupt
|
dataset/ETHPy150Open TheGhouls/oct/oct/core/hq.py/HightQuarter.run
|
3,334 |
def Install(self, package_name):
"""Installs a PerfKit package on the VM."""
package = linux_packages.PACKAGES[package_name]
try:
# Make sure another unit doesn't try
# to install the charm at the same time
with self.controller.installation_lock:
if package_name not in self.controller._installed_packages:
package.JujuInstall(self.controller, self.vm_group)
self.controller._installed_packages.add(package_name)
except __HOLE__ as e:
logging.warn('Failed to install package %s, falling back to Apt (%s)'
% (package_name, e))
if package_name not in self._installed_packages:
package.AptInstall(self)
self._installed_packages.add(package_name)
|
AttributeError
|
dataset/ETHPy150Open GoogleCloudPlatform/PerfKitBenchmarker/perfkitbenchmarker/linux_virtual_machine.py/JujuMixin.Install
|
3,335 |
def _reconnect(self, fd, *fd_sets):
for fd_set in fd_sets:
try:
fd_set.remove(fd)
except __HOLE__:
pass
fd.reconnect()
|
ValueError
|
dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/reactor.py/_Reactor._reconnect
|
3,336 |
def run(self):
try:
size = -1
read = self.size()
request = Request(self.url)
if read > 0:
request.add_header('range', 'bytes=' + str(read) + '-')
response = urlopen(request)
headers = response.info()
if read > 0 and 'Content-Range' in headers:
ranges = headers['Content-Range']
size = int(ranges.split('/')[-1].strip())
self.open('ab')
else:
if 'Content-Length' in headers:
size = int(headers['Content-Length'])
self.open('wb')
with self.file:
bs = 1024 * 8
lock = Lock()
self.onstart.emit()
while True:
lock.acquire()
block = response.read(bs)
if not block or self.file.closed:
break
read += len(block)
self.file.write(block)
self.onprogress.emit(read, size)
lock.release()
self.file.close()
self.onfinish.emit(read)
except __HOLE__ as error:
self.onerror.emit(error.code, error.msg)
except URLError as error:
self.onerror.emit(error.reason.errno, error.reason.strerror)
except Exception as error:
self.onerror.emit(-1, str(error))
|
HTTPError
|
dataset/ETHPy150Open Lanfei/hae/src/downloader.py/Downloader.run
|
3,337 |
def get_num_fds():
proc = psutil.Process(PID)
try:
return proc.num_fds()
except __HOLE__: # psutil < 2.0
return proc.get_num_fds()
|
AttributeError
|
dataset/ETHPy150Open scrapinghub/splash/splash/utils.py/get_num_fds
|
3,338 |
def get_total_phymem():
""" Return the total amount of physical memory available. """
try:
return psutil.virtual_memory().total
except __HOLE__: # psutil < 2.0
return psutil.phymem_usage().total
|
AttributeError
|
dataset/ETHPy150Open scrapinghub/splash/splash/utils.py/get_total_phymem
|
3,339 |
def firefox_installed():
try:
Browser("firefox")
except __HOLE__:
return False
return True
|
OSError
|
dataset/ETHPy150Open cobrateam/splinter/tests/test_webdriver_firefox.py/firefox_installed
|
3,340 |
def run(self):
# remove the build/temp.<plat> directory (unless it's already
# gone)
if os.path.exists(self.build_temp):
remove_tree(self.build_temp, dry_run=self.dry_run)
else:
log.debug("'%s' does not exist -- can't clean it",
self.build_temp)
if self.all:
# remove build directories
for directory in (self.build_lib,
self.bdist_base,
self.build_scripts):
if os.path.exists(directory):
remove_tree(directory, dry_run=self.dry_run)
else:
log.warn("'%s' does not exist -- can't clean it",
directory)
# just for the heck of it, try to remove the base build directory:
# we might have emptied it right now, but if not we don't care
if not self.dry_run:
try:
os.rmdir(self.build_base)
log.info("removing '%s'", self.build_base)
except __HOLE__:
pass
# class clean
|
OSError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/distutils/command/clean.py/clean.run
|
3,341 |
def ClassDoc(path):
"""Process the given Java source file and return ClassDoc instance.
Processing is done using com.sun.tools.javadoc APIs. The usage has
been figured out from sources at
http://www.java2s.com/Open-Source/Java-Document/JDK-Modules-com.sun/tools/com.sun.tools.javadoc.htm
Returned object implements com.sun.javadoc.ClassDoc interface, see
http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/doclet/
"""
try:
from com.sun.tools.javadoc import JavadocTool, Messager, ModifierFilter
from com.sun.tools.javac.util import List, Context
from com.sun.tools.javac.code.Flags import PUBLIC
except __HOLE__:
raise DataError("Creating documentation from Java source files "
"requires 'tools.jar' to be in CLASSPATH.")
context = Context()
Messager.preRegister(context, 'libdoc')
jdoctool = JavadocTool.make0(context)
filter = ModifierFilter(PUBLIC)
java_names = List.of(path)
root = jdoctool.getRootDocImpl('en', 'utf-8', filter, java_names,
List.nil(), False, List.nil(),
List.nil(), False, False, True)
return root.classes()[0]
|
ImportError
|
dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/libdocpkg/javabuilder.py/ClassDoc
|
3,342 |
def import_string(import_name, silent=False):
"""Imports an object based on a string. This is 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.sax.saxutils:escape``).
If `silent` is True the return value will be `None` if the import fails.
:param import_name: the dotted name for the object to import.
:param silent: if set to `True` import errors are ignored and
`None` is returned instead.
:return: imported object
"""
try:
if ':' in import_name:
module, obj = import_name.split(':', 1)
elif '.' in import_name:
module, obj = import_name.rsplit('.', 1)
else:
return __import__(import_name)
try:
return getattr(__import__(module, None, None, [obj]), obj)
except (ImportError, __HOLE__):
# support importing modules not yet set up by the parent module
# (or package for that matter)
modname = module + '.' + obj
try:
__import__(modname)
except ImportError as e:
raise ImportError('Failed to import %s: %s' % (modname, e))
return sys.modules[modname]
except ImportError:
if not silent:
raise
|
AttributeError
|
dataset/ETHPy150Open aino/aino-utkik/utkik/utils.py/import_string
|
3,343 |
def _initialize_service_helpers(self, host):
svc_helper_class = self.conf.cfg_agent.routing_svc_helper_class
try:
self.routing_service_helper = importutils.import_object(
svc_helper_class, host, self.conf, self)
except __HOLE__ as e:
LOG.warning(_LW("Error in loading routing service helper. Class "
"specified is %(class)s. Reason:%(reason)s"),
{'class': self.conf.cfg_agent.routing_svc_helper_class,
'reason': e})
self.routing_service_helper = None
|
ImportError
|
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py/CiscoCfgAgent._initialize_service_helpers
|
3,344 |
def agent_updated(self, context, payload):
"""Deal with agent updated RPC message."""
try:
if payload['admin_state_up']:
#TODO(hareeshp): implement agent updated handling
pass
except __HOLE__ as e:
LOG.error(_LE("Invalid payload format for received RPC message "
"`agent_updated`. Error is %(error)s. Payload is "
"%(payload)s"), {'error': e, 'payload': payload})
|
KeyError
|
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py/CiscoCfgAgent.agent_updated
|
3,345 |
def hosting_devices_assigned_to_cfg_agent(self, context, payload):
"""Deal with hosting devices assigned to this config agent."""
LOG.debug("Got hosting device assigned, payload: %s" % payload)
try:
if payload['hosting_device_ids']:
#TODO(hareeshp): implement assignment of hosting devices
self.routing_service_helper.fullsync = True
except __HOLE__ as e:
LOG.error(_LE("Invalid payload format for received RPC message "
"`hosting_devices_assigned_to_cfg_agent`. Error is "
"%(error)s. Payload is %(payload)s"),
{'error': e, 'payload': payload})
|
KeyError
|
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py/CiscoCfgAgent.hosting_devices_assigned_to_cfg_agent
|
3,346 |
def hosting_devices_unassigned_from_cfg_agent(self, context, payload):
"""Deal with hosting devices unassigned from this config agent."""
try:
if payload['hosting_device_ids']:
#TODO(hareeshp): implement unassignment of hosting devices
pass
except __HOLE__ as e:
LOG.error(_LE("Invalid payload format for received RPC message "
"`hosting_devices_unassigned_from_cfg_agent`. Error "
"is %(error)s. Payload is %(payload)s"),
{'error': e, 'payload': payload})
|
KeyError
|
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py/CiscoCfgAgent.hosting_devices_unassigned_from_cfg_agent
|
3,347 |
def hosting_devices_removed(self, context, payload):
"""Deal with hosting device removed RPC message."""
try:
if payload['hosting_data']:
if payload['hosting_data'].keys():
self.process_services(removed_devices_info=payload)
except __HOLE__ as e:
LOG.error(_LE("Invalid payload format for received RPC message "
"`hosting_devices_removed`. Error is %(error)s. "
"Payload is %(payload)s"), {'error': e,
'payload': payload})
|
KeyError
|
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py/CiscoCfgAgent.hosting_devices_removed
|
3,348 |
def send_agent_report(self, report, context):
"""Send the agent report via RPC."""
try:
self.state_rpc.report_state(context, report, self.use_call)
report.pop('start_flag', None)
self.use_call = False
LOG.debug("Send agent report successfully completed")
except __HOLE__:
# This means the server does not support report_state
LOG.warning(_LW("Neutron server does not support state report. "
"State report for this agent will be disabled."))
self.heartbeat.stop()
return
except Exception:
LOG.exception(_LE("Failed sending agent report!"))
|
AttributeError
|
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py/CiscoCfgAgentWithStateReport.send_agent_report
|
3,349 |
def __str__(self):
try:
return self.text
except __HOLE__:
return "Empty OE"
|
AttributeError
|
dataset/ETHPy150Open varunsrin/one-py/onepy/onepy.py/OE.__str__
|
3,350 |
def __str__(self):
try:
return self.preferredName
except __HOLE__:
return "Unnamed File"
|
AttributeError
|
dataset/ETHPy150Open varunsrin/one-py/onepy/onepy.py/InsertedFile.__str__
|
3,351 |
def __str__(self):
try:
return self.preferredName
except __HOLE__:
return "Unnamed Media File"
|
AttributeError
|
dataset/ETHPy150Open varunsrin/one-py/onepy/onepy.py/MediaFile.__str__
|
3,352 |
def __str__(self):
try:
return self.recognizedText
except __HOLE__:
return "Unrecognized Ink"
|
AttributeError
|
dataset/ETHPy150Open varunsrin/one-py/onepy/onepy.py/Ink.__str__
|
3,353 |
def get_object(self, request, object_id, from_field=None):
"""
Returns an instance matching the primary key provided. ``None`` is
returned if no match is found (or the object_id failed validation
against the primary key field).
"""
queryset = self.get_queryset(request)
model = queryset._document
field = model._meta.pk if from_field is None else model._meta.get_field(from_field)
try:
object_id = field.to_python(object_id)
return queryset.get(**{field.name: object_id})
except (model.DoesNotExist, __HOLE__, ValueError):
return None
|
ValidationError
|
dataset/ETHPy150Open jschrewe/django-mongoadmin/mongoadmin/options.py/DocumentAdmin.get_object
|
3,354 |
def poll(self):
try:
while 1:
self._knob.poll()
except __HOLE__:
pass
|
KeyboardInterrupt
|
dataset/ETHPy150Open kdart/pycopia/core/pycopia/OS/Linux/mastervolume.py/VolumeControl.poll
|
3,355 |
def _process_fds():
counts = {(k,): 0 for k in TYPES.values()}
counts[("other",)] = 0
# Not every OS will have a /proc/self/fd directory
if not os.path.exists("/proc/self/fd"):
return counts
for fd in os.listdir("/proc/self/fd"):
try:
s = os.stat("/proc/self/fd/%s" % (fd))
fmt = stat.S_IFMT(s.st_mode)
if fmt in TYPES:
t = TYPES[fmt]
else:
t = "other"
counts[(t,)] += 1
except __HOLE__:
# the dirh itself used by listdir() is usually missing by now
pass
return counts
|
OSError
|
dataset/ETHPy150Open matrix-org/synapse/synapse/metrics/__init__.py/_process_fds
|
3,356 |
def get_service_port(app):
try:
return app['container']['docker']['portMappings'][0]['servicePort']
except __HOLE__:
return app['ports'][0]
|
KeyError
|
dataset/ETHPy150Open mesosphere/marathon-lb/bluegreen_deploy.py/get_service_port
|
3,357 |
def set_service_port(app, servicePort):
try:
app['container']['docker']['portMappings'][0]['servicePort'] \
= int(servicePort)
except __HOLE__:
app['ports'][0] = int(servicePort)
return app
|
KeyError
|
dataset/ETHPy150Open mesosphere/marathon-lb/bluegreen_deploy.py/set_service_port
|
3,358 |
def set_service_ports(app, servicePort):
app['labels']['HAPROXY_0_PORT'] = str(get_service_port(app))
try:
app['container']['docker']['portMappings'][0]['servicePort'] \
= int(servicePort)
return app
except __HOLE__:
app['ports'][0] = int(servicePort)
return app
|
KeyError
|
dataset/ETHPy150Open mesosphere/marathon-lb/bluegreen_deploy.py/set_service_ports
|
3,359 |
def __hash__(self):
try:
return self._hash
except __HOLE__:
self._hash = hash(self._comparison_key)
return self._hash
|
AttributeError
|
dataset/ETHPy150Open nltk/nltk/nltk/ccg/api.py/AbstractCCGCategory.__hash__
|
3,360 |
def __hash__(self):
try:
return self._hash
except __HOLE__:
self._hash = hash(self._comparison_key)
return self._hash
|
AttributeError
|
dataset/ETHPy150Open nltk/nltk/nltk/ccg/api.py/Direction.__hash__
|
3,361 |
def __repr__(self):
try:
return 'MonthDelta({0})'.format(self.__months)
except __HOLE__:
return 'MonthDelta(' + str(self.__months) + ')'
|
AttributeError
|
dataset/ETHPy150Open zulip/zulip/tools/deprecated/finbot/monthdelta.py/MonthDelta.__repr__
|
3,362 |
def __add__(self, other):
if isinstance(other, MonthDelta):
return MonthDelta(self.__months + other.months)
if isinstance(other, date):
day = other.day
# subract one because months are not zero-based
month = other.month + self.__months - 1
year = other.year + month // 12
# now add it back
month = month % 12 + 1
if month == 2:
if day >= 29 and not year%4 and (year%100 or not year%400):
day = 29
elif day > 28:
day = 28
elif month in (4, 6, 9, 11) and day > 30:
day = 30
try:
return other.replace(year, month, day)
except __HOLE__:
raise OverflowError('date value out of range')
return NotImplemented
|
ValueError
|
dataset/ETHPy150Open zulip/zulip/tools/deprecated/finbot/monthdelta.py/MonthDelta.__add__
|
3,363 |
def _dist_from_eggfile(filename, logger, observer):
""" Create distribution by unpacking egg file. """
if not os.path.exists(filename):
msg = "'%s' not found." % filename
observer.exception(msg)
raise ValueError(msg)
if not zipfile.is_zipfile(filename):
msg = "'%s' is not an egg/zipfile." % filename
observer.exception(msg)
raise ValueError(msg)
# Extract files.
archive = zipfile.ZipFile(filename, 'r', allowZip64=True)
try:
name = archive.read('EGG-INFO/top_level.txt').split('\n')[0]
logger.log(LOG_DEBUG2, " name '%s'", name)
if observer.observer is not None:
# Collect totals.
total_files = 0.
total_bytes = 0.
for info in archive.infolist():
fname = info.filename
# Just being defensive.
if not fname.startswith(name) and \
not fname.startswith('EGG-INFO'): #pragma no cover
continue
total_files += 1
total_bytes += info.file_size
else:
total_files = 1. # Avoid divide-by-zero.
total_bytes = 1.
files = 0.
size = 0.
for info in archive.infolist():
fname = info.filename
# Just being defensive.
if not fname.startswith(name) and \
not fname.startswith('EGG-INFO'): #pragma no cover
continue
observer.extract(fname, files/total_files, size/total_bytes)
dirname = os.path.dirname(fname)
if dirname == 'EGG-INFO':
# Extract EGG-INFO as subdirectory.
archive.extract(fname, name)
else:
archive.extract(fname)
if sys.platform != 'win32':
# Set permissions, extract() doesn't.
rwx = (info.external_attr >> 16) & 0777
if rwx:
os.chmod(fname, rwx) # Only if something valid.
files += 1
size += info.file_size
finally:
archive.close()
# Create distribution from extracted files.
location = os.getcwd()
egg_info = os.path.join(location, name, 'EGG-INFO')
provider = pkg_resources.PathMetadata(location, egg_info)
dist = pkg_resources.Distribution.from_location(location,
os.path.basename(filename),
provider)
logger.log(LOG_DEBUG2, ' project_name: %s', dist.project_name)
logger.log(LOG_DEBUG2, ' version: %s', dist.version)
logger.log(LOG_DEBUG2, ' py_version: %s', dist.py_version)
logger.log(LOG_DEBUG2, ' platform: %s', dist.platform)
logger.log(LOG_DEBUG2, ' requires:')
for req in dist.requires():
logger.log(LOG_DEBUG2, ' %s', req)
# If any module didn't have a distribution, check that we can import it.
if provider.has_metadata('openmdao_orphans.txt'):
errors = 0
orphan_names = []
for mod in provider.get_metadata_lines('openmdao_orphans.txt'):
mod = mod.strip()
logger.log(LOG_DEBUG2, " checking for 'orphan' module: %s", mod)
try:
__import__(mod)
# Difficult to generate a distribution that can't be reloaded.
except __HOLE__: #pragma no cover
logger.error("Can't import %s, which didn't have a known"
" distribution when the egg was written.", mod)
orphan_names.append(mod)
errors += 1
# Difficult to generate a distribution that can't be reloaded.
if errors: #pragma no cover
plural = 's' if errors > 1 else ''
msg = "Couldn't import %d 'orphan' module%s: %s." \
% (errors, plural, orphan_names)
observer.exception(msg)
raise RuntimeError(msg)
return (name, dist)
|
ImportError
|
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.util/src/openmdao/util/eggloader.py/_dist_from_eggfile
|
3,364 |
def motion(self, *args):
tvRowId = self.treeView.identify_row(args[0].y)
if tvRowId != self.toolTipRowId:
text = None
if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM, PLUGIN):
self.toolTipRowId = tvRowId
if tvRowId and len(tvRowId) > 4:
try:
text = self.filenames[ int(tvRowId[4:]) ]
if isinstance(text, tuple):
text = (text[1] or "").replace("\\n","\n")
except (KeyError, __HOLE__):
pass
elif self.openType == ENTRY_POINTS:
try:
epUrl = self.taxonomyPackage["nameToUrls"][tvRowId][1]
text = "{0}\n{1}".format(tvRowId, epUrl)
except KeyError:
pass
self.setToolTip(text)
|
ValueError
|
dataset/ETHPy150Open Arelle/Arelle/arelle/DialogOpenArchive.py/DialogOpenArchive.motion
|
3,365 |
def test_ex_list_ptr_not_found(self):
RackspaceMockHttp.type = 'RECORD_DOES_NOT_EXIST'
try:
records = self.driver.ex_iterate_ptr_records(RDNS_NODE)
except Exception as exc:
self.fail("PTR Records list 404 threw %s" % exc)
try:
next(records)
self.fail("PTR Records list 404 did not produce an empty list")
except __HOLE__:
self.assertTrue(True, "Got empty list on 404")
|
StopIteration
|
dataset/ETHPy150Open apache/libcloud/libcloud/test/dns/test_rackspace.py/RackspaceUSTests.test_ex_list_ptr_not_found
|
3,366 |
def __getstate__(self):
if hasattr(self, '__dict__'):
# We don't require that all sub-classes also define slots,
# so they may provide a dictionary
statedict = self.__dict__.copy()
else:
statedict = {}
# Get all slots of potential parent classes
for slot in self.__all_slots__:
try:
value = getattr(self, slot)
statedict[slot] = value
except __HOLE__:
pass
# Pop slots that cannot or should not be pickled
statedict.pop('__dict__', None)
statedict.pop('__weakref__', None)
return statedict
|
AttributeError
|
dataset/ETHPy150Open SmokinCaterpillar/pypet/pypet/slots.py/HasSlots.__getstate__
|
3,367 |
def get_dataset(dataverse, doi):
if dataverse is None:
return
dataset = dataverse.get_dataset_by_doi(doi, timeout=settings.REQUEST_TIMEOUT)
try:
if dataset and dataset.get_state() == 'DEACCESSIONED':
raise HTTPError(http.GONE, data=dict(
message_short='Dataset deaccessioned',
message_long='This dataset has been deaccessioned and can no longer be linked to the OSF.'
))
return dataset
except __HOLE__:
raise HTTPError(http.NOT_ACCEPTABLE, data=dict(
message_short='Not acceptable',
message_long='This dataset cannot be connected due to forbidden '
'characters in one or more of the file names.'
))
|
UnicodeDecodeError
|
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/addons/dataverse/client.py/get_dataset
|
3,368 |
def __read_master_key(self):
'''
Read in the rotating master authentication key
'''
key_user = self.salt_user
if key_user == 'root':
if self.opts.get('user', 'root') != 'root':
key_user = self.opts.get('user', 'root')
if key_user.startswith('sudo_'):
key_user = self.opts.get('user', 'root')
keyfile = os.path.join(self.opts['cachedir'],
'.{0}_key'.format(key_user))
# Make sure all key parent directories are accessible
salt.utils.verify.check_path_traversal(self.opts['cachedir'],
key_user,
self.skip_perm_errors)
try:
with salt.utils.fopen(keyfile, 'r') as key:
return key.read()
except (OSError, __HOLE__):
# Fall back to eauth
return ''
|
IOError
|
dataset/ETHPy150Open saltstack/salt/salt/client/__init__.py/LocalClient.__read_master_key
|
3,369 |
def _get_timeout(self, timeout):
'''
Return the timeout to use
'''
if timeout is None:
return self.opts['timeout']
if isinstance(timeout, int):
return timeout
if isinstance(timeout, six.string_types):
try:
return int(timeout)
except __HOLE__:
return self.opts['timeout']
# Looks like the timeout is invalid, use config
return self.opts['timeout']
|
ValueError
|
dataset/ETHPy150Open saltstack/salt/salt/client/__init__.py/LocalClient._get_timeout
|
3,370 |
def cmd_async(
self,
tgt,
fun,
arg=(),
expr_form='glob',
ret='',
jid='',
kwarg=None,
**kwargs):
'''
Asynchronously send a command to connected minions
The function signature is the same as :py:meth:`cmd` with the
following exceptions.
:returns: A job ID or 0 on failure.
.. code-block:: python
>>> local.cmd_async('*', 'test.sleep', [300])
'20131219215921857715'
'''
arg = salt.utils.args.condition_input(arg, kwarg)
pub_data = self.run_job(tgt,
fun,
arg,
expr_form,
ret,
jid=jid,
**kwargs)
try:
return pub_data['jid']
except __HOLE__:
return 0
|
KeyError
|
dataset/ETHPy150Open saltstack/salt/salt/client/__init__.py/LocalClient.cmd_async
|
3,371 |
def cmd_cli(
self,
tgt,
fun,
arg=(),
timeout=None,
expr_form='glob',
ret='',
verbose=False,
kwarg=None,
progress=False,
**kwargs):
'''
Used by the :command:`salt` CLI. This method returns minion returns as
they come back and attempts to block until all minions return.
The function signature is the same as :py:meth:`cmd` with the
following exceptions.
:param verbose: Print extra information about the running command
:returns: A generator
'''
arg = salt.utils.args.condition_input(arg, kwarg)
pub_data = self.run_job(
tgt,
fun,
arg,
expr_form,
ret,
timeout,
**kwargs)
if not pub_data:
yield pub_data
else:
try:
for fn_ret in self.get_cli_event_returns(
pub_data['jid'],
pub_data['minions'],
self._get_timeout(timeout),
tgt,
expr_form,
verbose,
progress,
**kwargs):
if not fn_ret:
continue
yield fn_ret
except __HOLE__:
msg = ('Exiting on Ctrl-C\nThis job\'s jid is:\n{0}\n'
'The minions may not have all finished running and any '
'remaining minions will return upon completion. To '
'look up the return data for this job later run:\n'
'salt-run jobs.lookup_jid {0}').format(pub_data['jid'])
raise SystemExit(msg)
|
KeyboardInterrupt
|
dataset/ETHPy150Open saltstack/salt/salt/client/__init__.py/LocalClient.cmd_cli
|
3,372 |
def get_event_iter_returns(self, jid, minions, timeout=None):
'''
Gather the return data from the event system, break hard when timeout
is reached.
'''
log.trace('entered - function get_event_iter_returns()')
if timeout is None:
timeout = self.opts['timeout']
timeout_at = time.time() + timeout
found = set()
# Check to see if the jid is real, if not return the empty dict
if self.returners['{0}.get_load'.format(self.opts['master_job_cache'])](jid) == {}:
log.warning('jid does not exist')
yield {}
# stop the iteration, since the jid is invalid
raise StopIteration()
# Wait for the hosts to check in
while True:
raw = self.event.get_event(timeout)
if raw is None or time.time() > timeout_at:
# Timeout reached
break
if 'minions' in raw.get('data', {}):
continue
try:
found.add(raw['id'])
ret = {raw['id']: {'ret': raw['return']}}
except __HOLE__:
# Ignore other erroneous messages
continue
if 'out' in raw:
ret[raw['id']]['out'] = raw['out']
yield ret
time.sleep(0.02)
|
KeyError
|
dataset/ETHPy150Open saltstack/salt/salt/client/__init__.py/LocalClient.get_event_iter_returns
|
3,373 |
def __lt__(self, other):
sort_col = self.treeWidget().sortColumn()
if sort_col in set([1]):
try:
return int(self.text(sort_col)) < int(other.text(sort_col))
except __HOLE__:
pass
return QtGui.QTreeWidgetItem.__lt__(self, other)
|
ValueError
|
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/gui/collection/explorer.py/QExecutionItem.__lt__
|
3,374 |
def __lt__(self, other):
sort_col = self.treeWidget().sortColumn()
if sort_col in set([1]):
try:
return int(self.text(sort_col)) < int(other.text(sort_col))
except __HOLE__:
pass
return QtGui.QTreeWidgetItem.__lt__(self, other)
|
ValueError
|
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/gui/collection/explorer.py/QWorkflowItem.__lt__
|
3,375 |
def plot(self, db_path, label='time', ax=None, title=True):
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, DateFormatter
results = self.get_results(db_path)
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111)
timing = results['timing']
if self.start_date is not None:
timing = timing.truncate(before=self.start_date)
timing.plot(ax=ax, style='b-', label=label)
ax.set_xlabel('Date')
ax.set_ylabel('milliseconds')
if self.logy:
ax2 = ax.twinx()
try:
timing.plot(ax=ax2, label='%s (log scale)' % label,
style='r-',
logy=self.logy)
ax2.set_ylabel('milliseconds (log scale)')
ax.legend(loc='best')
ax2.legend(loc='best')
except __HOLE__:
pass
ylo, yhi = ax.get_ylim()
if ylo < 1:
ax.set_ylim([0, yhi])
formatter = DateFormatter("%b %Y")
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(formatter)
ax.autoscale_view(scalex=True)
if title:
ax.set_title(self.name)
return ax
|
ValueError
|
dataset/ETHPy150Open pydata/vbench/vbench/benchmark.py/Benchmark.plot
|
3,376 |
def avTimeExpression(infile):
'''
Calculate average expression over replicates at each time point
Requires genes as columns with 'replicates' and 'times' as additional
columns
'''
# check file compression
if infile.split(".")[-1] == "gz":
comp = "gzip"
else:
comp = None
df = pd.read_table(infile, sep="\t",
header=0, index_col=0,
compression=comp)
# average over replicates at each time point
# then recombine
df_groups = df.groupby(by='times')
data_frame = pd.DataFrame(index=df.columns,
columns=None)
for names, groups in df_groups:
_df = groups.drop(['times', 'replicates'], axis=1)
_df = _df.apply(np.mean, axis=0)
data_frame[names] = _df
# check no extraneous columns remaining
try:
data_frame.drop(['replicates', 'times'],
inplace=True,
axis=0)
except __HOLE__:
pass
return data_frame
|
KeyError
|
dataset/ETHPy150Open CGATOxford/cgat/CGAT/Timeseries/__init__.py/avTimeExpression
|
3,377 |
def drawVennDiagram(deg_dict, header, out_dir):
'''
Take a dictionary of gene IDs, with keys corresponding
to timepoints/differential expression analyses and
generate a Venn diagram. Maximum of 5 overlapping sets
possible using R package:: VennDiagram.
'''
keys = deg_dict.keys()
try:
keys = sorted(keys, key=lambda x: int(x.split("_")[1].rstrip("-time")))
except __HOLE__:
pass
venn_size = len(keys)
R('''suppressPackageStartupMessages(library("VennDiagram"))''')
n1 = set(deg_dict[keys[0]])
n2 = set(deg_dict[keys[1]])
area1 = len(n1)
area2 = len(n2)
n12 = len(n1.intersection(n2))
# for Venn > 2 sets
if venn_size == 3:
n3 = set(deg_dict[keys[2]])
area3 = len(n3)
n13 = len(n1.intersection(n3))
n23 = len(n2.intersection(n3))
n123 = len((n1.intersection(n2)).intersection(n3))
cat1, cat2, cat3 = keys
R('''png("%(out_dir)s/%(header)s-venn.png", '''
'''width=1.8, height=1.8, res=90, units="in")''' % locals())
R('''draw.triple.venn(%(area1)d, %(area2)d, %(area3)d, '''
'''%(n12)d, %(n23)d, %(n13)d, %(n123)d, '''
'''c('%(cat1)s', '%(cat2)s', '%(cat3)s'), '''
'''col=c('red', 'yellow', 'skyblue'), '''
'''fill=c('red', 'yellow', 'skyblue'), '''
'''margin=0.05, alpha=0.5)''' % locals())
R('''dev.off()''')
elif venn_size == 4:
n3 = set(deg_dict[keys[2]])
area3 = len(n3)
n13 = len(n1.intersection(n3))
n23 = len(n2.intersection(n3))
n123 = len((n1.intersection(n2)).intersection(n3))
n4 = set(deg_dict[keys[3]])
area4 = len(n4)
n14 = len(n1.intersection(n4))
n24 = len(n2.intersection(n4))
n34 = len(n3.intersection(n4))
n124 = len((n1.intersection(n2)).intersection(n4))
n134 = len((n1.intersection(n3)).intersection(n4))
n234 = len((n2.intersection(n3)).intersection(n4))
n1234 = len(((n1.intersection(n2)).intersection(n3)).intersection(n4))
cat1, cat2, cat3, cat4 = keys
R('''png("%(out_dir)s/%(header)s-venn.png",'''
'''width=2.3, height=2.3, res=300, units="in")''' % locals())
R('''draw.quad.venn(%(area1)d, %(area2)d, %(area3)d, %(area4)d,'''
'''%(n12)d, %(n13)d, %(n14)d, %(n23)d, %(n24)d, %(n34)d,'''
'''%(n123)d, %(n124)d, %(n134)d, %(n234)d, %(n1234)d,'''
'''c('%(cat1)s', '%(cat2)s', '%(cat3)s', '%(cat4)s'), '''
'''col=c("red", "yellow", "skyblue", "orange"), '''
'''fill=c("red", "yellow", "skyblue", "orange"), '''
'''margin=0.05, alpha=0.5)''' % locals())
R('''dev.off()''')
elif venn_size == 5:
n3 = set(deg_dict[keys[2]])
area3 = len(n3)
n13 = len(n1.intersection(n3))
n23 = len(n2.intersection(n3))
n123 = len((n1.intersection(n2)).intersection(n3))
n4 = set(deg_dict[keys[3]])
area4 = len(n4)
n14 = len(n1.intersection(n4))
n24 = len(n2.intersection(n4))
n34 = len(n3.intersection(n4))
n124 = len((n1.intersection(n2)).intersection(n4))
n134 = len((n1.intersection(n3)).intersection(n4))
n234 = len((n2.intersection(n3)).intersection(n4))
n1234 = len(((n1.intersection(n2)).intersection(n3)).intersection(n4))
n5 = set(deg_dict[keys[4]])
area5 = len(n5)
n15 = len(n1.intersection(n5))
n25 = len(n2.intersection(n5))
n35 = len(n3.intersection(n5))
n45 = len(n4.intersection(n5))
n125 = len((n1.intersection(n2)).intersection(n5))
n135 = len((n1.intersection(n3)).intersection(n5))
n145 = len((n1.intersection(n4)).intersection(n5))
n235 = len((n2.intersection(n3)).intersection(n5))
n245 = len((n2.intersection(n4)).intersection(n5))
n345 = len((n3.intersection(n4)).intersection(n5))
n1235 = len(((n1.intersection(n2)).intersection(n3)).intersection(n5))
n1245 = len(((n1.intersection(n2)).intersection(n4)).intersection(n5))
n1345 = len(((n1.intersection(n3)).intersection(n4)).intersection(n5))
n2345 = len(((n2.intersection(n3)).intersection(n4)).intersection(n5))
nstep = ((n1.intersection(n2)).intersection(n3))
n12345 = len((nstep.intersection(n4)).intersection(n5))
cat1, cat2, cat3, cat4, cat5 = keys
R('''png("%(out_dir)s/%(header)s-venn.png", '''
'''height=1.8, width=1.8, res=90, units="in")''' % locals())
R('''draw.quintuple.venn(%(area1)d, %(area2)d, %(area3)d, '''
'''%(area4)d, %(area5)d, %(n12)d, %(n13)d, %(n14)d,'''
'''%(n15)d, %(n23)d, %(n24)d, %(n25)d, %(n34)d, %(n35)d,'''
'''%(n45)d, %(n123)d, %(n124)d, %(n125)d, %(n134)d,'''
'''%(n135)d, %(n145)d, %(n234)d, %(n235)d, %(n245)d,'''
'''%(n345)d, %(n1234)d, %(n1235)d, %(n1245)d, %(n1345)d,'''
'''%(n2345)d, %(n12345)d, '''
'''c('%(cat1)s', '%(cat2)s', '%(cat3)s', '%(cat4)s', '%(cat5)s'),'''
'''col=c("red", "yellow", "skyblue", "orange", "purple"),'''
'''fill=c("red", "yellow", "skyblue", "orange", "purple"),'''
'''alpha=0.05, margin=0.05, cex=rep(0.8, 31))''' % locals())
R('''dev.off()''')
elif venn_size > 5:
raise ValueError("Illegal venn diagram size, must be <= 5")
|
IndexError
|
dataset/ETHPy150Open CGATOxford/cgat/CGAT/Timeseries/__init__.py/drawVennDiagram
|
3,378 |
def split_first_key(values, key):
try:
index = values.index(key)
return (values[:index], values[index+1:])
except __HOLE__:
return (values, None)
|
ValueError
|
dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/pulitools/puliexec/puliexec.py/split_first_key
|
3,379 |
def __del__(self):
'''Attempt to clean up'''
if self.plist:
launchctl_cmd = ['/bin/launchctl', 'unload', self.plist_path]
dummy_result = subprocess.call(launchctl_cmd)
try:
self.stdout.close()
self.stderr.close()
except AttributeError:
pass
try:
os.unlink(self.plist_path)
os.unlink(self.stdout_path)
os.unlink(self.stderr_path)
except (OSError, __HOLE__):
pass
|
IOError
|
dataset/ETHPy150Open munki/munki/code/client/munkilib/launchd.py/Job.__del__
|
3,380 |
def start(self):
'''Start the launchd job'''
launchctl_cmd = ['/bin/launchctl', 'start', self.label]
proc = subprocess.Popen(launchctl_cmd, shell=False, bufsize=-1,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
err = proc.communicate()[1]
if proc.returncode:
raise LaunchdJobException(err)
else:
if (not os.path.exists(self.stdout_path) or
not os.path.exists(self.stderr_path)):
# wait a second for the stdout/stderr files
# to be created by launchd
time.sleep(1)
try:
# open the stdout and stderr output files and
# store their file descriptors for use
self.stdout = open(self.stdout_path, 'r')
self.stderr = open(self.stderr_path, 'r')
except (OSError, __HOLE__), err:
raise LaunchdJobException(err)
|
IOError
|
dataset/ETHPy150Open munki/munki/code/client/munkilib/launchd.py/Job.start
|
3,381 |
def _test_fields(iterkv, test, efrag):
try:
for k, v in iterkv:
if not test(v):
raise ValueError()
except __HOLE__:
raise QSeqFormatError('Field %r is not %s.' % (k, efrag))
|
ValueError
|
dataset/ETHPy150Open biocore/scikit-bio/skbio/io/format/qseq.py/_test_fields
|
3,382 |
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (__HOLE__, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
kwargs = {
'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None),
'locale': to_locale(get_language() or settings.LANGUAGE_CODE),
}
return format_currency(value, **kwargs)
|
TypeError
|
dataset/ETHPy150Open django-oscar/django-oscar/src/oscar/templatetags/currency_filters.py/currency
|
3,383 |
def _parse_srs_attrs(self, attrsD):
srsName = attrsD.get('srsname')
try:
srsDimension = int(attrsD.get('srsdimension', '2'))
except __HOLE__:
srsDimension = 2
context = self._getContext()
context['where']['srsName'] = srsName
context['where']['srsDimension'] = srsDimension
|
ValueError
|
dataset/ETHPy150Open SickRage/SickRage/lib/feedparser/namespaces/georss.py/Namespace._parse_srs_attrs
|
3,384 |
def _parse_georss_point(value, swap=True, dims=2):
# A point contains a single latitude-longitude pair, separated by
# whitespace. We'll also handle comma separators.
try:
coords = list(_gen_georss_coords(value, swap, dims))
return {'type': 'Point', 'coordinates': coords[0]}
except (IndexError, __HOLE__):
return None
|
ValueError
|
dataset/ETHPy150Open SickRage/SickRage/lib/feedparser/namespaces/georss.py/_parse_georss_point
|
3,385 |
def _parse_georss_line(value, swap=True, dims=2):
# A line contains a space separated list of latitude-longitude pairs in
# WGS84 coordinate reference system, with each pair separated by
# whitespace. There must be at least two pairs.
try:
coords = list(_gen_georss_coords(value, swap, dims))
return {'type': 'LineString', 'coordinates': coords}
except (__HOLE__, ValueError):
return None
|
IndexError
|
dataset/ETHPy150Open SickRage/SickRage/lib/feedparser/namespaces/georss.py/_parse_georss_line
|
3,386 |
def _parse_georss_polygon(value, swap=True, dims=2):
# A polygon contains a space separated list of latitude-longitude pairs,
# with each pair separated by whitespace. There must be at least four
# pairs, with the last being identical to the first (so a polygon has a
# minimum of three actual points).
try:
ring = list(_gen_georss_coords(value, swap, dims))
except (__HOLE__, ValueError):
return None
if len(ring) < 4:
return None
return {'type': 'Polygon', 'coordinates': (ring,)}
|
IndexError
|
dataset/ETHPy150Open SickRage/SickRage/lib/feedparser/namespaces/georss.py/_parse_georss_polygon
|
3,387 |
def _parse_georss_box(value, swap=True, dims=2):
# A bounding box is a rectangular region, often used to define the extents
# of a map or a rough area of interest. A box contains two space seperate
# latitude-longitude pairs, with each pair separated by whitespace. The
# first pair is the lower corner, the second is the upper corner.
try:
coords = list(_gen_georss_coords(value, swap, dims))
return {'type': 'Box', 'coordinates': tuple(coords)}
except (IndexError, __HOLE__):
return None
# The list of EPSG codes for geographic (latitude/longitude) coordinate
# systems to support decoding of GeoRSS GML profiles.
|
ValueError
|
dataset/ETHPy150Open SickRage/SickRage/lib/feedparser/namespaces/georss.py/_parse_georss_box
|
3,388 |
def top_then_bottom_then_top_again_etc(expr, scope, **kwargs):
""" Compute expression against scope
Does the following interpreter strategy:
1. Try compute_down on the entire expression
2. Otherwise compute_up from the leaves until we experience a type change
(e.g. data changes from dict -> pandas DataFrame)
3. Re-optimize expression and re-pre-compute data
4. Go to step 1
Examples
--------
>>> import numpy as np
>>> s = symbol('s', 'var * {name: string, amount: int}')
>>> data = np.array([('Alice', 100), ('Bob', 200), ('Charlie', 300)],
... dtype=[('name', 'S7'), ('amount', 'i4')])
>>> e = s.amount.sum() + 1
>>> top_then_bottom_then_top_again_etc(e, {s: data})
601
See Also
--------
bottom_up_until_type_break -- uses this for bottom-up traversal
top_to_bottom -- older version
bottom_up -- older version still
"""
# 0. Base case: expression is in dict, return associated data
if expr in scope:
return scope[expr]
if not hasattr(expr, '_leaves'):
return expr
leaf_exprs = list(expr._leaves())
leaf_data = [scope.get(leaf) for leaf in leaf_exprs]
# 1. See if we have a direct computation path with compute_down
try:
return compute_down(expr, *leaf_data, **kwargs)
except __HOLE__:
pass
# 2. Compute from the bottom until there is a data type change
expr2, scope2 = bottom_up_until_type_break(expr, scope, **kwargs)
# 3. Re-optimize data and expressions
optimize_ = kwargs.get('optimize', optimize)
pre_compute_ = kwargs.get('pre_compute', pre_compute)
if pre_compute_:
scope3 = dict((e, pre_compute_(e, datum,
**assoc(kwargs, 'scope', scope2)))
for e, datum in scope2.items())
else:
scope3 = scope2
if optimize_:
try:
expr3 = optimize_(expr2, *[scope3[leaf]
for leaf in expr2._leaves()])
_d = dict(zip(expr2._leaves(), expr3._leaves()))
scope4 = dict((e._subs(_d), d) for e, d in scope3.items())
except NotImplementedError:
expr3 = expr2
scope4 = scope3
else:
expr3 = expr2
scope4 = scope3
# 4. Repeat
if expr.isidentical(expr3):
raise NotImplementedError("Don't know how to compute:\n"
"type(expr): %s\n"
"expr: %s\n"
"data: %s" % (type(expr3), expr3, scope4))
else:
return top_then_bottom_then_top_again_etc(expr3, scope4, **kwargs)
|
NotImplementedError
|
dataset/ETHPy150Open blaze/blaze/blaze/compute/core.py/top_then_bottom_then_top_again_etc
|
3,389 |
def bottom_up_until_type_break(expr, scope, **kwargs):
""" Traverse bottom up until data changes significantly
Parameters
----------
expr: Expression
Expression to compute
scope: dict
namespace matching leaves of expression to data
Returns
-------
expr: Expression
New expression with lower subtrees replaced with leaves
scope: dict
New scope with entries for those leaves
Examples
--------
>>> import numpy as np
>>> s = symbol('s', 'var * {name: string, amount: int}')
>>> data = np.array([('Alice', 100), ('Bob', 200), ('Charlie', 300)],
... dtype=[('name', 'S7'), ('amount', 'i8')])
This computation completes without changing type. We get back a leaf
symbol and a computational result
>>> e = (s.amount + 1).distinct()
>>> bottom_up_until_type_break(e, {s: data}) # doctest: +SKIP
(amount, {amount: array([101, 201, 301])})
This computation has a type change midstream (``list`` to ``int``), so we
stop and get the unfinished computation.
>>> e = s.amount.sum() + 1
>>> bottom_up_until_type_break(e, {s: data})
(amount_sum + 1, {<`amount_sum` symbol; dshape='int64'>: 600})
"""
# 0. Base case. Return if expression is in scope
if expr in scope:
leaf = makeleaf(expr)
return leaf, {leaf: scope[expr]}
inputs = list(unique(expr._inputs))
# 1. Recurse down the tree, calling this function on children
# (this is the bottom part of bottom up)
exprs, new_scopes = zip(*[bottom_up_until_type_break(i, scope, **kwargs)
for i in inputs])
# 2. Form new (much shallower) expression and new (more computed) scope
new_scope = toolz.merge(new_scopes)
new_expr = expr._subs({
i: e for i, e in zip(inputs, exprs) if not i.isidentical(e)
})
old_expr_leaves = expr._leaves()
old_data_leaves = [scope.get(leaf) for leaf in old_expr_leaves]
# 3. If the leaves have changed substantially then stop
key = lambda x: str(type(x))
if type_change(sorted(new_scope.values(), key=key),
sorted(old_data_leaves, key=key)):
return new_expr, new_scope
# 4. Otherwise try to do some actual work
try:
leaf = makeleaf(expr)
_data = [new_scope[i] for i in new_expr._inputs]
except KeyError:
return new_expr, new_scope
try:
return leaf, {leaf: compute_up(new_expr, *_data, scope=new_scope,
**kwargs)}
except __HOLE__:
return new_expr, new_scope
|
NotImplementedError
|
dataset/ETHPy150Open blaze/blaze/blaze/compute/core.py/bottom_up_until_type_break
|
3,390 |
@dispatch(Expr, Mapping)
def compute(expr, d, return_type=no_default, **kwargs):
"""Compute expression against data sources.
Parameters
----------
expr : str
blaze expression
d: resource
data source to compute expression on
return_type : {'native', 'core', type}, optional
Type to return data as. Defaults to 'native' but will be changed
to 'core' in version 0.11. 'core' forces the computation into a core type.
'native' returns the result as is from the respective backend's `post_compute`.
If a type is passed, it will odo the result into the type before returning.
>>> t = symbol('t', 'var * {name: string, balance: int}')
>>> deadbeats = t[t['balance'] < 0]['name']
>>> data = [['Alice', 100], ['Bob', -50], ['Charlie', -20]]
>>> list(compute(deadbeats, {t: data}))
['Bob', 'Charlie']
"""
_reset_leaves()
optimize_ = kwargs.get('optimize', optimize)
pre_compute_ = kwargs.get('pre_compute', pre_compute)
post_compute_ = kwargs.get('post_compute', post_compute)
expr2, d2 = swap_resources_into_scope(expr, d)
if pre_compute_:
d3 = dict(
(e, pre_compute_(e, dat, **kwargs))
for e, dat in d2.items()
if e in expr2
)
else:
d3 = d2
if optimize_:
try:
expr3 = optimize_(expr2, *[v for e, v in d3.items() if e in expr2])
_d = dict(zip(expr2._leaves(), expr3._leaves()))
d4 = dict((e._subs(_d), d) for e, d in d3.items())
except __HOLE__:
expr3 = expr2
d4 = d3
else:
expr3 = expr2
d4 = d3
result = top_then_bottom_then_top_again_etc(expr3, d4, **kwargs)
if post_compute_:
result = post_compute_(expr3, result, scope=d4)
# return the backend's native response
if return_type is no_default:
msg = ("The default behavior of compute will change in version >= 0.11"
" where the `return_type` parameter will default to 'core'.")
warnings.warn(msg, DeprecationWarning)
# return result as a core type
# (python type, pandas Series/DataFrame, numpy array)
elif return_type == 'core':
result = coerce_core(result, expr.dshape)
# user specified type
elif isinstance(return_type, type):
result = into(return_type, result)
elif return_type != 'native':
raise ValueError(
"Invalid return_type passed to compute: {}".format(return_type),
)
return result
|
NotImplementedError
|
dataset/ETHPy150Open blaze/blaze/blaze/compute/core.py/compute
|
3,391 |
def validate_response(self, data, status_code, headers):
"""
Validates the Response object based on what has been declared in the specification.
Ensures the response body matches the declated schema.
:type data: dict
:type status_code: int
:type headers: dict
:rtype bool | None
"""
response_definitions = self.operation.operation["responses"]
response_definition = response_definitions.get(str(status_code), {})
response_definition = self.operation.resolve_reference(response_definition)
# TODO handle default response definitions
if self.is_json_schema_compatible(response_definition):
schema = response_definition.get("schema")
v = ResponseBodyValidator(schema)
try:
# For cases of custom encoders, we need to encode and decode to
# transform to the actual types that are going to be returned.
data = json.dumps(data)
data = json.loads(data)
v.validate_schema(data)
except __HOLE__ as e:
raise NonConformingResponseBody(message=str(e))
if response_definition and response_definition.get("headers"):
response_definition_header_keys = response_definition.get("headers").keys()
if not all(item in headers.keys() for item in response_definition_header_keys):
raise NonConformingResponseHeaders(
message="Keys in header don't match response specification. Difference: %s"
% list(set(headers.keys()).symmetric_difference(set(response_definition_header_keys))))
return True
|
ValidationError
|
dataset/ETHPy150Open zalando/connexion/connexion/decorators/response.py/ResponseValidator.validate_response
|
3,392 |
def errcheck(result, func, arguments):
if _debug_gl_trace:
try:
name = func.__name__
except __HOLE__:
name = repr(func)
if _debug_gl_trace_args:
trace_args = ', '.join([repr(arg)[:20] for arg in arguments])
print '%s(%s)' % (name, trace_args)
else:
print name
from pyglet import gl
context = gl.current_context
if not context:
raise GLException('No GL context; create a Window first')
if not context._gl_begin:
error = gl.glGetError()
if error:
msg = ctypes.cast(gl.gluErrorString(error), ctypes.c_char_p).value
raise GLException(msg)
return result
|
AttributeError
|
dataset/ETHPy150Open ardekantur/pyglet/pyglet/gl/lib.py/errcheck
|
3,393 |
@classdef.singleton_method("size?", name="path")
def singleton_method_size_p(self, space, name):
try:
stat_val = os.stat(name)
except __HOLE__:
return space.w_nil
return space.w_nil if stat_val.st_size == 0 else space.newint_or_bigint(stat_val.st_size)
|
OSError
|
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.singleton_method_size_p
|
3,394 |
@classdef.singleton_method("unlink")
@classdef.singleton_method("delete")
def singleton_method_delete(self, space, args_w):
for w_path in args_w:
path = Coerce.path(space, w_path)
try:
os.unlink(path)
except __HOLE__ as e:
raise error_for_oserror(space, e)
return space.newint(len(args_w))
|
OSError
|
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.singleton_method_delete
|
3,395 |
@classdef.method("initialize", filename="path")
def method_initialize(self, space, filename, w_mode=None, w_perm_or_opt=None, w_opt=None):
if w_mode is None:
w_mode = space.w_nil
if w_perm_or_opt is None:
w_perm_or_opt = space.w_nil
if w_opt is None:
w_opt = space.w_nil
if isinstance(w_perm_or_opt, W_HashObject):
assert w_opt is space.w_nil
perm = 0665
w_opt = w_perm_or_opt
elif w_opt is not space.w_nil:
perm = space.int_w(w_perm_or_opt)
else:
perm = 0665
mode, encoding = map_filemode(space, w_mode)
if w_perm_or_opt is not space.w_nil or w_opt is not space.w_nil:
raise space.error(space.w_NotImplementedError, "options hash or permissions for File.new")
try:
self.fd = os.open(filename, mode, perm)
except __HOLE__ as e:
raise error_for_oserror(space, e)
self.filename = filename
return self
|
OSError
|
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.method_initialize
|
3,396 |
@classdef.singleton_method("expand_path", path="path")
def method_expand_path(self, space, path, w_dir=None):
if path and path[0] == "~":
try:
home = os.environ["HOME"]
except __HOLE__:
raise space.error(space.w_ArgumentError, "couldn't find HOME environment -- expanding")
if not home or (not IS_WINDOWS and home[0] != "/"):
raise space.error(space.w_ArgumentError, "non-absolute home")
if len(path) >= 2 and path[1] == "/":
path = home + path[1:]
elif len(path) < 2:
return space.newstr_fromstr(home)
else:
raise space.error(space.w_NotImplementedError, "~user for File.expand_path")
elif not path or path[0] != "/":
if w_dir is not None and w_dir is not space.w_nil:
dir = space.str_w(space.send(self, "expand_path", [w_dir]))
else:
dir = os.getcwd()
path = dir + "/" + path
items = []
if IS_WINDOWS:
path = path.replace("\\", "/")
parts = path.split("/")
was_letter = False
first_slash = True
for part in parts:
if not part and not was_letter:
if not first_slash:
items.append(part)
first_slash = False
elif part == "..":
if len(items) > 0:
items.pop()
elif part and part != ".":
was_letter = True
items.append(part)
if not IS_WINDOWS:
root = "/"
else:
root = ""
return space.newstr_fromstr(root + "/".join(items))
|
KeyError
|
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.method_expand_path
|
3,397 |
@classdef.singleton_method("identical?", file="path", other="path")
def method_identicalp(self, space, file, other):
try:
file_stat = os.stat(file)
other_stat = os.stat(other)
except __HOLE__:
return space.w_false
return space.newbool(file_stat.st_dev == other_stat.st_dev and
file_stat.st_ino == other_stat.st_ino)
|
OSError
|
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.method_identicalp
|
3,398 |
@classdef.method("truncate", length="int")
def method_truncate(self, space, length):
self.ensure_not_closed(space)
try:
ftruncate(self.fd, length)
except __HOLE__ as e:
raise error_for_oserror(space, e)
return space.newint(0)
|
OSError
|
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.method_truncate
|
3,399 |
@classdef.method("mtime")
def method_mtime(self, space):
try:
stat_val = os.stat(self.filename)
except __HOLE__ as e:
raise error_for_oserror(space, e)
return self._time_at(space, stat_val.st_mtime)
|
OSError
|
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.method_mtime
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.