Unnamed: 0
int64 0
10k
| function
stringlengths 79
138k
| label
stringclasses 20
values | info
stringlengths 42
261
|
---|---|---|---|
6,000 | def add_layer(self, layer=None, is_output=False, **kwargs):
'''Add a :ref:`layer <layers>` to our network graph.
Parameters
----------
layer : int, tuple, dict, or :class:`Layer <theanets.layers.base.Layer>`
A value specifying the layer to add. For more information, please
see :ref:`guide-creating-specifying-layers`.
is_output : bool, optional
True iff this is the output layer for the graph. This influences the
default activation function used for the layer: output layers in
most models have a linear activation, while output layers in
classifier networks default to a softmax activation.
'''
# if the given layer is a Layer instance, just add it and move on.
if isinstance(layer, layers.Layer):
self.layers.append(layer)
return
form = kwargs.pop('form', 'ff' if self.layers else 'input').lower()
# if layer is a tuple, assume that it contains one or more of the following:
# - a layers.Layer subclass to construct (type)
# - the name of a layers.Layer class (str)
# - the name of an activation function (str)
# - the number of units in the layer (int)
if isinstance(layer, (tuple, list)):
for el in layer:
try:
if issubclass(el, layers.Layer):
form = el.__name__
except __HOLE__:
pass
if isinstance(el, util.basestring):
if layers.Layer.is_registered(el):
form = el
else:
kwargs['activation'] = el
if isinstance(el, int):
kwargs['size'] = el
# if layer is a dictionary, try to extract a form for the layer, and
# override our default keyword arguments with the rest.
if isinstance(layer, dict):
for key, value in layer.items():
if key == 'form':
form = value.lower()
else:
kwargs[key] = value
name = 'hid{}'.format(len(self.layers))
if is_output:
name = 'out'
if form == 'input':
name = 'in'
kwargs.setdefault('name', name)
kwargs.setdefault('size', layer)
if form == 'input':
kwargs.setdefault('ndim', self.INPUT_NDIM)
else:
act = self.DEFAULT_OUTPUT_ACTIVATION if is_output else 'relu'
kwargs.setdefault('inputs', self.layers[-1].output_name)
kwargs.setdefault('rng', self._rng)
kwargs.setdefault('activation', act)
if form.lower() == 'tied' and 'partner' not in kwargs:
# we look backward through our list of layers for a partner.
# any "tied" layer that we find increases a counter by one,
# and any "untied" layer decreases the counter by one. our
# partner is the first layer we find with count zero.
#
# this is intended to handle the hopefully common case of a
# (possibly deep) tied-weights autoencoder.
tied = 1
partner = None
for l in self.layers[::-1]:
tied += 1 if isinstance(l, layers.Tied) else -1
if tied == 0:
partner = l.name
break
else:
raise util.ConfigurationError(
'cannot find partner for "{}"'.format(kwargs))
kwargs['partner'] = partner
layer = layers.Layer.build(form, **kwargs)
if isinstance(layer, layers.Input):
names = set(i.name for i in self.inputs)
assert layer.name not in names, \
'"{}": duplicate input name!'.format(layer.name)
self.layers.append(layer) | TypeError | dataset/ETHPy150Open lmjohns3/theanets/theanets/graph.py/Network.add_layer |
6,001 | def __new__(cls, name, bases, attrs):
attrs['base_fields'] = {}
declared_fields = {}
# Inherit any fields from parent(s).
try:
parents = [b for b in bases if issubclass(b, Resource)]
# Simulate the MRO.
parents.reverse()
for p in parents:
parent_fields = getattr(p, 'base_fields', {})
for field_name, field_object in parent_fields.items():
attrs['base_fields'][field_name] = deepcopy(field_object)
except __HOLE__:
pass
for field_name, obj in attrs.items():
# Look for ``dehydrated_type`` instead of doing ``isinstance``,
# which can break down if Tastypie is re-namespaced as something
# else.
if hasattr(obj, 'dehydrated_type'):
field = attrs.pop(field_name)
declared_fields[field_name] = field
attrs['base_fields'].update(declared_fields)
attrs['declared_fields'] = declared_fields
new_class = super(DeclarativeMetaclass, cls).__new__(cls, name, bases, attrs)
opts = getattr(new_class, 'Meta', None)
new_class._meta = ResourceOptions(opts)
if not getattr(new_class._meta, 'resource_name', None):
# No ``resource_name`` provided. Attempt to auto-name the resource.
class_name = new_class.__name__
name_bits = [bit for bit in class_name.split('Resource') if bit]
resource_name = ''.join(name_bits).lower()
new_class._meta.resource_name = resource_name
if getattr(new_class._meta, 'include_resource_uri', True):
if not 'resource_uri' in new_class.base_fields:
new_class.base_fields['resource_uri'] = fields.CharField(readonly=True)
elif 'resource_uri' in new_class.base_fields and not 'resource_uri' in attrs:
del(new_class.base_fields['resource_uri'])
for field_name, field_object in new_class.base_fields.items():
if hasattr(field_object, 'contribute_to_class'):
field_object.contribute_to_class(new_class, field_name)
return new_class | NameError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/DeclarativeMetaclass.__new__ |
6,002 | def wrap_view(self, view):
"""
Wraps methods so they can be called in a more functional way as well
as handling exceptions better.
Note that if ``BadRequest`` or an exception with a ``response`` attr
are seen, there is special handling to either present a message back
to the user or return the response traveling with the exception.
"""
@csrf_exempt
def wrapper(request, *args, **kwargs):
try:
callback = getattr(self, view)
response = callback(request, *args, **kwargs)
if request.is_ajax() and not response.has_header("Cache-Control"):
# IE excessively caches XMLHttpRequests, so we're disabling
# the browser cache here.
# See http://www.enhanceie.com/ie/bugs.asp for details.
patch_cache_control(response, no_cache=True)
return response
except (BadRequest, fields.ApiFieldError), e:
return http.HttpBadRequest(e.args[0])
except __HOLE__, e:
return http.HttpBadRequest(', '.join(e.messages))
except Exception, e:
if hasattr(e, 'response'):
return e.response
# A real, non-expected exception.
# Handle the case where the full traceback is more helpful
# than the serialized error.
if settings.DEBUG and getattr(settings, 'TASTYPIE_FULL_DEBUG', False):
raise
# Re-raise the error to get a proper traceback when the error
# happend during a test case
if request.META.get('SERVER_NAME') == 'testserver':
raise
# Rather than re-raising, we're going to things similar to
# what Django does. The difference is returning a serialized
# error message.
return self._handle_500(request, e)
return wrapper | ValidationError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.wrap_view |
6,003 | def remove_api_resource_names(self, url_dict):
"""
Given a dictionary of regex matches from a URLconf, removes
``api_name`` and/or ``resource_name`` if found.
This is useful for converting URLconf matches into something suitable
for data lookup. For example::
Model.objects.filter(**self.remove_api_resource_names(matches))
"""
kwargs_subset = url_dict.copy()
for key in ['api_name', 'resource_name']:
try:
del(kwargs_subset[key])
except __HOLE__:
pass
return kwargs_subset | KeyError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.remove_api_resource_names |
6,004 | def dehydrate_resource_uri(self, bundle):
"""
For the automatically included ``resource_uri`` field, dehydrate
the URI for the given bundle.
Returns empty string if no URI can be generated.
"""
try:
return self.get_resource_uri(bundle)
except __HOLE__:
return ''
except NoReverseMatch:
return '' | NotImplementedError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.dehydrate_resource_uri |
6,005 | def get_detail(self, request, **kwargs):
"""
Returns a single serialized resource.
Calls ``cached_obj_get/obj_get`` to provide the data, then handles that result
set and serializes it.
Should return a HttpResponse (200 OK).
"""
try:
obj = self.cached_obj_get(request=request, **self.remove_api_resource_names(kwargs))
except __HOLE__:
return http.HttpNotFound()
except MultipleObjectsReturned:
return http.HttpMultipleChoices("More than one resource is found at this URI.")
bundle = self.build_bundle(obj=obj, request=request)
bundle = self.full_dehydrate(bundle)
bundle = self.alter_detail_data_to_serialize(request, bundle)
return self.create_response(request, bundle) | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.get_detail |
6,006 | def patch_list(self, request, **kwargs):
"""
Updates a collection in-place.
The exact behavior of ``PATCH`` to a list resource is still the matter of
some debate in REST circles, and the ``PATCH`` RFC isn't standard. So the
behavior this method implements (described below) is something of a
stab in the dark. It's mostly cribbed from GData, with a smattering
of ActiveResource-isms and maybe even an original idea or two.
The ``PATCH`` format is one that's similar to the response returned from
a ``GET`` on a list resource::
{
"objects": [{object}, {object}, ...],
"deleted_objects": ["URI", "URI", "URI", ...],
}
For each object in ``objects``:
* If the dict does not have a ``resource_uri`` key then the item is
considered "new" and is handled like a ``POST`` to the resource list.
* If the dict has a ``resource_uri`` key and the ``resource_uri`` refers
to an existing resource then the item is a update; it's treated
like a ``PATCH`` to the corresponding resource detail.
* If the dict has a ``resource_uri`` but the resource *doesn't* exist,
then this is considered to be a create-via-``PUT``.
Each entry in ``deleted_objects`` referes to a resource URI of an existing
resource to be deleted; each is handled like a ``DELETE`` to the relevent
resource.
In any case:
* If there's a resource URI it *must* refer to a resource of this
type. It's an error to include a URI of a different resource.
* ``PATCH`` is all or nothing. If a single sub-operation fails, the
entire request will fail and all resources will be rolled back.
* For ``PATCH`` to work, you **must** have ``put`` in your
:ref:`detail-allowed-methods` setting.
* To delete objects via ``deleted_objects`` in a ``PATCH`` request you
**must** have ``delete`` in your :ref:`detail-allowed-methods`
setting.
"""
request = convert_post_to_patch(request)
deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
if "objects" not in deserialized:
raise BadRequest("Invalid data sent.")
if len(deserialized["objects"]) and 'put' not in self._meta.detail_allowed_methods:
raise ImmediateHttpResponse(response=http.HttpMethodNotAllowed())
for data in deserialized["objects"]:
# If there's a resource_uri then this is either an
# update-in-place or a create-via-PUT.
if "resource_uri" in data:
uri = data.pop('resource_uri')
try:
obj = self.get_via_uri(uri, request=request)
# The object does exist, so this is an update-in-place.
bundle = self.build_bundle(obj=obj, request=request)
bundle = self.full_dehydrate(bundle)
bundle = self.alter_detail_data_to_serialize(request, bundle)
self.update_in_place(request, bundle, data)
except (__HOLE__, MultipleObjectsReturned):
# The object referenced by resource_uri doesn't exist,
# so this is a create-by-PUT equivalent.
data = self.alter_deserialized_detail_data(request, data)
bundle = self.build_bundle(data=dict_strip_unicode_keys(data), request=request)
self.obj_create(bundle, request=request)
else:
# There's no resource URI, so this is a create call just
# like a POST to the list resource.
data = self.alter_deserialized_detail_data(request, data)
bundle = self.build_bundle(data=dict_strip_unicode_keys(data), request=request)
self.obj_create(bundle, request=request)
if len(deserialized.get('deleted_objects', [])) and 'delete' not in self._meta.detail_allowed_methods:
raise ImmediateHttpResponse(response=http.HttpMethodNotAllowed())
for uri in deserialized.get('deleted_objects', []):
obj = self.get_via_uri(uri, request=request)
self.obj_delete(request=request, _obj=obj)
return http.HttpAccepted() | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.patch_list |
6,007 | def patch_detail(self, request, **kwargs):
"""
Updates a resource in-place.
Calls ``obj_update``.
If the resource is updated, return ``HttpAccepted`` (202 Accepted).
If the resource did not exist, return ``HttpNotFound`` (404 Not Found).
"""
request = convert_post_to_patch(request)
# We want to be able to validate the update, but we can't just pass
# the partial data into the validator since all data needs to be
# present. Instead, we basically simulate a PUT by pulling out the
# original data and updating it in-place.
# So first pull out the original object. This is essentially
# ``get_detail``.
try:
obj = self.cached_obj_get(request=request, **self.remove_api_resource_names(kwargs))
except __HOLE__:
return http.HttpNotFound()
except MultipleObjectsReturned:
return http.HttpMultipleChoices("More than one resource is found at this URI.")
bundle = self.build_bundle(obj=obj, request=request)
bundle = self.full_dehydrate(bundle)
bundle = self.alter_detail_data_to_serialize(request, bundle)
# Now update the bundle in-place.
deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
self.update_in_place(request, bundle, deserialized)
if not self._meta.always_return_data:
return http.HttpAccepted()
else:
bundle = self.full_dehydrate(bundle)
bundle = self.alter_detail_data_to_serialize(request, bundle)
return self.create_response(request, bundle, response_class=http.HttpAccepted) | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.patch_detail |
6,008 | def get_multiple(self, request, **kwargs):
"""
Returns a serialized list of resources based on the identifiers
from the URL.
Calls ``obj_get`` to fetch only the objects requested. This method
only responds to HTTP GET.
Should return a HttpResponse (200 OK).
"""
self.method_check(request, allowed=['get'])
self.is_authenticated(request)
self.throttle_check(request)
# Rip apart the list then iterate.
kwarg_name = '%s_list' % self._meta.detail_uri_name
obj_identifiers = kwargs.get(kwarg_name, '').split(';')
objects = []
not_found = []
for identifier in obj_identifiers:
try:
obj = self.obj_get(request, **{self._meta.detail_uri_name: identifier})
bundle = self.build_bundle(obj=obj, request=request)
bundle = self.full_dehydrate(bundle)
objects.append(bundle)
except __HOLE__:
not_found.append(identifier)
object_list = {
'objects': objects,
}
if len(not_found):
object_list['not_found'] = not_found
self.log_throttled_access(request)
return self.create_response(request, object_list) | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/Resource.get_multiple |
6,009 | def obj_get_list(self, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_get_list``.
Takes an optional ``request`` object, whose ``GET`` dictionary can be
used to narrow the query.
"""
filters = {}
if hasattr(request, 'GET'):
# Grab a mutable copy.
filters = request.GET.copy()
# Update with the provided kwargs.
filters.update(kwargs)
applicable_filters = self.build_filters(filters=filters)
try:
base_object_list = self.apply_filters(request, applicable_filters)
return self.apply_authorization_limits(request, base_object_list)
except __HOLE__:
raise BadRequest("Invalid resource lookup data provided (mismatched type).") | ValueError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/ModelResource.obj_get_list |
6,010 | def obj_get(self, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_get``.
Takes optional ``kwargs``, which are used to narrow the query to find
the instance.
"""
try:
base_object_list = self.get_object_list(request).filter(**kwargs)
object_list = self.apply_authorization_limits(request, base_object_list)
stringified_kwargs = ', '.join(["%s=%s" % (k, v) for k, v in kwargs.items()])
if len(object_list) <= 0:
raise self._meta.object_class.DoesNotExist("Couldn't find an instance of '%s' which matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs))
elif len(object_list) > 1:
raise MultipleObjectsReturned("More than '%s' matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs))
return object_list[0]
except __HOLE__:
raise NotFound("Invalid resource lookup data provided (mismatched type).") | ValueError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/ModelResource.obj_get |
6,011 | def obj_update(self, bundle, request=None, skip_errors=False, **kwargs):
"""
A ORM-specific implementation of ``obj_update``.
"""
if not bundle.obj or not self.get_bundle_detail_data(bundle):
# Attempt to hydrate data from kwargs before doing a lookup for the object.
# This step is needed so certain values (like datetime) will pass model validation.
try:
bundle.obj = self.get_object_list(bundle.request).model()
bundle.data.update(kwargs)
bundle = self.full_hydrate(bundle)
lookup_kwargs = kwargs.copy()
for key in kwargs.keys():
if key == self._meta.detail_uri_name:
continue
elif getattr(bundle.obj, key, NOT_AVAILABLE) is not NOT_AVAILABLE:
lookup_kwargs[key] = getattr(bundle.obj, key)
else:
del lookup_kwargs[key]
except:
# if there is trouble hydrating the data, fall back to just
# using kwargs by itself (usually it only contains a "pk" key
# and this will work fine.
lookup_kwargs = kwargs
try:
bundle.obj = self.obj_get(bundle.request, **lookup_kwargs)
except __HOLE__:
raise NotFound("A model instance matching the provided arguments could not be found.")
bundle = self.full_hydrate(bundle)
self.is_valid(bundle,request)
if bundle.errors and not skip_errors:
self.error_response(bundle.errors, request)
# Save FKs just in case.
self.save_related(bundle)
# Save the main object.
bundle.obj.save()
# Now pick up the M2M bits.
m2m_bundle = self.hydrate_m2m(bundle)
self.save_m2m(m2m_bundle)
return bundle | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/ModelResource.obj_update |
6,012 | def obj_delete(self, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_delete``.
Takes optional ``kwargs``, which are used to narrow the query to find
the instance.
"""
obj = kwargs.pop('_obj', None)
if not hasattr(obj, 'delete'):
try:
obj = self.obj_get(request, **kwargs)
except __HOLE__:
raise NotFound("A model instance matching the provided arguments could not be found.")
obj.delete() | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/ModelResource.obj_delete |
6,013 | def save_related(self, bundle):
"""
Handles the saving of related non-M2M data.
Calling assigning ``child.parent = parent`` & then calling
``Child.save`` isn't good enough to make sure the ``parent``
is saved.
To get around this, we go through all our related fields &
call ``save`` on them if they have related, non-M2M data.
M2M data is handled by the ``ModelResource.save_m2m`` method.
"""
for field_name, field_object in self.fields.items():
if not getattr(field_object, 'is_related', False):
continue
if getattr(field_object, 'is_m2m', False):
continue
if not field_object.attribute:
continue
if field_object.blank and not bundle.data.has_key(field_name):
continue
# Get the object.
try:
related_obj = getattr(bundle.obj, field_object.attribute)
except __HOLE__:
related_obj = None
# Because sometimes it's ``None`` & that's OK.
if related_obj:
if field_object.related_name:
if not self.get_bundle_detail_data(bundle):
bundle.obj.save()
setattr(related_obj, field_object.related_name, bundle.obj)
related_obj.save()
setattr(bundle.obj, field_object.attribute, related_obj) | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/ModelResource.save_related |
6,014 | def convert_post_to_VERB(request, verb):
"""
Force Django to process the VERB.
"""
if request.method == verb:
if hasattr(request, '_post'):
del(request._post)
del(request._files)
try:
request.method = "POST"
request._load_post_and_files()
request.method = verb
except __HOLE__:
request.META['REQUEST_METHOD'] = 'POST'
request._load_post_and_files()
request.META['REQUEST_METHOD'] = verb
setattr(request, verb, request.POST)
return request | AttributeError | dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastypie/tastypie/resources.py/convert_post_to_VERB |
6,015 | def run(self, fake=False, *args, **kwargs):
"""
Execute import.
"""
from panda.models import DataUpload, RelatedUpload
log = logging.getLogger(self.name)
log.info('Purging orphaned uploads')
local_files = os.listdir(settings.MEDIA_ROOT)
data_uploads = DataUpload.objects.all()
related_uploads = RelatedUpload.objects.all()
for upload in chain(data_uploads, related_uploads):
# This file is accounted for
try:
local_files.remove(upload.filename)
except __HOLE__:
pass
if not upload.dataset:
if fake:
log.info('Would delete upload: %s\n' % upload)
else:
log.info('Deleted upload: %s\n' % upload)
upload.delete()
for f in local_files:
path = os.path.join(settings.MEDIA_ROOT, f)
if fake:
log.info('Would delete file: %s\n' % path)
else:
log.info('Deleted file: %s\n' % path)
os.remove(path)
log.info('Purge complete') | ValueError | dataset/ETHPy150Open pandaproject/panda/panda/tasks/purge_orphaned_uploads.py/PurgeOrphanedUploadsTask.run |
6,016 | @classmethod
def get_build_step_for_job(cls, job_id):
jobplan = cls.query.filter(
cls.job_id == job_id,
).first()
if jobplan is None:
return None, None
steps = jobplan.get_steps()
try:
step = steps[0]
except __HOLE__:
return jobplan, None
return jobplan, step.get_implementation() | IndexError | dataset/ETHPy150Open dropbox/changes/changes/models/jobplan.py/JobPlan.get_build_step_for_job |
6,017 | def remove_chartjunk(ax, spines, grid=None, ticklabels=None, show_ticks=False,
xkcd=False):
'''
Removes "chartjunk", such as extra lines of axes and tick marks.
If grid="y" or "x", will add a white grid at the "y" or "x" axes,
respectively
If ticklabels="y" or "x", or ['x', 'y'] will remove ticklabels from that
axis
'''
all_spines = ['top', 'bottom', 'right', 'left', 'polar']
for spine in spines:
# The try/except is for polar coordinates, which only have a 'polar'
# spine and none of the others
try:
ax.spines[spine].set_visible(False)
except KeyError:
pass
# For the remaining spines, make their line thinner and a slightly
# off-black dark grey
if not xkcd:
for spine in set(all_spines).difference(set(spines)):
# The try/except is for polar coordinates, which only have a
# 'polar' spine and none of the others
try:
ax.spines[spine].set_linewidth(0.5)
except __HOLE__:
pass
# ax.spines[spine].set_color(almost_black)
# ax.spines[spine].set_tick_params(color=almost_black)
# Check that the axes are not log-scale. If they are, leave
# the ticks because otherwise people assume a linear scale.
x_pos = set(['top', 'bottom'])
y_pos = set(['left', 'right'])
xy_pos = [x_pos, y_pos]
xy_ax_names = ['xaxis', 'yaxis']
for ax_name, pos in zip(xy_ax_names, xy_pos):
axis = ax.__dict__[ax_name]
# axis.set_tick_params(color=almost_black)
#print 'axis.get_scale()', axis.get_scale()
if show_ticks or axis.get_scale() == 'log':
# if this spine is not in the list of spines to remove
for p in pos.difference(spines):
#print 'p', p
axis.set_tick_params(direction='out')
axis.set_ticks_position(p)
# axis.set_tick_params(which='both', p)
else:
axis.set_ticks_position('none')
if grid is not None:
for g in grid:
assert g in ('x', 'y')
ax.grid(axis=grid, color='white', linestyle='-', linewidth=0.5)
if ticklabels is not None:
if type(ticklabels) is str:
assert ticklabels in set(('x', 'y'))
if ticklabels == 'x':
ax.set_xticklabels([])
if ticklabels == 'y':
ax.set_yticklabels([])
else:
assert set(ticklabels) | set(('x', 'y')) > 0
if 'x' in ticklabels:
ax.set_xticklabels([])
elif 'y' in ticklabels:
ax.set_yticklabels([]) | KeyError | dataset/ETHPy150Open olgabot/prettyplotlib/prettyplotlib/utils.py/remove_chartjunk |
6,018 | def maybe_get_linewidth(**kwargs):
try:
key = (set(["lw", "linewidth", 'linewidths']) & set(kwargs)).pop()
lw = kwargs[key]
except __HOLE__:
lw = 0.15
return lw | KeyError | dataset/ETHPy150Open olgabot/prettyplotlib/prettyplotlib/utils.py/maybe_get_linewidth |
6,019 | def has(data, sub_data):
# Recursive approach to look for a subset of data in data.
# WARNING: Don't use on huge structures
# :param data: Data structure
# :param sub_data: subset being checked for
# :return: True or False
try:
(item for item in data if item == sub_data).next()
return True
except __HOLE__:
lists_and_dicts = list_or_dict(data)
for item in lists_and_dicts:
if has(item, sub_data):
return True
return False | StopIteration | dataset/ETHPy150Open CenterForOpenScience/osf.io/tests/test_notifications.py/has |
6,020 | def open_sysfs_numa_stats():
"""Returns a possibly empty list of opened files."""
try:
nodes = os.listdir(NUMADIR)
except __HOLE__, (errno, msg):
if errno == 2: # No such file or directory
return [] # We don't have NUMA stats.
raise
nodes = [node for node in nodes if node.startswith("node")]
numastats = []
for node in nodes:
try:
numastats.append(open(os.path.join(NUMADIR, node, "numastat")))
except OSError, (errno, msg):
if errno == 2: # No such file or directory
continue
raise
return numastats | OSError | dataset/ETHPy150Open scalyr/scalyr-agent-2/scalyr_agent/third_party/tcollector/collectors/0/procstats.py/open_sysfs_numa_stats |
6,021 | @register_test(tier=2)
def test_packed_packages(err, package=None):
if not package:
return
processed_files = 0
garbage_files = 0
# Iterate each item in the package.
for name in package:
file_info = package.info(name)
file_name = file_info["name_lower"]
file_size = file_info["size"]
if "__MACOSX" in name or file_name[0] in (".", "_", ):
err.warning(
err_id=("testcases_content", "test_packed_packages",
"hidden_files"),
warning="Unused files or directories flagged.",
description="Hidden files and folders can make the review process "
"difficult and may contain sensitive information "
"about the system that generated the zip. Please "
"modify the packaging process so that these files "
"aren't included.",
filename=name)
garbage_files += file_size
continue
elif (any(name.endswith(ext) for ext in FLAGGED_EXTENSIONS) or
name in FLAGGED_FILES):
err.warning(
err_id=("testcases_content", "test_packaged_packages",
"flagged_files"),
warning="Garbage file detected",
description="Files were found that are either unnecessary "
"or have been included unintentionally. They "
"should be removed.",
filename=name)
garbage_files += file_size
continue
# Read the file from the archive if possible.
file_data = u""
try:
file_data = package.read(name)
except __HOLE__:
pass
# Skip over whitelisted hashes - only applies to .js files for now.
if name.endswith('.js'):
file_data = file_data.replace("\r\n", "\n")
if hashlib.sha256(file_data).hexdigest() in hashes_whitelist:
continue
# Process the file.
processed = _process_file(err, package, name, file_data)
# If the file is processed, it will return True. If the process goes
# badly, it will return False. If the processing is skipped, it returns
# None. We should respect that.
if processed is None:
continue
# This aids in creating unit tests.
processed_files += 1
if garbage_files >= MAX_GARBAGE:
err.error(
err_id=("testcases_content", "garbage"),
error="Too much garbage in package",
description="Your app contains too many unused or garbage files. "
"These include temporary files, 'dot files', IDE and "
"editor backup and configuration, and operating "
"system hidden files. They must be removed before "
"your app can be submitted.")
return processed_files | KeyError | dataset/ETHPy150Open mozilla/app-validator/appvalidator/testcases/content.py/test_packed_packages |
6,022 | def apiDecorator(api_type):
def _apiDecorator(func):
lines = ['']
marked = False
if not func.__doc__:
func.__doc__ = func.__name__
lines = func.__doc__.split('\n')
for idx, line in enumerate(lines):
if '@' in line:
l = line.replace('\t', ' ')
l2 = line.lstrip()
indent = len(l) - len(l2)
lines.insert(idx, (' ' * indent) + '(%s)' % api_type)
marked = True
break
if not marked:
lines[0] = lines[0] + ' (%s)' % api_type
try:
func.__doc__ = '\n'.join(lines)
except __HOLE__:
# maybe a C function.
pass
return func
return _apiDecorator | TypeError | dataset/ETHPy150Open sassoftware/conary/conary/lib/api.py/apiDecorator |
6,023 | def split_string(self, string):
""" Yields substrings for which the same escape code applies.
"""
self.actions = []
start = 0
for match in ANSI_PATTERN.finditer(string):
raw = string[start:match.start()]
substring = SPECIAL_PATTERN.sub(self._replace_special, raw)
if substring or self.actions:
yield substring
start = match.end()
self.actions = []
groups = [x for x in match.groups() if x is not None]
params = [ param for param in groups[1].split(';') if param ]
if groups[0].startswith('['):
# Case 1: CSI code.
try:
params = list(map(int, params))
except __HOLE__:
# Silently discard badly formed codes.
pass
else:
self.set_csi_code(groups[2], params)
elif groups[0].startswith(']'):
# Case 2: OSC code.
self.set_osc_code(params)
raw = string[start:]
substring = SPECIAL_PATTERN.sub(self._replace_special, raw)
if substring or self.actions:
yield substring | ValueError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/frontend/qt/console/ansi_code_processor.py/AnsiCodeProcessor.split_string |
6,024 | def set_osc_code(self, params):
""" Set attributes based on OSC (Operating System Command) parameters.
Parameters
----------
params : sequence of str
The parameters for the command.
"""
try:
command = int(params.pop(0))
except (IndexError, __HOLE__):
return
if command == 4:
# xterm-specific: set color number to color spec.
try:
color = int(params.pop(0))
spec = params.pop(0)
self.color_map[color] = self._parse_xterm_color_spec(spec)
except (IndexError, ValueError):
pass | ValueError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/frontend/qt/console/ansi_code_processor.py/AnsiCodeProcessor.set_osc_code |
6,025 | def setUp(self):
try:
from pikos.cymonitors.focused_function_monitor import (
FocusedFunctionMonitor)
except __HOLE__:
self.skipTest('Cython FocusedFunctionMonitor is not available')
self.maxDiff = None
self.stream = StringIO.StringIO()
def monitor_factory(functions=[]):
return FocusedFunctionMonitor(
functions=functions, recorder=self.recorder)
self.helper = FocusedMonitoringHelper(monitor_factory)
self.filename = self.helper.filename
self.recorder = TextStreamRecorder(
text_stream=self.stream,
filter_=OnValue('filename', self.filename)) | ImportError | dataset/ETHPy150Open enthought/pikos/pikos/tests/test_focused_cfunction_monitor.py/TestFocusedCFunctionMonitor.setUp |
6,026 | @classmethod
def mr_job_script(cls):
"""Path of this script. This returns the file containing
this class, or ``None`` if there isn't any (e.g. it was
defined from the command line interface.)"""
try:
return inspect.getsourcefile(cls)
except __HOLE__:
return None
### Other useful utilities ### | TypeError | dataset/ETHPy150Open Yelp/mrjob/mrjob/job.py/MRJob.mr_job_script |
6,027 | def MVgammaln(x, D):
''' Compute log of the D-dimensional multivariate Gamma func. for input x
Notes: Caching gives big speedup!
-------
caching : 208 sec for 5 iters of CGS on K=50, D=2 problem with N=10000
no cache : 300 sec
'''
try:
return MVgCache[D][x]
except __HOLE__:
result = gammaln(x+ 0.5*(1 - np.arange(1,D+1)) ).sum() + 0.25*D*(D-1)*LOGPI
MVgCache[D][x] = result
return result | KeyError | dataset/ETHPy150Open daeilkim/refinery/refinery/bnpy/bnpy-dev/bnpy/util/SpecialFuncUtil.py/MVgammaln |
6,028 | def test_server(self):
logging.debug('')
logging.debug('test_server')
testdir = 'test_server'
if os.path.exists(testdir):
shutil.rmtree(testdir, onerror=onerror)
os.mkdir(testdir)
os.chdir(testdir)
try:
# Create a server.
server = ObjServer()
# Create a component.
exec_comp = server.create('openmdao.test.execcomp.ExecComp')
exec_comp.run()
egg_info = exec_comp.save_to_egg('exec_comp', '0')
# Echo some arguments.
args = server.echo('Hello', 'world!')
self.assertEqual(args[0], 'Hello')
self.assertEqual(args[1], 'world!')
# Try to execute a command.
cmd = 'dir' if sys.platform == 'win32' else 'ls'
rdesc = {'remote_command': cmd,
'output_path': 'cmd.out',
'hard_runtime_limit': 10}
code = 'server.execute_command(rdesc)'
assert_raises(self, code, globals(), locals(), RuntimeError,
'shell access is not allowed by this server')
# Try to load a model.
assert_raises(self, 'server.load_model(egg_info[0])',
globals(), locals(), RuntimeError,
'shell access is not allowed by this server')
# Bogus file accesses.
assert_raises(self, "server.open('../xyzzy', 'r')", globals(), locals(),
RuntimeError, "Can't open '../xyzzy', not within root ")
assert_raises(self, "server.open('xyzzy', 'r')", globals(), locals(),
IOError, "[Errno 2] No such file or directory: 'xyzzy'")
# Create a file using context.
with server.open('xyzzy', 'w') as out:
out.write('Hello world!\n')
# Create another file using file proxy.
out = server.open('fred', 'w')
out.write('Hello fred!\n')
out.flush() # Not really necessary, just for coverage.
out.close()
# Zip it.
server.pack_zipfile(['xyzzy', 'fred'], 'zipped')
# Make it read-only.
server.chmod('zipped', 0400)
if sys.platform == 'win32':
msg = '[Error 2] The system cannot find the file specified'
else:
msg = "[Errno 2] No such file or directory: 'no-such-file'"
assert_raises(self, "server.chmod('no-such-file', 0400)",
globals(), locals(), OSError, msg)
# Get stats.
info = server.stat('zipped')
assert_raises(self, "server.stat('no-such-file')",
globals(), locals(), OSError, msg)
# Remove zipped contents.
server.remove('xyzzy')
server.remove('fred')
if sys.platform == 'win32':
msg = '[Error 2] The system cannot find the file specified'
else:
msg = "[Errno 2] No such file or directory: 'xyzzy'"
assert_raises(self, "server.remove('xyzzy')",
globals(), locals(), OSError, msg)
# Unpack.
server.unpack_zipfile('zipped')
server.chmod('zipped', 0600) # Ensure we can remove under Windows.
# Verify contents.
with server.open('xyzzy', 'r') as inp:
data = inp.read()
self.assertEqual(data, 'Hello world!\n')
inp = server.open('fred', 'r')
try:
data = inp.read(1000)
self.assertEqual(data, 'Hello fred!\n')
finally:
inp.close()
# Try to create a process.
args = 'dir' if sys.platform == 'win32' else 'ls'
try:
proc = server.create('subprocess.Popen', args=args, shell=True)
proc.wait()
except __HOLE__ as exc:
msg = "'subprocess.Popen' is not an allowed type"
self.assertEqual(str(exc), msg)
else:
self.fail('Expected TypeError')
# isdir().
self.assertTrue(server.isdir('.'))
# listdir().
self.assertEqual(sorted(server.listdir('.')),
[egg_info[0], 'fred', 'xyzzy', 'zipped'])
if sys.platform == 'win32':
msg = "[Error 3] The system cannot find the path specified: '42/*.*'"
else:
msg = "[Errno 2] No such file or directory: '42'"
assert_raises(self, "server.listdir('42')",
globals(), locals(), OSError, msg)
finally:
SimulationRoot.chroot('..')
shutil.rmtree(testdir, onerror=onerror) | TypeError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/test/test_objserverfactory.py/TestCase.test_server |
6,029 | def _setup_pre_commit_hook(self):
"""
Copy the pre-commit hook found at config.pre_commit_hook to the
closest .git directory. If no .git directory exists, throw an
exception.
"""
if self.config.get('pre_commit_hook') is None:
return
check_dir = os.getcwd()
while 1:
if os.path.exists(os.path.join(check_dir, '.git')):
break
elif os.path.normpath(check_dir) == '/':
raise Exception("No .git directory found for pre-commit hook")
else:
# Go up one level
check_dir = os.path.join(check_dir, os.pardir)
hook_path = os.path.join(os.getcwd(), self.config['pre_commit_hook'])
source = os.path.join(hook_path)
dest = os.path.join(check_dir, '.git', 'hooks', 'pre-commit')
sys.stdout.write("Setup git pre-commit hook: \n\t%s\n\t-> %s\n" % (dest, source))
try:
if os.readlink(dest) == source:
return
else:
os.unlink(dest)
except __HOLE__:
pass
os.symlink(source, dest) | OSError | dataset/ETHPy150Open appnexus/schema-tool/schematool/command/init.py/InitCommand._setup_pre_commit_hook |
6,030 | def quoted_string_literal(s, d):
"""
SOQL requires single quotes to be escaped.
http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_soql_select_quotedstringescapes.htm
"""
try:
return "'%s'" % (s.replace("\\", "\\\\").replace("'", "\\'"),)
except __HOLE__ as e:
raise NotImplementedError("Cannot quote %r objects: %r" % (type(s), s)) | TypeError | dataset/ETHPy150Open django-salesforce/django-salesforce/salesforce/backend/query.py/quoted_string_literal |
6,031 | def iterator(self):
"""
An iterator over the results from applying this QuerySet to the
remote web service.
"""
try:
sql, params = SQLCompiler(self.query, connections[self.db], None).as_sql()
except EmptyResultSet:
raise StopIteration
cursor = CursorWrapper(connections[self.db], self.query)
cursor.execute(sql, params)
pfd = prep_for_deserialize
only_load = self.query.get_loaded_field_names()
load_fields = []
# If only/defer clauses have been specified,
# build the list of fields that are to be loaded.
if not only_load:
model_cls = self.model
init_list = None
else:
fields = self.model._meta.concrete_fields
for field in fields:
model = field.model._meta.concrete_model
if model is None:
model = self.model
try:
selected_name = field.attname if DJANGO_18_PLUS else field.name
if selected_name in only_load[model]:
# Add a field that has been explicitly included
load_fields.append(field.name)
except __HOLE__:
# Model wasn't explicitly listed in the only_load table
# Therefore, we need to load all fields from this model
load_fields.append(field.name)
init_list = []
skip = set()
for field in fields:
if field.name not in load_fields:
skip.add(field.attname)
else:
init_list.append(field.name)
model_cls = deferred_class_factory(self.model, skip)
field_names = self.query.get_loaded_field_names()
for res in python.Deserializer(pfd(model_cls, r, self.db, init_list) for r in cursor.results):
# Store the source database of the object
res.object._state.db = self.db
# This object came from the database; it's not being added.
res.object._state.adding = False
yield res.object | KeyError | dataset/ETHPy150Open django-salesforce/django-salesforce/salesforce/backend/query.py/SalesforceQuerySet.iterator |
6,032 | def execute_delete(self, query):
table = query.model._meta.db_table
## the root where node's children may itself have children..
def recurse_for_pk(children):
for node in children:
if hasattr(node, 'rhs'):
pk = node.rhs[0]
else:
try:
pk = node[-1][0]
except __HOLE__:
pk = recurse_for_pk(node.children)
return pk
pk = recurse_for_pk(self.query.where.children)
assert pk
url = self.session.auth.instance_url + API_STUB + ('/sobjects/%s/%s' % (table, pk))
log.debug('DELETE %s(%s)' % (table, pk))
ret = handle_api_exceptions(url, self.session.delete, _cursor=self)
self.rowcount = 1 if (ret and ret.status_code == 204) else 0
return ret | TypeError | dataset/ETHPy150Open django-salesforce/django-salesforce/salesforce/backend/query.py/CursorWrapper.execute_delete |
6,033 | def fetchone(self):
"""
Fetch a single result from a previously executed query.
"""
try:
return next(self.results)
except __HOLE__:
return None | StopIteration | dataset/ETHPy150Open django-salesforce/django-salesforce/salesforce/backend/query.py/CursorWrapper.fetchone |
6,034 | def test_maybeDeferredSyncError(self):
"""
L{defer.maybeDeferred} should catch exception raised by a synchronous
function and errback its resulting L{defer.Deferred} with it.
"""
S, E = [], []
try:
'10' + 5
except __HOLE__, e:
expected = str(e)
d = defer.maybeDeferred((lambda x: x + 5), '10')
d.addCallbacks(S.append, E.append)
self.assertEquals(S, [])
self.assertEquals(len(E), 1)
self.assertEquals(str(E[0].value), expected)
return d | TypeError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/test/test_defer.py/DeferredTestCase.test_maybeDeferredSyncError |
6,035 | def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
self.active = kwargs.pop('active', None)
initial = kwargs.get('initial', {})
default_loc = utils.get_setting('TIMEPIECE_DEFAULT_LOCATION_SLUG')
if default_loc:
try:
loc = Location.objects.get(slug=default_loc)
except Location.DoesNotExist:
loc = None
if loc:
initial['location'] = loc.pk
project = initial.get('project', None)
try:
last_project_entry = Entry.objects.filter(
user=self.user, project=project).order_by('-end_time')[0]
except __HOLE__:
initial['activity'] = None
else:
initial['activity'] = last_project_entry.activity.pk
super(ClockInForm, self).__init__(*args, **kwargs)
self.fields['start_time'].initial = datetime.datetime.now()
self.fields['project'].queryset = Project.trackable.filter(
users=self.user)
if not self.active:
self.fields.pop('active_comment')
else:
self.fields['active_comment'].initial = self.active.comments
self.instance.user = self.user | IndexError | dataset/ETHPy150Open caktus/django-timepiece/timepiece/entries/forms.py/ClockInForm.__init__ |
6,036 | def test_loadTestsFromTestCase__TestSuite_subclass(self):
class NotATestCase(unittest.TestSuite):
pass
loader = unittest.TestLoader()
try:
loader.loadTestsFromTestCase(NotATestCase)
except __HOLE__:
pass
else:
self.fail('Should raise TypeError')
# "Return a suite of all tests cases contained in the TestCase-derived
# class testCaseClass"
#
# Make sure loadTestsFromTestCase() picks up the default test method
# name (as specified by TestCase), even though the method name does
# not match the default TestLoader.testMethodPrefix string | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromTestCase__TestSuite_subclass |
6,037 | def test_loadTestsFromName__empty_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('')
except __HOLE__ as e:
self.assertEqual(str(e), "Empty module name")
else:
self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# What happens when the name contains invalid characters? | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__empty_name |
6,038 | def test_loadTestsFromName__malformed_name(self):
loader = unittest.TestLoader()
# XXX Should this raise ValueError or ImportError?
try:
loader.loadTestsFromName('abc () //')
except __HOLE__:
pass
except ImportError:
pass
else:
self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
# "The specifier name is a ``dotted name'' that may resolve ... to a
# module"
#
# What happens when a module by that name can't be found? | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__malformed_name |
6,039 | def test_loadTestsFromName__unknown_module_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('sdasfasfasdf')
except __HOLE__ as e:
self.assertEqual(str(e), "No module named 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# What happens when the module is found, but the attribute can't? | ImportError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__unknown_module_name |
6,040 | def test_loadTestsFromName__unknown_attr_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('unittest.sdasfasfasdf')
except __HOLE__ as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# What happens when we provide the module, but the attribute can't be
# found? | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__unknown_attr_name |
6,041 | def test_loadTestsFromName__relative_unknown_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('sdasfasfasdf', unittest)
except __HOLE__ as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
# ...
# "The method optionally resolves name relative to the given module"
#
# Does loadTestsFromName raise ValueError when passed an empty
# name relative to a provided module?
#
# XXX Should probably raise a ValueError instead of an AttributeError | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__relative_unknown_name |
6,042 | def test_loadTestsFromName__relative_empty_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('', unittest)
except __HOLE__ as e:
pass
else:
self.fail("Failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
# ...
# "The method optionally resolves name relative to the given module"
#
# What happens when an impossible name is given, relative to the provided
# `module`? | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__relative_empty_name |
6,043 | def test_loadTestsFromName__relative_malformed_name(self):
loader = unittest.TestLoader()
# XXX Should this raise AttributeError or ValueError?
try:
loader.loadTestsFromName('abc () //', unittest)
except __HOLE__:
pass
except AttributeError:
pass
else:
self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
# "The method optionally resolves name relative to the given module"
#
# Does loadTestsFromName raise TypeError when the `module` argument
# isn't a module object?
#
# XXX Accepts the not-a-module object, ignorning the object's type
# This should raise an exception or the method name should be changed
#
# XXX Some people are relying on this, so keep it for now | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__relative_malformed_name |
6,044 | def test_loadTestsFromName__relative_bad_object(self):
m = types.ModuleType('m')
m.testcase_1 = object()
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('testcase_1', m)
except __HOLE__:
pass
else:
self.fail("Should have raised TypeError")
# "The specifier name is a ``dotted name'' that may
# resolve either to ... a test case class" | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__relative_bad_object |
6,045 | def test_loadTestsFromName__relative_invalid_testmethod(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('testcase_1.testfoo', m)
except __HOLE__ as e:
self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
else:
self.fail("Failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a ... TestSuite instance" | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__relative_invalid_testmethod |
6,046 | def test_loadTestsFromName__callable__wrong_type(self):
m = types.ModuleType('m')
def return_wrong():
return 6
m.return_wrong = return_wrong
loader = unittest.TestLoader()
try:
suite = loader.loadTestsFromName('return_wrong', m)
except __HOLE__:
pass
else:
self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
# "The specifier can refer to modules and packages which have not been
# imported; they will be imported as a side-effect" | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromName__callable__wrong_type |
6,047 | def test_loadTestsFromNames__empty_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames([''])
except __HOLE__ as e:
self.assertEqual(str(e), "Empty module name")
else:
self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# What happens when presented with an impossible module name? | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__empty_name |
6,048 | def test_loadTestsFromNames__malformed_name(self):
loader = unittest.TestLoader()
# XXX Should this raise ValueError or ImportError?
try:
loader.loadTestsFromNames(['abc () //'])
except ValueError:
pass
except __HOLE__:
pass
else:
self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# What happens when no module can be found for the given name? | ImportError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__malformed_name |
6,049 | def test_loadTestsFromNames__unknown_module_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['sdasfasfasdf'])
except __HOLE__ as e:
self.assertEqual(str(e), "No module named 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# What happens when the module can be found, but not the attribute? | ImportError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__unknown_module_name |
6,050 | def test_loadTestsFromNames__unknown_attr_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
except __HOLE__ as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
# ...
# "The method optionally resolves name relative to the given module"
#
# What happens when given an unknown attribute on a specified `module`
# argument? | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__unknown_attr_name |
6,051 | def test_loadTestsFromNames__unknown_name_relative_1(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
except __HOLE__ as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
# ...
# "The method optionally resolves name relative to the given module"
#
# Do unknown attributes (relative to a provided module) still raise an
# exception even in the presence of valid attribute names? | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__unknown_name_relative_1 |
6,052 | def test_loadTestsFromNames__unknown_name_relative_2(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
except __HOLE__ as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
# ...
# "The method optionally resolves name relative to the given module"
#
# What happens when faced with the empty string?
#
# XXX This currently raises AttributeError, though ValueError is probably
# more appropriate | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__unknown_name_relative_2 |
6,053 | def test_loadTestsFromNames__relative_empty_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames([''], unittest)
except __HOLE__:
pass
else:
self.fail("Failed to raise ValueError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
# ...
# "The method optionally resolves name relative to the given module"
#
# What happens when presented with an impossible attribute name? | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__relative_empty_name |
6,054 | def test_loadTestsFromNames__relative_malformed_name(self):
loader = unittest.TestLoader()
# XXX Should this raise AttributeError or ValueError?
try:
loader.loadTestsFromNames(['abc () //'], unittest)
except __HOLE__:
pass
except ValueError:
pass
else:
self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
# "The method optionally resolves name relative to the given module"
#
# Does loadTestsFromNames() make sure the provided `module` is in fact
# a module?
#
# XXX This validation is currently not done. This flexibility should
# either be documented or a TypeError should be raised. | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__relative_malformed_name |
6,055 | def test_loadTestsFromNames__relative_bad_object(self):
m = types.ModuleType('m')
m.testcase_1 = object()
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['testcase_1'], m)
except __HOLE__:
pass
else:
self.fail("Should have raised TypeError")
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a test case class" | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__relative_bad_object |
6,056 | def test_loadTestsFromNames__relative_invalid_testmethod(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['testcase_1.testfoo'], m)
except __HOLE__ as e:
self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
else:
self.fail("Failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a ... TestSuite instance" | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__relative_invalid_testmethod |
6,057 | def test_loadTestsFromNames__callable__wrong_type(self):
m = types.ModuleType('m')
def return_wrong():
return 6
m.return_wrong = return_wrong
loader = unittest.TestLoader()
try:
suite = loader.loadTestsFromNames(['return_wrong'], m)
except __HOLE__:
pass
else:
self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
# "The specifier can refer to modules and packages which have not been
# imported; they will be imported as a side-effect" | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/test/test_loader.py/Test_TestLoader.test_loadTestsFromNames__callable__wrong_type |
6,058 | def normalize_scopes(scopes):
"""
Given a list of public-facing scope names from a CAS token, return the list of internal scopes
This is useful for converting a single broad scope name (from CAS) into the small constituent parts
(as used by views)
:param list scopes: a list public facing scopes
"""
all_scopes = set()
for sc in scopes:
try:
scope_tuple = public_scopes[sc]
all_scopes |= scope_tuple.parts
except __HOLE__:
pass
return all_scopes | KeyError | dataset/ETHPy150Open CenterForOpenScience/osf.io/framework/auth/oauth_scopes.py/normalize_scopes |
6,059 | def find(self, **kwargs):
"""
Find a single item with attributes matching ``**kwargs``.
This isn't very efficient: it loads the entire list then filters on
the Python side.
"""
rl = self.findall(**kwargs)
try:
return rl[0]
except __HOLE__:
raise NotFound(404, "No %s matching %s." % (self.resource_class.__name__, kwargs)) | IndexError | dataset/ETHPy150Open jacobian-archive/openstack.compute/openstack/compute/base.py/ManagerWithFind.find |
6,060 | def findall(self, **kwargs):
"""
Find all items with attributes matching ``**kwargs``.
This isn't very efficient: it loads the entire list then filters on
the Python side.
"""
found = []
searches = kwargs.items()
for obj in self.list():
try:
if all(getattr(obj, attr) == value for (attr, value) in searches):
found.append(obj)
except __HOLE__:
continue
return found | AttributeError | dataset/ETHPy150Open jacobian-archive/openstack.compute/openstack/compute/base.py/ManagerWithFind.findall |
6,061 | def getid(obj):
"""
Abstracts the common pattern of allowing both an object or an object's ID
(integer) as a parameter when dealing with relationships.
"""
try:
return obj.id
except __HOLE__:
return int(obj) | AttributeError | dataset/ETHPy150Open jacobian-archive/openstack.compute/openstack/compute/base.py/getid |
6,062 | def bdecode(x):
try:
r, l = decode_func[six.indexbytes(x, 0)](x, 0)
except (IndexError, KeyError, __HOLE__):
raise
raise BTFailure("not a valid bencoded string")
if l != len(x):
raise BTFailure("invalid bencoded value (data after valid prefix)")
return r | ValueError | dataset/ETHPy150Open JohnDoee/autotorrent/autotorrent/bencode.py/bdecode |
6,063 | @csrf_exempt
def rest(request, *pargs):
"""
Calls python function corresponding with HTTP METHOD name.
Calls with incomplete arguments will return HTTP 400
"""
if request.method == 'GET':
rest_function = get
elif request.method == 'POST':
rest_function = post
elif request.method == 'PUT':
rest_function = put
elif request.method == 'DELETE':
rest_function = delete
else:
return JsonResponse({"error": "HTTP METHOD UNKNOWN"})
try:
return rest_function(request, *pargs)
except __HOLE__:
return HttpResponseBadRequest("argument mismatch") | TypeError | dataset/ETHPy150Open emccode/heliosburn/heliosburn/django/hbproject/api/views/testplan.py/rest |
6,064 | @RequireLogin()
def post(request):
"""
Create new test plan.
"""
try:
new = json.loads(request.body)
assert "name" in new
except __HOLE__:
return HttpResponseBadRequest("invalid JSON")
except AssertionError:
return HttpResponseBadRequest("argument mismatch")
if 'rules' in new:
new['rules'] = [rule_model.validate(rule) for rule in new['rules']]
if None in new['rules']: # Invalid rules are re-assigned to None
return HttpResponse("invalid rule(s) provided")
dbc = db_model.connect()
testplan = dbc.testplan.find_one({"name": new['name']})
if testplan is not None:
return HttpResponseBadRequest("testplan named '%s' already exists" % new['name'])
new['createdAt'] = datetime.isoformat(datetime.now())
new['updatedAt'] = datetime.isoformat(datetime.now())
testplan_id = str(dbc.testplan.save(new))
r = JsonResponse({"id": testplan_id}, status=200)
r['location'] = "/api/testplan/%s" % testplan_id
logger.info("test plan '%s' created by '%s'" % (testplan_id, request.user['username']))
return r | ValueError | dataset/ETHPy150Open emccode/heliosburn/heliosburn/django/hbproject/api/views/testplan.py/post |
6,065 | @RequireLogin()
def put(request, testplan_id):
"""
Update existing test plan based on testplan_id.
"""
try:
in_json = json.loads(request.body)
except __HOLE__:
return HttpResponseBadRequest("invalid JSON")
dbc = db_model.connect()
try:
testplan = dbc.testplan.find_one({"_id": ObjectId(testplan_id)})
except InvalidId:
return HttpResponseNotFound()
if testplan is None:
return HttpResponseNotFound()
else:
if "name" in in_json:
testplan['name'] = in_json['name']
if "description" in in_json:
testplan['description'] = in_json['description']
if "rules" in in_json:
testplan['rules'] = [rule_model.validate(rule) for rule in in_json['rules']]
if None in in_json['rules']:
return HttpResponse("invalid rule(s) provided")
try:
testplan['updatedAt'] = datetime.isoformat(datetime.now())
dbc.testplan.save(testplan)
except DuplicateKeyError:
return HttpResponseBadRequest("testplan named '%s' already exists" % in_json['name'])
logger.info("test plan '%s' updated by '%s'" % (testplan_id, request.user['username']))
return HttpResponse(status=200) | ValueError | dataset/ETHPy150Open emccode/heliosburn/heliosburn/django/hbproject/api/views/testplan.py/put |
6,066 | def prep_trans_tar(file_client, chunks, file_refs, pillar=None, id_=None):
'''
Generate the execution package from the saltenv file refs and a low state
data structure
'''
gendir = tempfile.mkdtemp()
trans_tar = salt.utils.mkstemp()
lowfn = os.path.join(gendir, 'lowstate.json')
pillarfn = os.path.join(gendir, 'pillar.json')
sync_refs = [
[salt.utils.url.create('_modules')],
[salt.utils.url.create('_states')],
[salt.utils.url.create('_grains')],
[salt.utils.url.create('_renderers')],
[salt.utils.url.create('_returners')],
[salt.utils.url.create('_output')],
[salt.utils.url.create('_utils')],
]
with salt.utils.fopen(lowfn, 'w+') as fp_:
fp_.write(json.dumps(chunks))
if pillar:
with salt.utils.fopen(pillarfn, 'w+') as fp_:
fp_.write(json.dumps(pillar))
cachedir = os.path.join('salt-ssh', id_)
for saltenv in file_refs:
file_refs[saltenv].extend(sync_refs)
env_root = os.path.join(gendir, saltenv)
if not os.path.isdir(env_root):
os.makedirs(env_root)
for ref in file_refs[saltenv]:
for name in ref:
short = salt.utils.url.parse(name)[0]
path = file_client.cache_file(name, saltenv, cachedir=cachedir)
if path:
tgt = os.path.join(env_root, short)
tgt_dir = os.path.dirname(tgt)
if not os.path.isdir(tgt_dir):
os.makedirs(tgt_dir)
shutil.copy(path, tgt)
continue
files = file_client.cache_dir(name, saltenv, cachedir=cachedir)
if files:
for filename in files:
fn = filename[filename.find(short) + len(short):]
if fn.startswith('/'):
fn = fn.strip('/')
tgt = os.path.join(
env_root,
short,
fn,
)
tgt_dir = os.path.dirname(tgt)
if not os.path.isdir(tgt_dir):
os.makedirs(tgt_dir)
shutil.copy(filename, tgt)
continue
try:
# cwd may not exist if it was removed but salt was run from it
cwd = os.getcwd()
except __HOLE__:
cwd = None
os.chdir(gendir)
with closing(tarfile.open(trans_tar, 'w:gz')) as tfp:
for root, dirs, files in os.walk(gendir):
for name in files:
full = os.path.join(root, name)
tfp.add(full[len(gendir):].lstrip(os.sep))
if cwd:
os.chdir(cwd)
shutil.rmtree(gendir)
return trans_tar | OSError | dataset/ETHPy150Open saltstack/salt/salt/client/ssh/state.py/prep_trans_tar |
6,067 | def _get_http(timeout):
try:
http = Http(timeout=timeout)
except __HOLE__:
# The user's version of http2lib is old. Omit the timeout.
http = Http()
return http | TypeError | dataset/ETHPy150Open njr0/fish/fish/fishlib.py/_get_http |
6,068 | def get_values_by_query(self, query, tags):
"""
Gets the values of a set of tags satisfying a given query.
Returns them as a dictionary (hash) keyed on object ID.
The values in the dictionary are simple objects with each tag
value in the object's dictionary (__dict__).
query is a unicode string representing a valid Fluidinfo query.
e.g. 'has njr/rating'
tags is a list (or tuple) containing the tags whose values are
required.
Example:
db = Fluidinfo()
tag_by_query(db, u'has njr/rating < 3', ('fluiddb/about',))
NOTE: Unlike in much of the rest of fish.py, tags need to be full paths
without a leading slash.
NOTE: All strings must be (and will be) unicode.
"""
maxTextSize = 1024
(v, r) = self.call(u'GET', u'/values', None, {u'query': query,
u'tag': tags})
assert_status(v, STATUS.OK)
H = r[u'results'][u'id']
results = []
for id in H:
o = O()
o.id = id
for tag in tags:
if tag in H[id]:
try:
if tag == u'fluiddb/about':
o.about = H[id][tag][u'value']
else:
o.tags[tag] = H[id][tag][u'value']
o.types[tag] = None
except __HOLE__:
size = H[id][tag][u'size']
mime = H[id][tag][u'value-type']
if (mime.startswith(u'text')
and size < maxTextSize):
o.tags[tag] = self.get_tag_value_by_about(id,
u'/%s' % tag)
else:
o.tags[tag] = (u'%s value of size %d bytes' % (mime,
size))
o.types[tag] = mime
results.append(o)
return results # hash of objects, keyed on ID, with attributes
# corresponding to tags, inc id. | KeyError | dataset/ETHPy150Open njr0/fish/fish/fishlib.py/Fluidinfo.get_values_by_query |
6,069 | def get_typed_tag_value(v):
"""Uses some simple rules to extract simple typed values from strings.
Specifically:
true and t (any case) return True (boolean)
false and f (any case) return False (boolean)
simple integers (possibly signed) are returned as ints
simple floats (possibly signed) are returned as floats
(supports '.' and ',' as floating-point separator,
subject to locale)
Everything else is returned as a string, with matched
enclosing quotes stripped.
"""
if v.lower() in (u'true', u't'):
return True
elif v.lower() in (u'false', u'f'):
return False
elif re.match(INTEGER_RE, v):
return int(v)
elif re.match(DECIMAL_RE, v) or re.match(DECIMAL_RE2, v):
try:
r = float(v)
except __HOLE__:
return toStr(v)
return r
elif len(v) > 1 and v[0] == v[-1] and v[0] in (u'"\''):
return v[1:-1]
elif len(v) > 1 and ((v[0] == u'[' and v[-1] == ']') or
(v[0] == u'{' and v[-1] == '}')):
return cline.CScanSplit(v[1:-1], ' \t,', quotes='"\'').words
else:
return toStr(v) | ValueError | dataset/ETHPy150Open njr0/fish/fish/fishlib.py/get_typed_tag_value |
6,070 | def get_typed_tag_value_from_file(path, options):
path = expandpath(path)
mime = options.mime[0] if options.mime else None
if os.path.exists(path):
v = Dummy()
stem, ext = os.path.splitext(path)
ext = ext[1:].lower()
if (mime and mime in TEXTUAL_MIMES.values()) or ext in TEXTUAL_MIMES:
f = open(path)
v.value = f.read()
f.close()
try:
v.value = v.value.decode('UTF-8')
except __HOLE__: # clearly wasn't UTF-8
raise UnicodeError('Content doesn\'t seem to be UTF-8')
v.mime = mime or TEXTUAL_MIMES[ext]
elif mime or ext in BINARY_MIMES:
f = open(path, 'rb')
v.value = f.read()
f.close()
v.mime = mime or BINARY_MIMES[ext]
else:
if ext:
raise MIMEError('Extension .%s unknown and no MIME type'
' given (with -M)' % ext)
else:
raise MIMEError('You need to specify a MIME type with -M for'
'files with no Extension.')
return v
else:
raise FileNotFoundError('Could not find or read %s.' % path) | UnicodeDecodeError | dataset/ETHPy150Open njr0/fish/fish/fishlib.py/get_typed_tag_value_from_file |
6,071 | def to_typed(v):
"""
Turns json-formatted string into python value.
Unicode.
"""
L = v.lower()
if v.startswith(u'"') and v.startswith(u'"') and len(v) >= 2:
return v[1:-1]
elif v.startswith(u"'") and v.startswith(u"'") and len(v) >= 2:
return v[1:-1]
elif L == u'true':
return True
elif L == u'false':
return False
elif re.match(INTEGER_RE, v):
return int(v)
elif re.match(DECIMAL_RE, v) or re.match(DECIMAL_RE2, v):
try:
r = float(v)
except __HOLE__:
return unicode(v)
return r
else:
return unicode(v) | ValueError | dataset/ETHPy150Open njr0/fish/fish/fishlib.py/to_typed |
6,072 | def number_try_parse(str):
for func in (int, float):
try:
return func(str)
except __HOLE__:
pass
return str | ValueError | dataset/ETHPy150Open membase/membase-cli/pump_csv.py/number_try_parse |
6,073 | def provide_batch(self):
if self.done:
return 0, None
if not self.r:
try:
self.r = csv.reader(open(self.spec, 'rU'))
self.fields = self.r.next()
if not 'id' in self.fields:
return ("error: no 'id' field in 1st line of csv: %s" %
(self.spec)), None
except StopIteration:
return ("error: could not read 1st line of csv: %s" %
(self.spec)), None
except IOError, e:
return ("error: could not open csv: %s; exception: %s" %
(self.spec, e)), None
batch = pump.Batch(self)
batch_max_size = self.opts.extra['batch_max_size']
batch_max_bytes = self.opts.extra['batch_max_bytes']
cmd = memcacheConstants.CMD_TAP_MUTATION
vbucket_id = 0x0000ffff
cas, exp, flg = 0, 0, 0
while (self.r and
batch.size() < batch_max_size and
batch.bytes < batch_max_bytes):
try:
vals = self.r.next()
doc = {}
for i, field in enumerate(self.fields):
if field == 'id':
doc[field] = vals[i]
else:
doc[field] = number_try_parse(vals[i])
doc_json = json.dumps(doc)
msg = (cmd, vbucket_id, doc['id'], flg, exp, cas, '', doc_json)
batch.append(msg, len(doc))
except __HOLE__:
self.done = True
self.r = None
if batch.size() <= 0:
return 0, None
return 0, batch | StopIteration | dataset/ETHPy150Open membase/membase-cli/pump_csv.py/CSVSource.provide_batch |
6,074 | def consume_batch_async(self, batch):
if not self.writer:
self.writer = csv.writer(sys.stdout)
self.writer.writerow(['id', 'flags', 'expiration', 'cas', 'value'])
for msg in batch.msgs:
cmd, vbucket_id, key, flg, exp, cas, meta, val = msg
if self.skip(key, vbucket_id):
continue
try:
if cmd == memcacheConstants.CMD_TAP_MUTATION:
self.writer.writerow([key, flg, exp, cas, val])
elif cmd == memcacheConstants.CMD_TAP_DELETE:
pass
elif cmd == memcacheConstants.CMD_GET:
pass
else:
return "error: CSVSink - unknown cmd: " + str(cmd), None
except __HOLE__:
return "error: could not write csv to stdout", None
future = pump.SinkBatchFuture(self, batch)
self.future_done(future, 0)
return 0, future | IOError | dataset/ETHPy150Open membase/membase-cli/pump_csv.py/CSVSink.consume_batch_async |
6,075 | def test_constructor(self):
pi = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')
assert_equal(len(pi), 9)
pi = PeriodIndex(freq='Q', start='1/1/2001', end='12/1/2009')
assert_equal(len(pi), 4 * 9)
pi = PeriodIndex(freq='M', start='1/1/2001', end='12/1/2009')
assert_equal(len(pi), 12 * 9)
pi = PeriodIndex(freq='D', start='1/1/2001', end='12/31/2009')
assert_equal(len(pi), 365 * 9 + 2)
pi = PeriodIndex(freq='B', start='1/1/2001', end='12/31/2009')
assert_equal(len(pi), 261 * 9)
pi = PeriodIndex(freq='H', start='1/1/2001', end='12/31/2001 23:00')
assert_equal(len(pi), 365 * 24)
pi = PeriodIndex(freq='Min', start='1/1/2001', end='1/1/2001 23:59')
assert_equal(len(pi), 24 * 60)
pi = PeriodIndex(freq='S', start='1/1/2001', end='1/1/2001 23:59:59')
assert_equal(len(pi), 24 * 60 * 60)
start = Period('02-Apr-2005', 'B')
i1 = PeriodIndex(start=start, periods=20)
assert_equal(len(i1), 20)
assert_equal(i1.freq, start.freq)
assert_equal(i1[0], start)
end_intv = Period('2006-12-31', 'W')
i1 = PeriodIndex(end=end_intv, periods=10)
assert_equal(len(i1), 10)
assert_equal(i1.freq, end_intv.freq)
assert_equal(i1[-1], end_intv)
end_intv = Period('2006-12-31', '1w')
i2 = PeriodIndex(end=end_intv, periods=10)
assert_equal(len(i1), len(i2))
self.assertTrue((i1 == i2).all())
assert_equal(i1.freq, i2.freq)
end_intv = Period('2006-12-31', ('w', 1))
i2 = PeriodIndex(end=end_intv, periods=10)
assert_equal(len(i1), len(i2))
self.assertTrue((i1 == i2).all())
assert_equal(i1.freq, i2.freq)
try:
PeriodIndex(start=start, end=end_intv)
raise AssertionError('Cannot allow mixed freq for start and end')
except __HOLE__:
pass
end_intv = Period('2005-05-01', 'B')
i1 = PeriodIndex(start=start, end=end_intv)
try:
PeriodIndex(start=start)
raise AssertionError(
'Must specify periods if missing start or end')
except ValueError:
pass
# infer freq from first element
i2 = PeriodIndex([end_intv, Period('2005-05-05', 'B')])
assert_equal(len(i2), 2)
assert_equal(i2[0], end_intv)
i2 = PeriodIndex(np.array([end_intv, Period('2005-05-05', 'B')]))
assert_equal(len(i2), 2)
assert_equal(i2[0], end_intv)
# Mixed freq should fail
vals = [end_intv, Period('2006-12-31', 'w')]
self.assertRaises(ValueError, PeriodIndex, vals)
vals = np.array(vals)
self.assertRaises(ValueError, PeriodIndex, vals) | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/tseries/tests/test_period.py/TestPeriodIndex.test_constructor |
6,076 | def test_period_index_length(self):
pi = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')
assert_equal(len(pi), 9)
pi = PeriodIndex(freq='Q', start='1/1/2001', end='12/1/2009')
assert_equal(len(pi), 4 * 9)
pi = PeriodIndex(freq='M', start='1/1/2001', end='12/1/2009')
assert_equal(len(pi), 12 * 9)
start = Period('02-Apr-2005', 'B')
i1 = PeriodIndex(start=start, periods=20)
assert_equal(len(i1), 20)
assert_equal(i1.freq, start.freq)
assert_equal(i1[0], start)
end_intv = Period('2006-12-31', 'W')
i1 = PeriodIndex(end=end_intv, periods=10)
assert_equal(len(i1), 10)
assert_equal(i1.freq, end_intv.freq)
assert_equal(i1[-1], end_intv)
end_intv = Period('2006-12-31', '1w')
i2 = PeriodIndex(end=end_intv, periods=10)
assert_equal(len(i1), len(i2))
self.assertTrue((i1 == i2).all())
assert_equal(i1.freq, i2.freq)
end_intv = Period('2006-12-31', ('w', 1))
i2 = PeriodIndex(end=end_intv, periods=10)
assert_equal(len(i1), len(i2))
self.assertTrue((i1 == i2).all())
assert_equal(i1.freq, i2.freq)
try:
PeriodIndex(start=start, end=end_intv)
raise AssertionError('Cannot allow mixed freq for start and end')
except __HOLE__:
pass
end_intv = Period('2005-05-01', 'B')
i1 = PeriodIndex(start=start, end=end_intv)
try:
PeriodIndex(start=start)
raise AssertionError(
'Must specify periods if missing start or end')
except ValueError:
pass
# infer freq from first element
i2 = PeriodIndex([end_intv, Period('2005-05-05', 'B')])
assert_equal(len(i2), 2)
assert_equal(i2[0], end_intv)
i2 = PeriodIndex(np.array([end_intv, Period('2005-05-05', 'B')]))
assert_equal(len(i2), 2)
assert_equal(i2[0], end_intv)
# Mixed freq should fail
vals = [end_intv, Period('2006-12-31', 'w')]
self.assertRaises(ValueError, PeriodIndex, vals)
vals = np.array(vals)
self.assertRaises(ValueError, PeriodIndex, vals) | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/tseries/tests/test_period.py/TestPeriodIndex.test_period_index_length |
6,077 | def test_get_loc_msg(self):
idx = period_range('2000-1-1', freq='A', periods=10)
bad_period = Period('2012', 'A')
self.assertRaises(KeyError, idx.get_loc, bad_period)
try:
idx.get_loc(bad_period)
except __HOLE__ as inst:
self.assertEqual(inst.args[0], bad_period) | KeyError | dataset/ETHPy150Open pydata/pandas/pandas/tseries/tests/test_period.py/TestPeriodIndex.test_get_loc_msg |
6,078 | def scan(build, root, desc, **custom_vars ):
global numStamped
numStamped = 0
try:
build = string.atoi(build)
except __HOLE__:
print 'ERROR: build number is not a number: %s' % build
sys.exit(1)
debug = 0 ### maybe fix this one day
varList = ['major', 'minor', 'sub', 'company', 'copyright', 'trademarks', 'product']
vars, descriptions = load_descriptions(desc, varList)
vars['build'] = build
vars.update(custom_vars)
arg = vars, debug, descriptions
os.path.walk(root, walk, arg)
print "Stamped %d files." % (numStamped) | ValueError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/scripts/VersionStamp/bulkstamp.py/scan |
6,079 | def getDecodableAttributes(self, obj, attrs, codec=None):
"""
Returns a dictionary of attributes for C{obj} that has been filtered,
based on the supplied C{attrs}. This allows for fine grain control
over what will finally end up on the object or not.
@param obj: The object that will recieve the attributes.
@param attrs: The C{attrs} dictionary that has been decoded.
@param codec: An optional argument that will contain the decoder
instance calling this function.
@return: A dictionary of attributes that can be applied to C{obj}
@since: 0.5
"""
if not self._compiled:
self.compile()
changed = False
props = set(attrs.keys())
if self.static_attrs:
missing_attrs = self.static_attrs_set.difference(props)
if missing_attrs:
raise AttributeError('Static attributes %r expected '
'when decoding %r' % (missing_attrs, self.klass))
props.difference_update(self.static_attrs)
if not props:
return attrs
if not self.dynamic:
if not self.decodable_properties:
props = set()
else:
props.intersection_update(self.decodable_properties)
changed = True
if self.readonly_attrs:
props.difference_update(self.readonly_attrs)
changed = True
if self.exclude_attrs:
props.difference_update(self.exclude_attrs)
changed = True
if self.proxy_attrs is not None and codec:
context = codec.context
for k in self.proxy_attrs:
try:
v = attrs[k]
except __HOLE__:
continue
attrs[k] = context.getObjectForProxy(v)
if self.synonym_attrs:
missing = object()
for k, v in self.synonym_attrs.iteritems():
value = attrs.pop(k, missing)
if value is missing:
continue
attrs[v] = value
if not changed:
return attrs
a = {}
[a.__setitem__(p, attrs[p]) for p in props]
return a | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/alias.py/ClassAlias.getDecodableAttributes |
6,080 | def parse_json(self, json):
self.doi = DOI(json.get('URL', None))
self.score = float(json.get('score', 0.))
try:
self.title = self.format_title(json['title'][0])
except (IndexError, KeyError):
self.title = self.UNKNOWN_TITLE
#self.timestamp = float(json['deposited']['timestamp'])/1000.
try:
self.year = int(json['issued']['date-parts'][0][0])
except (TypeError, __HOLE__, IndexError):
self.year = self.UNKNOWN_YEAR
try:
self.authors = self.__format_authors(json['author'])
except KeyError:
self.authors = self.UNKNOWN_AUTHORS
self.type = json.get('type', None)
self.publisher = json.get('publisher', None)
self.url = json.get('URL', None) | KeyError | dataset/ETHPy150Open dotcs/doimgr/lib/search/result.py/SearchResult.parse_json |
6,081 | def endElement(self, name, value, connection):
if name == 'InstanceType':
self.instance_type = value
elif name == 'LaunchConfigurationName':
self.name = value
elif name == 'KeyName':
self.key_name = value
elif name == 'ImageId':
self.image_id = value
elif name == 'CreatedTime':
try:
self.created_time = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ')
except __HOLE__:
self.created_time = datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ')
elif name == 'KernelId':
self.kernel_id = value
elif name == 'RamdiskId':
self.ramdisk_id = value
elif name == 'UserData':
self.user_data = base64.b64decode(value)
elif name == 'LaunchConfigurationARN':
self.launch_configuration_arn = value
elif name == 'InstanceMonitoring':
self.instance_monitoring = value
else:
setattr(self, name, value) | ValueError | dataset/ETHPy150Open radlab/sparrow/deploy/third_party/boto-2.1.1/boto/ec2/autoscale/launchconfig.py/LaunchConfiguration.endElement |
6,082 | def _volume_type_and_iops_for_profile_name(profile_name, size):
"""
Determines and returns the volume_type and iops for a boto create_volume
call for a given profile_name.
:param profile_name: The name of the profile.
:param size: The size of the volume to create in GiB.
:returns: A tuple of (volume_type, iops) to be passed to a create_volume
call.
"""
volume_type = None
iops = None
try:
A = EBSMandatoryProfileAttributes.lookupByName(
MandatoryProfiles.lookupByValue(profile_name).name).value
except __HOLE__:
pass
else:
volume_type = A.volume_type.value
iops = A.requested_iops(size)
return volume_type, iops | ValueError | dataset/ETHPy150Open ClusterHQ/flocker/flocker/node/agents/ebs.py/_volume_type_and_iops_for_profile_name |
6,083 | def _set_environ(self, env, name, value):
if value is self.Unset:
try:
del env[name]
except __HOLE__:
pass
else:
env[name] = value | KeyError | dataset/ETHPy150Open Masood-M/yalih/mechanize/_testcase.py/MonkeyPatcher._set_environ |
6,084 | def instart(cls, name, display_name=None, stay_alive=True):
'''Install and Start (auto) a Service
cls : the class (derived from Service) that implement the Service
name : Service name
display_name : the name displayed in the service manager
stay_alive : Service will stop on logout if False
'''
cls._svc_name_ = name
cls._svc_display_name_ = display_name or name
try:
module_path = modules[cls.__module__].__file__
except __HOLE__:
# maybe py2exe went by
from sys import executable
module_path = executable
module_file = splitext(abspath(module_path))[0]
cls._svc_reg_class_ = '{0}.{1}'.format(module_file, cls.__name__)
if stay_alive:
win32api.SetConsoleCtrlHandler(lambda x: True, True)
try:
win32serviceutil.InstallService(
cls._svc_reg_class_,
cls._svc_name_,
cls._svc_display_name_,
startType=win32service.SERVICE_AUTO_START
)
print('Install ok')
win32serviceutil.StartService(
cls._svc_name_
)
print('Start ok')
except Exception as err:
print(str(err)) | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/utils/winservice.py/instart |
6,085 | def get_connection(path=None, fail_silently=False, **kwargs):
"""
Load an sms backend and return an instance of it.
:param string path: backend python path. Default: sendsms.backends.console.SmsBackend
:param bool fail_silently: Flag to not throw exceptions on error. Default: False
:returns: backend class instance.
:rtype: :py:class:`~sendsms.backends.base.BaseSmsBackend` subclass
"""
path = path or getattr(settings, 'SENDSMS_BACKEND', 'sendsms.backends.locmem.SmsBackend')
try:
mod_name, klass_name = path.rsplit('.', 1)
mod = import_module(mod_name)
except __HOLE__ as e:
raise ImproperlyConfigured(u'Error importing sms backend module %s: "%s"' % (mod_name, e))
try:
klass = getattr(mod, klass_name)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a "%s" class' % (mod_name, klass_name))
return klass(fail_silently=fail_silently, **kwargs) | AttributeError | dataset/ETHPy150Open stefanfoulis/django-sendsms/sendsms/api.py/get_connection |
6,086 | @classmethod
def callable_info(cls, f):
'''Info about a callable.
The results are cached for efficiency.
:param f:
:type f: callable
:rtype: frozendict
'''
if not callable(f):
return None
if isinstance(f, FunctionType):
# in case of ensure_va_kwa
try:
f = f.wrapped_func
except __HOLE__:
pass
cache_key = callable_cache_key(f)
try:
return cls._info_cache[cache_key]
except KeyError:
pass
is_method, args, varargs, varkw, defaults = cls.getargspec(f)
_args = []
args_len = len(args)
defaults_len = 0
if defaults is not None:
defaults_len = len(defaults)
for i,n in enumerate(args):
default_index = i-(args_len-defaults_len)
v = Undefined
if default_index > -1:
v = defaults[default_index]
_args.append((n, v))
info = frozendict({
'name':f.func_name,
'args':tuple(_args),
'varargs':bool(varargs),
'varkw':bool(varkw),
'method':is_method
})
cls._info_cache[cache_key] = info
return info | AttributeError | dataset/ETHPy150Open rsms/smisk/lib/smisk/util/introspect.py/introspect.callable_info |
6,087 | @classmethod
def ensure_va_kwa(cls, f, parent=None):
'''Ensures `f` accepts both ``*varargs`` and ``**kwargs``.
If `f` does not support ``*args``, it will be wrapped with a
function which cuts away extra arguments in ``*args``.
If `f` does not support ``*args``, it will be wrapped with a
function which discards the ``**kwargs``.
:param f:
:type f: callable
:param parent: The parent on which `f` is defined. If specified, we will perform
``parent.<name of f> = wrapper`` in the case we needed to wrap `f`.
:type parent: object
:returns: A callable which is guaranteed to accept both ``*args`` and ``**kwargs``.
:rtype: callable
'''
is_method, args, varargs, varkw, defaults = cls.getargspec(f)
va_kwa_wrapper = None
if varargs is None and varkw is None:
if args:
def va_kwa_wrapper(*va, **kw):
kws = kw.copy()
for k in kw:
if k not in args:
del kws[k]
return f(*va[:len(args)], **kws)
else:
def va_kwa_wrapper(*va, **kw):
return f()
elif varargs is None:
if args:
def va_kwa_wrapper(*va, **kw):
return f(*va[:len(args)], **kw)
else:
def va_kwa_wrapper(*va, **kw):
return f(**kw)
elif varkw is None:
if args:
def va_kwa_wrapper(*va, **kw):
kws = kw.copy()
for k in kw:
if k not in args:
del kws[k]
return f(*va, **kw)
else:
def va_kwa_wrapper(*va, **kw):
return f(*va)
if va_kwa_wrapper:
va_kwa_wrapper.info = frozendict(cls.callable_info(f).update({
'varargs': True,
'varkw': True
}))
cls._info_cache[callable_cache_key(f)] = va_kwa_wrapper.info
va_kwa_wrapper.wrapped_func = f
va_kwa_wrapper.im_func = f
va_kwa_wrapper.__name__ = f.__name__
try:
va_kwa_wrapper.im_class = f.im_class
except __HOLE__:
pass
for k in dir(f):
if k[0] != '_' or k in ('__name__'):
setattr(va_kwa_wrapper, k, getattr(f, k))
if parent is not None:
setattr(parent, info['name'], va_kwa_wrapper)
return va_kwa_wrapper
return f | AttributeError | dataset/ETHPy150Open rsms/smisk/lib/smisk/util/introspect.py/introspect.ensure_va_kwa |
6,088 | def _mk_exception(exception, name=None):
# Create an exception inheriting from both JoblibException
# and that exception
if name is None:
name = exception.__name__
this_name = 'Joblib%s' % name
if this_name in _exception_mapping:
# Avoid creating twice the same exception
this_exception = _exception_mapping[this_name]
else:
if exception is Exception:
# JoblibException is already a subclass of Exception. No
# need to use multiple inheritance
return JoblibException, this_name
try:
this_exception = type(
this_name, (JoblibException, exception), {})
_exception_mapping[this_name] = this_exception
except __HOLE__:
# This happens if "Cannot create a consistent method
# resolution order", e.g. because 'exception' is a
# subclass of JoblibException or 'exception' is not an
# acceptable base class
this_exception = JoblibException
return this_exception, this_name | TypeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/externals/joblib/my_exceptions.py/_mk_exception |
6,089 | def openfile(path, mode="r", *args, **kw):
"""Open file
Aside from the normal modes accepted by `open()`, this function
accepts an `x` mode that causes the file to be opened for exclusive-
write, which means that an exception (`FileExists`) will be raised
if the file being opened already exists.
"""
if "x" not in mode or sys.version_info > (3, 0):
return open(path, mode, *args, **kw)
# http://stackoverflow.com/a/10979569/10840
# O_EXCL is only supported on NFS when using NFSv3 or later on kernel 2.6 or later.
flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
try:
handle = os.open(path, flags)
except __HOLE__ as err:
if err.errno == errno.EEXIST:
raise FileExists(path)
raise
return os.fdopen(handle, mode.replace("x", "w"), *args, **kw) | OSError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/blobs/fsdb.py/openfile |
6,090 | @staticmethod
def parser(config_file):
if not ConfigParser.result:
try:
with open(config_file, 'r') as stream:
cfg = yaml.load(stream)
except __HOLE__:
raise FlashLightExceptions("{0} cannot be opened !!!".format(config_file))
except Exception, err:
raise FlashLightExceptions(str(err))
for section in cfg:
ConfigParser.result[section] = ','.join([ value.strip() for value in ''.join([value for value in cfg[section] ]).split(',') ])
return ConfigParser.result | IOError | dataset/ETHPy150Open galkan/flashlight/lib/core/config_parser.py/ConfigParser.parser |
6,091 | @staticmethod
def get_screen_ports(config_file):
cfg = ConfigParser.parser if ConfigParser.result else ConfigParser.parser(config_file)
try:
return cfg["screen_ports"]
except __HOLE__:
return ConfigParser.default_ports
except:
raise FlashLightExceptions(str(err)) | KeyError | dataset/ETHPy150Open galkan/flashlight/lib/core/config_parser.py/ConfigParser.get_screen_ports |
6,092 | def open(self, path, flags, attr):
path = self.files.normalize(path)
try:
fobj = self.files[path]
except __HOLE__:
if flags & os.O_WRONLY:
# Only allow writes to files in existing directories.
if os.path.dirname(path) not in self.files:
return ssh.SFTP_NO_SUCH_FILE
self.files[path] = fobj = FakeFile("", path)
# No write flag means a read, which means they tried to read a
# nonexistent file.
else:
return ssh.SFTP_NO_SUCH_FILE
f = FakeSFTPHandle()
f.readfile = f.writefile = fobj
return f | KeyError | dataset/ETHPy150Open fabric/fabric/tests/server.py/FakeSFTPServer.open |
6,093 | def stat(self, path):
path = self.files.normalize(path)
try:
fobj = self.files[path]
except __HOLE__:
return ssh.SFTP_NO_SUCH_FILE
return fobj.attributes
# Don't care about links right now | KeyError | dataset/ETHPy150Open fabric/fabric/tests/server.py/FakeSFTPServer.stat |
6,094 | def logEI_gaussian(mean, var, thresh):
"""Return log(EI(mean, var, thresh))
This formula avoids underflow in cdf for
thresh >= mean + 37 * sqrt(var)
"""
assert np.asarray(var).min() >= 0
sigma = np.sqrt(var)
score = (mean - thresh) / sigma
n = scipy.stats.norm
try:
float(mean)
is_scalar = True
except __HOLE__:
is_scalar = False
if is_scalar:
if score < 0:
pdf = n.logpdf(score)
r = np.exp(np.log(-score) + n.logcdf(score) - pdf)
rval = np.log(sigma) + pdf + np.log1p(-r)
if not np.isfinite(rval):
return -np.inf
else:
return rval
else:
return np.log(sigma) + np.log(score * n.cdf(score) + n.pdf(score))
else:
score = np.asarray(score)
rval = np.zeros_like(score)
olderr = np.seterr(all='ignore')
try:
negs = score < 0
nonnegs = np.logical_not(negs)
negs_score = score[negs]
negs_pdf = n.logpdf(negs_score)
r = np.exp(np.log(-negs_score)
+ n.logcdf(negs_score)
- negs_pdf)
rval[negs] = np.log(sigma[negs]) + negs_pdf + np.log1p(-r)
nonnegs_score = score[nonnegs]
rval[nonnegs] = np.log(sigma[nonnegs]) + np.log(
nonnegs_score * n.cdf(nonnegs_score) + n.pdf(nonnegs_score))
rval[np.logical_not(np.isfinite(rval))] = -np.inf
finally:
np.seterr(**olderr)
return rval | TypeError | dataset/ETHPy150Open hyperopt/hyperopt/hyperopt/criteria.py/logEI_gaussian |
6,095 | def _validate_property_values(self, properties):
"""Check if the input of local_gb, cpus and memory_mb are valid.
:param properties: a dict contains the node's information.
"""
if not properties:
return
invalid_msgs_list = []
for param in REQUIRED_INT_PROPERTIES:
value = properties.get(param)
if value is None:
continue
try:
int_value = int(value)
assert int_value >= 0
except (ValueError, __HOLE__):
msg = (('%(param)s=%(value)s') %
{'param': param, 'value': value})
invalid_msgs_list.append(msg)
if invalid_msgs_list:
msg = (_('The following properties for node %(node)s '
'should be non-negative integers, '
'but provided values are: %(msgs)s') %
{'node': self.uuid, 'msgs': ', '.join(invalid_msgs_list)})
raise exception.InvalidParameterValue(msg)
# NOTE(xek): We don't want to enable RPC on this call just yet. Remotable
# methods can be used in the future to replace current explicit RPC calls.
# Implications of calling new remote procedures should be thought through.
# @object_base.remotable_classmethod | AssertionError | dataset/ETHPy150Open openstack/ironic/ironic/objects/node.py/Node._validate_property_values |
6,096 | @utils.synchronized('connect_volume')
def connect_volume(self, connection_info, disk_info):
"""Connect the volume."""
data = connection_info['data']
quobyte_volume = self._normalize_export(data['export'])
mount_path = self._get_mount_path(connection_info)
mounted = libvirt_utils.is_mounted(mount_path,
SOURCE_PROTOCOL
+ '@' + quobyte_volume)
if mounted:
try:
os.stat(mount_path)
except __HOLE__ as exc:
if exc.errno == errno.ENOTCONN:
mounted = False
LOG.info(_LI('Fixing previous mount %s which was not'
' unmounted correctly.'), mount_path)
umount_volume(mount_path)
if not mounted:
mount_volume(quobyte_volume,
mount_path,
CONF.libvirt.quobyte_client_cfg)
validate_volume(mount_path) | OSError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/libvirt/volume/quobyte.py/LibvirtQuobyteVolumeDriver.connect_volume |
6,097 | def short(self, url):
params = json.dumps({'longUrl': url})
headers = {'content-type': 'application/json'}
url = '{0}?key={1}'.format(self.api_url, self.api_key)
response = self._post(url, data=params, headers=headers)
if response.ok:
try:
data = response.json()
except __HOLE__ as e:
raise ShorteningErrorException('There was an error shortening'
' this url - {0}'.format(e))
if 'id' in data:
return data['id']
raise ShorteningErrorException('There was an error shortening this '
'url - {0}'.format(response.content)) | ValueError | dataset/ETHPy150Open ellisonleao/pyshorteners/pyshorteners/shorteners/googl.py/Google.short |
6,098 | def expand(self, url):
params = {'shortUrl': url}
url = '{0}?key={1}'.format(self.api_url, self.api_key)
response = self._get(url, params=params)
if response.ok:
try:
data = response.json()
except __HOLE__:
raise ExpandingErrorException('There was an error expanding'
' this url - {0}'.format(
response.content))
if 'longUrl' in data:
return data['longUrl']
raise ExpandingErrorException('There was an error expanding '
'this url - {0}'.format(
response.content)) | ValueError | dataset/ETHPy150Open ellisonleao/pyshorteners/pyshorteners/shorteners/googl.py/Google.expand |
6,099 | def get_cache_stats():
"""Return a dictionary containing information on the current cache stats.
This only supports memcache.
"""
hostnames = get_memcached_hosts()
if not hostnames:
return None
all_stats = []
for hostname in hostnames:
try:
host, port = hostname.split(":")
if host == 'unix':
socket_af = socket.AF_UNIX
connect_param = port
else:
socket_af = socket.AF_INET
connect_param = (host, int(port))
except ValueError:
logging.error('Invalid cache hostname "%s"' % hostname)
continue
s = socket.socket(socket_af, socket.SOCK_STREAM)
try:
s.connect(connect_param)
except socket.error:
s.close()
continue
s.send(b"stats\r\n")
data = s.recv(2048).decode('ascii')
s.close()
stats = {}
for line in data.splitlines():
info = line.split(" ")
if info[0] == "STAT":
try:
value = int(info[2])
except __HOLE__:
value = info[2]
stats[info[1]] = value
if stats['cmd_get'] == 0:
stats['hit_rate'] = 0
stats['miss_rate'] = 0
else:
stats['hit_rate'] = 100 * stats['get_hits'] / stats['cmd_get']
stats['miss_rate'] = 100 * stats['get_misses'] / stats['cmd_get']
all_stats.append((hostname, stats))
return all_stats | ValueError | dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/admin/cache_stats.py/get_cache_stats |
Subsets and Splits