Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
5,000 | def _get_allocations(self):
utils.ensure_dir(TMP_DIR)
try:
with open(self._state_file_path, 'r') as allocations_file:
contents = allocations_file.read()
except __HOLE__:
contents = None
# If the file was empty, we want to return an empty set, not... | IOError | dataset/ETHPy150Open openstack/neutron/neutron/tests/common/exclusive_resources/resource_allocator.py/ResourceAllocator._get_allocations |
5,001 | def fit_point_cloud(src_pts, tgt_pts, rotate=True, translate=True,
scale=0, x0=None, leastsq_args={}, out='params'):
"""Find a transform that minimizes the squared distance from each source
point to its closest target point
Uses :func:`scipy.optimize.leastsq` to find a transformation in... | ImportError | dataset/ETHPy150Open mne-tools/mne-python/mne/coreg.py/fit_point_cloud |
5,002 | def resolveBoundary( self, boundarySpecifier, property, client, value ):
"""Resolve a particular boundary specifier into a boundary class"""
try:
return latebind.bind( boundarySpecifier )
except (ImportError, __HOLE__):
raise BoundaryTypeError(
property, self, client, value,
"Class/type %s could not... | AttributeError | dataset/ETHPy150Open correl/Transmission-XBMC/resources/lib/basictypes/boundary.py/Type.resolveBoundary |
5,003 | def __init__(self, data, subject, **kwargs):
if isinstance(data, str):
import nibabel
nib = nibabel.load(data)
data = nib.get_data().T
self._data = data
try:
basestring
except __HOLE__:
subject = subject if isinstance(subject, s... | NameError | dataset/ETHPy150Open gallantlab/pycortex/cortex/dataset/braindata.py/BrainData.__init__ |
5,004 | def __init__(self, data, subject, xfmname, mask=None, **kwargs):
"""Three possible variables: volume, movie, vertex. Enumerated with size:
volume movie: (t, z, y, x)
volume image: (z, y, x)
linear movie: (t, v)
linear image: (v,)
"""
if self.__class__ == VolumeDat... | NameError | dataset/ETHPy150Open gallantlab/pycortex/cortex/dataset/braindata.py/VolumeData.__init__ |
5,005 | def __init__(self, data, subject, **kwargs):
"""Represents `data` at each vertex on a `subject`s cortex.
`data` shape possibilities:
reg linear movie: (t, v)
reg linear image: (v,)
None: creates zero-filled VertexData
where t is the number of time points, c is colors (i... | IOError | dataset/ETHPy150Open gallantlab/pycortex/cortex/dataset/braindata.py/VertexData.__init__ |
5,006 | @classmethod
def empty(cls, subject, value=0, **kwargs):
try:
left, right = db.get_surf(subject, "wm")
except __HOLE__:
left, right = db.get_surf(subject, "fiducial")
nverts = len(left[0]) + len(right[0])
return cls(np.ones((nverts,))*value, subject, **kwargs) | IOError | dataset/ETHPy150Open gallantlab/pycortex/cortex/dataset/braindata.py/VertexData.empty |
5,007 | @classmethod
def random(cls, subject, **kwargs):
try:
left, right = db.get_surf(subject, "wm")
except __HOLE__:
left, right = db.get_surf(subject, "fiducial")
nverts = len(left[0]) + len(right[0])
return cls(np.random.randn(nverts), subject, **kwargs) | IOError | dataset/ETHPy150Open gallantlab/pycortex/cortex/dataset/braindata.py/VertexData.random |
5,008 | def _hdf_write(h5, data, name="data", group="/data"):
try:
node = h5.require_dataset("%s/%s"%(group, name), data.shape, data.dtype, exact=True)
except __HOLE__:
del h5[group][name]
node = h5.create_dataset("%s/%s"%(group, name), data.shape, data.dtype, exact=True)
node[:] = data
... | TypeError | dataset/ETHPy150Open gallantlab/pycortex/cortex/dataset/braindata.py/_hdf_write |
5,009 | def convert_pdf(filename, type='xml'):
commands = {'text': ['pdftotext', '-layout', filename, '-'],
'text-nolayout': ['pdftotext', filename, '-'],
'xml': ['pdftohtml', '-xml', '-stdout', filename],
'html': ['pdftohtml', '-stdout', filename]}
try:
pipe = su... | OSError | dataset/ETHPy150Open opencivicdata/pupa/pupa/utils/generic.py/convert_pdf |
5,010 | def _find_cached_images(session, sr_ref):
"""Return a dict(uuid=vdi_ref) representing all cached images."""
cached_images = {}
for vdi_ref, vdi_rec in _get_all_vdis_in_sr(session, sr_ref):
try:
image_id = vdi_rec['other_config']['image-id']
except __HOLE__:
continue
... | KeyError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/xenapi/vm_utils.py/_find_cached_images |
5,011 | def create_image(context, session, instance, name_label, image_id,
image_type):
"""Creates VDI from the image stored in the local cache. If the image
is not present in the cache, it streams it from glance.
Returns: A list of dictionaries that describe VDIs
"""
cache_images = CONF.x... | KeyError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/xenapi/vm_utils.py/create_image |
5,012 | def _image_uses_bittorrent(context, instance):
bittorrent = False
torrent_images = CONF.xenserver.torrent_images.lower()
if torrent_images == 'all':
bittorrent = True
elif torrent_images == 'some':
sys_meta = utils.instance_sys_meta(instance)
try:
bittorrent = struti... | KeyError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/xenapi/vm_utils.py/_image_uses_bittorrent |
5,013 | def _fetch_disk_image(context, session, instance, name_label, image_id,
image_type):
"""Fetch the image from Glance
NOTE:
Unlike _fetch_vhd_image, this method does not use the Glance
plugin; instead, it streams the disks through domU to the VDI
directly.
Returns: A single... | IOError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/xenapi/vm_utils.py/_fetch_disk_image |
5,014 | def determine_disk_image_type(image_meta):
"""Disk Image Types are used to determine where the kernel will reside
within an image. To figure out which type we're dealing with, we use
the following rules:
1. If we're using Glance, we can use the image_type field to
determine the image_type
2... | KeyError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/xenapi/vm_utils.py/determine_disk_image_type |
5,015 | def _find_sr(session):
"""Return the storage repository to hold VM images."""
host = session.host_ref
try:
tokens = CONF.xenserver.sr_matching_filter.split(':')
filter_criteria = tokens[0]
filter_pattern = tokens[1]
except __HOLE__:
# oops, flag is invalid
LOG.war... | IndexError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/xenapi/vm_utils.py/_find_sr |
5,016 | def _get_rrd(server, vm_uuid):
"""Return the VM RRD XML as a string."""
try:
xml = urllib.urlopen("%s://%s:%s@%s/vm_rrd?uuid=%s" % (
server[0],
CONF.xenserver.connection_username,
CONF.xenserver.connection_password,
server[1],
vm_uuid))
... | IOError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/xenapi/vm_utils.py/_get_rrd |
5,017 | def get_this_vm_uuid(session):
if session and session.is_local_connection:
# UUID is the control domain running on this host
vms = session.call_xenapi("VM.get_all_records_where",
'field "is_control_domain"="true" and '
'field "resid... | IOError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/xenapi/vm_utils.py/get_this_vm_uuid |
5,018 | def input(self, datum, *a, **kw):
if datum == NOTHING:
return
try:
output, newstate = self.states[self.state][datum]
except __HOLE__:
self.invalidInput(datum)
else:
OLDSTATE = self.state.upper()
NEWSTATE = newstate.upper()
... | KeyError | dataset/ETHPy150Open twisted/vertex/vertex/statemachine.py/StateMachine.input |
5,019 | def _find_element_by_class_name(self, class_name, index_or_name):
elements = self._find_elements_by_class_name(class_name)
if self._is_index(index_or_name):
try:
index = int(index_or_name.split('=')[-1])
element = elements[index]
except (In... | TypeError | dataset/ETHPy150Open jollychang/robotframework-appiumlibrary/src/AppiumLibrary/keywords/_element.py/_ElementKeywords._find_element_by_class_name |
5,020 | def main(app):
target_dir = os.path.join(app.builder.srcdir, 'book_figures')
source_dir = os.path.abspath(app.builder.srcdir + '/../' + 'book_figures')
try:
plot_gallery = eval(app.builder.config.plot_gallery)
except __HOLE__:
plot_gallery = bool(app.builder.config.plot_gallery)
i... | TypeError | dataset/ETHPy150Open cigroup-ol/windml/doc/sphinxext/gen_figure_rst.py/main |
5,021 | def is_classic_task(tup):
"""
Takes (name, object) tuple, returns True if it's a non-Fab public callable.
"""
name, func = tup
try:
is_classic = (
callable(func) and (func not in _internals) and not
name.startswith('_')
)
# Handle poorly behaved __eq__ imp... | ValueError | dataset/ETHPy150Open prestodb/presto-admin/prestoadmin/main.py/is_classic_task |
5,022 | def run_tasks(task_list):
for name, args, kwargs, arg_hosts, arg_roles, arg_excl_hosts in task_list:
try:
if state.env.nodeps and name.strip() != 'package.install':
sys.stderr.write('Invalid argument --nodeps to task: %s\n'
% name)
... | TypeError | dataset/ETHPy150Open prestodb/presto-admin/prestoadmin/main.py/run_tasks |
5,023 | def _handle_generic_set_env_vars(non_default_options):
if not hasattr(non_default_options, 'env_settings'):
return non_default_options
# Allow setting of arbitrary env keys.
# This comes *before* the "specific" env_options so that those may
# override these ones. Specific should override generi... | ValueError | dataset/ETHPy150Open prestodb/presto-admin/prestoadmin/main.py/_handle_generic_set_env_vars |
5,024 | def _get_config_callback(commands_to_run):
config_callback = None
if len(commands_to_run) != 1:
raise Exception('Multiple commands are not supported')
c = commands_to_run[0][0]
module, command = c.split('.')
module_dict = state.commands[module]
command_callable = module_dict[command]
... | AttributeError | dataset/ETHPy150Open prestodb/presto-admin/prestoadmin/main.py/_get_config_callback |
5,025 | def parse_and_validate_commands(args=sys.argv[1:]):
# Find local fabfile path or abort
fabfile = "prestoadmin"
# Store absolute path to fabfile in case anyone needs it
state.env.real_fabfile = fabfile
# Load fabfile (which calls its module-level code, including
# tweaks to env values) and put ... | NameError | dataset/ETHPy150Open prestodb/presto-admin/prestoadmin/main.py/parse_and_validate_commands |
5,026 | def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except __HOLE__:
return self._reverse[key] | KeyError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/parallel/util.py/ReverseDict.__getitem__ |
5,027 | def get(self, key, default=None):
try:
return self[key]
except __HOLE__:
return default
#-----------------------------------------------------------------------------
# Functions
#----------------------------------------------------------------------------- | KeyError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/parallel/util.py/ReverseDict.get |
5,028 | def validate_url(url):
"""validate a url for zeromq"""
if not isinstance(url, str):
raise TypeError("url must be a string, not %r"%type(url))
url = url.lower()
proto_addr = url.split('://')
assert len(proto_addr) == 2, 'Invalid url: %r'%url
proto, addr = proto_addr
assert proto ... | ValueError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/parallel/util.py/validate_url |
5,029 | def disambiguate_ip_address(ip, location=None):
"""turn multi-ip interfaces '0.0.0.0' and '*' into connectable
ones, based on the location (default interpretation of location is localhost)."""
if ip in ('0.0.0.0', '*'):
try:
external_ips = socket.gethostbyname_ex(socket.gethostname())[2]... | IndexError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/parallel/util.py/disambiguate_ip_address |
5,030 | def disambiguate_url(url, location=None):
"""turn multi-ip interfaces '0.0.0.0' and '*' into connectable
ones, based on the location (default interpretation is localhost).
This is for zeromq urls, such as tcp://*:10101."""
try:
proto,ip,port = split_url(url)
except __HOLE__:
# p... | AssertionError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/parallel/util.py/disambiguate_url |
5,031 | def integer_loglevel(loglevel):
try:
loglevel = int(loglevel)
except __HOLE__:
if isinstance(loglevel, str):
loglevel = getattr(logging, loglevel)
return loglevel | ValueError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/parallel/util.py/integer_loglevel |
5,032 | def api_request(self, **kwargs):
from gcloud.exceptions import NotFound
self._requested.append(kwargs)
try:
return self._responses.pop(0)
except __HOLE__:
raise NotFound('miss') | IndexError | dataset/ETHPy150Open GoogleCloudPlatform/gcloud-python/gcloud/monitoring/test_metric.py/_Connection.api_request |
5,033 | def _get_commit_title(self):
# Check if we're inside a git checkout
try:
subp = subprocess.Popen( # nosec
['git', 'rev-parse', '--show-toplevel'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
gitdir = subp.communicate()[0].rstrip()
exce... | OSError | dataset/ETHPy150Open openstack/sahara/sahara/utils/hacking/commit_message.py/GitCheck._get_commit_title |
5,034 | def table_context(request,
table,
links=None,
paginate_by=None,
page=None,
extra_context=None,
context_processors=None,
paginator=None,
show_hits=False,
hit_l... | ValueError | dataset/ETHPy150Open TriOptima/tri.table/lib/tri/table/__init__.py/table_context |
5,035 | def send_message(source_jid, password, target_jid, body, subject = None,
message_type = "chat", message_thread = None, settings = None):
"""Star an XMPP session and send a message, then exit.
:Parameters:
- `source_jid`: sender JID
- `password`: sender password
- `target... | KeyboardInterrupt | dataset/ETHPy150Open kuri65536/python-for-android/python3-alpha/python-libs/pyxmpp2/simple.py/send_message |
5,036 | def parse_hl_lines(expr):
"""Support our syntax for emphasizing certain lines of code.
expr should be like '1 2' to emphasize lines 1 and 2 of a code block.
Returns a list of ints, the line numbers to emphasize.
"""
if not expr:
return []
try:
return list(map(int, expr.split())... | ValueError | dataset/ETHPy150Open dragondjf/QMarkdowner/markdown/extensions/codehilite.py/parse_hl_lines |
5,037 | def hilite(self):
"""
Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with
optional line numbers. The output should then be styled with css to
your liking. No styles are applied by default - only styling hooks
(i.e.: <span class="k">).
returns : A strin... | ValueError | dataset/ETHPy150Open dragondjf/QMarkdowner/markdown/extensions/codehilite.py/CodeHilite.hilite |
5,038 | def _parseHeader(self):
"""
Determines language of a code block from shebang line and whether said
line should be removed or left in place. If the sheband line contains a
path (even a single /) then it is assumed to be a real shebang line and
left alone. However, if no path is gi... | IndexError | dataset/ETHPy150Open dragondjf/QMarkdowner/markdown/extensions/codehilite.py/CodeHilite._parseHeader |
5,039 | def parse_authorization_header(value, charset='utf-8'):
'''Parse an HTTP basic/digest authorisation header.
:param value: the authorisation header to parse.
:return: either `None` if the header was invalid or
not given, otherwise an :class:`Auth` object.
'''
if not value:
return
... | ValueError | dataset/ETHPy150Open quantmind/pulsar/pulsar/apps/wsgi/auth.py/parse_authorization_header |
5,040 | def request(self, is_idempotent=False, **kwargs):
"""
Execute an HTTP request with the current client session.
Use the retry policy configured in the client when is_idempotent is True
"""
kwargs.setdefault('timeout', self.connection_timeout)
def invoke_request():
... | HTTPError | dataset/ETHPy150Open scrapinghub/python-hubstorage/hubstorage/client.py/HubstorageClient.request |
5,041 | def charset__set(self, charset):
if charset is None:
del self.charset
return
try:
header = self.headers.pop('content-type')
except __HOLE__:
raise AttributeError(
"You cannot set the charset when no content-type is defined")
... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/wsgiwrappers.py/WSGIResponse.charset__set |
5,042 | def charset__del(self):
try:
header = self.headers.pop('content-type')
except __HOLE__:
# Don't need to remove anything
return
match = _CHARSET_RE.search(header)
if match:
header = header[:match.start()] + header[match.end():]
self.... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/wsgiwrappers.py/WSGIResponse.charset__del |
5,043 | def content_type__del(self):
try:
del self.headers['content-type']
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/wsgiwrappers.py/WSGIResponse.content_type__del |
5,044 | def init():
"""
Some ORMs, e.g. Django, may require initialization to be performed, but only at some certain
point, e.g. after some variables are set and so on, this function provides an ability to run
this initialization for all supported ORMs automatically but only when needed by the caller
"""
... | ImportError | dataset/ETHPy150Open maxtepkeev/architect/architect/orms/__init__.py/init |
5,045 | def __init__(self, spec, image_size=None):
super(Transform, self).__init__(spec)
self.flag = getattr(Image, self[0].upper())
try:
axis = (None, 0, 1) + TRANSFORM_AXIS[self.flag]
except __HOLE__:
raise ValueError('unknown transform %r' % self[0])
if len(... | KeyError | dataset/ETHPy150Open mikeboers/Flask-Images/flask_images/transform.py/Transform.__init__ |
5,046 | def put_state(self, request_dict):
registration = request_dict['params'].get('registration', None)
if registration:
s, created = ActivityState.objects.get_or_create(state_id=request_dict['params']['stateId'], agent=self.Agent,
activity_id=request_dict['params']['activityId'],... | OSError | dataset/ETHPy150Open adlnet/ADL_LRS/lrs/managers/ActivityStateManager.py/ActivityStateManager.put_state |
5,047 | def status(host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Get memcached status
CLI Example:
.. code-block:: bash
salt '*' memcached.status
'''
conn = _connect(host, port)
try:
stats = _check_stats(conn)[0]
except (CommandExecutionError, __HOLE__):
return False
... | IndexError | dataset/ETHPy150Open saltstack/salt/salt/modules/memcached.py/status |
5,048 | def increment(key, delta=1, host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Increment the value of a key
CLI Example:
.. code-block:: bash
salt '*' memcached.increment <key>
salt '*' memcached.increment <key> 2
'''
conn = _connect(host, port)
_check_stats(conn)
cur = get(ke... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/modules/memcached.py/increment |
5,049 | def decrement(key, delta=1, host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Decrement the value of a key
CLI Example:
.. code-block:: bash
salt '*' memcached.decrement <key>
salt '*' memcached.decrement <key> 2
'''
conn = _connect(host, port)
_check_stats(conn)
cur = get(k... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/modules/memcached.py/decrement |
5,050 | def info_prep(r):
"""
Preprocessor for CAP Info segments
- whether accessed via /eden/info or /eden/alert/x/info
"""
if s3.debug:
s3.scripts.append("/%s/static/scripts/S3/s3.cap.js" % appname)
else:
s3.scripts.append("/%s/static/scripts/S3/s3.cap.min.js" % appname)
s... | AttributeError | dataset/ETHPy150Open sahana/eden/controllers/cap.py/info_prep |
5,051 | def alert():
""" REST controller for CAP Alerts and Components """
tablename = "cap_alert"
def prep(r):
from s3 import S3OptionsFilter
itable = s3db.cap_info
rows = db(itable.expires < request.utcnow).select(itable.id,
order... | ValueError | dataset/ETHPy150Open sahana/eden/controllers/cap.py/alert |
5,052 | def notify_approver():
"""
Send message to the people with role of Alert Approval
"""
if settings.has_module("msg"):
# Notify People with the role of Alert Approval via email and SMS
alert_id = get_vars.get("cap_alert.id")
atable = s3db.cap_alert
if not alert_id and ... | ValueError | dataset/ETHPy150Open sahana/eden/controllers/cap.py/notify_approver |
5,053 | @classmethod
def setupClass(cls):
global numpy
try:
import numpy.linalg
import scipy.sparse
except __HOLE__:
raise SkipTest('SciPy not available.') | ImportError | dataset/ETHPy150Open networkx/networkx/networkx/linalg/tests/test_algebraic_connectivity.py/TestAlgebraicConnectivity.setupClass |
5,054 | @classmethod
def setupClass(cls):
global numpy
try:
import numpy.linalg
import scipy.sparse
except __HOLE__:
raise SkipTest('SciPy not available.') | ImportError | dataset/ETHPy150Open networkx/networkx/networkx/linalg/tests/test_algebraic_connectivity.py/TestSpectralOrdering.setupClass |
5,055 | @defer.inlineCallbacks
def getPath(netstatus, guard_manager, exit_request=None, fast=True,
stable=True, internal=False):
# Raises:
# - NoUsableGuardsException (i.e. we need to find a new guard)
# - PathSelectionFailedException
consensus = yield netstatus.getMicroconsensus()
descripto... | ValueError | dataset/ETHPy150Open nskinkel/oppy/oppy/path/path.py/getPath |
5,056 | def selectGuardNode(cons_rel_stats, descriptors, guards, fast, stable,
exit_desc, exit_status_entry):
try:
guard_candidates = [g for g in guards
if guardFilter(g, cons_rel_stats, descriptors,
fast, stable, exit_desc,
... | IndexError | dataset/ETHPy150Open nskinkel/oppy/oppy/path/path.py/selectGuardNode |
5,057 | def exitFilter(exit_fprint, cons_rel_stats, descriptors, fast, stable,
internal, port):
try:
rel_stat = cons_rel_stats[exit_fprint]
desc = descriptors[rel_stat.digest]
except __HOLE__:
return False
if desc.ntor_onion_key is None:
return False
if Flag.BADEX... | KeyError | dataset/ETHPy150Open nskinkel/oppy/oppy/path/path.py/exitFilter |
5,058 | def guardFilter(guard, cons_rel_stats, descriptors, fast, stable, exit_desc,
exit_status_entry):
try:
rel_stat = cons_rel_stats[guard]
guard_desc = descriptors[rel_stat.digest]
except __HOLE__:
return False
if (fast is True) and (Flag.FAST not in rel_stat.flags):
... | KeyError | dataset/ETHPy150Open nskinkel/oppy/oppy/path/path.py/guardFilter |
5,059 | def middleFilter(node, cons_rel_stats, descriptors, exit_desc,
exit_status_entry, guard_desc, guard_status_entry,
fast=False, stable=False):
try:
rel_stat = cons_rel_stats[node]
node_desc = descriptors[rel_stat.digest]
except __HOLE__:
return False
... | KeyError | dataset/ETHPy150Open nskinkel/oppy/oppy/path/path.py/middleFilter |
5,060 | def coerce( self, value ):
"""Coerce the value to one of our types"""
if self.check( value ):
return value
best = self.bestMatch( value )
if best is not None:
return best.coerce( value )
else:
err = None
for typ in self:
try:
return typ.coerce( value )
except (ValueError,__HOLE__), er... | TypeError | dataset/ETHPy150Open correl/Transmission-XBMC/resources/lib/basictypes/typeunion.py/TypeUnion.coerce |
5,061 | def call_with_stack(self, glob, start, stack):
old_sep = self.next.separator
self.next.separator = self.separator
self.next.call(glob, start)
self.next.separator = old_sep
while stack:
path = stack.pop()
try:
entries = os.listdir(path)
... | OSError | dataset/ETHPy150Open topazproject/topaz/topaz/utils/glob.py/RecursiveDirectories.call_with_stack |
5,062 | def call(self, glob, path):
if path and not os.path.exists(path + "/."):
return
try:
entries = [".", ".."] + os.listdir(path if path else ".")
except __HOLE__:
return
for ent in entries:
if self.ismatch(glob.cache, ent):
g... | OSError | dataset/ETHPy150Open topazproject/topaz/topaz/utils/glob.py/EntryMatch.call |
5,063 | def test(_platform=None):
failed = False
libs = 'cublas cusparse cufft curand nvvm'.split()
for lib in libs:
path = get_cudalib(lib, _platform)
print('Finding', lib)
if path:
print('\tlocated at', path)
else:
print('\tERROR: can\'t locate lib')
... | OSError | dataset/ETHPy150Open numba/numba/numba/cuda/cudadrv/libs.py/test |
5,064 | def _load_module(self, module):
try:
importlib.import_module(module)
except __HOLE__:
raise ImportError("Failed to import hook module '%s'. "
"Verify it exists in PYTHONPATH" % (module)) | ImportError | dataset/ETHPy150Open softlayer/jumpgate/jumpgate/common/hooks/__init__.py/APIHooks.__APIHooks._load_module |
5,065 | def __new__(mcs, cls, bases, attrs):
def make_test(fname):
fpath = osp.join(mcs.dpath, fname)
module = osp.splitext(fname)[0]
def test(self):
try:
load_source(module, fpath)
except __HOLE__:
# Unmet dependency.
raise SkipTest
test.__name__ = '... | ImportError | dataset/ETHPy150Open mtth/hdfs/test/test_examples.py/_ExamplesType.__new__ |
5,066 | @lib.api_call
def rotate(self, rate):
"""
Pass (angular) rate as -100 to +100
(positive is counterclockwise).
"""
# NOTE(Vijay): to be tested
# Validate params
self.logger.debug("Rotating with angular rate: {}".format(rate))
try:
assert Omn... | AssertionError | dataset/ETHPy150Open IEEERobotics/bot/bot/driver/omni_driver.py/OmniDriver.rotate |
5,067 | @lib.api_call
def move(self, speed, angle=0):
"""Move holonomically without rotation.
:param speed: Magnitude of robot's translation speed (% of max).
:type speed: float
:param angle: Angle of translation in degrees (90=left, 270=right).
:type angle: float
"""
... | AssertionError | dataset/ETHPy150Open IEEERobotics/bot/bot/driver/omni_driver.py/OmniDriver.move |
5,068 | def add(self, command):
"""
Adds a command object.
If a command with the same name already exists, it will be overridden.
:param command: A Command object or a dictionary defining the command
:type command: Command or dict
:return: The registered command
:rtype... | AttributeError | dataset/ETHPy150Open sdispater/cleo/cleo/application.py/Application.add |
5,069 | def configure_io(self, input_, output_):
"""
Configures the input and output instances based on the user arguments and options.
:param input_: An Input instance
:type input_: Input
:param output_: An Output instance
:type output_: Output
"""
if input_.has... | TypeError | dataset/ETHPy150Open sdispater/cleo/cleo/application.py/Application.configure_io |
5,070 | def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azu... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/cloud/clouds/msazure.py/create |
5,071 | def HandleCommand(self, chan, user, cmd, args=None):
client = self.client._protocol.clientFromUsername(user)
cmd = cmd.lower()
if chan in self._root.channels:
channel = self._root.channels[chan]
access = channel.getAccess(client)
if cmd == 'info':
founder = self.client._protocol.clientFromID(chann... | ValueError | dataset/ETHPy150Open lunixbochs/uberserver/ChanServ.py/ChanServ.HandleCommand |
5,072 | def _instantiate(self, cmd):
"""
checks so that object is an instantiated command and not, say
a cmdclass. If it is, instantiate it. Other types, like
strings, are passed through.
Args:
cmd (any): Entity to analyze.
Returns:
result (any): An ins... | TypeError | dataset/ETHPy150Open evennia/evennia/evennia/commands/cmdset.py/CmdSet._instantiate |
5,073 | def add(self, cmd):
"""
Add a new command or commands to this CmdSetcommand, a list of
commands or a cmdset to this cmdset. Note that this is *not*
a merge operation (that is handled by the + operator).
Args:
cmd (Command, list, Cmdset): This allows for adding one or... | RuntimeError | dataset/ETHPy150Open evennia/evennia/evennia/commands/cmdset.py/CmdSet.add |
5,074 | def remove(self, cmd):
"""
Remove a command instance from the cmdset.
Args:
cmd (Command or str): Either the Command object to remove
or the key of such a command.
"""
cmd = self._instantiate(cmd)
if cmd.key.startswith("__"):
try:... | ValueError | dataset/ETHPy150Open evennia/evennia/evennia/commands/cmdset.py/CmdSet.remove |
5,075 | def TestFindFileInDirectoryOrAncestors():
""" Test FindFileInDirectoryOrAncestors"""
# Create an empty temp directory
root_dir = tempfile.mkdtemp()
a_dir = os.path.join(root_dir, "a")
b_dir = os.path.join(a_dir, "b")
# Create subdirectories
os.mkdir(a_dir)
os.mkdir(b_dir)
# Create temporary file
f... | IOError | dataset/ETHPy150Open spranesh/Redhawk/redhawk/test/test_utils_util.py/TestFindFileInDirectoryOrAncestors |
5,076 | def onClickOpen(self, sender):
global has_getAsText
data = None
filename = None
if self.files:
if self.files.length == 0:
return
if self.files.length > 1:
alert("Cannot open more than one file")
return
fi... | AttributeError | dataset/ETHPy150Open pyjs/pyjs/examples/timesheet/libtimesheet/view/components/FileOpenDlg.py/FileOpenDlg.onClickOpen |
5,077 | def test_expect_setecho_off(self):
'''This tests that echo may be toggled off.
'''
p = pexpect.spawn('cat', echo=True, timeout=5)
try:
self._expect_echo_toggle(p)
except __HOLE__:
if sys.platform.lower().startswith('sunos'):
if hasattr(unit... | IOError | dataset/ETHPy150Open Calysto/metakernel/metakernel/tests/test_expect.py/ExpectTestCase.test_expect_setecho_off |
5,078 | def test_expect_setecho_off_exact(self):
p = pexpect.spawn('cat', echo=True, timeout=5)
p.expect = p.expect_exact
try:
self._expect_echo_toggle(p)
except __HOLE__:
if sys.platform.lower().startswith('sunos'):
if hasattr(unittest, 'SkipTest'):
... | IOError | dataset/ETHPy150Open Calysto/metakernel/metakernel/tests/test_expect.py/ExpectTestCase.test_expect_setecho_off_exact |
5,079 | def test_waitnoecho(self):
" Tests setecho(False) followed by waitnoecho() "
p = pexpect.spawn('cat', echo=False, timeout=5)
try:
p.setecho(False)
p.waitnoecho()
except __HOLE__:
if sys.platform.lower().startswith('sunos'):
if hasattr(u... | IOError | dataset/ETHPy150Open Calysto/metakernel/metakernel/tests/test_expect.py/ExpectTestCase.test_waitnoecho |
5,080 | def test_waitnoecho_order(self):
''' This tests that we can wait on a child process to set echo mode.
For example, this tests that we could wait for SSH to set ECHO False
when asking of a password. This makes use of an external script
_echo_wait.py. '''
p1 = pexpect.spawn('%s _... | IOError | dataset/ETHPy150Open Calysto/metakernel/metakernel/tests/test_expect.py/ExpectTestCase.test_waitnoecho_order |
5,081 | def takeSomeFromQueue(self):
"""Use self.queue, which is a collections.deque, to pop up to
settings.MAX_DATAPOINTS_PER_MESSAGE items from the left of the
queue.
"""
def yield_max_datapoints():
for count in range(settings.MAX_DATAPOINTS_PER_MESSAGE):
try:
yield self.queue.popl... | IndexError | dataset/ETHPy150Open graphite-project/carbon/lib/carbon/client.py/CarbonClientFactory.takeSomeFromQueue |
5,082 | def process_request(self, request_items):
# set all required simpleapi arguments
access_key = request_items.pop('_access_key', None)
method = request_items.pop('_call', None)
if self.restful:
method = self.sapi_request.method.lower()
data = request_items.pop('_data'... | ValueError | dataset/ETHPy150Open flosch/simpleapi/simpleapi/server/request.py/Request.process_request |
5,083 | def suggestFile(filename, folder='.', threshold=2, includeIdenticalFilename=False):
'''Returns the closest matching filename to the filenames in the folder. If
there are multiple files with the same edit distance, the one returned is
undefined. Returns None if there are no suggestions within the threshold.
Arg... | StopIteration | dataset/ETHPy150Open asweigart/pydidyoumean/pydidyoumean/__init__.py/suggestFile |
5,084 | def suggest(name, possibleSuggestions=None, threshold=2, includeIdenticalName=False):
'''Returns the closest matching name to the suggestions in
possibleSuggestions. Pass a list of all possible matches for the
possibleSuggestions parameter. If there are multiple names with the same edit
distance, the one return... | StopIteration | dataset/ETHPy150Open asweigart/pydidyoumean/pydidyoumean/__init__.py/suggest |
5,085 | def intersection(*entities):
"""The intersection of a collection of GeometryEntity instances.
Parameters
==========
entities : sequence of GeometryEntity
Returns
=======
intersection : list of GeometryEntity
Raises
======
NotImplementedError
When unable to calculate... | NotImplementedError | dataset/ETHPy150Open sympy/sympy/sympy/geometry/util.py/intersection |
5,086 | def convex_hull(*args, **kwargs):
"""The convex hull surrounding the Points contained in the list of entities.
Parameters
==========
args : a collection of Points, Segments and/or Polygons
Returns
=======
convex_hull : Polygon if ``polygon`` is True else as a tuple `(U, L)` where ``L`` a... | NotImplementedError | dataset/ETHPy150Open sympy/sympy/sympy/geometry/util.py/convex_hull |
5,087 | def closest_points(*args):
"""Return the subset of points from a set of points that were
the closest to each other in the 2D plane.
Parameters
==========
args : a collection of Points on 2D plane.
Notes
=====
This can only be performed on a set of points whose coordinates can
be ... | TypeError | dataset/ETHPy150Open sympy/sympy/sympy/geometry/util.py/closest_points |
5,088 | def are_similar(e1, e2):
"""Are two geometrical entities similar.
Can one geometrical entity be uniformly scaled to the other?
Parameters
==========
e1 : GeometryEntity
e2 : GeometryEntity
Returns
=======
are_similar : boolean
Raises
======
GeometryError
Wh... | AttributeError | dataset/ETHPy150Open sympy/sympy/sympy/geometry/util.py/are_similar |
5,089 | def main():
flock = FlockManager(
match_found,
config["BLEET_TIMEOUT"],
config["SERVICE_TIMEOUT"]
)
logger.info("Shepherd starting.")
while True:
# Wait until either the public or sheep socket has messages waiting
zmq.select([public, sheep], [], [], timeout = 5)... | ValueError | dataset/ETHPy150Open ucrcsedept/galah/galah/shepherd/shepherd.py/main |
5,090 | @cache_page(LONG_CACHE_TIME)
def committee_search_html(request):
params = request.GET
committees = None
try:
committee_name_fragment = params['name']
if len(committee_name_fragment) > 3:
print committee_name_fragment
committees = Committee_Overlay.objects.filter(... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/public_views/datapages/views.py/committee_search_html |
5,091 | def weekly_comparison(request, race_list, blog_or_feature):
print "weekly comparison"
if not (blog_or_feature in ['feature', 'blog', 'narrow']):
raise Http404
race_ids = race_list.split('-')
if len(race_ids) == 0 or len(race_ids) > 6:
raise Http404
race_id_text = ",".join(race_ids)
... | IndexError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/public_views/datapages/views.py/weekly_comparison |
5,092 | def weekly_comparison_cumulative(request, race_list, blog_or_feature):
print "weekly comparison"
if not (blog_or_feature in ['feature', 'blog', 'narrow']):
raise Http404
race_ids = race_list.split('-')
if len(race_ids) == 0 or len(race_ids) > 6:
raise Http404
race_id_text = ",".join... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/public_views/datapages/views.py/weekly_comparison_cumulative |
5,093 | def contrib_comparison(request, race_list, blog_or_feature):
print "weekly comparison"
if not (blog_or_feature in ['feature', 'blog', 'narrow']):
raise Http404
race_ids = race_list.split('-')
if len(race_ids) == 0 or len(race_ids) > 6:
raise Http404
race_id_text = ",".join(race_ids)... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/public_views/datapages/views.py/contrib_comparison |
5,094 | def contrib_comparison_cumulative(request, race_list, blog_or_feature):
print "weekly comparison"
if not (blog_or_feature in ['feature', 'blog', 'narrow']):
raise Http404
race_ids = race_list.split('-')
if len(race_ids) == 0 or len(race_ids) > 6:
raise Http404
race_id_text = ",".joi... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/public_views/datapages/views.py/contrib_comparison_cumulative |
5,095 | def run(self, meth, args=(), kwargs={}, argiterator=None):
res = FunctionTimerResult(_form_name(meth, args, kwargs))
if argiterator:
iterator = itertools.cycle(argiterator)
else:
iterator = itertools.repeat(args)
start = now()
try:
_next = iter... | AttributeError | dataset/ETHPy150Open kdart/pycopia/core/pycopia/benchmarks.py/FunctionTimer.run |
5,096 | @public
def field_isomorphism(a, b, **args):
"""Construct an isomorphism between two number fields. """
a, b = sympify(a), sympify(b)
if not a.is_AlgebraicNumber:
a = AlgebraicNumber(a)
if not b.is_AlgebraicNumber:
b = AlgebraicNumber(b)
if a == b:
return a.coeffs()
n... | NotImplementedError | dataset/ETHPy150Open sympy/sympy/sympy/polys/numberfields.py/field_isomorphism |
5,097 | def loadAllMayaPlugins():
'''will load all maya-installed plugins
WARNING: tthe act of loading all the plugins may crash maya, especially if
done from a non-GUI session
'''
import logging
logger = logging.getLogger('pymel')
logger.debug("loading all maya plugins...")
for plugin in mayaP... | RuntimeError | dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/maya/site-packages/pymel-1.0.5/pymel/api/plugins.py/loadAllMayaPlugins |
5,098 | def pluginCommands(pluginName, reportedOnly=False):
'''Returns the list of all commands that the plugin provides, to the best
of our knowledge.
Note that depending on your version of maya, this may not actually be the
list of all commands provided.
'''
import logging
logger = logging.getLog... | TypeError | dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/maya/site-packages/pymel-1.0.5/pymel/api/plugins.py/pluginCommands |
5,099 | def __call__(self, method):
def wrapped_method(*args, **kwargs):
try:
for data in self.neede_data:
data_value = args[1][data]
if self.options.get('force_int', False):
try:
args[1][data] = int... | IndexError | dataset/ETHPy150Open ierror/BeautifulMind.io/beautifulmind/mindmaptornado/decorators.py/check_for_data.__call__ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.