Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
5,400 | def test_wrong_initial_size(self):
# Give a clear error message if an array variable changes size at
# runtime compared to its initial value used to size the framework arrays
t = set_as_top(ArrayAsmb())
t.source.out = np.zeros(2)
try:
t.run()
except __HOLE_... | RuntimeError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/test/test_system.py/TestArrayConnectErrors.test_wrong_initial_size |
5,401 | def TranslationTool( model_inst, lint=False, enable_blackbox=False, verilator_xinit="zeros" ):
"""Translates a PyMTL model into Python-wrapped Verilog.
model_inst: an un-elaborated Model instance
lint: run verilator linter, warnings are fatal
(disables -Wno-lint flag)
enable_... | AttributeError | dataset/ETHPy150Open cornell-brg/pymtl/pymtl/tools/translation/verilator_sim.py/TranslationTool |
5,402 | def _bootstrap(self):
from . import util
global _current_process
try:
self._children = set()
self._counter = itertools.count(1)
try:
os.close(sys.stdin.fileno())
except (__HOLE__, ValueError):
pass
... | OSError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/multiprocessing/process.py/Process._bootstrap |
5,403 | def provide_batch(self):
if self.done:
return 0, None
if not self.f:
try:
self.f = open(self.spec.replace(BSON_SCHEME, ""))
except __HOLE__, e:
return "error: could not open bson: %s; exception: %s" % \
(self.spec, ... | IOError | dataset/ETHPy150Open membase/membase-cli/pump_bson.py/BSONSource.provide_batch |
5,404 | def __init__(self, extra_vars_func=None, options=None):
self.get_extra_vars = extra_vars_func
if options is None:
options = {}
self.options = options
self.default_encoding = options.get('genshi.default_encoding', None)
auto_reload = options.get('genshi.auto_reload', ... | ValueError | dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python3/genshi/template/plugin.py/AbstractTemplateEnginePlugin.__init__ |
5,405 | def Collect(infile,
with_headers=False,
annotator_format=False,
use_annotator_fdr=False,
delims="",
ignore="",
max_pvalue=1.0,
max_qvalue=None):
"""read input table."""
data = []
lines = filter(lambda x: x[0] != "#", infil... | ValueError | dataset/ETHPy150Open CGATOxford/cgat/scripts/go2svg.py/Collect |
5,406 | def addValue(self, row, col, size, colour_value):
"""add a dot in row/col.
"""
# decide the size of the box
pos = bisect.bisect(self.mThresholdsSize, size)
if self.mRevertSize:
size = self.mMaxBoxSize * \
(1.0 - float(pos) / len(self.mThresholdsSize)... | KeyError | dataset/ETHPy150Open CGATOxford/cgat/scripts/go2svg.py/GoPlot.addValue |
5,407 | 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")
parser.add_option("-e", "--header-names", dest="headers", action="store_true",
... | IOError | dataset/ETHPy150Open CGATOxford/cgat/scripts/go2svg.py/main |
5,408 | def _stop_current_lights(self):
if self.debug:
self.log.debug("Stopping current lights. Show: %s",
self.running_light_show)
try:
self.running_light_show.stop(hold=False, reset=False)
except __HOLE__:
pass
if self.debug:
... | AttributeError | dataset/ETHPy150Open missionpinball/mpf/mpf/devices/shot.py/Shot._stop_current_lights |
5,409 | def hit(self, mode='default#$%', waterfall_hits=None,
**kwargs):
"""Method which is called to indicate this shot was just hit. This
method will advance the currently-active shot profile.
Args:
force: Boolean that forces this hit to be registered. Default is
... | KeyError | dataset/ETHPy150Open missionpinball/mpf/mpf/devices/shot.py/Shot.hit |
5,410 | def update_enable_table(self, profile=None, enable=None, mode=None):
if mode:
priority = mode.priority
else:
priority = 0
if not profile:
try:
profile = self.enable_table[mode]['profile']
except KeyError:
profile =... | KeyError | dataset/ETHPy150Open missionpinball/mpf/mpf/devices/shot.py/Shot.update_enable_table |
5,411 | def remove_from_enable_table(self, mode):
if self.debug:
self.log.debug("Removing mode: %s from enable_table", mode)
try:
del self.enable_table[mode]
self._sort_enable_table()
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open missionpinball/mpf/mpf/devices/shot.py/Shot.remove_from_enable_table |
5,412 | def update_current_state_name(self, mode):
if self.debug:
self.log.debug("Old current state name for mode %s: %s",
mode, self.enable_table[mode]['current_state_name'])
try:
self.enable_table[mode]['current_state_name'] = (
self.enable_... | TypeError | dataset/ETHPy150Open missionpinball/mpf/mpf/devices/shot.py/Shot.update_current_state_name |
5,413 | def add_to_group(self, group):
if self.debug:
self.log.debug("Received request to add this shot to the %s group",
group)
if type(group) is str:
try:
group = self.machine.shot_groups[group]
except __HOLE__:
... | KeyError | dataset/ETHPy150Open missionpinball/mpf/mpf/devices/shot.py/Shot.add_to_group |
5,414 | def remove_from_group(self, group):
if self.debug:
self.log.debug("Received request to remove this shot from the %s "
"group", group)
if type(group) is str:
try:
group = self.machine.shot_groups[group]
except __HOLE__:
... | KeyError | dataset/ETHPy150Open missionpinball/mpf/mpf/devices/shot.py/Shot.remove_from_group |
5,415 | def run(self):
try:
self.conn.main()
except __HOLE__:
print('Exiting on keyboard interrupt') | KeyboardInterrupt | dataset/ETHPy150Open acrisci/i3ipc-python/examples/stop-application-on-unfocus.py/FocusMonitor.run |
5,416 | def search(name, year=None):
if name is None or name == '':
raise Exception
if isinstance(name, unicode):
name = name.encode('utf8')
endpoint = TMDB_HOST + '/search/movie'
payload = {'api_key': TMDB_API_KEY, 'query': urllib.quote_plus(str(name))}
if year is not None:
payloa... | ValueError | dataset/ETHPy150Open divijbindlish/movienamer/movienamer/tmdb.py/search |
5,417 | def value_from_object(self, obj):
"""If the field template is a :class:`DateField` or a :class:`DateTimeField`, this will convert the default return value to a datetime instance."""
value = super(JSONAttribute, self).value_from_object(obj)
if isinstance(self.field_template, (models.DateField, models.DateTimeField... | ValidationError | dataset/ETHPy150Open ithinksw/philo/philo/models/fields/entities.py/JSONAttribute.value_from_object |
5,418 | def handle_noargs(self, **options):
database = options.get('database')
connection = connections[database]
verbosity = int(options.get('verbosity'))
interactive = options.get('interactive')
# The following are stealth options used by Django's internals.
reset_sequences = o... | ImportError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/core/management/commands/flush.py/Command.handle_noargs |
5,419 | def get_suffixes( txt_file, suffix_file, stdout_file="", threshold=sys.maxint, prefix=u'__' ):
"""
Replace all words in <txt_file> with suffixes where possible.
Set of suffixes must be provided in <suffix_file>
The new corpus is written to <stdout_file> or to standard output if no file provided
<prefix> -- st... | KeyError | dataset/ETHPy150Open qe-team/marmot/marmot/preprocessing/get_suffixes.py/get_suffixes |
5,420 | def catch_notimplementederror(f):
"""Decorator to simplify catching drivers raising NotImplementedError
If a particular call makes a driver raise NotImplementedError, we
log it so that we can extract this information afterwards as needed.
"""
def wrapped_func(self, *args, **kwargs):
try:
... | NotImplementedError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/tests/unit/virt/test_virt_drivers.py/catch_notimplementederror |
5,421 | def _check_available_resource_fields(self, host_status):
super(FakeConnectionTestCase, self)._check_available_resource_fields(
host_status)
hypervisor_type = host_status['hypervisor_type']
supported_instances = host_status['supported_instances']
try:
# supported_... | TypeError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/tests/unit/virt/test_virt_drivers.py/FakeConnectionTestCase._check_available_resource_fields |
5,422 | def __contains__(self, item):
try:
self[item]
return True
except __HOLE__:
return False | KeyError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/client.py/Entity.__contains__ |
5,423 | def __contains__(self, name):
"""Is there at least one entry called *name* in this collection?
Makes a single roundtrip to the server, plus at most two more
if
the ``autologin`` field of :func:`connect` is set to ``True``.
"""
try:
self[name]
retu... | KeyError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/client.py/ReadOnlyCollection.__contains__ |
5,424 | def __getitem__(self, key):
"""Fetch an item named *key* from this collection.
A name is not a unique identifier in a collection. The unique
identifier is a name plus a namespace. For example, there can
be a saved search named ``'mysearch'`` with sharing ``'app'``
in application... | HTTPError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/client.py/ReadOnlyCollection.__getitem__ |
5,425 | def delete(self, name, **params):
"""Deletes a specified entity from the collection.
:param name: The name of the entity to delete.
:type name: ``string``
:return: The collection.
:rtype: ``self``
This method is implemented for consistency with the REST API's DELETE
... | HTTPError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/client.py/Collection.delete |
5,426 | def __getitem__(self, key):
# The superclass implementation is designed for collections that contain
# entities. This collection (Configurations) contains collections
# (ConfigurationFile).
#
# The configurations endpoint returns multiple entities when we ask for a single file.
... | HTTPError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/client.py/Configurations.__getitem__ |
5,427 | def __contains__(self, key):
# configs/conf-{name} never returns a 404. We have to post to properties/{name}
# in order to find out if a configuration exists.
try:
response = self.get(key)
return True
except __HOLE__ as he:
if he.status == 404: # No en... | HTTPError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/client.py/Configurations.__contains__ |
5,428 | def __getitem__(self, key):
# The key needed to retrieve the input needs it's parenthesis to be URL encoded
# based on the REST API for input
# <http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTinput>
if isinstance(key, tuple) and len(key) == 2:
# Fetch a single... | HTTPError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/client.py/Inputs.__getitem__ |
5,429 | def __contains__(self, key):
if isinstance(key, tuple) and len(key) == 2:
# If we specify a kind, this will shortcut properly
try:
self.__getitem__(key)
return True
except __HOLE__:
return False
else:
# Witho... | KeyError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/client.py/Inputs.__contains__ |
5,430 | def list(self, *kinds, **kwargs):
"""Returns a list of inputs that are in the :class:`Inputs` collection.
You can also filter by one or more input kinds.
This function iterates over all possible inputs, regardless of any arguments you
specify. Because the :class:`Inputs` collection is t... | HTTPError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/client.py/Inputs.list |
5,431 | def cancel(self):
"""Stops the current search and deletes the results cache.
:return: The :class:`Job`.
"""
try:
self.post("control", action="cancel")
except __HOLE__ as he:
if he.status == 404:
# The job has already been cancelled, so
... | HTTPError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/client.py/Job.cancel |
5,432 | def check(db, rev_id, page_id=None, radius=defaults.RADIUS, check_archive=False,
before=None, window=None):
"""
Checks whether a revision was reverted (identity) and returns a named tuple
of Revert(reverting, reverteds, reverted_to).
:Parameters:
db : `mw.database.DB`
A d... | IndexError | dataset/ETHPy150Open mediawiki-utilities/python-mediawiki-utilities/mw/lib/reverts/database.py/check |
5,433 | @exception.wrap_pecan_controller_exception
@pecan.expose('json', content_type='application/json-patch+json')
def patch(self, uuid):
"""Patch an existing CAMP-style plan."""
handler = (plan_handler.
PlanHandler(pecan.request.security_context))
plan_obj = handler.get(uu... | KeyError | dataset/ETHPy150Open openstack/solum/solum/api/controllers/camp/v1_1/plans.py/PlansController.patch |
5,434 | @exception.wrap_pecan_controller_exception
@pecan.expose('json', content_type='application/x-yaml')
def post(self):
"""Create a new CAMP-style plan."""
if not pecan.request.body or len(pecan.request.body) < 1:
raise exception.BadRequest
# check to make sure the request has t... | ValueError | dataset/ETHPy150Open openstack/solum/solum/api/controllers/camp/v1_1/plans.py/PlansController.post |
5,435 | def forward(app):
app = TestApp(RecursiveMiddleware(app))
res = app.get('')
assert res.header('content-type') == 'text/plain'
assert res.full_status == '200 OK'
assert 'requested page returned' in res
res = app.get('/error')
assert res.header('content-type') == 'text/plain'
assert res.fu... | AssertionError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/tests/test_recursive.py/forward |
5,436 | def test_ForwardRequest_factory():
from paste.errordocument import StatusKeeper
class TestForwardRequestMiddleware(Middleware):
def __call__(self, environ, start_response):
if environ['PATH_INFO'] != '/not_found':
return self.app(environ, start_response)
environ... | AssertionError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/tests/test_recursive.py/test_ForwardRequest_factory |
5,437 | def exist(self, item_name, index=None):
if item_name in self.db:
if index is not None:
try:
self.db[item_name]['value'][index]
except __HOLE__:
return False
return True
return False | IndexError | dataset/ETHPy150Open nyddle/pystash/pystash/common.py/ShelveStorage.exist |
5,438 | def _GetTempOutputFileHandles(self, value_type):
"""Initializes output AFF4Image for a given value type."""
try:
return self.temp_output_trackers[value_type], False
except __HOLE__:
return self._CreateOutputFileHandles(value_type), True | KeyError | dataset/ETHPy150Open google/grr/grr/lib/output_plugins/bigquery_plugin.py/BigQueryOutputPlugin._GetTempOutputFileHandles |
5,439 | def __init__(self, repo, log, weak=True, git_bin='git', git_fs_encoding=None):
self.logger = log
with StorageFactory.__dict_lock:
try:
i = StorageFactory.__dict[repo]
except __HOLE__:
i = Storage(repo, log, git_bin, git_fs_encoding)
... | KeyError | dataset/ETHPy150Open hvr/trac-git-plugin/tracext/git/PyGIT.py/StorageFactory.__init__ |
5,440 | @staticmethod
def git_version(git_bin="git"):
GIT_VERSION_MIN_REQUIRED = (1, 5, 6)
try:
g = GitCore(git_bin=git_bin)
[v] = g.version().splitlines()
_, _, version = v.strip().split()
# 'version' has usually at least 3 numeric version components, e.g.::
... | ValueError | dataset/ETHPy150Open hvr/trac-git-plugin/tracext/git/PyGIT.py/Storage.git_version |
5,441 | def get_rev_cache(self):
"""
Retrieve revision cache
may rebuild cache on the fly if required
returns RevCache tuple
"""
with self.__rev_cache_lock:
if self.__rev_cache is None: # can be cleared by Storage.__rev_cache_sync()
self.logger.debu... | KeyError | dataset/ETHPy150Open hvr/trac-git-plugin/tracext/git/PyGIT.py/Storage.get_rev_cache |
5,442 | def get_branch_contains(self, sha, resolve=False):
"""
return list of reachable head sha ids or (names, sha) pairs if resolve is true
see also get_branches()
"""
_rev_cache = self.rev_cache
try:
rheads = _rev_cache.rev_dict[sha][3]
except __HOLE__:
... | KeyError | dataset/ETHPy150Open hvr/trac-git-plugin/tracext/git/PyGIT.py/Storage.get_branch_contains |
5,443 | def fullrev(self, srev):
"try to reverse shortrev()"
srev = str(srev)
_rev_cache = self.rev_cache
# short-cut
if len(srev) == 40 and srev in _rev_cache.rev_dict:
return srev
if not GitCore.is_sha(srev):
return None
try:
srev... | KeyError | dataset/ETHPy150Open hvr/trac-git-plugin/tracext/git/PyGIT.py/Storage.fullrev |
5,444 | def get_obj_size(self, sha):
sha = str(sha)
try:
obj_size = int(self.repo.cat_file("-s", sha).strip())
except __HOLE__:
raise GitErrorSha("object '%s' not found" % sha)
return obj_size | ValueError | dataset/ETHPy150Open hvr/trac-git-plugin/tracext/git/PyGIT.py/Storage.get_obj_size |
5,445 | def children(self, sha):
db = self.get_commits()
try:
return list(db[sha][0])
except __HOLE__:
return [] | KeyError | dataset/ETHPy150Open hvr/trac-git-plugin/tracext/git/PyGIT.py/Storage.children |
5,446 | def parents(self, sha):
db = self.get_commits()
try:
return list(db[sha][1])
except __HOLE__:
return [] | KeyError | dataset/ETHPy150Open hvr/trac-git-plugin/tracext/git/PyGIT.py/Storage.parents |
5,447 | @contextmanager
def get_historian(self, sha, base_path):
p = []
change = {}
next_path = []
def name_status_gen():
p[:] = [self.repo.log_pipe('--pretty=format:%n%H', '--name-status',
sha, '--', base_path)]
f = p[0].stdout... | KeyError | dataset/ETHPy150Open hvr/trac-git-plugin/tracext/git/PyGIT.py/Storage.get_historian |
5,448 | @contextmanager
def cleanup(self, prog):
try:
yield
except __HOLE__:
log.error('KeyboardInterrupt')
finally:
if not prog.is_ok:
log.info("Program manager letting program fail") | KeyboardInterrupt | dataset/ETHPy150Open Anaconda-Platform/chalmers/chalmers/program_manager.py/ProgramManager.cleanup |
5,449 | def _write(self, file, node, encoding, namespaces):
# write XML to file
tag = node.tag
if tag is Comment:
file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))
elif tag is ProcessingInstruction:
file.write("<?%s?>" % _escape_cdata(node.text, encoding))
... | TypeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/xml/etree/ElementTree.py/ElementTree._write |
5,450 | def _encode(s, encoding):
try:
return s.encode(encoding)
except __HOLE__:
return s # 1.5.2: assume the string uses the right encoding | AttributeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/xml/etree/ElementTree.py/_encode |
5,451 | def _encode_entity(text, pattern=_escape):
# map reserved and non-ascii characters to numerical entities
def escape_entities(m, map=_escape_map):
out = []
append = out.append
for char in m.group():
text = map.get(char)
if text is None:
text = "&#%d... | TypeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/xml/etree/ElementTree.py/_encode_entity |
5,452 | def _escape_cdata(text, encoding=None, replace=string.replace):
# escape character data
try:
if encoding:
try:
text = _encode(text, encoding)
except UnicodeError:
return _encode_entity(text)
text = replace(text, "&", "&")
text =... | TypeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/xml/etree/ElementTree.py/_escape_cdata |
5,453 | def _escape_attrib(text, encoding=None, replace=string.replace):
# escape attribute value
try:
if encoding:
try:
text = _encode(text, encoding)
except UnicodeError:
return _encode_entity(text)
text = replace(text, "&", "&")
text... | AttributeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/xml/etree/ElementTree.py/_escape_attrib |
5,454 | def __init__(self, source, events=None):
if not hasattr(source, "read"):
source = open(source, "rb")
self._file = source
self._events = []
self._index = 0
self.root = self._root = None
self._parser = XMLTreeBuilder()
# wire up the parser for event repo... | AttributeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/xml/etree/ElementTree.py/iterparse.__init__ |
5,455 | def next(self):
while 1:
try:
item = self._events[self._index]
except __HOLE__:
if self._parser is None:
self.root = self._root
try:
raise StopIteration
except NameError:
... | IndexError | dataset/ETHPy150Open babble/babble/include/jython/Lib/xml/etree/ElementTree.py/iterparse.next |
5,456 | def __init__(self, html=0, target=None):
try:
from xml.parsers import expat
except __HOLE__:
raise ImportError(
"No module named expat; use SimpleXMLTreeBuilder instead"
)
self._parser = parser = expat.ParserCreate(None, "}")
if tar... | ImportError | dataset/ETHPy150Open babble/babble/include/jython/Lib/xml/etree/ElementTree.py/XMLTreeBuilder.__init__ |
5,457 | def _fixname(self, key):
# expand qname, and convert name string to ascii, if possible
try:
name = self._names[key]
except __HOLE__:
name = key
if "}" in name:
name = "{" + name
self._names[key] = name = self._fixtext(name)
... | KeyError | dataset/ETHPy150Open babble/babble/include/jython/Lib/xml/etree/ElementTree.py/XMLTreeBuilder._fixname |
5,458 | def _default(self, text):
prefix = text[:1]
if prefix == "&":
# deal with undefined entities
try:
self._target.data(self.entity[text[1:-1]])
except __HOLE__:
from xml.parsers import expat
raise expat.error(
... | KeyError | dataset/ETHPy150Open babble/babble/include/jython/Lib/xml/etree/ElementTree.py/XMLTreeBuilder._default |
5,459 | def test_expiration():
time = 1
cache = Cache(max_age=5, clock=lambda: time)
# Ensure that the clock value is coming from the current value of the
# `time` variable.
assert cache.clock() == 1
time = 2
assert cache.clock() == 2
cache['a'] = 'b'
cache['b'] = 'c'
time += 3
... | IndexError | dataset/ETHPy150Open kgaughan/uwhoisd/tests/test_cache.py/test_expiration |
5,460 | def clean_json(resource_json, resources_map):
"""
Cleanup the a resource dict. For now, this just means replacing any Ref node
with the corresponding physical_resource_id.
Eventually, this is where we would add things like function parsing (fn::)
"""
if isinstance(resource_json, dict):
... | NotImplementedError | dataset/ETHPy150Open spulec/moto/moto/cloudformation/parsing.py/clean_json |
5,461 | def _parse_comments(s):
""" Parses vim's comments option to extract comment format """
i = iter(s.split(","))
rv = []
try:
while True:
# get the flags and text of a comment part
flags, text = next(i).split(':', 1)
if len(flags) == 0:
rv.appen... | StopIteration | dataset/ETHPy150Open honza/vim-snippets/pythonx/vimsnippets.py/_parse_comments |
5,462 | def lpsolve(self, solver="scip", clean=True):
self.print_instance()
solver = SCIPSolver if solver == "scip" else GLPKSolver
lp_data = self.handle.getvalue()
self.handle.close()
g = solver(lp_data, clean=clean)
selected = set(g.results)
try:
obj_val =... | AttributeError | dataset/ETHPy150Open tanghaibao/jcvi/algorithms/lpsolve.py/LPInstance.lpsolve |
5,463 | def get_names_from_path(fontpath):
"""Parse underscore(or hyphen)-separated font file names into ``family`` and ``style`` names."""
_file = os.path.basename(fontpath)
_file_name = os.path.splitext(_file)[0]
try:
family_name, style_name = _file_name.split('_')
except __HOLE__:
family_... | ValueError | dataset/ETHPy150Open gferreira/hTools2/Lib/hTools2/modules/fileutils.py/get_names_from_path |
5,464 | def create_indexes(self, colname, ncolname, extracolname):
if not self.indexed:
return
try:
kind = self.kind
vprint("* Indexing ``%s`` columns. Type: %s." % (colname, kind))
for acolname in [colname, ncolname, extracolname]:
acolumn = self.... | NotImplementedError | dataset/ETHPy150Open PyTables/PyTables/tables/tests/test_queries.py/BaseTableQueryTestCase.create_indexes |
5,465 | def create_test_method(type_, op, extracond, func=None):
sctype = sctype_from_type[type_]
# Compute the value of bounds.
condvars = {'bound': right_bound,
'lbound': left_bound,
'rbound': right_bound,
'func_bound': func_bound}
for (bname, bvalue) in six.it... | NotImplementedError | dataset/ETHPy150Open PyTables/PyTables/tables/tests/test_queries.py/create_test_method |
5,466 | def transcript_iterator(gff_iterator, strict=True):
"""iterate over the contents of a gtf file.
return a list of entries with the same transcript id.
Any features without a transcript_id will be ignored.
The entries for the same transcript have to be consecutive
in the file. If *strict* is set an... | AttributeError | dataset/ETHPy150Open CGATOxford/cgat/CGAT/GTF.py/transcript_iterator |
5,467 | def iterator_transcripts2genes(gtf_iterator, min_overlap=0):
"""cluster transcripts by exon overlap.
The gene id is set to the first transcript encountered of a gene.
If a gene stretches over several contigs, subsequent copies are
appended a number.
"""
map_transcript2gene = {}
gene_ids = ... | ValueError | dataset/ETHPy150Open CGATOxford/cgat/CGAT/GTF.py/iterator_transcripts2genes |
5,468 | def read(self, line):
"""read gff entry from line in GTF/GFF format.
<seqname> <source> <feature> <start> <end> <score> \
<strand> <frame> [attributes] [comments]
"""
data = line[:-1].split("\t")
try:
(self.contig, self.source, self.feature,
... | ValueError | dataset/ETHPy150Open CGATOxford/cgat/CGAT/GTF.py/Entry.read |
5,469 | def parseInfo(self, attributes, line):
"""parse attributes.
This method will set the gene_id and transcript_id attributes
if present.
"""
# remove comments
attributes = attributes.split("#")[0]
# separate into fields
# Fields might contain a ";", for ex... | TypeError | dataset/ETHPy150Open CGATOxford/cgat/CGAT/GTF.py/Entry.parseInfo |
5,470 | def copy(self, other):
"""fill from other entry.
This method works if other is :class:`GTF.Entry` or
:class:`pysam.GTFProxy`.
"""
self.contig = other.contig
self.source = other.source
self.feature = other.feature
self.start = other.start
self.end ... | KeyError | dataset/ETHPy150Open CGATOxford/cgat/CGAT/GTF.py/Entry.copy |
5,471 | def check_dependencies(self, obj, failed):
for dep in self.dependencies:
peer_name = dep[0].lower() + dep[1:] # django names are camelCased with the first letter lower
peer_objects=[]
try:
peer_names = plural(peer_name)
peer_object_list=[]
... | AttributeError | dataset/ETHPy150Open open-cloud/xos/xos/synchronizers/base/syncstep.py/SyncStep.check_dependencies |
5,472 | def sync_record(self, o):
try:
controller = o.get_controller()
controller_register = json.loads(controller.backend_register)
if (controller_register.get('disabled',False)):
raise InnocuousException('Controller %s is disabled'%controller.name)
except _... | AttributeError | dataset/ETHPy150Open open-cloud/xos/xos/synchronizers/base/syncstep.py/SyncStep.sync_record |
5,473 | def delete_record(self, o):
try:
controller = o.get_controller()
controller_register = json.loads(o.node.site_deployment.controller.backend_register)
if (controller_register.get('disabled',False)):
raise InnocuousException('Controller %s is disabled'%sliver.n... | AttributeError | dataset/ETHPy150Open open-cloud/xos/xos/synchronizers/base/syncstep.py/SyncStep.delete_record |
5,474 | def call(self, failed=[], deletion=False):
#if ('Instance' in self.__class__.__name__):
# pdb.set_trace()
pending = self.fetch_pending(deletion)
for o in pending:
# another spot to clean up debug state
try:
reset_queries()
except:
... | KeyError | dataset/ETHPy150Open open-cloud/xos/xos/synchronizers/base/syncstep.py/SyncStep.call |
5,475 | def get_default_columns(self, with_aliases=False, col_aliases=None,
start_alias=None, opts=None, as_pairs=False, local_only=False):
"""
Computes the default columns for selecting every field in the base
model. Will sometimes be called to pull in related models (e.g. via
selec... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/db/models/sql/compiler.py/SQLCompiler.get_default_columns |
5,476 | def get_from_clause(self):
"""
Returns a list of strings that are joined together to go after the
"FROM" part of the query, as well as a list any extra parameters that
need to be included. Sub-classes, can override this to create a
from-clause via a "select".
This should... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/db/models/sql/compiler.py/SQLCompiler.get_from_clause |
5,477 | @classmethod
def query_mongo(cls, username, query=None, fields=None, sort=None, start=0,
limit=DEFAULT_LIMIT, count=False):
query = dict_for_mongo(query) if query else {}
query[cls.ACCOUNT] = username
# TODO find better method
# check for the created_on key in que... | ValueError | dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/main/models/audit.py/AuditLog.query_mongo |
5,478 | def get_plural(locale=LC_CTYPE):
"""A tuple with the information catalogs need to perform proper
pluralization. The first item of the tuple is the number of plural
forms, the second the plural expression.
>>> get_plural(locale='en')
(2, '(n != 1)')
>>> get_plural(locale='ga')
(3, '... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Babel-0.9.6/babel/messages/plurals.py/get_plural |
5,479 | def _clean_output(out):
try:
out = out.decode('utf-8')
except __HOLE__: # python3, pragma: no cover
pass
return out.strip() | AttributeError | dataset/ETHPy150Open hayd/pep8radius/pep8radius/shell.py/_clean_output |
5,480 | def _validate_database(self):
"""
Makes sure that the database is openable. Removes the file if it's not.
"""
# If there is no file there, that's fine. It will get created when
# we connect.
if not os.path.exists(self.filename):
self._create_database()
... | ValueError | dataset/ETHPy150Open Backblaze/B2_Command_Line_Tool/b2/account_info.py/SqliteAccountInfo._validate_database |
5,481 | def test_upload_url_concurrency():
# Clean up from previous tests
file_name = '/tmp/test_upload_conncurrency.db'
try:
os.unlink(file_name)
except __HOLE__:
pass
# Make an account info with a bunch of upload URLs in it.
account_info = SqliteAccountInfo(file_name)
available_ur... | OSError | dataset/ETHPy150Open Backblaze/B2_Command_Line_Tool/b2/account_info.py/test_upload_url_concurrency |
5,482 | def mod_data(opts, full):
'''
Grab the module's data
'''
ret = {}
finder = modulefinder.ModuleFinder()
try:
finder.load_file(full)
except __HOLE__ as exc:
print('ImportError - {0} (Reason: {1})'.format(full, exc), file=sys.stderr)
return ret
for name, mod in finde... | ImportError | dataset/ETHPy150Open saltstack/salt/tests/modparser.py/mod_data |
5,483 | def handle_noargs(self, **options):
try:
for line in self.handle_inspection(options):
self.stdout.write("%s\n" % line)
except __HOLE__:
raise CommandError("Database inspection isn't supported for the currently selected database backend.") | NotImplementedError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/core/management/commands/inspectdb.py/Command.handle_noargs |
5,484 | def handle_inspection(self, options):
connection = connections[options.get('database')]
# 'table_name_filter' is a stealth option
table_name_filter = options.get('table_name_filter')
table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '')
... | NotImplementedError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/core/management/commands/inspectdb.py/Command.handle_inspection |
5,485 | def get_field_type(self, connection, table_name, row):
"""
Given the database connection, the table name, and the cursor row
description, this routine will return the given field type name, as
well as any additional keyword parameters and notes for the field.
"""
field_pa... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/core/management/commands/inspectdb.py/Command.get_field_type |
5,486 | def run(self):
self.assert_has_content()
text = '\n'.join(self.content)
try:
if self.arguments:
classes = directives.class_option(self.arguments[0])
else:
classes = []
except __HOLE__:
raise self.error(
'... | ValueError | dataset/ETHPy150Open adieu/allbuttonspressed/docutils/parsers/rst/directives/body.py/Container.run |
5,487 | def test_class_object_qualname(self):
# Test preservation of instance method __qualname__ attribute.
try:
__qualname__ = OldClass1o.original.__qualname__
except __HOLE__:
pass
else:
self.assertEqual(OldClass1d.function.__qualname__, __qualname__) | AttributeError | dataset/ETHPy150Open GrahamDumpleton/wrapt/tests/test_instancemethod.py/TestNamingInstanceMethodOldStyle.test_class_object_qualname |
5,488 | def test_instance_object_qualname(self):
# Test preservation of instance method __qualname__ attribute.
try:
__qualname__ = OldClass1o().original.__qualname__
except __HOLE__:
pass
else:
self.assertEqual(OldClass1d().function.__qualname__, __qualname_... | AttributeError | dataset/ETHPy150Open GrahamDumpleton/wrapt/tests/test_instancemethod.py/TestNamingInstanceMethodOldStyle.test_instance_object_qualname |
5,489 | def test_class_object_qualname(self):
# Test preservation of instance method __qualname__ attribute.
try:
__qualname__ = NewClass1o.original.__qualname__
except __HOLE__:
pass
else:
self.assertEqual(NewClass1d.function.__qualname__, __qualname__) | AttributeError | dataset/ETHPy150Open GrahamDumpleton/wrapt/tests/test_instancemethod.py/TestNamingInstanceMethodNewStyle.test_class_object_qualname |
5,490 | def test_instance_object_qualname(self):
# Test preservation of instance method __qualname__ attribute.
try:
__qualname__ = NewClass1o().original.__qualname__
except __HOLE__:
pass
else:
self.assertEqual(NewClass1d().function.__qualname__, __qualname_... | AttributeError | dataset/ETHPy150Open GrahamDumpleton/wrapt/tests/test_instancemethod.py/TestNamingInstanceMethodNewStyle.test_instance_object_qualname |
5,491 | def remove(self, player):
if _debug:
print 'DirectSoundWorker remove', player
self.condition.acquire()
try:
self.players.remove(player)
except __HOLE__:
pass
self.condition.notify()
self.condition.release()
if _debug:
... | KeyError | dataset/ETHPy150Open ardekantur/pyglet/experimental/mt_media/drivers/directsound/__init__.py/DirectSoundWorker.remove |
5,492 | def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_liblsl', [dirname(__file__)])
except __HOLE__:
import _liblsl
return _liblsl
if fp is not None:
tr... | ImportError | dataset/ETHPy150Open sccn/SNAP/src/pylsl/binaries-python2.4-win32/liblsl.py/swig_import_helper |
5,493 | def replaceReads(targetbam, donorbam, outputbam, nameprefix=None, excludefile=None, allreads=False, keepqual=False, progress=False, keepsecondary=False, seed=None):
''' targetbam, donorbam, and outputbam are pysam.Samfile objects
outputbam must be writeable and use targetbam as template
read names i... | ValueError | dataset/ETHPy150Open adamewing/bamsurgeon/bamsurgeon/replacereads.py/replaceReads |
5,494 | def _get_font_id(self):
if PY2:
try:
return '|'.join([unicode(self.options[x]) for x in
('font_size', 'font_name_r',
'bold', 'italic')])
except __HOLE__:
pass
return '|'.join([str(s... | UnicodeDecodeError | dataset/ETHPy150Open kivy/kivy/kivy/core/text/text_pygame.py/LabelPygame._get_font_id |
5,495 | def create_nonce(user, action, offset=0):
if not user:
nick = ""
else:
try:
nick = user.nick
except __HOLE__:
if settings.MANAGE_PY:
# extra case to make testing easier
nick = clean.nick(user)
else:
raise
i = math.ceil(time.time() / 43200)
i += offset
non... | AttributeError | dataset/ETHPy150Open CollabQ/CollabQ/common/util.py/create_nonce |
5,496 | def get_user_from_topic(s):
"""Extracts the username from a topic or Stream object.
Topics look like: 'stream/[email protected]/comments'
Returns:
A string, the username, or None if the topic name didn't appear to contain a
valid userid.
"""
o = None
# Check whether we got a topic name or a Stream i... | IndexError | dataset/ETHPy150Open CollabQ/CollabQ/common/util.py/get_user_from_topic |
5,497 | def page_offset(request):
"""attempts to normalize timestamps into datetimes for offsets"""
offset = request.GET.get('offset', None)
if offset:
try:
offset = datetime.datetime.fromtimestamp(float(offset))
except (__HOLE__, ValueError):
offset = None
return offset, (offset and True or False) | TypeError | dataset/ETHPy150Open CollabQ/CollabQ/common/util.py/page_offset |
5,498 | def paging_get_page(request):
try:
page = int(request.GET.get('page', 1))
except __HOLE__:
page = 1
if page <= 0:
page = 1
return page | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/common/util.py/paging_get_page |
5,499 | def get_metadata(name, default=None):
metadata_ref = get_metadata_ref(name)
if metadata_ref:
value = metadata_ref.get_value()
return value
if default is None:
try:
default = getattr(settings, name)
except __HOLE__:
logging.warning("AttributeError, %s is not in settings" % name)
retur... | AttributeError | dataset/ETHPy150Open CollabQ/CollabQ/common/util.py/get_metadata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.