Unnamed: 0
int64 0
10k
| function
stringlengths 79
138k
| label
stringclasses 20
values | info
stringlengths 42
261
|
|---|---|---|---|
9,500
|
def get_logging_config(logging_dir):
try:
log_file = os.path.join(logging_dir, 'pynacea.log')
if not os.path.exists(logging_dir):
os.makedirs(logging_dir)
if not os.path.exists(log_file):
with open(log_file, 'w') as f:
pass
log_level = config.settings['logging level']
if isinstance(log_level, str) and log_level.lower() in constants.LOGGING_LEVELS:
log_level = constants.LOGGING_LEVELS[log_level.lower()]
return log_file, int(log_level)
except __HOLE__:
return None, None
|
KeyError
|
dataset/ETHPy150Open evfredericksen/pynacea/pynhost/pynhost/utilities.py/get_logging_config
|
9,501
|
def check_negative(value):
e = argparse.ArgumentTypeError('{} is an invalid non-negative float value'.format(value))
try:
fvalue = float(value)
except __HOLE__:
raise e
if fvalue < 0:
raise e
return fvalue
|
ValueError
|
dataset/ETHPy150Open evfredericksen/pynacea/pynhost/pynhost/utilities.py/check_negative
|
9,502
|
def get_number_string(line):
num_words = []
for word in line.split():
if hasattr(_locals, 'NUMBERS_MAP') and word in _locals.NUMBERS_MAP:
num_words.append(_locals.NUMBERS_MAP[word])
else:
try:
num = float(word)
if int(num) - num == 0:
num = int(num)
num_words.append(str(num))
except (ValueError, __HOLE__, IndexError):
pass
return ' '.join(num_words)
|
TypeError
|
dataset/ETHPy150Open evfredericksen/pynacea/pynhost/pynhost/utilities.py/get_number_string
|
9,503
|
def convert_to_num(word):
try:
return _locals.NUMBERS_MAP[word]
except AttributeError:
try:
num = float(word)
if num.is_integer():
num = int(num)
return str(num)
except (ValueError, __HOLE__, IndexError):
return None
|
TypeError
|
dataset/ETHPy150Open evfredericksen/pynacea/pynhost/pynhost/utilities.py/convert_to_num
|
9,504
|
def log_message(log_handler, level, message):
try:
handler_method = getattr(log_handler, level)
handler_method(message)
except __HOLE__:
pass
|
AttributeError
|
dataset/ETHPy150Open evfredericksen/pynacea/pynhost/pynhost/utilities.py/log_message
|
9,505
|
def safe_import(module_name, class_name):
"""
try to import a module, and if it fails because an ImporError
it logs on WARNING, and logs the traceback on DEBUG level
"""
if type(class_name) is list:
for name in class_name:
safe_import(module_name, name)
return
package = __package__
# TODO: remove when we really want to drop 3.2 support
# python 3.2 don't set __package__
if not package:
package = __name__
try:
module = importlib.import_module(module_name, package)
globals()[class_name] = getattr(module, class_name)
except __HOLE__ as error:
logger.warning("Can't Import Widget: '%s.%s', %s", module_name, class_name, error)
logger.debug("%s", traceback.format_exc())
|
ImportError
|
dataset/ETHPy150Open qtile/qtile/libqtile/widget/__init__.py/safe_import
|
9,506
|
def open(self, url, new=0, autoraise=True):
cmdline = [self.name] + [arg.replace("%s", url)
for arg in self.args]
inout = file(os.devnull, "r+")
try:
if sys.platform[:3] == 'win':
p = subprocess.Popen(cmdline)
else:
setsid = getattr(os, 'setsid', None)
if not setsid:
setsid = getattr(os, 'setpgrp', None)
p = subprocess.Popen(cmdline, close_fds=True,
stdin=inout, stdout=inout,
stderr=inout, preexec_fn=setsid)
return (p.poll() is None)
except __HOLE__:
return False
|
OSError
|
dataset/ETHPy150Open openstack/gertty/gertty/app.py/BackgroundBrowser.open
|
9,507
|
def run(self):
try:
self.loop.run()
except __HOLE__:
pass
|
KeyboardInterrupt
|
dataset/ETHPy150Open openstack/gertty/gertty/app.py/App.run
|
9,508
|
def _syncOneChangeFromQuery(self, query):
number = changeid = restid = None
if query.startswith("change:"):
number = query.split(':')[1].strip()
try:
number = int(number)
except __HOLE__:
number = None
changeid = query.split(':')[1].strip()
if not (number or changeid):
return
with self.db.getSession() as session:
if number:
changes = [session.getChangeByNumber(number)]
elif changeid:
changes = session.getChangesByChangeID(changeid)
change_keys = [c.key for c in changes if c]
restids = [c.id for c in changes if c]
if not change_keys:
if self.sync.offline:
raise Exception('Can not sync change while offline.')
dialog = mywid.SystemMessage("Syncing change...")
self.popup(dialog, width=40, height=6)
self.loop.draw_screen()
try:
task = sync.SyncChangeByNumberTask(number or changeid, sync.HIGH_PRIORITY)
self.sync.submitTask(task)
succeeded = task.wait(300)
if not succeeded:
raise Exception('Unable to find change.')
for subtask in task.tasks:
succeeded = subtask.wait(300)
if not succeeded:
raise Exception('Unable to sync change.')
finally:
# Remove "syncing..." popup
self.backScreen()
with self.db.getSession() as session:
if number:
changes = [session.getChangeByNumber(number)]
elif changeid:
changes = session.getChangesByChangeID(changeid)
change_keys = [c.key for c in changes if c]
elif restids:
for restid in restids:
task = sync.SyncChangeTask(restid, sync.HIGH_PRIORITY)
self.sync.submitTask(task)
if not change_keys:
raise Exception('Change is not in local database.')
|
ValueError
|
dataset/ETHPy150Open openstack/gertty/gertty/app.py/App._syncOneChangeFromQuery
|
9,509
|
@classmethod
def get_installer(cls, name, path, adapter_info, cluster_info, hosts_info):
try:
mod_file, path, descr = imp.find_module(name, [path])
if mod_file:
mod = imp.load_module(name, mod_file, path, descr)
config_manager = BaseConfigManager(adapter_info, cluster_info,
hosts_info)
return getattr(mod, mod.NAME)(config_manager)
except __HOLE__ as exc:
logging.error('No such module found: %s', name)
logging.exception(exc)
return None
|
ImportError
|
dataset/ETHPy150Open openstack/compass-core/compass/deployment/installers/installer.py/BaseInstaller.get_installer
|
9,510
|
def get_all_permissions(self, user, obj=None):
"""Returns a set of permission strings that the user has.
This permission available to the user is derived from the user's
Keystone "roles".
The permissions are returned as ``"openstack.{{ role.name }}"``.
"""
if user.is_anonymous() or obj is not None:
return set()
# TODO(gabrielhurley): Integrate policy-driven RBAC
# when supported by Keystone.
role_perms = {utils.get_role_permission(role['name'])
for role in user.roles}
services = []
for service in user.service_catalog:
try:
service_type = service['type']
except __HOLE__:
continue
service_regions = [utils.get_endpoint_region(endpoint) for endpoint
in service.get('endpoints', [])]
if user.services_region in service_regions:
services.append(service_type.lower())
service_perms = {"openstack.services.%s" % service
for service in services}
return role_perms | service_perms
|
KeyError
|
dataset/ETHPy150Open openstack/django_openstack_auth/openstack_auth/backend.py/KeystoneBackend.get_all_permissions
|
9,511
|
def _write_cache(self, code, ts, file_info):
""" Write the cached file for then given info, creating the
cache directory if needed. This call will suppress any
IOError or OSError exceptions.
Parameters
----------
code : types.CodeType
The code object to write to the cache.
ts : int
The integer timestamp for the file.
file_info : EnamlFileInfo
The file info object for the file.
"""
try:
if not os.path.exists(file_info.cache_dir):
os.mkdir(file_info.cache_dir)
with open(file_info.cache_path, 'w+b') as cache_file:
cache_file.write(MAGIC)
cache_file.write(struct.pack('i', ts))
marshal.dump(code, cache_file)
except (OSError, __HOLE__):
pass
|
IOError
|
dataset/ETHPy150Open ContinuumIO/ashiba/enaml/enaml/core/import_hooks.py/EnamlImporter._write_cache
|
9,512
|
@classmethod
def get_ip_port(cls, ip=None, port=None):
ip = ip or os.environ.get('LIBPROCESS_IP', '0.0.0.0')
try:
port = int(port or os.environ.get('LIBPROCESS_PORT', 0))
except __HOLE__:
raise cls.Error('Invalid ip/port provided')
return ip, port
|
ValueError
|
dataset/ETHPy150Open wickman/compactor/compactor/context.py/Context.get_ip_port
|
9,513
|
def _get_dispatch_method(self, pid, method):
try:
return getattr(self._processes[pid], method)
except __HOLE__:
raise self.InvalidProcess('Unknown process %s' % pid)
except AttributeError:
raise self.InvalidMethod('Unknown method %s on %s' % (method, pid))
|
KeyError
|
dataset/ETHPy150Open wickman/compactor/compactor/context.py/Context._get_dispatch_method
|
9,514
|
def __erase_link(self, to_pid):
for pid, links in self._links.items():
try:
links.remove(to_pid)
log.debug('PID link from %s <- %s exited.' % (pid, to_pid))
self._processes[pid].exited(to_pid)
except __HOLE__:
continue
|
KeyError
|
dataset/ETHPy150Open wickman/compactor/compactor/context.py/Context.__erase_link
|
9,515
|
def rm_empty_dir(path):
try:
os.rmdir(path)
except __HOLE__: # directory might not exist or not be empty
pass
|
OSError
|
dataset/ETHPy150Open ContinuumIO/menuinst/menuinst/utils.py/rm_empty_dir
|
9,516
|
def utcparse(input):
""" Translate a string into a time using dateutil.parser.parse but make sure it's in UTC time and strip
the timezone, so that it's compatible with normal datetime.datetime objects.
For safety this can also handle inputs that are either timestamps, or datetimes
"""
# prepare the input for the checks below by
# casting strings ('1327098335') to ints
if isinstance(input, StringTypes):
try:
input = int(input)
except __HOLE__:
pass
if isinstance (input, datetime.datetime):
logger.warn ("argument to utcparse already a datetime - doing nothing")
return input
elif isinstance (input, StringTypes):
t = dateutil.parser.parse(input)
if t.utcoffset() is not None:
t = t.utcoffset() + t.replace(tzinfo=None)
return t
elif isinstance (input, (int,float,long)):
return datetime.datetime.fromtimestamp(input)
else:
logger.error("Unexpected type in utcparse [%s]"%type(input))
|
ValueError
|
dataset/ETHPy150Open fp7-ofelia/ocf/ofam/src/src/foam/sfa/util/sfatime.py/utcparse
|
9,517
|
def get_revision(self, id_):
"""Return the :class:`.Script` instance with the given rev id."""
id_ = self.as_revision_number(id_)
try:
return self._revision_map[id_]
except __HOLE__:
# do a partial lookup
revs = [x for x in self._revision_map
if x is not None and x.startswith(id_)]
if not revs:
raise util.CommandError("No such revision '%s'" % id_)
elif len(revs) > 1:
raise util.CommandError(
"Multiple revisions start "
"with '%s', %s..." % (
id_,
", ".join("'%s'" % r for r in revs[0:3])
))
else:
return self._revision_map[revs[0]]
|
KeyError
|
dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/alembic/script.py/ScriptDirectory.get_revision
|
9,518
|
def ia_credentials_helper(client_id, client_secret,
credentials_cache_file="credentials.json",
cache_key="default"):
"""Helper function to manage a credentials cache during testing.
This function attempts to load and refresh a credentials object from a
json cache file, using the cache_key and client_id as a lookup.
If this isn't found then it starts an OAuth2 authentication flow, using
the client_id and client_secret and if successful, saves those to the local
cache. See :ref:`helper`.
Args:
client_id (str): Google Drive API client id string for an installed app
client_secret (str): The corresponding client secret.
credentials_cache_file (str): Filepath to the json credentials cache file
cache_key (str): Optional string to allow multiple credentials for a client
to be stored in the cache.
Returns:
OAuth2Credentials: A google api credentials object. As described here:
https://developers.google.com/api-client-library/python/guide/aaa_oauth
"""
def _load_credentials(key):
with open(credentials_cache_file, 'rb') as inf:
cache = json.load(inf)
cred_json = cache[key]
return OAuth2Credentials.from_json(cred_json)
def _save_credentials(key, credentials):
cache = {}
try:
with open(credentials_cache_file, 'rb') as inf:
cache = json.load(inf)
except (__HOLE__, ValueError), e:
pass
cache[key] = credentials.to_json()
with open(credentials_cache_file, 'wb') as ouf:
json.dump(cache, ouf)
credentials_key = "%s/%s/%s" % (client_id, client_secret, cache_key)
try:
credentials = _load_credentials(credentials_key)
if credentials.access_token_expired:
http = httplib2.Http()
credentials.refresh(http)
except (IOError,
ValueError,
KeyError,
AccessTokenRefreshError), e:
# Check https://developers.google.com/drive/scopes for all available scopes
OAUTH_SCOPE = ('https://www.googleapis.com/auth/drive '+
'https://spreadsheets.google.com/feeds')
# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(client_id, client_secret, OAUTH_SCOPE,
redirect_uri=REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print('Go to the following link in your browser:\n' + authorize_url)
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
_save_credentials(credentials_key, credentials)
return credentials
|
IOError
|
dataset/ETHPy150Open mbrenig/SheetSync/sheetsync/__init__.py/ia_credentials_helper
|
9,519
|
def google_equivalent(text1, text2):
# Google spreadsheets modify some characters, and anything that looks like
# a date. So this function will return true if text1 would equal text2 if
# both were input into a google cell.
lines1 = [l.replace('\t',' ').strip() for l in text1.splitlines()]
lines2 = [l.replace('\t',' ').strip() for l in text2.splitlines()]
if len(lines1) != len(lines2):
return False
if len(lines1) == 0 and len(lines2) == 0:
return True
if len(lines1) > 1:
for a,b in zip(lines1, lines2):
if a != b:
return False
# Multiline string matches on every line.
return True
elif lines1[0] == lines2[0]:
# Single line string.. that matches.
return True
# Might be dates.
text1 = lines1[0]
text2 = lines2[0]
if _is_google_fmt_date(text1) or _is_google_fmt_date(text2):
try:
date1 = dateutil.parser.parse(text1)
date2 = dateutil.parser.parse(text2)
if date1 == date2:
return True
except __HOLE__:
# Couldn't parse one of the dates.
pass
return False
|
ValueError
|
dataset/ETHPy150Open mbrenig/SheetSync/sheetsync/__init__.py/google_equivalent
|
9,520
|
def _get_value_for_column(self, key_tuple, raw_row, col):
# Given a column, and a row dictionary.. returns the value
# of the field corresponding with that column.
try:
header = self.header.col_lookup(col)
except __HOLE__:
logger.error("Unexpected: column %s has no header", col)
return ""
if header in self.key_column_headers:
key_dict = dict(zip(self.key_column_headers, key_tuple))
key_val = key_dict[header]
if key_val.isdigit() and not key_val.startswith('0'):
# Do not prefix integers so that the key column can be sorted
# numerically.
return key_val
return "'%s" % key_val
elif header in raw_row:
return raw_row[header]
elif header in self.header_to_ref_formula:
return self.header_to_ref_formula[header]
return ""
|
KeyError
|
dataset/ETHPy150Open mbrenig/SheetSync/sheetsync/__init__.py/Sheet._get_value_for_column
|
9,521
|
def _decode(self, data, decode_content, flush_decoder):
"""
Decode the data passed in and potentially flush the decoder.
"""
try:
if decode_content and self._decoder:
data = self._decoder.decompress(data)
except (__HOLE__, zlib.error) as e:
content_encoding = self.headers.get('content-encoding', '').lower()
raise DecodeError(
"Received response with content-encoding: %s, but "
"failed to decode it." % content_encoding, e)
if flush_decoder and decode_content and self._decoder:
buf = self._decoder.decompress(binary_type())
data += buf + self._decoder.flush()
return data
|
IOError
|
dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/requests/packages/urllib3/response.py/HTTPResponse._decode
|
9,522
|
def _update_chunk_length(self):
# First, we'll figure out length of a chunk and then
# we'll try to read it from socket.
if self.chunk_left is not None:
return
line = self._fp.fp.readline()
line = line.split(b';', 1)[0]
try:
self.chunk_left = int(line, 16)
except __HOLE__:
# Invalid chunked protocol response, abort.
self.close()
raise httplib.IncompleteRead(line)
|
ValueError
|
dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/requests/packages/urllib3/response.py/HTTPResponse._update_chunk_length
|
9,523
|
def __init__(self, parent):
parent.title = "PectoralisSegmentation" # TODO make this more human readable by adding spaces
parent.categories = ["Chest Imaging Platform"]
parent.dependencies = []
parent.contributors = ["Applied Chest Imaging Laboratory, Brigham and Women's Hopsital"] # replace with "Firstname Lastname (Org)"
parent.helpText = """
This is an example of scripted loadable module bundled in an extension.
"""
parent.acknowledgementText = """
This work is funded by the National Heart, Lung, And Blood Institute of the National Institutes of Health under Award Number R01HL116931. The content is solely the responsibility of the authors and does not necessarily represent the official views of the National Institutes of Health.
""" # 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['PectoralisSegmentation'] = self.runTest
|
AttributeError
|
dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/attic/PectoralisSegmentation/PectoralisSegmentation.py/PectoralisSegmentation.__init__
|
9,524
|
def conv_unixtime(t):
try:
t = datetime.strptime(t, '%Y-%m-%d %H:%M:%S')
t = int(time.mktime(t.timetuple()))
except TypeError:
t = None
except __HOLE__:
print('error: invalid time \'%s\'' % t)
exit(1)
return t
|
ValueError
|
dataset/ETHPy150Open YoshiyukiYamauchi/mrtparse/examples/slice.py/conv_unixtime
|
9,525
|
def get_range(self, name, min_value=None, max_value=None, default=0):
"""Parses the given int argument, limiting it to the given range.
Args:
name: the name of the argument
min_value: the minimum int value of the argument (if any)
max_value: the maximum int value of the argument (if any)
default: the default value of the argument if it is not given
Returns:
An int within the given range for the argument
"""
try:
value = int(self.get(name, default))
except __HOLE__:
value = default
if max_value != None:
value = min(value, max_value)
if min_value != None:
value = max(value, min_value)
return value
|
ValueError
|
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/ext/webapp/__init__.py/Request.get_range
|
9,526
|
def assert_has_keys(dct, required=[], optional=[]):
for k in required:
try:
assert k in dct
except __HOLE__:
extra_keys = set(dct.keys()).difference(set(required + optional))
raise AssertionError("found unexpected keys: %s" %
list(extra_keys))
|
AssertionError
|
dataset/ETHPy150Open openstack/python-rackclient/rackclient/openstack/common/apiclient/fake_client.py/assert_has_keys
|
9,527
|
def client_request(self, client, method, url, **kwargs):
# Check that certain things are called correctly
if method in ["GET", "DELETE"]:
assert "json" not in kwargs
# Note the call
self.callstack.append(
(method,
url,
kwargs.get("headers") or {},
kwargs.get("json") or kwargs.get("data")))
try:
fixture = self.fixtures[url][method]
except __HOLE__:
pass
else:
return TestResponse({"headers": fixture[0],
"text": fixture[1]})
# Call the method
args = parse.parse_qsl(parse.urlparse(url)[4])
kwargs.update(args)
munged_url = url.rsplit('?', 1)[0]
munged_url = munged_url.strip('/').replace('/', '_').replace('.', '_')
munged_url = munged_url.replace('-', '_')
callback = "%s_%s" % (method.lower(), munged_url)
if not hasattr(self, callback):
raise AssertionError('Called unknown API method: %s %s, '
'expected fakes method name: %s' %
(method, url, callback))
resp = getattr(self, callback)(**kwargs)
if len(resp) == 3:
status, headers, body = resp
else:
status, body = resp
headers = {}
return TestResponse({
"status_code": status,
"text": body,
"headers": headers,
})
|
KeyError
|
dataset/ETHPy150Open openstack/python-rackclient/rackclient/openstack/common/apiclient/fake_client.py/FakeHTTPClient.client_request
|
9,528
|
def format_default_result(result):
try:
output = json.loads(result) if isinstance(result, six.string_types) else result
return _serialize(output)
except (ValueError, __HOLE__):
return result
|
TypeError
|
dataset/ETHPy150Open StackStorm/st2contrib/packs/hubot/actions/post_result.py/format_default_result
|
9,529
|
def format_localrunner_result(result, do_serialize=True):
output = format_possible_failure_result(result)
# Add in various properties if they have values
stdout = result.get('stdout', None)
if stdout:
try:
output['stdout'] = stdout.strip()
except __HOLE__:
output['stdout'] = stdout
stderr = result.get('stderr', None)
if stderr:
output['stderr'] = stderr.strip()
return_code = result.get('return_code', 0)
if return_code != 0:
output['return_code'] = return_code
error = result.get('error', None)
if error:
output['error'] = error
return _serialize(output) if do_serialize else output
|
AttributeError
|
dataset/ETHPy150Open StackStorm/st2contrib/packs/hubot/actions/post_result.py/format_localrunner_result
|
9,530
|
def format_pythonrunner_result(result):
output = format_possible_failure_result(result)
# Add in various properties if they have values
result_ = result.get('result', None)
if result_ is not None:
output['result'] = result_
stdout = result.get('stdout', None)
if stdout:
try:
output['stdout'] = stdout.strip()
except __HOLE__:
output['stdout'] = stdout
stderr = result.get('stderr', None)
if stderr:
output['stderr'] = stderr.strip()
exit_code = result.get('exit_code', 0)
if exit_code != 0:
output['exit_code'] = exit_code
return _serialize(output)
|
AttributeError
|
dataset/ETHPy150Open StackStorm/st2contrib/packs/hubot/actions/post_result.py/format_pythonrunner_result
|
9,531
|
def _get_result(self, data):
result = data.get('data', {'result': {}}).get('result', '{}')
try:
result = json.loads(result)
except __HOLE__:
# if json.loads fails then very return result as-is. Should not happen.
return result
return FORMATTERS.get(data['runner_ref'], format_default_result)(result)
|
ValueError
|
dataset/ETHPy150Open StackStorm/st2contrib/packs/hubot/actions/post_result.py/PostResultAction._get_result
|
9,532
|
def test_object_qualname(self):
# Test preservation of function __qualname__ attribute.
try:
__qualname__ = function1o().__qualname__
except __HOLE__:
pass
else:
self.assertEqual(function1d().__qualname__, __qualname__)
|
AttributeError
|
dataset/ETHPy150Open GrahamDumpleton/wrapt/tests/test_nested_function.py/TestNamingNestedFunction.test_object_qualname
|
9,533
|
def __call__(self, obj, do_raise=False):
"""Select a datum to operate on.
Selects the relevant datum within the object.
:param obj: The object from which to select the object.
:param do_raise: If False (the default), return None if the
indexed datum does not exist. Otherwise,
raise a KeyError.
"""
# Walk the selector list
for elem in self.chain:
# If it's callable, call it
if callable(elem):
obj = elem(obj)
else:
if obj == '':
return ''
# Use indexing
try:
obj = obj[elem]
except (KeyError, __HOLE__):
# No sense going any further
if do_raise:
# Convert to a KeyError, for consistency
raise KeyError(elem)
return None
# Return the finally-selected object
return obj
|
IndexError
|
dataset/ETHPy150Open openstack/rack/rack/api/xmlutil.py/Selector.__call__
|
9,534
|
def __call__(self, obj, do_raise=False):
"""Returns empty string if the selected value does not exist."""
try:
return super(EmptyStringSelector, self).__call__(obj, True)
except __HOLE__:
return ""
|
KeyError
|
dataset/ETHPy150Open openstack/rack/rack/api/xmlutil.py/EmptyStringSelector.__call__
|
9,535
|
def apply(self, elem, obj):
"""Apply text and attributes to an etree.Element.
Applies the text and attribute instructions in the template
element to an etree.Element instance.
:param elem: An etree.Element instance.
:param obj: The base object associated with this template
element.
"""
# Start with the text...
if self.text is not None:
elem.text = unicode(self.text(obj))
# Now set up all the attributes...
for key, value in self.attrib.items():
try:
elem.set(key, unicode(value(obj, True)))
except __HOLE__:
# Attribute has no value, so don't include it
pass
|
KeyError
|
dataset/ETHPy150Open openstack/rack/rack/api/xmlutil.py/TemplateElement.apply
|
9,536
|
def reset(self):
expatreader.ExpatParser.reset(self)
if self.forbid_dtd:
self._parser.StartDoctypeDeclHandler = self.start_doctype_decl
self._parser.EndDoctypeDeclHandler = None
if self.forbid_entities:
self._parser.EntityDeclHandler = self.entity_decl
self._parser.UnparsedEntityDeclHandler = self.unparsed_entity_decl
self._parser.ExternalEntityRefHandler = self.external_entity_ref
self._parser.NotationDeclHandler = self.notation_decl
try:
self._parser.SkippedEntityHandler = None
except __HOLE__:
# some pyexpat versions do not support SkippedEntity
pass
|
AttributeError
|
dataset/ETHPy150Open openstack/rack/rack/api/xmlutil.py/ProtectedExpatParser.reset
|
9,537
|
def safe_minidom_parse_string(xml_string):
"""Parse an XML string using minidom safely."""
try:
return minidom.parseString(xml_string, parser=ProtectedExpatParser())
except (sax.SAXParseException, __HOLE__,
expat.ExpatError, LookupError) as e:
# NOTE(Vijaya Erukala): XML input such as
# <?xml version="1.0" encoding="TF-8"?>
# raises LookupError: unknown encoding: TF-8
raise exception.MalformedRequestBody(reason=str(e))
|
ValueError
|
dataset/ETHPy150Open openstack/rack/rack/api/xmlutil.py/safe_minidom_parse_string
|
9,538
|
def compile_template(func):
try:
spec = inspect.getargspec(func)
except __HOLE__:
spec = ArgSpec((), 'args', 'kwargs', None)
# Slicing with [1:-1] to get rid of parentheses
spec_str = inspect.formatargspec(*spec)
assigns = '\n'.join(" __call.{0} = {0}".format(arg) for arg in spec.args)
func_str = WRAPPER_TEMPLATE.format(name=func.__name__, spec=spec_str, assigns=assigns)
env = {}
# print func_str
exec func_str in env
return env['__wrapper_fab']
|
TypeError
|
dataset/ETHPy150Open Suor/funcy/drafts/bench_decorators.py/compile_template
|
9,539
|
def eventlet_rpc_server():
pool = eventlet.GreenPool()
LOG.info(_LI("Eventlet based AMQP RPC server starting..."))
try:
neutron_rpc = service.serve_rpc()
except __HOLE__:
LOG.info(_LI("RPC was already started in parent process by "
"plugin."))
else:
pool.spawn(neutron_rpc.wait)
pool.waitall()
|
NotImplementedError
|
dataset/ETHPy150Open openstack/neutron/neutron/server/rpc_eventlet.py/eventlet_rpc_server
|
9,540
|
def _package_conf_ordering(conf, clean=True, keep_backup=False):
'''
Move entries in the correct file.
'''
if conf in SUPPORTED_CONFS:
rearrange = []
path = BASE_PATH.format(conf)
backup_files = []
for triplet in os.walk(path):
for file_name in triplet[2]:
file_path = '{0}/{1}'.format(triplet[0], file_name)
cp = triplet[0][len(path) + 1:] + '/' + file_name
shutil.copy(file_path, file_path + '.bak')
backup_files.append(file_path + '.bak')
if cp[0] == '/' or cp.split('/') > 2:
rearrange.extend(list(salt.utils.fopen(file_path)))
os.remove(file_path)
else:
new_contents = ''
with salt.utils.fopen(file_path, 'r+') as file_handler:
for line in file_handler:
try:
atom = line.strip().split()[0]
except __HOLE__:
new_contents += line
else:
if atom[0] == '#' or \
portage.dep_getkey(atom) == cp:
new_contents += line
else:
rearrange.append(line.strip())
if len(new_contents) != 0:
file_handler.seek(0)
file_handler.truncate(len(new_contents))
file_handler.write(new_contents)
if len(new_contents) == 0:
os.remove(file_path)
for line in rearrange:
append_to_package_conf(conf, string=line)
if not keep_backup:
for bfile in backup_files:
try:
os.remove(bfile)
except OSError:
pass
if clean:
for triplet in os.walk(path):
if len(triplet[1]) == 0 and len(triplet[2]) == 0 and \
triplet[0] != path:
shutil.rmtree(triplet[0])
|
IndexError
|
dataset/ETHPy150Open saltstack/salt/salt/modules/portage_config.py/_package_conf_ordering
|
9,541
|
def append_to_package_conf(conf, atom='', flags=None, string='', overwrite=False):
'''
Append a string or a list of flags for a given package or DEPEND atom to a
given configuration file.
CLI Example:
.. code-block:: bash
salt '*' portage_config.append_to_package_conf use string="app-admin/salt ldap -libvirt"
salt '*' portage_config.append_to_package_conf use atom="> = app-admin/salt-0.14.1" flags="['ldap', '-libvirt']"
'''
if flags is None:
flags = []
if conf in SUPPORTED_CONFS:
if not string:
if '/' not in atom:
atom = _p_to_cp(atom)
if not atom:
return
string = '{0} {1}'.format(atom, ' '.join(flags))
new_flags = list(flags)
else:
atom = string.strip().split()[0]
new_flags = [flag for flag in string.strip().split(' ') if flag][1:]
if '/' not in atom:
atom = _p_to_cp(atom)
string = '{0} {1}'.format(atom, ' '.join(new_flags))
if not atom:
return
to_delete_if_empty = []
if conf == 'accept_keywords':
if '-~ARCH' in new_flags:
new_flags.remove('-~ARCH')
to_delete_if_empty.append(atom)
if '~ARCH' in new_flags:
new_flags.remove('~ARCH')
append_to_package_conf(conf, string=atom, overwrite=overwrite)
if not new_flags:
return
# Next sort is just aesthetic, can be commented for a small performance
# boost
new_flags.sort(cmp=lambda x, y: cmp(x.lstrip('-'), y.lstrip('-')))
complete_file_path = _get_config_file(conf, atom)
pdir = os.path.dirname(complete_file_path)
if not os.path.exists(pdir):
os.makedirs(pdir, 0o755)
try:
shutil.copy(complete_file_path, complete_file_path + '.bak')
except IOError:
pass
try:
file_handler = salt.utils.fopen(complete_file_path, 'r+')
except IOError:
file_handler = salt.utils.fopen(complete_file_path, 'w+')
new_contents = ''
added = False
for l in file_handler:
l_strip = l.strip()
if l_strip == '':
new_contents += '\n'
elif l_strip[0] == '#':
new_contents += l
elif l_strip.split()[0] == atom:
if l_strip in to_delete_if_empty:
continue
if overwrite:
new_contents += string.strip() + '\n'
added = True
else:
old_flags = [flag for flag in l_strip.split(' ') if flag][1:]
if conf == 'accept_keywords':
if not old_flags:
new_contents += l
if not new_flags:
added = True
continue
elif not new_flags:
continue
merged_flags = _merge_flags(new_flags, old_flags, conf)
if merged_flags:
new_contents += '{0} {1}\n'.format(
atom, ' '.join(merged_flags))
else:
new_contents += '{0}\n'.format(atom)
added = True
else:
new_contents += l
if not added:
new_contents += string.strip() + '\n'
file_handler.seek(0)
file_handler.truncate(len(new_contents))
file_handler.write(new_contents)
file_handler.close()
try:
os.remove(complete_file_path + '.bak')
except __HOLE__:
pass
|
OSError
|
dataset/ETHPy150Open saltstack/salt/salt/modules/portage_config.py/append_to_package_conf
|
9,542
|
def get_flags_from_package_conf(conf, atom):
'''
Get flags for a given package or DEPEND atom.
Warning: This only works if the configuration files tree is in the correct
format (the one enforced by enforce_nice_config)
CLI Example:
.. code-block:: bash
salt '*' portage_config.get_flags_from_package_conf license salt
'''
if conf in SUPPORTED_CONFS:
package_file = _get_config_file(conf, atom)
if '/' not in atom:
atom = _p_to_cp(atom)
has_wildcard = '*' in atom
if has_wildcard:
match_list = set(atom)
else:
try:
match_list = set(_porttree().dbapi.xmatch("match-all", atom))
except __HOLE__:
return []
flags = []
try:
file_handler = salt.utils.fopen(package_file)
except IOError:
return []
else:
for line in file_handler:
line = line.strip()
line_package = line.split()[0]
found_match = False
if has_wildcard:
found_match = line_package == atom
else:
line_list = _porttree().dbapi.xmatch("match-all", line_package)
found_match = match_list.issubset(line_list)
if found_match:
f_tmp = [flag for flag in line.strip().split(' ') if flag][1:]
if f_tmp:
flags.extend(f_tmp)
else:
flags.append('~ARCH')
return _merge_flags(flags)
|
AttributeError
|
dataset/ETHPy150Open saltstack/salt/salt/modules/portage_config.py/get_flags_from_package_conf
|
9,543
|
def is_present(conf, atom):
'''
Tell if a given package or DEPEND atom is present in the configuration
files tree.
Warning: This only works if the configuration files tree is in the correct
format (the one enforced by enforce_nice_config)
CLI Example:
.. code-block:: bash
salt '*' portage_config.is_present unmask salt
'''
if conf in SUPPORTED_CONFS:
if not isinstance(atom, portage.dep.Atom):
atom = portage.dep.Atom(atom, allow_wildcard=True)
has_wildcard = '*' in atom
package_file = _get_config_file(conf, str(atom))
# wildcards are valid in confs
if has_wildcard:
match_list = set(atom)
else:
match_list = set(_porttree().dbapi.xmatch("match-all", atom))
try:
file_handler = salt.utils.fopen(package_file)
except __HOLE__:
return False
else:
for line in file_handler:
line = line.strip()
line_package = line.split()[0]
if has_wildcard:
if line_package == str(atom):
return True
else:
line_list = _porttree().dbapi.xmatch("match-all", line_package)
if match_list.issubset(line_list):
return True
return False
|
IOError
|
dataset/ETHPy150Open saltstack/salt/salt/modules/portage_config.py/is_present
|
9,544
|
def get_all_cpv_use(cp):
'''
.. versionadded:: 2015.8.0
Uses portage to determine final USE flags and settings for an emerge.
@type cp: string
@param cp: eg cat/pkg
@rtype: lists
@return use, use_expand_hidden, usemask, useforce
'''
cpv = _get_cpv(cp)
portage = _get_portage()
use = None
_porttree().dbapi.settings.unlock()
try:
_porttree().dbapi.settings.setcpv(cpv, mydb=portage.portdb)
use = portage.settings['PORTAGE_USE'].split()
use_expand_hidden = portage.settings["USE_EXPAND_HIDDEN"].split()
usemask = list(_porttree().dbapi.settings.usemask)
useforce = list(_porttree().dbapi.settings.useforce)
except __HOLE__:
_porttree().dbapi.settings.reset()
_porttree().dbapi.settings.lock()
return [], [], [], []
# reset cpv filter
_porttree().dbapi.settings.reset()
_porttree().dbapi.settings.lock()
return use, use_expand_hidden, usemask, useforce
|
KeyError
|
dataset/ETHPy150Open saltstack/salt/salt/modules/portage_config.py/get_all_cpv_use
|
9,545
|
def is_changed_uses(cp):
'''
.. versionadded:: 2015.8.0
Uses portage for determine if the use flags of installed package
is compatible with use flags in portage configs.
@type cp: string
@param cp: eg cat/pkg
'''
cpv = _get_cpv(cp)
i_flags, conf_flags = get_cleared_flags(cpv)
for i in i_flags:
try:
conf_flags.remove(i)
except __HOLE__:
return True
return True if conf_flags else False
|
ValueError
|
dataset/ETHPy150Open saltstack/salt/salt/modules/portage_config.py/is_changed_uses
|
9,546
|
def _Exists(self):
"""Returns true if the affinity group exists."""
show_cmd = [AZURE_PATH,
'account',
'affinity-group',
'show',
'--json',
self.name]
stdout, _, _ = vm_util.IssueCommand(show_cmd, suppress_warning=True)
try:
json.loads(stdout)
except __HOLE__:
return False
return True
|
ValueError
|
dataset/ETHPy150Open GoogleCloudPlatform/PerfKitBenchmarker/perfkitbenchmarker/providers/azure/azure_network.py/AzureAffinityGroup._Exists
|
9,547
|
def _Exists(self):
"""Returns true if the storage account exists."""
show_cmd = [AZURE_PATH,
'storage',
'account',
'show',
'--json',
self.name]
stdout, _, _ = vm_util.IssueCommand(show_cmd, suppress_warning=True)
try:
json.loads(stdout)
except __HOLE__:
return False
return True
|
ValueError
|
dataset/ETHPy150Open GoogleCloudPlatform/PerfKitBenchmarker/perfkitbenchmarker/providers/azure/azure_network.py/AzureStorageAccount._Exists
|
9,548
|
def init(self, app, cache, timeout=None, debug=None):
twitter_timeout = 60*60*24*365
if timeout > twitter_timeout:
raise Exception("TwitterOEmbedder: Cache expiry should not exceed 1 year "
"per Twitter API specification")
max_timeout = {'saslmemcached':60*60*24*30,
'simple': twitter_timeout}
if not timeout:
default_timeout = app.config.get('CACHE_DEFAULT_TIMEOUT', 300)
timeout = min(max_timeout.get(app.config.get('CACHE_TYPE', default_timeout)),
twitter_timeout)
@app.context_processor
def tweet_processor():
def oembed_tweet(tweet_id,
access_token=app.config['TWITTER_ACCESS_TOKEN'],
token_secret=app.config['TWITTER_TOKEN_SECRET'],
omit_script=False):
auth = OAuth1(app.config['TWITTER_CONSUMER_KEY'],
app.config['TWITTER_CONSUMER_SECRET'],
access_token,
token_secret)
url = 'https://api.twitter.com/1.1/statuses/oembed.json'
@cache.memoize(timeout=timeout)
def get_tweet_html(tweet_id, omit_script):
params = {'id':tweet_id,
'omit_script':omit_script}
r = requests.get(url, params=params, auth=auth)
try:
tweet_html = Markup(r.json()[u'html'])
except __HOLE__ as e:
if debug or (debug is None and app.debug):
raise e
else:
return ''
return tweet_html
return get_tweet_html(tweet_id, omit_script)
return dict(oembed_tweet=oembed_tweet)
|
KeyError
|
dataset/ETHPy150Open eriktaubeneck/flask-twitter-oembedder/flask_twitter_oembedder.py/TwitterOEmbedder.init
|
9,549
|
@system.setter
def system(self, new_system):
if new_system is not None and not isinstance(new_system, System):
msg = "{} should be a valid pydy.System object".format(new_system)
raise TypeError(msg)
if new_system is not None:
msg = ('The {} attribute has already been set, so the system '
'cannot be set. Use the clear_trajectories method to '
'set all relevant attributes to None.')
for attr in ['times', 'constants', 'states_symbols',
'states_trajectories']:
try:
if getattr(self, attr) is not None:
raise ValueError(msg.format(attr))
except __HOLE__:
pass
self._system = new_system
|
AttributeError
|
dataset/ETHPy150Open pydy/pydy/pydy/viz/scene.py/Scene.system
|
9,550
|
@times.setter
def times(self, new_times):
try:
if new_times is not None and self.system is not None:
msg = ('The system attribute has already been set, so the '
'times cannot be set. Set Scene.system = None to '
'allow a time array to be added.')
raise ValueError(msg)
except AttributeError:
pass
try:
if new_times is not None and self.states_trajectories is not None:
len_traj = self.states_trajectories.shape[0]
if len(new_times) != len_traj:
msg = ('The times array length, {}, does not match the '
'length of the state trajectories array, {}.')
raise ValueError(msg.format(len(new_times), len_traj))
except __HOLE__:
pass
if new_times is None:
self._times = new_times
else:
self._times = np.array(new_times)
|
AttributeError
|
dataset/ETHPy150Open pydy/pydy/pydy/viz/scene.py/Scene.times
|
9,551
|
@states_symbols.setter
def states_symbols(self, new_states_symbols):
try:
if new_states_symbols is not None and self.system is not None:
msg = ('The system attribute has already been set, so the '
'coordinates cannot be set. Set Scene.system = None '
'to allow a coordinates array to be added.')
raise ValueError(msg)
except AttributeError:
pass
try:
if (new_states_symbols is not None and self.states_trajectories
is not None):
len_traj = self.states_trajectories.shape[1]
if len(new_states_symbols) != len_traj:
msg = ('The number of states, {}, does not match the '
'number of states present in the state '
'trajectories array, {}.')
raise ValueError(msg.format(len(new_states_symbols), len_traj))
except __HOLE__:
pass
self._states_symbols = new_states_symbols
|
AttributeError
|
dataset/ETHPy150Open pydy/pydy/pydy/viz/scene.py/Scene.states_symbols
|
9,552
|
@states_trajectories.setter
def states_trajectories(self, new_states_trajectories):
try:
if new_states_trajectories is not None and self.system is not None:
msg = ('The system attribute has already been set, so the '
'states_trajectories cannot be set. Set Scene.system '
'= None to allow a states_trajectories array to be '
'added.')
raise ValueError(msg)
except AttributeError:
pass
try:
if new_states_trajectories is not None and self.times is not None:
if len(self.times) != new_states_trajectories.shape[0]:
msg = ("The number of time instances do not match the "
"number in the times array.")
raise ValueError(msg)
except __HOLE__:
pass
try:
if (new_states_trajectories is not None and self.states_symbols
is not None):
if new_states_trajectories.shape[1] != len(self.states_symbols):
msg = ("The number of states in the trajectory do not "
"match the number of states symbols.")
raise ValueError(msg)
except AttributeError:
pass
self._states_trajectories = new_states_trajectories
|
AttributeError
|
dataset/ETHPy150Open pydy/pydy/pydy/viz/scene.py/Scene.states_trajectories
|
9,553
|
@constants.setter
def constants(self, new_constants):
try:
if new_constants is not None and self.system is not None:
msg = ('The system attribute has already been set, so the '
'constants cannot be set. Set Scene.system = None to '
'allow a constants array to be added.')
raise ValueError(msg)
except __HOLE__:
pass
self._constants = new_constants
|
AttributeError
|
dataset/ETHPy150Open pydy/pydy/pydy/viz/scene.py/Scene.constants
|
9,554
|
def _v1_auth(self, token_url):
creds = self.creds
headers = {}
headers['X-Auth-User'] = creds['username']
headers['X-Auth-Key'] = creds['password']
tenant = creds.get('tenant')
if tenant:
headers['X-Auth-Tenant'] = tenant
resp, resp_body = self._do_request(token_url, 'GET', headers=headers)
def _management_url(self, resp):
for url_header in ('x-image-management-url',
'x-server-management-url',
'x-glance'):
try:
return resp[url_header]
except __HOLE__ as e:
not_found = e
raise not_found
if resp.status in (200, 204):
try:
self.management_url = _management_url(self, resp)
self.auth_token = resp['x-auth-token']
except KeyError:
raise exception.AuthorizationFailure()
elif resp.status == 305:
raise exception.AuthorizationRedirect(resp['location'])
elif resp.status == 400:
raise exception.AuthBadRequest(url=token_url)
elif resp.status == 401:
raise exception.NotAuthorized()
elif resp.status == 404:
raise exception.AuthUrlNotFound(url=token_url)
else:
raise Exception(_('Unexpected response: %s' % resp.status))
|
KeyError
|
dataset/ETHPy150Open rcbops/glance-buildpackage/glance/common/auth.py/KeystoneStrategy._v1_auth
|
9,555
|
def annotateWindows(contig, windows, gff_data, fasta, options):
"""annotate windows."""
index = IndexedGenome.IndexedGenome()
for g in gff_data:
index.add(g.contig, g.start, g.end, g)
is_gtf = options.is_gtf
if options.transform == "none":
transform = lambda x, y, z: map(lambda x: (x[0], x[1]), z)
elif options.transform == "overlap":
transform = transform_overlap
elif options.transform == "complement":
transform = transform_complement
elif options.transform == "third_codon":
transform = transform_third_codon
else:
raise ValueError("unknown transform %s" % options.transform)
work_on_intervals = True
if options.decorator == "counts":
decorator = decorator_counts
elif options.decorator == "mean-length":
decorator = decorator_mean_length
elif options.decorator == "median-length":
decorator = decorator_median_length
elif options.decorator == "percent-coverage":
decorator = decorator_percent_coverage
elif options.decorator == "gc":
decorator = decorator_percent_gc
elif options.decorator == "median-score":
decorator = decorator_median_score
work_on_intervals = False
elif options.decorator == "mean-score":
decorator = decorator_mean_score
work_on_intervals = False
elif options.decorator == "stddev-score":
decorator = decorator_stddev_score
work_on_intervals = False
elif options.decorator == "min-score":
decorator = decorator_min_score
work_on_intervals = False
elif options.decorator == "max-score":
decorator = decorator_max_score
work_on_intervals = False
else:
raise ValueError("unknown decorator %s" % options.decorator)
for start, end in windows:
# counts/length before/after transformation
n1, l1, n2, l2 = 0, 0, 0, 0
values, intervals_with_gff, genes, transcripts = [], [], set(), set()
try:
for istart, iend, value in index.get(contig, start, end):
n1 += 1
l1 += iend - istart
intervals_with_gff.append((istart, iend, value))
values.append(value.score)
if is_gtf:
genes.add(value.gene_id)
transcripts.add(value.transcript_id)
except __HOLE__:
pass
if n1 == 0 and options.skip_empty:
continue
if work_on_intervals:
if options.loglevel >= 3:
options.stdlog.write("# intervals in window %i:%i before transformation: %s\n" % (
start, end, str(intervals)))
intervals = transform(start, end, intervals_with_gff)
for xstart, xend in intervals:
n2 += 1
l2 += xend - xstart
if options.loglevel >= 3:
options.stdlog.write("# intervals in window %i:%i after transformation: %s\n" % (
start, end, str(intervals)))
score, extra_info = decorator(intervals, start, end, contig, fasta)
else:
if len(values) > 0:
values = map(float, values)
score, extra_info = decorator(values, start, end, contig)
else:
score, extra_info = 0, None
l2 = 0
n2 = 0
if is_gtf:
ngenes, ntranscripts = len(genes), len(transcripts)
else:
ngenes, ntranscripts = 0, 0
if extra_info:
extra_info = re.sub("\t", ";", extra_info)
options.stdout.write("\t".join(
map(str, (contig, start, end,
ngenes, ntranscripts,
n1, l1,
n2, l2,
score,
extra_info))) + "\n")
|
KeyError
|
dataset/ETHPy150Open CGATOxford/cgat/scripts/gff2table.py/annotateWindows
|
9,556
|
@environmentfilter
def do_first(environment, seq):
"""Return the first item of a sequence."""
try:
return iter(seq).next()
except __HOLE__:
return environment.undefined('No first item, sequence was empty.')
|
StopIteration
|
dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_first
|
9,557
|
@environmentfilter
def do_last(environment, seq):
"""Return the last item of a sequence."""
try:
return iter(reversed(seq)).next()
except __HOLE__:
return environment.undefined('No last item, sequence was empty.')
|
StopIteration
|
dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_last
|
9,558
|
@environmentfilter
def do_random(environment, seq):
"""Return a random item from the sequence."""
try:
return choice(seq)
except __HOLE__:
return environment.undefined('No random item, sequence was empty.')
|
IndexError
|
dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_random
|
9,559
|
def do_int(value, default=0):
"""Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter.
"""
try:
return int(value)
except (TypeError, ValueError):
# this quirk is necessary so that "42.23"|int gives 42.
try:
return int(float(value))
except (__HOLE__, ValueError):
return default
|
TypeError
|
dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_int
|
9,560
|
def do_float(value, default=0.0):
"""Convert the value into a floating point number. If the
conversion doesn't work it will return ``0.0``. You can
override this default using the first parameter.
"""
try:
return float(value)
except (TypeError, __HOLE__):
return default
|
ValueError
|
dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_float
|
9,561
|
def do_reverse(value):
"""Reverse the object or return an iterator the iterates over it the other
way round.
"""
if isinstance(value, basestring):
return value[::-1]
try:
return reversed(value)
except __HOLE__:
try:
rv = list(value)
rv.reverse()
return rv
except TypeError:
raise FilterArgumentError('argument must be iterable')
|
TypeError
|
dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_reverse
|
9,562
|
@environmentfilter
def do_attr(environment, obj, name):
"""Get an attribute of an object. ``foo|attr("bar")`` works like
``foo["bar"]`` just that always an attribute is returned and items are not
looked up.
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
"""
try:
name = str(name)
except UnicodeError:
pass
else:
try:
value = getattr(obj, name)
except __HOLE__:
pass
else:
if environment.sandboxed and not \
environment.is_safe_attribute(obj, name, value):
return environment.unsafe_undefined(obj, name)
return value
return environment.undefined(obj=obj, name=name)
|
AttributeError
|
dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_attr
|
9,563
|
def readfile(self,filepath=''):
"""Read a table from a file
Parameters:
1. filepath: the path to a file to read
"""
#open a file
fn=os.path.join(filepath,self.get_name()+'.xls')
try:
f=open(fn,'r')
except __HOLE__:
raise Exception('No table, %s exists in %s' %(self.get_name(),filepath))
# reset the current table
if not self.isempty():
warnings.warn("Resetting the current table, %s") %(self.get_name())
self.table={}
chrom=''
for line in f.xreadlines():
# obtaining the parameters
line=line.strip()
if line=='' or line[0]=="#": continue
# get chromosomes
elements=self.parse_line(line)
newchrom=elements[0]
# when new chromosome is met
if chrom!=newchrom:
chrom=newchrom
self.init_table(chrom)
self.add_row(chrom,elements[1:])
f.close()
|
IOError
|
dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/Table.readfile
|
9,564
|
def fit_to_db(self,chrom,i):
"""Fit the ith row of the table to the db"""
export_data=[]
for column in self.columns[1:]:
element=self.table[chrom][column][i]
if type(element).__name__=='list': element=str(element)[1:-1]+','
try:
export_data.append(abs(element))
except __HOLE__:
export_data.append(element)
return export_data
|
TypeError
|
dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/AnnotTable.fit_to_db
|
9,565
|
def add_row(self,chrom,elements):
"""Add a row to the table"""
try:
self[chrom]['coordinate'].append(elements[0])
self[chrom]['promoter'].append(elements[1])
self[chrom]['bipromoter'].append(elements[2])
self[chrom]['downstream'].append(elements[3])
self[chrom]['gene'].append(elements[4])
self[chrom]['rel_loc'].append([elements[5],elements[6]])
self[chrom]['rel_loc_cds'].append([elements[7],elements[8]])
self[chrom]['roi'].append(elements[-1])
except __HOLE__:
raise Exception("Invalid table format: %s" %('\t'.join([chrom]+[str(e) for e in elements])))
|
IndexError
|
dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/AnnotTable.add_row
|
9,566
|
def size(self,chrom=''):
"""Return a tuple of the table size"""
numcol=len(self.columns)
numrow=0
if not chrom:
chrs=self.get_chroms()
try:
for chr in chrs:
numrow+=len(self.table[chr][self.columns[1]])
except IndexError:
numrow=0
else:
try:
numrow=len(self.table[chrom][self.columns[1]])
except __HOLE__:
pass
return (numrow,numcol)
|
IndexError
|
dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/AnnotTable.size
|
9,567
|
def fit_to_db(self,chrom):
"""Fit the ith row to the db"""
export_data=[chrom]
for column in self.columns[1:]:
element=self.table[chrom][column]
if column=='rel_loc' or column=='rel_loc_cds': element=element[0]+element[1]
if type(element)==list: element=str(element)[1:-1]+','
try:
export_data.append(abs(element))
except __HOLE__:
export_data.append(element)
return export_data
|
TypeError
|
dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/Summary.fit_to_db
|
9,568
|
def summarize(self):
"""Summarize the table in 'whole' row"""
try:
chroms=self.get_chroms()
if not chroms: raise ValueError
except (__HOLE__,ValueError):
return
# obtain a summary statistics
self.init_table('whole')
array_adder=lambda x,y: [x[i]+y[i] for i in range(0,len(x))]
for chrom in chroms:
if chrom!='whole':
self['whole']['promoter']=array_adder(self['whole']['promoter'],self[chrom]['promoter'])
self['whole']['bipromoter']=array_adder(self['whole']['bipromoter'],self[chrom]['bipromoter'])
self['whole']['downstream']=array_adder(self['whole']['downstream'],self[chrom]['downstream'])
self['whole']['gene']=array_adder(self['whole']['gene'],self[chrom]['gene'])
self['whole']['rel_loc'][0]=array_adder(self['whole']['rel_loc'][0],self[chrom]['rel_loc'][0])
self['whole']['rel_loc'][1]=array_adder(self['whole']['rel_loc'][1],self[chrom]['rel_loc'][1])
self['whole']['rel_loc_cds'][0]=array_adder(self['whole']['rel_loc_cds'][0],self[chrom]['rel_loc_cds'][0])
self['whole']['rel_loc_cds'][1]=array_adder(self['whole']['rel_loc_cds'][1],self[chrom]['rel_loc_cds'][1])
self['whole']['roi']+=self[chrom]['roi']
self['whole']['Ns']+=self[chrom]['Ns']
|
AttributeError
|
dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/Summary.summarize
|
9,569
|
def get_p(self):
"""Return a P object of probabilites"""
p=P()
try:
chroms=self.get_chroms()
if not chroms: raise ValueError
except (__HOLE__,ValueError):
return p
for chrom in chroms:
total=self[chrom]['Ns']
p.init_table(chrom)
# check if the denominator is zero
try:
p[chrom]['promoter']=map(lambda x: 1.0*x/total,self[chrom]['promoter'])
except ZeroDivisionError:
total=1
p[chrom]['promoter']=map(lambda x: 1.0*x/total,self[chrom]['promoter'])
p[chrom]['bipromoter']=map(lambda x: 1.0*x/total,self[chrom]['bipromoter'])
p[chrom]['downstream']=map(lambda x: 1.0*x/total,self[chrom]['downstream'])
p[chrom]['gene']=map(lambda x: 1.0*x/total,self[chrom]['gene'])
#relative locations
total_rel_loc=sum(self[chrom]['rel_loc'][0])
total_rel_loc_cds=sum(self[chrom]['rel_loc_cds'][0])
# check if the denominator is zero
try:
p_rel_loc0=map(lambda x: 1.0*x/total_rel_loc,self[chrom]['rel_loc'][0])
except ZeroDivisionError:
total_rel_loc=1
p_rel_loc0=map(lambda x: 1.0*x/total_rel_loc,self[chrom]['rel_loc'][0])
p_rel_loc1=map(lambda x: 1.0*x/total_rel_loc,self[chrom]['rel_loc'][1])
try:
p_rel_loc_cds0=map(lambda x: 1.0*x/total_rel_loc_cds,self[chrom]['rel_loc_cds'][0])
except ZeroDivisionError:
total_rel_loc_cds=1
p_rel_loc_cds0=map(lambda x: 1.0*x/total_rel_loc_cds,self[chrom]['rel_loc_cds'][0])
p_rel_loc_cds1=map(lambda x: 1.0*x/total_rel_loc_cds,self[chrom]['rel_loc_cds'][1])
p[chrom]['rel_loc']=[p_rel_loc0,p_rel_loc1]
p[chrom]['rel_loc_cds']=[p_rel_loc_cds0,p_rel_loc_cds1]
try:
p[chrom]['roi']=1.0*self[chrom]['roi']/total
except ZeroDivisionError:
p[chrom]['roi']=1.0*self[chrom]['roi']
except KeyError:
pass
try:
p[chrom]['chroms']=1.0*self[chrom]['Ns']/self['whole']['Ns']
except ZeroDivisionError:
p[chrom]['chroms']=total
return p
|
AttributeError
|
dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/Summary.get_p
|
9,570
|
def fit_to_db(self,chrom):
"""Fit the ith row to the db"""
export_data=[chrom]
for column in self.columns[1:]:
element=self.table[chrom][column]
if column=='rel_loc' or column=='rel_loc_cds': element=element[0]+element[1]
if type(element)==list: element=str(element)[1:-1]+','
try:
export_data.append(abs(element))
except __HOLE__:
export_data.append(element)
return export_data
|
TypeError
|
dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/P.fit_to_db
|
9,571
|
def get_p(self):
"""Return a P object of probabilites"""
p=PGBG(numprom=self.numprom,numbiprom=self.numbiprom,numdown=self.numdown)
try:
chroms=self.get_chroms()
if not chroms: raise ValueError
except (__HOLE__,ValueError):
return p
for chrom in chroms:
total=self[chrom]['Ns']
p.init_table(chrom)
# check if the denominator is zero
try:
p[chrom]['promoter']=map(lambda x: 1.0*x/total,self[chrom]['promoter'])
except ZeroDivisionError:
total=1
p[chrom]['promoter']=map(lambda x: 1.0*x/total,self[chrom]['promoter'])
p[chrom]['bipromoter']=map(lambda x: 1.0*x/total,self[chrom]['bipromoter'])
p[chrom]['downstream']=map(lambda x: 1.0*x/total,self[chrom]['downstream'])
p[chrom]['gene']=map(lambda x: 1.0*x/total,self[chrom]['gene'])
#relative locations
total_rel_loc=sum(self[chrom]['rel_loc'][0])
total_rel_loc_cds=sum(self[chrom]['rel_loc_cds'][0])
# check if the denominator is zero
try:
p_rel_loc0=map(lambda x: 1.0*x/total_rel_loc,self[chrom]['rel_loc'][0])
except ZeroDivisionError:
total_rel_loc=1
p_rel_loc0=map(lambda x: 1.0*x/total_rel_loc,self[chrom]['rel_loc'][0])
p_rel_loc1=map(lambda x: 1.0*x/total_rel_loc,self[chrom]['rel_loc'][1])
try:
p_rel_loc_cds0=map(lambda x: 1.0*x/total_rel_loc_cds,self[chrom]['rel_loc_cds'][0])
except ZeroDivisionError:
total_rel_loc_cds=1
p_rel_loc_cds0=map(lambda x: 1.0*x/total_rel_loc_cds,self[chrom]['rel_loc_cds'][0])
p_rel_loc_cds1=map(lambda x: 1.0*x/total_rel_loc_cds,self[chrom]['rel_loc_cds'][1])
p[chrom]['rel_loc']=[p_rel_loc0,p_rel_loc1]
p[chrom]['rel_loc_cds']=[p_rel_loc_cds0,p_rel_loc_cds1]
try:
p[chrom]['roi']=1.0*self[chrom]['roi']/total
except ZeroDivisionError:
p[chrom]['roi']=1.0*self[chrom]['roi']
except KeyError:
pass
try:
p[chrom]['chroms']=1.0*self[chrom]['Ns']/self['whole']['Ns']
except ZeroDivisionError:
p[chrom]['chroms']=total
return p
|
AttributeError
|
dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/SummaryGBG.get_p
|
9,572
|
def collect_tcp(self, uri):
parsed = self.parse_url(uri)
try:
host, port = parsed.netloc.split(':')
port = int(port)
except __HOLE__:
self.log.error('OpenVPN expected host:port in URI, got "%s"',
parsed.netloc)
return
if '?' in parsed.path:
name = parsed.path[1:]
else:
name = host.replace('.', '_')
self.log.info('OpenVPN parsing "%s" tcp: %s:%d', name, host, port)
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.settimeout(int(self.config['timeout']))
server.connect((host, port))
fd = server.makefile('rb')
line = fd.readline()
if not line.startswith('>INFO:OpenVPN'):
self.log.debug('OpenVPN received: %s', line.rstrip())
self.log.error('OpenVPN protocol error')
server.close()
return
server.send('status\r\n')
lines = []
while True:
line = fd.readline()
lines.append(line)
if line.strip() == 'END':
break
# Hand over data to the parser
self.parse(name, lines)
# Bye
server.close()
except socket.error, e:
self.log.error('OpenVPN management connection error: %s', e)
return
|
ValueError
|
dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/openvpn/openvpn.py/OpenVPNCollector.collect_tcp
|
9,573
|
def publish_number(self, key, value):
key = key.replace('/', '-').replace(' ', '_').lower()
try:
value = long(value)
except __HOLE__:
self.log.error('OpenVPN expected a number for "%s", got "%s"',
key, value)
return
else:
self.publish(key, value)
|
ValueError
|
dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/openvpn/openvpn.py/OpenVPNCollector.publish_number
|
9,574
|
def is_ipv6_supported():
has_ipv6_support = socket.has_ipv6
try:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
s.close()
except socket.error as e:
if e.errno == errno.EAFNOSUPPORT:
has_ipv6_support = False
else:
raise
# check if there is at least one interface with ipv6
if has_ipv6_support and sys.platform.startswith('linux'):
try:
with open('/proc/net/if_inet6') as f:
if not f.read():
has_ipv6_support = False
except __HOLE__:
has_ipv6_support = False
return has_ipv6_support
|
IOError
|
dataset/ETHPy150Open openstack/rack/rack/tests/utils.py/is_ipv6_supported
|
9,575
|
def from_str(self, s):
for typ in self.elem_types:
try:
return typ.from_str(s)
except __HOLE__:
pass
raise ValueError('No match found')
|
ValueError
|
dataset/ETHPy150Open rllab/rllab/rllab/envs/box2d/parser/xml_attr_types.py/Either.from_str
|
9,576
|
@property
def apps(self):
INSTALLED_APPS = []
# optionaly enable sorl.thumbnail
try:
import sorl # noqa
INSTALLED_APPS += ['sorl.thumbnail']
except Exception:
pass
# optionaly enable easy_thumbnails
try:
import easy_thumbnails # noqa
INSTALLED_APPS += ['easy_thumbnails']
except Exception:
pass
# optionaly enable constance
try:
import constance
except __HOLE__:
pass
else:
INSTALLED_APPS += ['constance',
'constance.backends.database']
return INSTALLED_APPS + [
'feincms',
'mptt',
'crispy_forms',
'floppyforms',
'dbtemplates',
'leonardo.module',
'feincms.module.page', # noqa
'leonardo.module.web',
'markupfield',
]
|
ImportError
|
dataset/ETHPy150Open django-leonardo/django-leonardo/leonardo/module/web/__init__.py/Default.apps
|
9,577
|
def _SetupColours():
"""Initializes the colour constants.
"""
# pylint: disable=W0603
# due to global usage
global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ
# Don't use colours if stdout isn't a terminal
if not sys.stdout.isatty():
return
try:
import curses
except __HOLE__:
# Don't use colours if curses module can't be imported
return
curses.setupterm()
_RESET_SEQ = curses.tigetstr("op")
setaf = curses.tigetstr("setaf")
_INFO_SEQ = curses.tparm(setaf, curses.COLOR_GREEN)
_WARNING_SEQ = curses.tparm(setaf, curses.COLOR_YELLOW)
_ERROR_SEQ = curses.tparm(setaf, curses.COLOR_RED)
|
ImportError
|
dataset/ETHPy150Open ganeti/ganeti/qa/qa_logging.py/_SetupColours
|
9,578
|
def validate_number(self, number):
"""Validates the given 1-based page number.
Override to stop checking if we have gone to far since that requires
knowing the total number of pages.
"""
try:
number = int(number)
except __HOLE__:
raise PageNotAnInteger('That page number is not an integer')
if number < 1:
raise EmptyPage('That page number is less than 1')
return number
|
ValueError
|
dataset/ETHPy150Open mozilla/kitsune/kitsune/sumo/paginator.py/SimplePaginator.validate_number
|
9,579
|
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
parser = E.OptionParser(version="%prog version: $Id: matrix2stats.py 2795 2009-09-16 15:29:23Z andreas $",
usage=globals()["__doc__"])
parser.add_option("-m", "--method", dest="method", type="choice",
choices=("chi-squared", "pearson-chi-squared"),
help="statistical methods to apply.")
parser.add_option("-t", "--header-names", dest="headers", action="store_true",
help="matrix has row/column headers.")
parser.add_option("--no-headers", dest="headers", action="store_false",
help="matrix has no row/column headers.")
parser.add_option("-i", "--input-format", dest="input_format", type="choice",
choices=("full", "sparse", "phylip"),
help="""input format for matrix.""" )
parser.add_option("-o", "--output-format", dest="output_format", type="choice",
choices=("full", "sparse", "phylip"),
help="""output format for matrix.""" )
parser.add_option("-p", "--parameters", dest="parameters", action="append", type="string",
help="parameters for various functions.")
parser.add_option("-a", "--iteration", dest="iteration", type="choice",
choices=("pairwise", "all-vs-all"),
help="""how to compute stats [%default].""" )
parser.set_defaults(
method="chi-squared",
headers=True,
value_format="%6.4f",
pvalue_format="%6.4e",
input_format="full",
write_separators=True,
parameters=[],
iteration=None,
)
(options, args) = E.Start(parser)
lines = filter(lambda x: x[0] != "#", sys.stdin.readlines())
chunks = filter(lambda x: lines[x][0] == ">", range(len(lines)))
if not chunks:
options.write_separators = False
chunks = [-1]
chunks.append(len(lines))
ninput, noutput, nskipped = 0, 0, 0
if options.write_separators:
options.stdout.write("test\t")
header_prefix = ""
if options.method == "chi-squared":
header_prefix = "observed\texpected"
options.stdout.write("\t".join(
(header_prefix, "n", "min", "max", "chi", "df", "P", "passed", "phi")) + "\n")
elif options.method in ("pearson-chi-squared",):
options.stdout.write("column\t")
options.stdout.write("\t".join(
(header_prefix, "n", "prob", "obs", "exp", "chi", "df", "P", "passed", "phi")) + "\n")
if len(options.parameters) == 0:
raise "out of parameters - please supply probability or filename with probabilities."
param = options.parameters[0]
del options.parameters[0]
if options.write_separators:
probabilities = IOTools.ReadMap(
open(param, "r"), map_functions=(str, float))
else:
probability = float(param)
for x in range(len(chunks) - 1):
ninput += 1
matrix, row_headers, col_headers = MatlabTools.readMatrix(StringIO.StringIO("".join(lines[chunks[x] + 1:chunks[x + 1]])),
format=options.input_format,
headers=options.headers)
nrows, ncols = matrix.shape
if options.loglevel >= 2:
options.stdlog.write("# read matrix: %i x %i, %i row titles, %i colum titles.\n" %
(nrows, ncols, len(row_headers), len(col_headers)))
if options.write_separators:
options.stdout.write(lines[chunks[x]][1:-1] + "\t")
pairs = []
if options.iteration == "pairwise":
pairs = []
for row1 in range(0, len(row_headers)):
for row2 in range(row1 + 1, len(row_headers)):
pairs.append((row1, row2))
elif options.iteration == "all-vs-all":
pairs = []
for row1 in range(0, len(row_headers)):
for row2 in range(0, len(row_headers)):
if row1 == row2:
continue
pairs.append((row1, row2))
if options.method == "chi-squared":
for row1, row2 in pairs:
row_header1 = row_headers[row1]
row_header2 = row_headers[row2]
try:
result = Stats.doChiSquaredTest(
numpy.vstack((matrix[row1], matrix[row2])))
except __HOLE__:
nskipped += 1
continue
noutput += 1
options.stdout.write("\t".join(("%s" % row_header1,
"%s" % row_header2,
"%i" % result.mSampleSize,
"%i" % min(matrix.flat),
"%i" % max(matrix.flat),
options.value_format % result.mChiSquaredValue,
"%i" % result.mDegreesFreedom,
options.pvalue_format % result.mProbability,
"%s" % result.mSignificance,
options.value_format % result.mPhi)) + "\n")
elif options.method == "pearson-chi-squared":
if nrows != 2:
raise "only implemented for 2xn table"
if options.write_separators:
id = re.match("(\S+)", lines[chunks[x]][1:-1]).groups()[0]
probability = probabilities[id]
for col in range(ncols):
options.stdout.write("%s\t" % col_headers[col])
result = Stats.doPearsonChiSquaredTest(
probability, sum(matrix[:, col]), matrix[0, col])
options.stdout.write("\t".join(("%i" % result.mSampleSize,
"%f" % probability,
"%i" % result.mObserved,
"%f" % result.mExpected,
options.value_format % result.mChiSquaredValue,
"%i" % result.mDegreesFreedom,
options.pvalue_format % result.mProbability,
"%s" % result.mSignificance,
options.value_format % result.mPhi)))
if col < ncols - 1:
options.stdout.write("\n")
if options.write_separators:
options.stdout.write(lines[chunks[x]][1:-1] + "\t")
options.stdout.write("\n")
E.info("# ninput=%i, noutput=%i, nskipped=%i\n" %
(ninput, noutput, nskipped))
E.Stop()
|
ValueError
|
dataset/ETHPy150Open CGATOxford/cgat/scripts/matrix2stats.py/main
|
9,580
|
@staticmethod
def _get_commands(inst):
cmds = {}
for objname in dir(inst):
obj = getattr(inst, objname)
if getattr(obj, '_is_cmd', False):
try:
cmds[obj._cmd_name] = (obj, inst)
except __HOLE__:
# skip it if there's no _cmd_name
pass
return cmds
|
AttributeError
|
dataset/ETHPy150Open rackerlabs/openstack-guest-agents-unix/commands/__init__.py/CommandBase._get_commands
|
9,581
|
@classmethod
def command_instance(cls, cmd_name):
try:
return cls._cmds[cmd_name][1]
except __HOLE__:
raise CommandNotFoundError(cmd_name)
|
KeyError
|
dataset/ETHPy150Open rackerlabs/openstack-guest-agents-unix/commands/__init__.py/CommandBase.command_instance
|
9,582
|
@classmethod
def command_function(cls, cmd_name):
try:
return cls._cmds[cmd_name][0]
except __HOLE__:
raise CommandNotFoundError(cmd_name)
|
KeyError
|
dataset/ETHPy150Open rackerlabs/openstack-guest-agents-unix/commands/__init__.py/CommandBase.command_function
|
9,583
|
def __getattr__(self, key):
try:
return getattr(self.wrapped_module, key)
except __HOLE__:
return getattr(CommandBase, key)
|
AttributeError
|
dataset/ETHPy150Open rackerlabs/openstack-guest-agents-unix/commands/__init__.py/CommandModuleWrapper.__getattr__
|
9,584
|
@login_required
def log_detail(request, slug, id, template='threebot/workflow/log.html'):
orgs = get_my_orgs(request)
workflow_log = get_object_or_404(WorkflowLog, id=id)
workflow = get_object_or_404(Workflow, owner__in=orgs, slug=slug)
try:
templates = render_templates(workflow_log, mask=True)
except Exception, e:
templates = None
try:
outputs = sorted(workflow_log.outputs.iteritems())
except __HOLE__:
outputs = None
return render_to_response(template, {'request': request,
'workflow': workflow,
'workflow_log': workflow_log,
'outputs': outputs,
'templates': templates,
}, context_instance=RequestContext(request))
|
AttributeError
|
dataset/ETHPy150Open 3bot/3bot/threebot/views/workflow.py/log_detail
|
9,585
|
@login_required
def log_detail_render(request, slug, id):
# get id params, slug+type
format = request.GET.get("format", 'raw')
wf_task_slug = request.GET.get("task")
orgs = get_my_orgs(request)
workflow_log = get_object_or_404(WorkflowLog, id=id)
workflow = get_object_or_404(Workflow, owner__in=orgs, slug=slug)
lookup_key = unquote_plus(wf_task_slug)
output_item = workflow_log.outputs[lookup_key]
try:
output = output_item['stdout']
except __HOLE__:
output = output_item['output']
if format == 'raw':
return HttpResponse(output, content_type="text/plain")
elif format == 'html':
return HttpResponse(output, content_type="text/html")
|
KeyError
|
dataset/ETHPy150Open 3bot/3bot/threebot/views/workflow.py/log_detail_render
|
9,586
|
def calculate_total_active(self):
""" Read proc.txt file and calculate 'self.active' and 'self.total' """
all_cores = set(xrange(self.cores))
self.total = [[] for _ in all_cores]
self.active = [[] for _ in all_cores]
with open(self.infile, "r") as fh:
# parsing logic:
# - keep spinning through lines until see the cpu summary line
# (taken to indicate start of new record).
# - extract values for individual cores after the summary line,
# keeping track of seen cores until no more lines match 'cpu\d+'
# pattern.
# - For every core not seen in this record, pad zeros.
# - Loop
try:
while True:
line = fh.next()
if not line.startswith('cpu '):
continue
seen_cores = set([])
line = fh.next()
match = self.cpuid_regex.match(line)
while match:
cpu_id = int(match.group(1))
seen_cores.add(cpu_id)
times = map(int, line.split()[1:]) # first column is the cpu_id
self.total[cpu_id].append(sum(times))
self.active[cpu_id].append(sum(times) - times[self.idle_time_index])
line = fh.next()
match = self.cpuid_regex.match(line)
for unseen_core in all_cores - seen_cores:
self.total[unseen_core].append(0)
self.active[unseen_core].append(0)
except __HOLE__: # EOF
pass
|
StopIteration
|
dataset/ETHPy150Open ARM-software/workload-automation/wlauto/instrumentation/coreutil/__init__.py/Calculator.calculate_total_active
|
9,587
|
def reset_module_registry(module):
try:
registry = module.__warningregistry__
except __HOLE__:
pass
else:
registry.clear()
|
AttributeError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_py3kwarn.py/reset_module_registry
|
9,588
|
def test_forbidden_names(self):
# So we don't screw up our globals
def safe_exec(expr):
def f(**kwargs): pass
exec expr in {'f' : f}
tests = [("True", "assignment to True or False is forbidden in 3.x"),
("False", "assignment to True or False is forbidden in 3.x"),
("nonlocal", "nonlocal is a keyword in 3.x")]
with check_py3k_warnings(('', SyntaxWarning)) as w:
for keyword, expected in tests:
safe_exec("{0} = False".format(keyword))
self.assertWarning(None, w, expected)
w.reset()
try:
safe_exec("obj.{0} = True".format(keyword))
except __HOLE__:
pass
self.assertWarning(None, w, expected)
w.reset()
safe_exec("def {0}(): pass".format(keyword))
self.assertWarning(None, w, expected)
w.reset()
safe_exec("class {0}: pass".format(keyword))
self.assertWarning(None, w, expected)
w.reset()
safe_exec("def f({0}=43): pass".format(keyword))
self.assertWarning(None, w, expected)
w.reset()
|
NameError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_py3kwarn.py/TestPy3KWarnings.test_forbidden_names
|
9,589
|
def check_removal(self, module_name, optional=False):
"""Make sure the specified module, when imported, raises a
DeprecationWarning and specifies itself in the message."""
with CleanImport(module_name), warnings.catch_warnings():
warnings.filterwarnings("error", ".+ (module|package) .+ removed",
DeprecationWarning, __name__)
warnings.filterwarnings("error", ".+ removed .+ (module|package)",
DeprecationWarning, __name__)
try:
__import__(module_name, level=0)
except DeprecationWarning as exc:
self.assertIn(module_name, exc.args[0],
"%s warning didn't contain module name"
% module_name)
except __HOLE__:
if not optional:
self.fail("Non-optional module {0} raised an "
"ImportError.".format(module_name))
else:
# For extension modules, check the __warningregistry__.
# They won't rerun their init code even with CleanImport.
if not check_deprecated_module(module_name):
self.fail("DeprecationWarning not raised for {0}"
.format(module_name))
|
ImportError
|
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_py3kwarn.py/TestStdlibRemovals.check_removal
|
9,590
|
def get_hexdigest(algorithm, salt, raw_password):
"""
Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or 'crypt').
"""
raw_password, salt = smart_str(raw_password), smart_str(salt)
if algorithm == 'crypt':
try:
import crypt
except __HOLE__:
raise ValueError('"crypt" password algorithm not supported in this '
'environment')
return crypt.crypt(raw_password, salt)
if algorithm == 'md5':
return md5_constructor(salt + raw_password).hexdigest()
elif algorithm == 'sha1':
return sha_constructor(salt + raw_password).hexdigest()
raise ValueError("Got unknown password algorithm type in password.")
|
ImportError
|
dataset/ETHPy150Open aino/django-primate/primate/auth/helpers.py/get_hexdigest
|
9,591
|
def setup(self):
# Check mode
if self.args.mode =="rw":
print("Mode = %s, changes to file will be committed to disk." % self.args.mode)
elif self.args.mode != "r":
print("Warning: invalud mode: " + self.args.mode)
# Try to read in file
print("Reading: " + self.args.in_file[0])
try:
inFile = laspy.file.File(self.args.in_file[0], mode = self.args.mode)
self.inFile = inFile
READ_SUCCESS = True
print("Read successful, file object is called inFile")
except Exception, error:
print("Error while reading file:")
print(error)
READ_SUCCESS = False
# If we have a file and user wants verbose, print summary.
if READ_SUCCESS and not self.args.q:
print("LAS File Summary:")
print("File Version: " + str(inFile.header.version))
print("Point Format: " + str(inFile.header.data_format_id))
print("Number of Point Records: " + str(len(inFile)))
print("Point Dimensions: ")
for dim in inFile.point_format:
print(" " + dim.name)
def explore(self):
inFile = self.inFile
interp = code.InteractiveConsole(locals={"inFile":inFile})
try:
interp.interact()
except __HOLE__, SystemExit:
quit()
|
KeyboardInterrupt
|
dataset/ETHPy150Open grantbrown/laspy/laspy/tools/lasexplorer.py/lasexplorer.setup
|
9,592
|
def _handle_other(self, text):
if text.startswith('&'):
# deal with undefined entities
try:
text = unichr(entities.name2codepoint[text[1:-1]])
self._enqueue(TEXT, text)
except __HOLE__:
filename, lineno, offset = self._getpos()
error = expat.error('undefined entity "%s": line %d, column %d'
% (text, lineno, offset))
error.code = expat.errors.XML_ERROR_UNDEFINED_ENTITY
error.lineno = lineno
error.offset = offset
raise error
|
KeyError
|
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/input.py/XMLParser._handle_other
|
9,593
|
def handle_entityref(self, name):
try:
text = unichr(entities.name2codepoint[name])
except __HOLE__:
text = '&%s;' % name
self._enqueue(TEXT, text)
|
KeyError
|
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/input.py/HTMLParser.handle_entityref
|
9,594
|
def handle_pi(self, data):
if data.endswith('?'):
data = data[:-1]
try:
target, data = data.split(None, 1)
except __HOLE__:
# PI with no data
target = data
data = ''
self._enqueue(PI, (target.strip(), data.strip()))
|
ValueError
|
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/input.py/HTMLParser.handle_pi
|
9,595
|
def generate_create_database(engine_str):
"Generate a create_database function that creates the database"
if engine_str == 'sqlite':
import sqlite3
dbi = sqlite3
def create_database_sqlite(admin_username, admin_password, database_name, new_user, new_password, host = "localhost", port = None, db_dir = '.'):
fname = os.path.join(db_dir, '%s.db' % database_name)
if os.path.exists(fname):
os.remove(fname)
sqlite3.connect(database = fname).close()
return create_database_sqlite
elif engine_str == 'mysql':
try:
import MySQLdb
dbi = MySQLdb
except ImportError:
try:
import pymysql_sa
except __HOLE__:
raise Exception("Neither MySQLdb nor pymysql have been installed. First install them by running 'pip install pymysql' or 'pip install python-mysql'")
pymysql_sa.make_default_mysql_dialect()
import pymysql
dbi = pymysql
def create_database_mysql(error_message, admin_username, admin_password, database_name, new_user, new_password, host = "localhost", port = None, db_dir = '.'):
args = {
'DATABASE_NAME' : database_name,
'USER' : new_user,
'PASSWORD' : new_password,
}
sentence1 = "DROP DATABASE IF EXISTS %(DATABASE_NAME)s;" % args
sentence2 = "CREATE DATABASE %(DATABASE_NAME)s;" % args
sentence3 = "GRANT ALL ON %(DATABASE_NAME)s.* TO '%(USER)s'@'%%' IDENTIFIED BY '%(PASSWORD)s';" % args
sentence4 = "GRANT ALL ON %(DATABASE_NAME)s.* TO '%(USER)s'@'localhost' IDENTIFIED BY '%(PASSWORD)s';" % args
sentence5 = "FLUSH PRIVILEGES;" % args
try:
kwargs = dict(db=database_name, user = admin_username, passwd = admin_password, host = host)
if port is not None:
kwargs['port'] = port
dbi.connect(**kwargs).close()
except Exception, e:
if e[1].startswith("Unknown database"):
sentence1 = "SELECT 1"
for sentence in (sentence1, sentence2, sentence3, sentence4, sentence5):
try:
kwargs = dict(user = admin_username, passwd = admin_password, host = host)
if port is not None:
kwargs['port'] = port
connection = dbi.connect(**kwargs)
except dbi.OperationalError:
traceback.print_exc()
print("", file=sys.stderr)
print(" %s" % error_message, file=sys.stderr)
print("", file=sys.stderr)
sys.exit(-1)
else:
cursor = connection.cursor()
cursor.execute(sentence)
connection.commit()
connection.close()
return create_database_mysql
else:
return None
|
ImportError
|
dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/weblab/admin/deploy.py/generate_create_database
|
9,596
|
def parse_date_to_obj(date_str):
try:
return parse(date_str)
except __HOLE__:
raise ValueError("Invalid date", date_str)
|
ValueError
|
dataset/ETHPy150Open practo/r5d4/r5d4/mapping_functions.py/parse_date_to_obj
|
9,597
|
def expand_integer(str_range):
"""
>>> expand_integer('1') == set(['1'])
True
>>> expand_integer('1..5,10') == set(['1','2','3','4','5','10'])
True
>>> expand_integer('9..3') == set(['3','4','5','6','7','8','9'])
True
>>> expand_integer('1..5,8..3') == set(['1','2','3','4','5','6','7','8'])
True
>>> expand_integer('try me')
Traceback (most recent call last):
...
ValueError: integer range 'try me' not parseable
>>> expand_integer('1..a')
Traceback (most recent call last):
...
ValueError: integer range '1..a' not parseable
"""
try:
answer = set()
for i_group in str_range.split(','):
if RANGE_OPERATOR in i_group:
i_start, i_end = i_group.split(RANGE_OPERATOR)
if i_start > i_end:
i_start, i_end = i_end, i_start
start_int = parse_integer(i_start)
end_int = parse_integer(i_end)
answer |= set(map(str, range(start_int, end_int + 1)))
else:
answer.add(str(parse_integer(i_group)))
return answer
except __HOLE__:
raise ValueError("integer range '%s' not parseable" % str_range)
|
ValueError
|
dataset/ETHPy150Open practo/r5d4/r5d4/mapping_functions.py/expand_integer
|
9,598
|
def parse_table_definition_file(file, options):
'''
This function parses the input to get run sets and columns.
The param 'file' is an XML file defining the result files and columns.
If column titles are given in the XML file,
they will be searched in the result files.
If no title is given, all columns of the result file are taken.
@return: a list of RunSetResult objects
'''
logging.info("Reading table definition from '%s'...", file)
if not os.path.isfile(file):
logging.error("File '%s' does not exist.", file)
exit(1)
try:
tableGenFile = ElementTree.ElementTree().parse(file)
except __HOLE__ as e:
logging.error('Could not read result file %s: %s', file, e)
exit(1)
except ElementTree.ParseError as e:
logging.error('Table file %s is invalid: %s', file, e)
exit(1)
if 'table' != tableGenFile.tag:
logging.error("Table file %s is invalid: It's root element is not named 'table'.", file)
exit(1)
defaultColumnsToShow = extract_columns_from_table_definition_file(tableGenFile, file)
return Util.flatten(
parallel.map(
handle_tag_in_table_definition_file,
tableGenFile,
itertools.repeat(file),
itertools.repeat(defaultColumnsToShow),
itertools.repeat(options)))
|
IOError
|
dataset/ETHPy150Open sosy-lab/benchexec/benchexec/tablegenerator/__init__.py/parse_table_definition_file
|
9,599
|
def _get_decimal_digits(decimal_number_match, number_of_significant_digits):
"""
Returns the amount of decimal digits of the given regex match, considering the number of significant
digits for the provided column.
@param decimal_number_match: a regex match of a decimal number, resulting from REGEX_MEASURE.match(x).
@param column: the Column the decimal number is a part of. The column's information is used to compute
the number of decimal digits.
@return: the number of decimal digits of the given decimal number match's representation, after expanding
the number to the required amount of significant digits
"""
assert 'e' not in decimal_number_match.group() # check that only decimal notation is used
try:
num_of_digits = int(number_of_significant_digits)
except __HOLE__:
num_of_digits = DEFAULT_NUMBER_OF_SIGNIFICANT_DIGITS
if not decimal_number_match.group(GROUP_DEC_PART):
return 0
# If 1 > value > 0, only look at the decimal digits.
# In the second condition, we have to remove the first character from the decimal part group because the
# first character always is '.'
if int(decimal_number_match.group(GROUP_INT_PART)) == 0\
and int(decimal_number_match.group(GROUP_DEC_PART)[1:]) != 0:
max_num_of_digits = len(decimal_number_match.group(GROUP_SIG_DEC_PART))
num_of_digits = min(num_of_digits, max_num_of_digits)
# number of needed decimal digits = number of zeroes after decimal point + significant digits
curr_dec_digits = len(decimal_number_match.group(GROUP_ZEROES)) + int(num_of_digits)
else:
max_num_of_digits =\
len(decimal_number_match.group(GROUP_INT_PART)) + len(decimal_number_match.group(GROUP_DEC_PART))
num_of_digits = min(num_of_digits, max_num_of_digits)
# number of needed decimal digits = significant digits - number of digits in front of decimal point
curr_dec_digits = int(num_of_digits) - len(decimal_number_match.group(GROUP_INT_PART))
return curr_dec_digits
|
TypeError
|
dataset/ETHPy150Open sosy-lab/benchexec/benchexec/tablegenerator/__init__.py/_get_decimal_digits
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.