Unnamed: 0
int64 0
10k
| function
stringlengths 79
138k
| label
stringclasses 20
values | info
stringlengths 42
261
|
|---|---|---|---|
0
|
def __get__(self, instance, instance_type=None):
if instance is None:
return self
cache_name = self.field.get_cache_name()
try:
return getattr(instance, cache_name)
except __HOLE__:
val = getattr(instance, self.field.attname)
if val is None:
# If NULL is an allowed value, return it.
if self.field.null:
return None
raise self.field.rel.to.DoesNotExist
other_field = self.field.rel.get_related_field()
if other_field.rel:
params = {'%s__pk' % self.field.rel.field_name: val}
else:
params = {'%s__exact' % self.field.rel.field_name: val}
# If the related manager indicates that it should be used for
# related fields, respect that.
rel_mgr = self.field.rel.to._default_manager
if getattr(rel_mgr, 'use_for_related_fields', False):
rel_obj = rel_mgr.get(**params)
else:
rel_obj = QuerySet(self.field.rel.to).get(**params)
setattr(instance, cache_name, rel_obj)
return rel_obj
|
AttributeError
|
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/fields/related.py/ReverseSingleRelatedObjectDescriptor.__get__
|
1
|
def __set__(self, instance, value):
if instance is None:
raise AttributeError, "%s must be accessed via instance" % self._field.name
# If null=True, we can assign null here, but otherwise the value needs
# to be an instance of the related class.
if value is None and self.field.null == False:
raise ValueError('Cannot assign None: "%s.%s" does not allow null values.' %
(instance._meta.object_name, self.field.name))
elif value is not None and not isinstance(value, self.field.rel.to):
raise ValueError('Cannot assign "%r": "%s.%s" must be a "%s" instance.' %
(value, instance._meta.object_name,
self.field.name, self.field.rel.to._meta.object_name))
# If we're setting the value of a OneToOneField to None, we need to clear
# out the cache on any old related object. Otherwise, deleting the
# previously-related object will also cause this object to be deleted,
# which is wrong.
if value is None:
# Look up the previously-related object, which may still be available
# since we've not yet cleared out the related field.
# Use the cache directly, instead of the accessor; if we haven't
# populated the cache, then we don't care - we're only accessing
# the object to invalidate the accessor cache, so there's no
# need to populate the cache just to expire it again.
related = getattr(instance, self.field.get_cache_name(), None)
# If we've got an old related object, we need to clear out its
# cache. This cache also might not exist if the related object
# hasn't been accessed yet.
if related:
cache_name = '_%s_cache' % self.field.related.get_accessor_name()
try:
delattr(related, cache_name)
except AttributeError:
pass
# Set the value of the related field
try:
val = getattr(value, self.field.rel.get_related_field().attname)
except __HOLE__:
val = None
setattr(instance, self.field.attname, val)
# Since we already know what the related object is, seed the related
# object cache now, too. This avoids another db hit if you get the
# object you just set.
setattr(instance, self.field.get_cache_name(), value)
|
AttributeError
|
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/fields/related.py/ReverseSingleRelatedObjectDescriptor.__set__
|
2
|
def __init__(self, to, field_name, related_name=None,
limit_choices_to=None, lookup_overrides=None, parent_link=False):
try:
to._meta
except __HOLE__: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT
assert isinstance(to, basestring), "'to' must be either a model, a model name or the string %r" % RECURSIVE_RELATIONSHIP_CONSTANT
self.to, self.field_name = to, field_name
self.related_name = related_name
if limit_choices_to is None:
limit_choices_to = {}
self.limit_choices_to = limit_choices_to
self.lookup_overrides = lookup_overrides or {}
self.multiple = True
self.parent_link = parent_link
|
AttributeError
|
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/fields/related.py/ManyToOneRel.__init__
|
3
|
def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs):
try:
to_name = to._meta.object_name.lower()
except __HOLE__: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT
assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
else:
assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name)
to_field = to_field or to._meta.pk.name
kwargs['verbose_name'] = kwargs.get('verbose_name', None)
kwargs['rel'] = rel_class(to, to_field,
related_name=kwargs.pop('related_name', None),
limit_choices_to=kwargs.pop('limit_choices_to', None),
lookup_overrides=kwargs.pop('lookup_overrides', None),
parent_link=kwargs.pop('parent_link', False))
Field.__init__(self, **kwargs)
self.db_index = True
|
AttributeError
|
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/fields/related.py/ForeignKey.__init__
|
4
|
def __init__(self, to, **kwargs):
try:
assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name)
except __HOLE__: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT
assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
kwargs['verbose_name'] = kwargs.get('verbose_name', None)
kwargs['rel'] = ManyToManyRel(to,
related_name=kwargs.pop('related_name', None),
limit_choices_to=kwargs.pop('limit_choices_to', None),
symmetrical=kwargs.pop('symmetrical', True),
through=kwargs.pop('through', None))
self.db_table = kwargs.pop('db_table', None)
if kwargs['rel'].through is not None:
self.creates_table = False
assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used."
else:
self.creates_table = True
Field.__init__(self, **kwargs)
msg = ugettext_lazy('Hold down "Control", or "Command" on a Mac, to select more than one.')
self.help_text = string_concat(self.help_text, ' ', msg)
|
AttributeError
|
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/fields/related.py/ManyToManyField.__init__
|
5
|
def isValidIDList(self, field_data, all_data):
"Validates that the value is a valid list of foreign keys"
mod = self.rel.to
try:
pks = map(int, field_data.split(','))
except __HOLE__:
# the CommaSeparatedIntegerField validator will catch this error
return
objects = mod._default_manager.in_bulk(pks)
if len(objects) != len(pks):
badkeys = [k for k in pks if k not in objects]
raise exceptions.ValidationError(
ungettext("Please enter valid %(self)s IDs. The value %(value)r is invalid.",
"Please enter valid %(self)s IDs. The values %(value)r are invalid.",
len(badkeys)) % {
'self': self.verbose_name,
'value': len(badkeys) == 1 and badkeys[0] or tuple(badkeys),
})
|
ValueError
|
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/fields/related.py/ManyToManyField.isValidIDList
|
6
|
def contextMenu(self):
try:
return self.menu
except __HOLE__:
self.menu = Menu( self.viewFrame, tearoff = 0 )
return self.menu
|
AttributeError
|
dataset/ETHPy150Open Arelle/Arelle/arelle/ViewWinPane.py/ViewPane.contextMenu
|
7
|
def credentials_required(view_func):
"""
This decorator should be used with views that need simple authentication
against Django's authentication framework.
"""
@wraps(view_func, assigned=available_attrs(view_func))
def decorator(request, *args, **kwargs):
if settings.LOCALSHOP_USE_PROXIED_IP:
try:
ip_addr = request.META['HTTP_X_FORWARDED_FOR']
except __HOLE__:
return HttpResponseForbidden('No permission')
else:
# HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs.
# The client's IP will be the first one.
ip_addr = ip_addr.split(",")[0].strip()
else:
ip_addr = request.META['REMOTE_ADDR']
if CIDR.objects.has_access(ip_addr, with_credentials=False):
return view_func(request, *args, **kwargs)
if not CIDR.objects.has_access(ip_addr, with_credentials=True):
return HttpResponseForbidden('No permission')
# Just return the original view because already logged in
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
user = authenticate_user(request)
if user is not None:
login(request, user)
return view_func(request, *args, **kwargs)
return HttpResponseUnauthorized(content='Authorization Required')
return decorator
|
KeyError
|
dataset/ETHPy150Open mvantellingen/localshop/localshop/apps/permissions/utils.py/credentials_required
|
8
|
def picklers():
picklers = set()
if py2k:
try:
import cPickle
picklers.add(cPickle)
except __HOLE__:
pass
import pickle
picklers.add(pickle)
# yes, this thing needs this much testing
for pickle_ in picklers:
for protocol in -1, 0, 1, 2:
yield pickle_.loads, lambda d: pickle_.dumps(d, protocol)
|
ImportError
|
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/testing/util.py/picklers
|
9
|
def function_named(fn, name):
"""Return a function with a given __name__.
Will assign to __name__ and return the original function if possible on
the Python implementation, otherwise a new function will be constructed.
This function should be phased out as much as possible
in favor of @decorator. Tests that "generate" many named tests
should be modernized.
"""
try:
fn.__name__ = name
except __HOLE__:
fn = types.FunctionType(fn.__code__, fn.__globals__, name,
fn.__defaults__, fn.__closure__)
return fn
|
TypeError
|
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/testing/util.py/function_named
|
10
|
def __getattribute__(self, key):
try:
return self[key]
except __HOLE__:
return dict.__getattribute__(self, key)
|
KeyError
|
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/testing/util.py/adict.__getattribute__
|
11
|
def compute(self):
""" compute() -> None
Dispatch the HTML contents to the spreadsheet
"""
filename = self.get_input("File").name
text_format = self.get_input("Format")
with open(filename, 'rb') as fp:
if text_format == 'html':
html = fp.read() # reads bytes
elif text_format == 'rtf':
try:
py_import('pyth', {'pip': 'pyth'})
except __HOLE__:
raise ModuleError(self, "'rtf' format requires the pyth "
"Python library")
else:
from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter
doc = Rtf15Reader.read(fp)
html = XHTMLWriter.write(doc).read() # gets bytes
else:
raise ModuleError(self, "'%s' format is unknown" % text_format)
self.displayAndWait(RichTextCellWidget, (html,))
|
ImportError
|
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/spreadsheet/widgets/richtext/richtext.py/RichTextCell.compute
|
12
|
def make_request(request, permission, permittee, target_obj_or_class,
redirect_to=None):
"""When a permission is missing allow user to request a role.
Show the user a list of roles that have the missing permission, and
allow her to request the permission from a user who can give that role.
@see: L{ExpedientPermission} for information about permission redirection.
"""
if permittee != request.user:
raise PermissionDenied
assert(isinstance(permittee, User))
try:
done_url = request.session["breadcrumbs"][-1][1]
except __HOLE__:
done_url = reverse("home")
# get all the roles that have this permission
roles = ProjectRole.objects.filter_for_permission(
permission.name, target_obj_or_class)
if not roles:
return simple.direct_to_template(
request,
template=TEMPLATE_PATH+"/no_permission.html",
extra_context={
"cancel_url": done_url,
"target": target_obj_or_class,
}
)
# for each role get the users that can delegate it
roles_to_users = {}
for r in roles:
givers = get_users_for_role(r, can_delegate=True)
roles_to_users[r.id] = givers
if request.method == "POST":
req = ProjectRoleRequest(requester=request.user)
form = SelectRoleForm(
roles, roles_to_users, request.POST, instance=req)
if form.is_valid():
req = form.save()
DatedMessage.objects.post_message_to_user(
"Request for '%s' role in project '%s' sent to user '%s'"
% (req.requested_role.name,
req.requested_role.project,
req.giver.username),
user=request.user,
msg_type=DatedMessage.TYPE_SUCCESS)
return HttpResponseRedirect(done_url)
else:
form = SelectRoleForm(
roles, roles_to_users)
return simple.direct_to_template(
request,
template=TEMPLATE_PATH+"/make_request.html",
extra_context={
"cancel_url": done_url,
"form": form,
"target": target_obj_or_class,
}
)
|
IndexError
|
dataset/ETHPy150Open fp7-ofelia/ocf/expedient/src/python/expedient/clearinghouse/roles/views.py/make_request
|
13
|
def _get_payload(p):
try:
if isinstance(p, list):
return p
else:
return payloads[p]
except __HOLE__:
raise PayloadNotFound("Possible values are: " + ", ".join(payloads.keys()))
|
KeyError
|
dataset/ETHPy150Open securusglobal/abrupt/abrupt/injection.py/_get_payload
|
14
|
def _inject_json(r, value, pds, pre_func):
rs = []
try:
x = json.loads(r.content)
except (__HOLE__, TypeError):
return rs
if x.has_key(value):
n_json = x.copy()
for p in pds:
n_json[value] = pre_func(p)
r_new = r.copy()
r_new.raw_content = json.dumps(n_json)
r_new.content = r_new.raw_content
r_new.injection_point = value
r_new.payload = p
r_new.update_content_length()
rs.append(r_new)
return rs
|
ValueError
|
dataset/ETHPy150Open securusglobal/abrupt/abrupt/injection.py/_inject_json
|
15
|
def find_injection_points(r):
"""Find valid injection points.
This functions returns the injection points that could
be used by i().
"""
ips = []
if r.query:
i_pts = parse_qs(r.query)
if i_pts:
ips.extend(i_pts)
if r.content:
i_pts = parse_qs(r.content)
if i_pts:
ips.extend(i_pts)
if r.cookies:
i_pts = [ c.name for c in r.cookies]
if i_pts:
ips.extend(i_pts)
try:
i_pts = json.loads(r.content)
ips.extend(i_pts.keys())
except (__HOLE__,TypeError):
pass
return ips
|
ValueError
|
dataset/ETHPy150Open securusglobal/abrupt/abrupt/injection.py/find_injection_points
|
16
|
def get_ipv6_addr_by_EUI64(prefix, mac):
# Check if the prefix is IPv4 address
isIPv4 = netaddr.valid_ipv4(prefix)
if isIPv4:
msg = _("Unable to generate IP address by EUI64 for IPv4 prefix")
raise TypeError(msg)
try:
eui64 = int(netaddr.EUI(mac).eui64())
prefix = netaddr.IPNetwork(prefix)
return netaddr.IPAddress(prefix.first + eui64 ^ (1 << 57))
except (ValueError, netaddr.AddrFormatError):
raise TypeError(_('Bad prefix or mac format for generating IPv6 '
'address by EUI-64: %(prefix)s, %(mac)s:')
% {'prefix': prefix, 'mac': mac})
except __HOLE__:
raise TypeError(_('Bad prefix type for generate IPv6 address by '
'EUI-64: %s') % prefix)
|
TypeError
|
dataset/ETHPy150Open openstack/neutron/neutron/common/ipv6_utils.py/get_ipv6_addr_by_EUI64
|
17
|
def test_streaming_dtor(self):
# Ensure that the internal lcb_http_request_t is destroyed if the
# Python object is destroyed before the results are done.
ret = self.cb.query("beer", "brewery_beers", streaming=True)
v = iter(ret)
try:
v.next()
except __HOLE__:
v.__next__()
del ret
|
AttributeError
|
dataset/ETHPy150Open couchbase/couchbase-python-client/couchbase/tests/cases/view_iterator_t.py/ViewIteratorTest.test_streaming_dtor
|
18
|
def listdir_with_changed_status(self, d):
"""
Lists contents of a dir, but only using its realpath.
Returns tuple ([array of entries],changed)
Changed is only True if the current directory changed. Will not change if the child directory changes.
"""
if d in self.dirs:
de = self.dirs[d]
try:
st_mtime = os.stat(d).st_mtime
except OSError:
st_mtime = 0
del self.dirs[d]
return ([], True)
if st_mtime == de.st_mtime:
return (de.ents, False)
else:
cur_ents = self.dirs[d].ents
del self.dirs[d]
new_ents = self.listdir_with_changed_status(d)[0]
changed = set(new_ents) != set(cur_ents)
return (new_ents, changed)
else:
# directory is not in cache...
try:
st = os.stat(d)
st_mtime = st.st_mtime
ents = os.listdir(d)
except __HOLE__:
return ([], False)
ents = [e for e in ents if not self.is_ignored(e, os.path.join(d, e))]
de = DirEnt(st_mtime, ents)
self.dirs[d] = de
return (de.ents, True)
|
OSError
|
dataset/ETHPy150Open natduca/quickopen/src/dir_cache.py/DirCache.listdir_with_changed_status
|
19
|
def parse(date_str, inclusive=False, default_hour=None, default_minute=None):
"""Parses a string containing a fuzzy date and returns a datetime.datetime object"""
if not date_str:
return None
elif isinstance(date_str, datetime):
return date_str
default_date = DEFAULT_FUTURE if inclusive else DEFAULT_PAST
date = None
year_present = False
while not date:
try:
date = dateparse(date_str, default=default_date)
if date.year == FAKE_YEAR:
date = datetime(datetime.now().year, date.timetuple()[1:6])
else:
year_present = True
flag = 1 if date.hour == date.minute == 0 else 2
date = date.timetuple()
except Exception as e:
if e.args[0] == 'day is out of range for month':
y, m, d, H, M, S = default_date.timetuple()[:6]
default_date = datetime(y, m, d - 1, H, M, S)
else:
date, flag = CALENDAR.parse(date_str)
if not flag: # Oops, unparsable.
try: # Try and parse this as a single year
year = int(date_str)
return datetime(year, 1, 1)
except __HOLE__:
return None
except TypeError:
return None
if flag is 1: # Date found, but no time. Use the default time.
date = datetime(*date[:3],
hour=23 if inclusive else default_hour or 0,
minute=59 if inclusive else default_minute or 0,
second=59 if inclusive else 0)
else:
date = datetime(*date[:6])
# Ugly heuristic: if the date is more than 4 weeks in the future, we got the year wrong.
# Rather then this, we would like to see parsedatetime patched so we can tell it to prefer
# past dates
dt = datetime.now() - date
if dt.days < -28 and not year_present:
date = date.replace(date.year - 1)
return date
|
ValueError
|
dataset/ETHPy150Open maebert/jrnl/jrnl/time.py/parse
|
20
|
def getTableInfo(self, rowObject):
"""Get a TableInfo record about a particular instance.
This record contains various information about the instance's
class as registered with this reflector.
@param rowObject: a L{RowObject} instance of a class previously
registered with me.
@raises twisted.enterprise.row.DBError: raised if this class was not
previously registered.
"""
try:
return self.schema[rowObject.rowTableName]
except __HOLE__:
raise DBError("class %s was not registered with %s" % (
rowObject.__class__, self))
|
KeyError
|
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/enterprise/reflector.py/Reflector.getTableInfo
|
21
|
@view_config(request_param='__formid__=login')
def login(self):
try:
json_body = self.request.json_body
except __HOLE__ as err:
raise accounts.JSONError(
_('Could not parse request body as JSON: {message}'.format(
message=err.message)))
if not isinstance(json_body, dict):
raise accounts.JSONError(
_('Request JSON body must have a top-level object'))
# Transform non-string usernames and password into strings.
# Deform crashes otherwise.
json_body['username'] = unicode(json_body.get('username') or '')
json_body['password'] = unicode(json_body.get('password') or '')
appstruct = self.form.validate(json_body.items())
user = appstruct['user']
headers = self._login(user)
self.request.response.headers.extend(headers)
return ajax_payload(self.request, {'status': 'okay'})
|
ValueError
|
dataset/ETHPy150Open hypothesis/h/h/accounts/views.py/AjaxAuthController.login
|
22
|
@view_config(request_method='GET')
def get_when_not_logged_in(self):
"""
Handle a request for a user activation link.
Checks if the activation code passed is valid, and (as a safety check)
that it is an activation for the passed user id. If all is well,
activate the user and redirect them to the stream.
"""
code = self.request.matchdict.get('code')
id_ = self.request.matchdict.get('id')
try:
id_ = int(id_)
except __HOLE__:
raise httpexceptions.HTTPNotFound()
activation = Activation.get_by_code(code)
if activation is None:
self.request.session.flash(jinja2.Markup(_(
"We didn't recognize that activation link. "
"Perhaps you've already activated your account? "
'If so, try <a href="{url}">signing in</a> using the username '
'and password that you provided.').format(
url=self.request.route_url('login'))),
'error')
return httpexceptions.HTTPFound(
location=self.request.route_url('index'))
user = User.get_by_activation(activation)
if user is None or user.id != id_:
raise httpexceptions.HTTPNotFound()
user.activate()
self.request.session.flash(jinja2.Markup(_(
'Your account has been activated! '
'You can now <a href="{url}">sign in</a> using the password you '
'provided.').format(url=self.request.route_url('login'))),
'success')
self.request.registry.notify(ActivationEvent(self.request, user))
return httpexceptions.HTTPFound(
location=self.request.route_url('index'))
|
ValueError
|
dataset/ETHPy150Open hypothesis/h/h/accounts/views.py/ActivateController.get_when_not_logged_in
|
23
|
@view_config(request_method='GET',
effective_principals=security.Authenticated)
def get_when_logged_in(self):
"""Handle an activation link request while already logged in."""
id_ = self.request.matchdict.get('id')
try:
id_ = int(id_)
except __HOLE__:
raise httpexceptions.HTTPNotFound()
if id_ == self.request.authenticated_user.id:
# The user is already signed in to the account (so the account
# must already be activated).
self.request.session.flash(jinja2.Markup(_(
"Your account has been activated and you're now signed "
"in!")), 'success')
else:
self.request.session.flash(jinja2.Markup(_(
"You're already signed in to a different account. "
'<a href="{url}">Sign out</a> then try opening the '
'activation link again.').format(
url=self.request.route_url('logout'))),
'error')
return httpexceptions.HTTPFound(
location=self.request.route_url('index'))
|
ValueError
|
dataset/ETHPy150Open hypothesis/h/h/accounts/views.py/ActivateController.get_when_logged_in
|
24
|
def TestNodeListDrbd(node, is_drbd):
"""gnt-node list-drbd"""
master = qa_config.GetMasterNode()
result_output = GetCommandOutput(master.primary,
"gnt-node list-drbd --no-header %s" %
node.primary)
# Meaningful to note: there is but one instance, and the node is either the
# primary or one of the secondaries
if is_drbd:
# Invoked for both primary and secondary
per_disk_info = result_output.splitlines()
for line in per_disk_info:
try:
drbd_node, _, _, _, _, drbd_peer = line.split()
except __HOLE__:
raise qa_error.Error("Could not examine list-drbd output: expected a"
" single row of 6 entries, found the following:"
" %s" % line)
AssertIn(node.primary, [drbd_node, drbd_peer],
msg="The output %s does not contain the node" % line)
else:
# Output should be empty, barring newlines
AssertEqual(result_output.strip(), "")
|
ValueError
|
dataset/ETHPy150Open ganeti/ganeti/qa/qa_node.py/TestNodeListDrbd
|
25
|
def convert(self, argval):
'''
Given an argument to --filter of the form "<name>=<value>", convert
the value to the appropriate type by calling self.type on it, then
return a (name, converted_value) tuple. If the value's type conversion
doesn't work then an ArgumentTypeError will result. If the conversion
succeeds but does not appear in self.choices when it exists, an
ArgumentTypeError will result as well.
'''
if '=' not in argval:
msg = "filter '{0}' must have format 'NAME=VALUE'".format(argval)
raise argparse.ArgumentTypeError(msg)
(name, value_str) = argval.split('=', 1)
try:
value = self.type(value_str)
except __HOLE__:
msg = "{0} filter value '{1}' must have type {2}".format(
name, value_str, self.type.__name__)
raise argparse.ArgumentTypeError(msg)
if self.choices and value not in self.choices:
msg = "{0} filter value '{1}' must match one of {2}".format(
name, value,
', '.join([str(choice) for choice in self.choices]))
raise argparse.ArgumentTypeError(msg)
if value == '':
value = EMPTY
return (name, value)
|
ValueError
|
dataset/ETHPy150Open boto/requestbuilder/requestbuilder/__init__.py/Filter.convert
|
26
|
def test_discrete_basic():
for distname, arg in distdiscrete:
try:
distfn = getattr(stats, distname)
except __HOLE__:
distfn = distname
distname = 'sample distribution'
np.random.seed(9765456)
rvs = distfn.rvs(size=2000, *arg)
supp = np.unique(rvs)
m, v = distfn.stats(*arg)
yield check_cdf_ppf, distfn, arg, supp, distname + ' cdf_ppf'
yield check_pmf_cdf, distfn, arg, distname
yield check_oth, distfn, arg, supp, distname + ' oth'
yield check_edge_support, distfn, arg
alpha = 0.01
yield (check_discrete_chisquare, distfn, arg, rvs, alpha,
distname + ' chisquare')
seen = set()
for distname, arg in distdiscrete:
if distname in seen:
continue
seen.add(distname)
try:
distfn = getattr(stats, distname)
except TypeError:
distfn = distname
distname = 'sample distribution'
locscale_defaults = (0,)
meths = [distfn.pmf, distfn.logpmf, distfn.cdf, distfn.logcdf,
distfn.logsf]
# make sure arguments are within support
spec_k = {'randint': 11, 'hypergeom': 4, 'bernoulli': 0, }
k = spec_k.get(distname, 1)
yield check_named_args, distfn, k, arg, locscale_defaults, meths
if distname != 'sample distribution':
yield check_scale_docstring, distfn
yield check_random_state_property, distfn, arg
yield check_pickling, distfn, arg
# Entropy
yield check_entropy, distfn, arg, distname
if distfn.__class__._entropy != stats.rv_discrete._entropy:
yield check_private_entropy, distfn, arg, stats.rv_discrete
|
TypeError
|
dataset/ETHPy150Open scipy/scipy/scipy/stats/tests/test_discrete_basic.py/test_discrete_basic
|
27
|
def test_moments():
for distname, arg in distdiscrete:
try:
distfn = getattr(stats, distname)
except __HOLE__:
distfn = distname
distname = 'sample distribution'
m, v, s, k = distfn.stats(*arg, moments='mvsk')
yield check_normalization, distfn, arg, distname
# compare `stats` and `moment` methods
yield check_moment, distfn, arg, m, v, distname
yield check_mean_expect, distfn, arg, m, distname
yield check_var_expect, distfn, arg, m, v, distname
yield check_skew_expect, distfn, arg, m, v, s, distname
cond = distname in ['zipf']
msg = distname + ' fails kurtosis'
yield knf(cond, msg)(check_kurt_expect), distfn, arg, m, v, k, distname
# frozen distr moments
yield check_moment_frozen, distfn, arg, m, 1
yield check_moment_frozen, distfn, arg, v+m*m, 2
|
TypeError
|
dataset/ETHPy150Open scipy/scipy/scipy/stats/tests/test_discrete_basic.py/test_moments
|
28
|
def _initialize():
global _initialized
def _init_simplejson():
global _decode, _encode
import simplejson
_decode = lambda string, loads=simplejson.loads: loads(string)
_encode = lambda obj, dumps=simplejson.dumps: \
dumps(obj, allow_nan=False, ensure_ascii=False)
def _init_cjson():
global _decode, _encode
import cjson
_decode = lambda string, decode=cjson.decode: decode(string)
_encode = lambda obj, encode=cjson.encode: encode(obj)
def _init_stdlib():
global _decode, _encode
json = __import__('json', {}, {})
_decode = lambda string, loads=json.loads: loads(string)
_encode = lambda obj, dumps=json.dumps: \
dumps(obj, allow_nan=False, ensure_ascii=False)
if _using == 'simplejson':
_init_simplejson()
elif _using == 'cjson':
_init_cjson()
elif _using == 'json':
_init_stdlib()
elif _using != 'custom':
try:
_init_simplejson()
except __HOLE__:
_init_stdlib()
_initialized = True
|
ImportError
|
dataset/ETHPy150Open RDFLib/rdfextras/rdfextras/sparql/results/jsonlayer.py/_initialize
|
29
|
def _doctest_setup():
try:
os.remove("/tmp/open_atomic-example.txt")
except __HOLE__:
pass
|
OSError
|
dataset/ETHPy150Open shazow/unstdlib.py/unstdlib/standard/contextlib_.py/_doctest_setup
|
30
|
def abort(self):
try:
if os.name == "nt":
# Note: Windows can't remove an open file, so sacrifice some
# safety and close it before deleting it here. This is only a
# problem if ``.close()`` raises an exception, which it really
# shouldn't... But it's probably a better idea to be safe.
self.file.close()
os.remove(self.temp_name)
except __HOLE__ as e:
self.abort_error = e
self.file.close()
self.closed = True
self.aborted = True
|
OSError
|
dataset/ETHPy150Open shazow/unstdlib.py/unstdlib/standard/contextlib_.py/open_atomic.abort
|
31
|
def _generate_items(self, df, columns):
"""Produce list of unique tuples that identify each item."""
if self.sort:
# TODO (fpliger): this handles pandas API change so users do not experience
# the related annoying deprecation warning. This is probably worth
# removing when pandas deprecated version (0.16) is "old" enough
try:
df = df.sort_values(by=columns, ascending=self.ascending)
except __HOLE__:
df = df.sort(columns=columns, ascending=self.ascending)
items = df[columns].drop_duplicates()
self.items = [tuple(x) for x in items.to_records(index=False)]
|
AttributeError
|
dataset/ETHPy150Open bokeh/bokeh/bokeh/charts/attributes.py/AttrSpec._generate_items
|
32
|
def pathexpr(expr):
if not isinstance(expr, unicode):
expr = unicode(expr)
try:
return expression_cache[expr]
except __HOLE__:
compiled = PathExpression(expr)
if len(expression_cache) < max_cache_size:
return expression_cache.setdefault(expr, compiled)
else:
return compile
|
KeyError
|
dataset/ETHPy150Open jek/flatland/flatland/schema/paths.py/pathexpr
|
33
|
def __call__(self, element, strict=False):
found = []
contexts = [(self.ops, element)]
for _ops, el in contexts:
for idx in xrange(len(_ops)):
op, data = _ops[idx]
if op is TOP:
el = el.root
elif op is UP:
if el.parent:
el = el.parent
elif op is NAME:
try:
el = el._index(data)
except (LookupError, __HOLE__):
if strict:
if el.name:
type_ = '%s element %r' % (
el.__class__.__name__, el.name)
else:
type_ = 'Unnamed element %s' % (
el.__class__.__name__)
raise LookupError(
"%s has no child %r in expression %r" % (
type_, data, self.expr))
break
elif op is SLICE:
children = list(el.children)[data]
contexts.extend((_ops[idx + 1:], child)
for child in children)
break
else:
found.append(el)
return found
|
TypeError
|
dataset/ETHPy150Open jek/flatland/flatland/schema/paths.py/PathExpression.__call__
|
34
|
def test_describe_errors_unlock_describe_ring(self):
num_nodes = 5
pool_size = 10
with self.cluster_and_pool(num_nodes=num_nodes, pool_size=pool_size):
conn = list(self.pool.connectors)[0]
def exec_raises(x, y=None):
import time
time.sleep(1)
raise ValueError("Bad things.")
try:
conn.execute = exec_raises
x = conn.my_describe_ring()
self.assertTrue(self.pool.describing_ring)
yield x
self.assertTrue(False, "Expected exception.")
except __HOLE__, e:
self.assertFalse(self.pool.describing_ring)
|
ValueError
|
dataset/ETHPy150Open driftx/Telephus/test/test_cassandraclusterpool.py/CassandraClusterPoolTest.test_describe_errors_unlock_describe_ring
|
35
|
def get_meta_fields(model):
try:
fields = model._meta.sorted_fields
except __HOLE__:
fields = model._meta.get_fields()
return fields
|
AttributeError
|
dataset/ETHPy150Open flask-admin/flask-admin/flask_admin/contrib/peewee/tools.py/get_meta_fields
|
36
|
def polygon_observer(population, num_generations, num_evaluations, args):
try:
canvas = args['canvas']
except __HOLE__:
canvas = Canvas(Tk(), bg='white', height=400, width=400)
args['canvas'] = canvas
# Get the best polygon in the population.
poly = population[0].candidate
coords = [(100*x + 200, -100*y + 200) for (x, y) in poly]
old_polys = canvas.find_withtag('poly')
for p in old_polys:
canvas.delete(p)
old_rects = canvas.find_withtag('rect')
for r in old_rects:
canvas.delete(r)
old_verts = canvas.find_withtag('vert')
for v in old_verts:
canvas.delete(v)
canvas.create_rectangle(100, 100, 300, 300, fill='', outline='yellow', width=6, tags='rect')
canvas.create_polygon(coords, fill='', outline='black', width=2, tags='poly')
vert_radius = 3
for (x, y) in coords:
canvas.create_oval(x-vert_radius, y-vert_radius, x+vert_radius, y+vert_radius, fill='blue', tags='vert')
canvas.pack()
canvas.update()
print('{0} evaluations'.format(num_evaluations))
sleep(0.05)
#start_main
|
KeyError
|
dataset/ETHPy150Open aarongarrett/inspyred/docs/polyarea.py/polygon_observer
|
37
|
def update_wrapper(wrapper, wrapped, *a, **ka):
try: functools.update_wrapper(wrapper, wrapped, *a, **ka)
except __HOLE__: pass
# These helpers are used at module level and need to be defined first.
# And yes, I know PEP-8, but sometimes a lower-case classname makes more sense.
|
AttributeError
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/update_wrapper
|
38
|
def add(self, rule, method, target, name=None):
''' Add a new route or replace the target for an existing route. '''
if rule in self.rules:
self.rules[rule][method] = target
if name: self.builder[name] = self.builder[rule]
return
target = self.rules[rule] = {method: target}
# Build pattern and other structures for dynamic routes
anons = 0 # Number of anonymous wildcards
pattern = '' # Regular expression pattern
filters = [] # Lists of wildcard input filters
builder = [] # Data structure for the URL builder
is_static = True
for key, mode, conf in self.parse_rule(rule):
if mode:
is_static = False
mask, in_filter, out_filter = self.filters[mode](conf)
if key:
pattern += '(?P<%s>%s)' % (key, mask)
else:
pattern += '(?:%s)' % mask
key = 'anon%d' % anons; anons += 1
if in_filter: filters.append((key, in_filter))
builder.append((key, out_filter or str))
elif key:
pattern += re.escape(key)
builder.append((None, key))
self.builder[rule] = builder
if name: self.builder[name] = builder
if is_static and not self.strict_order:
self.static[self.build(rule)] = target
return
def fpat_sub(m):
return m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:'
flat_pattern = re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', fpat_sub, pattern)
try:
re_match = re.compile('^(%s)$' % pattern).match
except re.error:
raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, _e()))
def match(path):
""" Return an url-argument dictionary. """
url_args = re_match(path).groupdict()
for name, wildcard_filter in filters:
try:
url_args[name] = wildcard_filter(url_args[name])
except ValueError:
raise HTTPError(400, 'Path has wrong format.')
return url_args
try:
combined = '%s|(^%s$)' % (self.dynamic[-1][0].pattern, flat_pattern)
self.dynamic[-1] = (re.compile(combined), self.dynamic[-1][1])
self.dynamic[-1][1].append((match, target))
except (__HOLE__, IndexError): # AssertionError: Too many groups
self.dynamic.append((re.compile('(^%s$)' % flat_pattern),
[(match, target)]))
return match
|
AssertionError
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/Router.add
|
39
|
def build(self, _name, *anons, **query):
''' Build an URL by filling the wildcards in a rule. '''
builder = self.builder.get(_name)
if not builder: raise RouteBuildError("No route with that name.", _name)
try:
for i, value in enumerate(anons): query['anon%d'%i] = value
url = ''.join([f(query.pop(n)) if n else f for (n,f) in builder])
return url if not query else url+'?'+urlencode(query)
except __HOLE__:
raise RouteBuildError('Missing URL argument: %r' % _e().args[0])
|
KeyError
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/Router.build
|
40
|
def _handle(self, environ):
try:
environ['bottle.app'] = self
request.bind(environ)
response.bind()
route, args = self.router.match(environ)
environ['route.handle'] = route
environ['bottle.route'] = route
environ['route.url_args'] = args
return route.call(**args)
except HTTPResponse:
return _e()
except RouteReset:
route.reset()
return self._handle(environ)
except (__HOLE__, SystemExit, MemoryError):
raise
except Exception:
if not self.catchall: raise
stacktrace = format_exc()
environ['wsgi.errors'].write(stacktrace)
return HTTPError(500, "Internal Server Error", _e(), stacktrace)
|
KeyboardInterrupt
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/Bottle._handle
|
41
|
def _cast(self, out, peek=None):
""" Try to convert the parameter into something WSGI compatible and set
correct HTTP headers when possible.
Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
iterable of strings and iterable of unicodes
"""
# Empty output is done here
if not out:
if 'Content-Length' not in response:
response['Content-Length'] = 0
return []
# Join lists of byte or unicode strings. Mixed lists are NOT supported
if isinstance(out, (tuple, list))\
and isinstance(out[0], (bytes, unicode)):
out = out[0][0:0].join(out) # b'abc'[0:0] -> b''
# Encode unicode strings
if isinstance(out, unicode):
out = out.encode(response.charset)
# Byte Strings are just returned
if isinstance(out, bytes):
if 'Content-Length' not in response:
response['Content-Length'] = len(out)
return [out]
# HTTPError or HTTPException (recursive, because they may wrap anything)
# TODO: Handle these explicitly in handle() or make them iterable.
if isinstance(out, HTTPError):
out.apply(response)
out = self.error_handler.get(out.status_code, self.default_error_handler)(out)
return self._cast(out)
if isinstance(out, HTTPResponse):
out.apply(response)
return self._cast(out.output)
# File-like objects.
if hasattr(out, 'read'):
if 'wsgi.file_wrapper' in request.environ:
return request.environ['wsgi.file_wrapper'](out)
elif hasattr(out, 'close') or not hasattr(out, '__iter__'):
return WSGIFileWrapper(out)
# Handle Iterables. We peek into them to detect their inner type.
try:
out = iter(out)
first = next(out)
while not first:
first = next(out)
except __HOLE__:
return self._cast('')
except HTTPResponse:
first = _e()
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception:
if not self.catchall: raise
first = HTTPError(500, 'Unhandled exception', _e(), format_exc())
# These are the inner types allowed in iterator or generator objects.
if isinstance(first, HTTPResponse):
return self._cast(first)
if isinstance(first, bytes):
return itertools.chain([first], out)
if isinstance(first, unicode):
return imap(lambda x: x.encode(response.charset),
itertools.chain([first], out))
return self._cast(HTTPError(500, 'Unsupported response type: %s'\
% type(first)))
|
StopIteration
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/Bottle._cast
|
42
|
def wsgi(self, environ, start_response):
""" The bottle WSGI-interface. """
try:
out = self._cast(self._handle(environ))
# rfc2616 section 4.3
if response._status_code in (100, 101, 204, 304)\
or environ['REQUEST_METHOD'] == 'HEAD':
if hasattr(out, 'close'): out.close()
out = []
start_response(response._status_line, response.headerlist)
return out
except (KeyboardInterrupt, __HOLE__, MemoryError):
raise
except Exception:
if not self.catchall: raise
err = '<h1>Critical error while processing request: %s</h1>' \
% html_escape(environ.get('PATH_INFO', '/'))
if DEBUG:
err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
'<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
% (html_escape(repr(_e())), html_escape(format_exc()))
environ['wsgi.errors'].write(err)
headers = [('Content-Type', 'text/html; charset=UTF-8')]
start_response('500 INTERNAL SERVER ERROR', headers)
return [tob(err)]
|
SystemExit
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/Bottle.wsgi
|
43
|
def __getattr__(self, name):
''' Search in self.environ for additional user defined attributes. '''
try:
var = self.environ['bottle.request.ext.%s'%name]
return var.__get__(self) if hasattr(var, '__get__') else var
except __HOLE__:
raise AttributeError('Attribute %r not defined.' % name)
|
KeyError
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/BaseRequest.__getattr__
|
44
|
def local_property(name):
def fget(self):
try:
return getattr(_lctx, name)
except __HOLE__:
raise RuntimeError("Request context not initialized.")
def fset(self, value): setattr(_lctx, name, value)
def fdel(self): delattr(_lctx, name)
return property(fget, fset, fdel,
'Thread-local property stored in :data:`_lctx.%s`' % name)
|
AttributeError
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/local_property
|
45
|
def getunicode(self, name, default=None, encoding=None):
try:
return self._fix(self[name], encoding)
except (UnicodeError, __HOLE__):
return default
|
KeyError
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/FormsDict.getunicode
|
46
|
def parse_date(ims):
""" Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """
try:
ts = email.utils.parsedate_tz(ims)
return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone
except (TypeError, __HOLE__, IndexError, OverflowError):
return None
|
ValueError
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/parse_date
|
47
|
def parse_auth(header):
""" Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"""
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
user, pwd = touni(base64.b64decode(tob(data))).split(':',1)
return user, pwd
except (KeyError, __HOLE__):
return None
|
ValueError
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/parse_auth
|
48
|
def parse_range_header(header, maxlen=0):
''' Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive.'''
if not header or header[:6] != 'bytes=': return
ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
for start, end in ranges:
try:
if not start: # bytes=-100 -> last 100 bytes
start, end = max(0, maxlen-int(end)), maxlen
elif not end: # bytes=100- -> all but the first 99 bytes
start, end = int(start), maxlen
else: # bytes=100-200 -> bytes 100-200 (inclusive)
start, end = int(start), min(int(end)+1, maxlen)
if 0 <= start < end <= maxlen:
yield start, end
except __HOLE__:
pass
|
ValueError
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/parse_range_header
|
49
|
def validate(**vkargs):
"""
Validates and manipulates keyword arguments by user defined callables.
Handles ValueError and missing arguments by raising HTTPError(403).
"""
depr('Use route wildcard filters instead.')
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kargs):
for key, value in vkargs.items():
if key not in kargs:
abort(403, 'Missing parameter: %s' % key)
try:
kargs[key] = value(kargs[key])
except __HOLE__:
abort(403, 'Wrong parameter format for: %s' % key)
return func(*args, **kargs)
return wrapper
return decorator
|
ValueError
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/validate
|
50
|
def run(self, handler):
from eventlet import wsgi, listen
try:
wsgi.server(listen((self.host, self.port)), handler,
log_output=(not self.quiet))
except __HOLE__:
# Fallback, if we have old version of eventlet
wsgi.server(listen((self.host, self.port)), handler)
|
TypeError
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/EventletServer.run
|
51
|
def run(self, handler):
for sa in self.adapters:
try:
return sa(self.host, self.port, **self.options).run(handler)
except __HOLE__:
pass
|
ImportError
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/AutoServer.run
|
52
|
def run(app=None, server='wsgiref', host='127.0.0.1', port=8080,
interval=1, reloader=False, quiet=False, plugins=None,
debug=False, **kargs):
""" Start a server instance. This method blocks until the server terminates.
:param app: WSGI application or target string supported by
:func:`load_app`. (default: :func:`default_app`)
:param server: Server adapter to use. See :data:`server_names` keys
for valid names or pass a :class:`ServerAdapter` subclass.
(default: `wsgiref`)
:param host: Server address to bind to. Pass ``0.0.0.0`` to listens on
all interfaces including the external one. (default: 127.0.0.1)
:param port: Server port to bind to. Values below 1024 require root
privileges. (default: 8080)
:param reloader: Start auto-reloading server? (default: False)
:param interval: Auto-reloader interval in seconds (default: 1)
:param quiet: Suppress output to stdout and stderr? (default: False)
:param options: Options passed to the server adapter.
"""
if NORUN: return
if reloader and not os.environ.get('BOTTLE_CHILD'):
try:
lockfile = None
fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock')
os.close(fd) # We only need this file to exist. We never write to it
while os.path.exists(lockfile):
args = [sys.executable] + sys.argv
environ = os.environ.copy()
environ['BOTTLE_CHILD'] = 'true'
environ['BOTTLE_LOCKFILE'] = lockfile
p = subprocess.Popen(args, env=environ)
while p.poll() is None: # Busy wait...
os.utime(lockfile, None) # I am alive!
time.sleep(interval)
if p.poll() != 3:
if os.path.exists(lockfile): os.unlink(lockfile)
sys.exit(p.poll())
except __HOLE__:
pass
finally:
if os.path.exists(lockfile):
os.unlink(lockfile)
return
try:
_debug(debug)
app = app or default_app()
if isinstance(app, basestring):
app = load_app(app)
if not callable(app):
raise ValueError("Application is not callable: %r" % app)
for plugin in plugins or []:
app.install(plugin)
if server in server_names:
server = server_names.get(server)
if isinstance(server, basestring):
server = load(server)
if isinstance(server, type):
server = server(host=host, port=port, **kargs)
if not isinstance(server, ServerAdapter):
raise ValueError("Unknown or unsupported server: %r" % server)
server.quiet = server.quiet or quiet
if not server.quiet:
_stderr("Bottle v%s server starting up (using %s)...\n" % (__version__, repr(server)))
_stderr("Listening on http://%s:%d/\n" % (server.host, server.port))
_stderr("Hit Ctrl-C to quit.\n\n")
if reloader:
lockfile = os.environ.get('BOTTLE_LOCKFILE')
bgcheck = FileCheckerThread(lockfile, interval)
with bgcheck:
server.run(app)
if bgcheck.status == 'reload':
sys.exit(3)
else:
server.run(app)
except KeyboardInterrupt:
pass
except (SystemExit, MemoryError):
raise
except:
if not reloader: raise
if not getattr(server, 'quiet', quiet):
print_exc()
time.sleep(interval)
sys.exit(3)
|
KeyboardInterrupt
|
dataset/ETHPy150Open adampresley/bottlepy-bootstrap/app/bottle.py/run
|
53
|
def _bootstrap_inner(self):
try:
self._set_ident()
self._Thread__started.set()
with _active_limbo_lock:
_active[self._Thread__ident] = self
del _limbo[self]
if _trace_hook:
_sys.settrace(_trace_hook)
if _profile_hook:
_sys.setprofile(_profile_hook)
try:
self.run()
except __HOLE__:
pass
except:
if _sys:
_sys.stderr.write("Exception in thread %s:\n%s\n" %
(self.name, _format_exc()))
else:
exc_type, exc_value, exc_tb = self._exc_info()
try:
self._stderr.write(
"Exception in thread " + self.name + " (most likely "
"raised during interpreter shutdown):")
self._stderr.write("Traceback (most recent call last):")
while exc_tb:
self._stderr.write(
' File "%s", line %s, in %s' %
(exc_tb.tb_frame.f_code.co_filename,
exc_tb.tb_lineno,
exc_tb.tb_frame.f_code.co_name))
exc_tb = exc_tb.tb_next
self._stderr.write("%s: %s" % (exc_type, exc_value))
finally:
del exc_type, exc_value, exc_tb
finally:
pass
finally:
with _active_limbo_lock:
self._Thread__stop()
try:
del _active[self._Thread__ident]
except:
pass
|
SystemExit
|
dataset/ETHPy150Open tarekziade/boom/boom/_patch.py/_bootstrap_inner
|
54
|
def _delete(self):
try:
with _active_limbo_lock:
del _active[self._Thread__ident]
except __HOLE__:
if 'dummy_threading' not in _sys.modules:
raise
# http://bugs.python.org/issue14308
|
KeyError
|
dataset/ETHPy150Open tarekziade/boom/boom/_patch.py/_delete
|
55
|
def makedirs(self):
"""
Create all parent folders if they do not exist.
"""
normpath = os.path.normpath(self.path)
parentfolder = os.path.dirname(normpath)
if parentfolder:
try:
os.makedirs(parentfolder)
except __HOLE__:
pass
|
OSError
|
dataset/ETHPy150Open spotify/luigi/luigi/file.py/LocalTarget.makedirs
|
56
|
def __init__(self, sock, method="GET", scheme="http", path="/",
protocol=(1, 1), qs="", headers=None, server=None):
"initializes x; see x.__class__.__doc__ for signature"
self.sock = sock
self.method = method
self.scheme = scheme or Request.scheme
self.path = path
self.protocol = protocol
self.qs = qs
self.print_debug = getattr(server, "display_banner", False)
self.headers = headers or Headers()
self.server = server
self.cookie = SimpleCookie()
if sock is not None:
name = sock.getpeername()
if name is not None:
self.remote = Host(*name)
else:
name = sock.getsockname()
self.remote = Host(name, "", name)
cookie = self.headers.get("Cookie")
if cookie is not None:
self.cookie.load(cookie)
self.body = BytesIO()
if self.server is not None:
self.local = Host(self.server.host, self.server.port)
try:
host = self.headers["Host"]
if ":" in host:
parts = host.split(":", 1)
host = parts[0]
port = int(parts[1])
else:
port = 443 if self.scheme == "https" else 80
except __HOLE__:
host = self.local.name or self.local.ip
port = getattr(self.server, "port")
self.host = host
self.port = port
base = "{0:s}://{1:s}{2:s}/".format(
self.scheme,
self.host,
":{0:d}".format(self.port) if self.port not in (80, 443) else ""
)
self.base = parse_url(base)
url = "{0:s}{1:s}{2:s}".format(
base,
self.path,
"?{0:s}".format(self.qs) if self.qs else ""
)
self.uri = parse_url(url)
self.uri.sanitize()
|
KeyError
|
dataset/ETHPy150Open circuits/circuits/circuits/web/wrappers.py/Request.__init__
|
57
|
@cube_app.route('/', method='POST')
def cube_post(mongodb, slug=None):
ret = post(mongodb, collection, opt={'status': False})
try:
cube = json.loads(ret)
process.delay(cube)
except __HOLE__:
pass
return ret
|
TypeError
|
dataset/ETHPy150Open mining/mining/mining/controllers/api/cube.py/cube_post
|
58
|
def image_update(id=None, name=None, profile=None, **kwargs): # pylint: disable=C0103
'''
Update properties of given image.
Known to work for:
- min_ram (in MB)
- protected (bool)
- visibility ('public' or 'private')
'''
if id:
image = image_show(id=id, profile=profile)
if 'result' in image and not image['result']:
return image
elif len(image) == 1:
image = image.values()[0]
elif name:
img_list = image_list(name=name, profile=profile)
if img_list is dict and 'result' in img_list:
return img_list
elif len(img_list) == 0:
return {
'result': False,
'comment':
'No image with name \'{0}\' '
'found.'.format(name)
}
elif len(img_list) == 1:
try:
image = img_list[0]
except __HOLE__:
image = img_list[name]
else:
raise SaltInvocationError
log.debug('Found image:\n{0}'.format(image))
to_update = {}
for key, value in kwargs.items():
if key.startswith('_'):
continue
if key not in image or image[key] != value:
log.debug('add <{0}={1}> to to_update'.format(key, value))
to_update[key] = value
g_client = _auth(profile)
updated = g_client.images.update(image['id'], **to_update)
# I may want to use this code on Beryllium
# until we got 2016.3.0 packages for Ubuntu
# so please keep this code until Carbon!
warn_until('Carbon', 'Starting with \'2016.3.0\' image_update() '
'will stop wrapping the returned, updated image in '
'another dictionary.')
if CUR_VER < BORON:
updated = {updated.name: updated}
return updated
|
KeyError
|
dataset/ETHPy150Open saltstack/salt/salt/modules/glance.py/image_update
|
59
|
def hdf_to_string(self):
"""
Convert the temporary hdf file holding the data into a binary string. Cleanup by deleting the hdf file and
return the binary string.
@retval hdf_string
"""
# Return Value
# ------------
# hdf_string: ''
#
try:
# open the hdf5 file using python 'open()'
f = open(self.filename, mode='rb')
# read the binary string representation of the file
hdf_string = f.read()
f.close()
except __HOLE__:
log.exception("Error opening binary file for reading out hdfstring in HDFEncoder. ")
raise HDFEncoderException("Error while trying to open file. ")
finally:
FileSystem.unlink(self.filename)
return hdf_string
|
IOError
|
dataset/ETHPy150Open ooici/pyon/prototype/hdf/hdf_codec.py/HDFEncoder.hdf_to_string
|
60
|
def handle(self, app=None, target=None, skip=False, merge=False, backwards=False, fake=False, db_dry_run=False, show_list=False, show_changes=False, database=DEFAULT_DB_ALIAS, delete_ghosts=False, ignore_ghosts=False, **options):
# NOTE: THIS IS DUPLICATED FROM django.core.management.commands.syncdb
# This code imports any module named 'management' in INSTALLED_APPS.
# The 'management' module is the preferred way of listening to post_syncdb
# signals, and since we're sending those out with create_table migrations,
# we need apps to behave correctly.
for app_name in settings.INSTALLED_APPS:
try:
import_module('.management', app_name)
except __HOLE__ as exc:
msg = exc.args[0]
if not msg.startswith('No module named') or 'management' not in msg:
raise
# END DJANGO DUPE CODE
# if all_apps flag is set, shift app over to target
if options.get('all_apps', False):
target = app
app = None
# Migrate each app
if app:
try:
apps = [Migrations(app)]
except NoMigrations:
print("The app '%s' does not appear to use migrations." % app)
print("./manage.py migrate " + self.args)
return
else:
apps = list(migration.all_migrations())
# Do we need to show the list of migrations?
if show_list and apps:
list_migrations(apps, database, **options)
if show_changes and apps:
show_migration_changes(apps)
if not (show_list or show_changes):
for app in apps:
result = migration.migrate_app(
app,
target_name = target,
fake = fake,
db_dry_run = db_dry_run,
verbosity = int(options.get('verbosity', 0)),
interactive = options.get('interactive', True),
load_initial_data = not options.get('no_initial_data', False),
merge = merge,
skip = skip,
database = database,
delete_ghosts = delete_ghosts,
ignore_ghosts = ignore_ghosts,
)
if result is False:
sys.exit(1) # Migration failed, so the command fails.
|
ImportError
|
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/South-1.0.2/south/management/commands/migrate.py/Command.handle
|
61
|
def _g_open(self):
(self.shape, self.byteorder, object_id) = self._open_unimplemented()
try:
self.nrows = SizeType(self.shape[0])
except __HOLE__:
self.nrows = SizeType(0)
return object_id
|
IndexError
|
dataset/ETHPy150Open PyTables/PyTables/tables/unimplemented.py/UnImplemented._g_open
|
62
|
def find_template_loader(loader):
if isinstance(loader, (tuple, list)):
loader, args = loader[0], loader[1:]
else:
args = []
if isinstance(loader, six.string_types):
module, attr = loader.rsplit('.', 1)
try:
mod = import_module(module)
except ImportError as e:
raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))
try:
TemplateLoader = getattr(mod, attr)
except __HOLE__ as e:
raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))
if hasattr(TemplateLoader, 'load_template_source'):
func = TemplateLoader(*args)
else:
# Try loading module the old way - string is full path to callable
if args:
raise ImproperlyConfigured("Error importing template source loader %s - can't pass arguments to function-based loader." % loader)
func = TemplateLoader
if not func.is_usable:
import warnings
warnings.warn("Your TEMPLATE_LOADERS setting includes %r, but your Python installation doesn't support that type of template loading. Consider removing that line from TEMPLATE_LOADERS." % loader)
return None
else:
return func
else:
raise ImproperlyConfigured('Loader does not define a "load_template" callable template source loader')
|
AttributeError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/template/loader.py/find_template_loader
|
63
|
def poll(self, conn):
"""Poll DB socket and process async tasks."""
while 1:
state = conn.poll()
if state == psycopg2.extensions.POLL_OK:
while conn.notifies:
notify = conn.notifies.pop()
self.logger.info(
"Got NOTIFY (pid=%d, payload=%r)",
notify.pid, notify.payload,
)
# read the header and check seq/fin.
hdr, chunk = notify.payload.split('|', 1)
# print('RECEIVE: %s' % hdr)
header = ejson.loads(hdr)
uuid = header['uuid']
size, chunks = self.chunks.setdefault(uuid, [0, {}])
if header['fin']:
size = self.chunks[uuid][0] = header['seq']
# stash the chunk
chunks[header['seq']] = chunk
if len(chunks) != size:
# haven't got all the chunks yet
continue # process next NOTIFY in loop
# got the last chunk -> process it.
data = ''.join(
chunk for _, chunk in sorted(chunks.items())
)
del self.chunks[uuid] # don't forget to cleanup!
data = ejson.loads(data)
sender = data.pop('_sender', None)
tx_id = data.pop('_tx_id', None)
for connection_id in data.pop('_connection_ids'):
try:
websocket = self.connections[connection_id]
except __HOLE__:
continue # connection not in this process
if connection_id == sender:
websocket.send(data, tx_id=tx_id)
else:
websocket.send(data)
break
elif state == psycopg2.extensions.POLL_WRITE:
gevent.select.select([], [conn.fileno()], [])
elif state == psycopg2.extensions.POLL_READ:
gevent.select.select([conn.fileno()], [], [])
else:
self.logger.warn('POLL_ERR: %s', state)
|
KeyError
|
dataset/ETHPy150Open django-ddp/django-ddp/dddp/postgres.py/PostgresGreenlet.poll
|
64
|
def read_file(filename):
if os.path.isfile(filename):
try:
with open(filename) as f:
content = f.read()
return content
except __HOLE__:
logging.exception("Error in reading file: %s" % filename)
return None
|
IOError
|
dataset/ETHPy150Open tomashanacek/mock-server/mock_server/util.py/read_file
|
65
|
@contextmanager
def temporary_migration_module(self, app_label='migrations', module=None):
"""
Allows testing management commands in a temporary migrations module.
Wrap all invocations to makemigrations and squashmigrations with this
context manager in order to avoid creating migration files in your
source tree inadvertently.
Takes the application label that will be passed to makemigrations or
squashmigrations and the Python path to a migrations module.
The migrations module is used as a template for creating the temporary
migrations module. If it isn't provided, the application's migrations
module is used, if it exists.
Returns the filesystem path to the temporary migrations module.
"""
temp_dir = tempfile.mkdtemp()
try:
target_dir = tempfile.mkdtemp(dir=temp_dir)
with open(os.path.join(target_dir, '__init__.py'), 'w'):
pass
target_migrations_dir = os.path.join(target_dir, 'migrations')
if module is None:
module = apps.get_app_config(app_label).name + '.migrations'
try:
source_migrations_dir = module_dir(import_module(module))
except (__HOLE__, ValueError):
pass
else:
shutil.copytree(source_migrations_dir, target_migrations_dir)
with extend_sys_path(temp_dir):
new_module = os.path.basename(target_dir) + '.migrations'
with self.settings(MIGRATION_MODULES={app_label: new_module}):
yield target_migrations_dir
finally:
shutil.rmtree(temp_dir)
|
ImportError
|
dataset/ETHPy150Open django/django/tests/migrations/test_base.py/MigrationTestBase.temporary_migration_module
|
66
|
def resetModes(self, modes):
for m in modes:
try:
del self.modes[m]
except __HOLE__:
pass
|
KeyError
|
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/conch/insults/helper.py/TerminalBuffer.resetModes
|
67
|
def resetPrivateModes(self, modes):
"""
Disable the given modes.
@see: L{setPrivateModes}
@see: L{insults.ITerminalTransport.resetPrivateModes}
"""
for m in modes:
try:
del self.privateModes[m]
except __HOLE__:
pass
|
KeyError
|
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/conch/insults/helper.py/TerminalBuffer.resetPrivateModes
|
68
|
def selectGraphicRendition(self, *attributes):
for a in attributes:
if a == insults.NORMAL:
self.graphicRendition = {
'bold': False,
'underline': False,
'blink': False,
'reverseVideo': False,
'foreground': WHITE,
'background': BLACK}
elif a == insults.BOLD:
self.graphicRendition['bold'] = True
elif a == insults.UNDERLINE:
self.graphicRendition['underline'] = True
elif a == insults.BLINK:
self.graphicRendition['blink'] = True
elif a == insults.REVERSE_VIDEO:
self.graphicRendition['reverseVideo'] = True
else:
try:
v = int(a)
except __HOLE__:
log.msg("Unknown graphic rendition attribute: " + repr(a))
else:
if FOREGROUND <= v <= FOREGROUND + N_COLORS:
self.graphicRendition['foreground'] = v - FOREGROUND
elif BACKGROUND <= v <= BACKGROUND + N_COLORS:
self.graphicRendition['background'] = v - BACKGROUND
else:
log.msg("Unknown graphic rendition attribute: " + repr(a))
|
ValueError
|
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/conch/insults/helper.py/TerminalBuffer.selectGraphicRendition
|
69
|
def _doLogin(self):
idParams = {}
idParams['host'] = self._hostEntry.get_text()
idParams['port'] = self._portEntry.get_text()
idParams['identityName'] = self._identityNameEntry.get_text()
idParams['password'] = self._passwordEntry.get_text()
try:
idParams['port'] = int(idParams['port'])
except __HOLE__:
pass
f = pb.PBClientFactory()
from twisted.internet import reactor
reactor.connectTCP(idParams['host'], idParams['port'], f)
creds = UsernamePassword(idParams['identityName'], idParams['password'])
d = f.login(creds, self.client)
def _timeoutLogin():
self._timeoutID = None
d.errback(failure.Failure(defer.TimeoutError("Login timed out.")))
self._timeoutID = reactor.callLater(30, _timeoutLogin)
d.addCallbacks(self._cbGotPerspective, self._ebFailedLogin)
self.statusMsg("Contacting server...")
# serviceName = self._serviceNameEntry.get_text()
# perspectiveName = self._perspectiveNameEntry.get_text()
# if not perspectiveName:
# perspectiveName = idParams['identityName']
# d = _identityConnector.requestService(serviceName, perspectiveName,
# self.client)
# d.addCallbacks(self._cbGotPerspective, self._ebFailedLogin)
# setCursor to waiting
|
ValueError
|
dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/spread/ui/gtk2util.py/LoginDialog._doLogin
|
70
|
def _get_raw_post_data(self):
try:
return self._raw_post_data
except AttributeError:
buf = StringIO()
try:
# CONTENT_LENGTH might be absent if POST doesn't have content at all (lighttpd)
content_length = int(self.environ.get('CONTENT_LENGTH', 0))
except (ValueError, __HOLE__):
# If CONTENT_LENGTH was empty string or not an integer, don't
# error out. We've also seen None passed in here (against all
# specs, but see ticket #8259), so we handle TypeError as well.
content_length = 0
if content_length > 0:
safe_copyfileobj(self.environ['wsgi.input'], buf,
size=content_length)
self._raw_post_data = buf.getvalue()
buf.close()
return self._raw_post_data
|
TypeError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/handlers/wsgi.py/WSGIRequest._get_raw_post_data
|
71
|
def __call__(self, environ, start_response):
from django.conf import settings
# Set up middleware if needed. We couldn't do this earlier, because
# settings weren't available.
if self._request_middleware is None:
self.initLock.acquire()
try:
try:
# Check that middleware is still uninitialised.
if self._request_middleware is None:
self.load_middleware()
except:
# Unload whatever middleware we got
self._request_middleware = None
raise
finally:
self.initLock.release()
set_script_prefix(base.get_script_name(environ))
signals.request_started.send(sender=self.__class__)
try:
try:
request = self.request_class(environ)
except __HOLE__:
response = http.HttpResponseBadRequest()
else:
response = self.get_response(request)
# Apply response middleware
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
response = self.apply_response_fixes(request, response)
finally:
signals.request_finished.send(sender=self.__class__)
try:
status_text = STATUS_CODE_TEXT[response.status_code]
except KeyError:
status_text = 'UNKNOWN STATUS CODE'
status = '%s %s' % (response.status_code, status_text)
response_headers = [(str(k), str(v)) for k, v in response.items()]
for c in response.cookies.values():
response_headers.append(('Set-Cookie', str(c.output(header=''))))
start_response(status, response_headers)
return response
|
UnicodeDecodeError
|
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/handlers/wsgi.py/WSGIHandler.__call__
|
72
|
def get_errno(exc):
try:
return exc.errno
except AttributeError:
try:
# e.args = (errno, reason)
if isinstance(exc.args, tuple) and len(exc.args) == 2:
return exc.args[0]
except __HOLE__:
pass
return 0
|
AttributeError
|
dataset/ETHPy150Open veegee/amqpy/amqpy/utils.py/get_errno
|
73
|
def total(self, column_name):
if column_name not in self.default_columns:
raise ValueError("%s isn't a column in this table" % column_name)
try:
values = (float(v) for v in self.values(column_name))
except __HOLE__:
raise ValueError('Column %s contains non-numeric values' % column_name)
return sum(values)
|
ValueError
|
dataset/ETHPy150Open eyeseast/python-tablefu/table_fu/__init__.py/TableFu.total
|
74
|
def _get_style(self):
try:
return self.table.style[self.column_name]
except __HOLE__:
return None
|
KeyError
|
dataset/ETHPy150Open eyeseast/python-tablefu/table_fu/__init__.py/Datum._get_style
|
75
|
def _get_style(self):
try:
return self.table.style[self.name]
except __HOLE__:
return None
|
KeyError
|
dataset/ETHPy150Open eyeseast/python-tablefu/table_fu/__init__.py/Header._get_style
|
76
|
def get_databases():
try:
from django.db import connections
except __HOLE__:
from django.conf import settings
from django.db import connection
if settings.TEST_DATABASE_NAME:
connection['TEST_NAME'] = settings.TEST_DATABASE_NAME
connections = {
DEFAULT_DB_ALIAS : connection
}
return connections
|
ImportError
|
dataset/ETHPy150Open Almad/django-sane-testing/djangosanetesting/utils.py/get_databases
|
77
|
@mod.route('/subtitles')
def find_subtitles():
rel_path = request.args.get('src')[len(current_app.config["MOVIES_URL"])+1:]
json = cache.get(rel_path)
if json == None:
path = os.path.join(
current_app.config['MOVIES_DIR'],
urllib.unquote(rel_path).decode('utf8')
)
subtitles = []
results = os_search(path)
try:
for sub in results:
if sub['SubFormat'] == 'srt':
subtitles.append({
'url': sub['SubDownloadLink'],
'language': sub['LanguageName'],
'name': sub['MovieName']
})
except __HOLE__:
pass
json = jsonify(
subtitles=subtitles
)
cache.set(rel_path, json, timeout=7 * 24 * 60 * 60)
return json
|
TypeError
|
dataset/ETHPy150Open rangermeier/flaskberry/flaskberry/views/movies/routes.py/find_subtitles
|
78
|
def for_name(fq_name, recursive=False):
"""Find class/function/method specified by its fully qualified name.
Fully qualified can be specified as:
* <module_name>.<class_name>
* <module_name>.<function_name>
* <module_name>.<class_name>.<method_name> (an unbound method will be
returned in this case).
for_name works by doing __import__ for <module_name>, and looks for
<class_name>/<function_name> in module's __dict__/attrs. If fully qualified
name doesn't contain '.', the current module will be used.
Args:
fq_name: fully qualified name of something to find.
recursive: run recursively or not.
Returns:
class object or None if fq_name is None.
Raises:
ImportError: when specified module could not be loaded or the class
was not found in the module.
"""
if fq_name is None:
return
fq_name = str(fq_name)
module_name = __name__
short_name = fq_name
fq_name = _maybe_localize_fq_name(module_name, fq_name)
if fq_name.rfind(".") >= 0:
(module_name, short_name) = (fq_name[:fq_name.rfind(".")],
fq_name[fq_name.rfind(".") + 1:])
try:
result = __import__(module_name, None, None, [short_name])
return result.__dict__[short_name]
except __HOLE__:
raise ImportError("Could not find '%s' on path '%s'" % (
short_name, module_name))
except ImportError:
tb = sys.exc_info()[2]
if tb.tb_next is not None:
raise
try:
module = for_name(module_name, recursive=True)
if hasattr(module, short_name):
return getattr(module, short_name)
else:
raise KeyError()
except KeyError:
raise ImportError("Could not find '%s' in module '%s'" % (
short_name, module_name))
except ImportError:
tb = sys.exc_info()[2]
if tb.tb_next is not None:
raise
pass
raise
|
KeyError
|
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/ext/mapreduce/util.py/for_name
|
79
|
def FindDatabaseFromSpec(self, spec):
try:
return self.FindDatabase(spec['database'][0])
except __HOLE__:
return self.FindDatabase(None)
|
KeyError
|
dataset/ETHPy150Open google/mysql-tools/pylib/schema.py/Schema.FindDatabaseFromSpec
|
80
|
def get_network_details(uid, context):
"""
Extracts the VMs network adapter information.
uid -- Id of the VM.
context -- The os context.
"""
vm_instance = vm.get_vm(uid, context)
result = {'public': [], 'admin': []}
try:
net_info = NETWORK_API.get_instance_nw_info(context, vm_instance)[0]
except __HOLE__:
LOG.warn('Unable to retrieve network information - this is because '
'of OpenStack!!')
return result
gw = net_info['network']['subnets'][0]['gateway']['address']
mac = net_info['address']
if len(net_info['network']['subnets'][0]['ips']) == 0:
tmp = {'floating_ips': [], 'address': '0.0.0.0'}
else:
tmp = net_info['network']['subnets'][0]['ips'][0]
for item in tmp['floating_ips']:
result['public'].append({'interface': 'eth0',
'mac': 'aa:bb:cc:dd:ee:ff',
'state': 'active',
'address': item['address'],
'gateway': '0.0.0.0',
'allocation': 'static'})
result['admin'].append({'interface': 'eth0',
'mac': mac,
'state': 'active',
'address': tmp['address'],
'gateway': gw,
'allocation': 'static'})
return result
|
IndexError
|
dataset/ETHPy150Open tmetsch/occi-os/occi_os_api/nova_glue/net.py/get_network_details
|
81
|
def write_into_shared_storage(traj):
traj.f_add_result('ggg', 42)
traj.f_add_derived_parameter('huuu', 46)
root = get_root_logger()
daarrays = traj.res.daarrays
idx = traj.v_idx
ncores = traj[traj.v_environment_name].f_get_default('ncores', 1)
root.info('1. This')
a = daarrays.a
a[idx] = idx
root.info('2. is')
ca = daarrays.ca
ca[idx] = idx
root.info('3. a')
ea = daarrays.ea
ea.append(np.ones((1,10))*idx)
root.info('4. sequential')
vla = daarrays.vla
vla.append(np.ones(idx+2)*idx)
root.info('5. Block')
the_range = list(range(max(0, idx-2*ncores), max(0, idx)))
for irun in the_range:
x, y = a[irun], irun
if x != y and x != 0:
raise RuntimeError('ERROR in write_into_shared_storage %s != %s' % (str(x), str(y)))
x, y = ca[irun], irun
if x != y and x != 0:
raise RuntimeError('ERROR in write_into_shared_storage %s != %s' % (str(x), str(y)))
try:
x, y = ea[irun, 9], ea[irun, 8]
if x != y and x != 0:
raise RuntimeError('ERROR in write_into_shared_storage %s != %s' % (str(x), str(y)))
except IndexError:
pass # Array is not at this size yet
try:
x, y = vla[irun][0], vla[irun][1]
if x != y and x != 0:
raise RuntimeError('ERROR in write_into_shared_storage %s != %s' % (str(x), str(y)))
except __HOLE__:
pass # Array is not at this size yet
root.info('6. !!!!!!!!!')
tabs = traj.tabs
with StorageContextManager(traj) as cm:
t1 = tabs.t1
row = t1.row
row['run_name'] = compat.tobytes(traj.v_crun)
row['idx'] = idx
row.append()
t1.flush()
t2 = tabs.t2
row = t2[idx]
if row['run_name'] != compat.tobytes(traj.v_crun):
raise RuntimeError('Names in run table do not match, Run: %s != %s' % (row['run_name'],
traj.v_crun) )
df = traj.df
df.append(pd.DataFrame({'idx':[traj.v_idx], 'run_name':traj.v_crun}))
|
IndexError
|
dataset/ETHPy150Open SmokinCaterpillar/pypet/pypet/tests/integration/shared_data_test.py/write_into_shared_storage
|
82
|
def run(self):
# Connect up
try:
device = ciscolib.Device(self.host, PASSWORD)
device.connect()
except ciscolib.AuthenticationError:
try:
device = ciscolib.Device(self.host, USER_PASSWORD, USERNAME)
device.connect()
except:
print("Unable to connect to %s" % self.host)
return
except:
print("Unable to connect to %s" % self.host)
return
try:
model = device.get_model()
except ciscolib.ModelNotSupported:
print("!! Model of %s is not supported!" % self.host)
return
if model in models:
return # We already have a data for this switch model
else:
with models_lock:
models.append(model)
output_dir = 'fixtures/%s/' % model
try:
os.mkdir(output_dir)
except __HOLE__ as e:
if e.errno != 17:
print("!! Unable to create model directory %s" % output_dir)
return
open(output_dir + "show_int_status.txt", 'w').write(device.cmd("show int status"))
open(output_dir + "show_cdp_neighbors_detail.txt", 'w').write(device.cmd("show cdp neighbors detail"))
open(output_dir + "show_version.txt", 'w').write(device.cmd("show version"))
open(output_dir + "show_arp.txt", 'w').write(device.cmd("show arp"))
mac_data = ''
mac_cmd = ''
try:
mac_cmd = 'show mac-address-table'
mac_data = device.cmd(mac_cmd)
except ciscolib.InvalidCommand:
try:
mac_cmd = 'show mac address-table'
mac_data = device.cmd(mac_cmd)
except:
print("!! Unable to get mac data for %s" % self.host)
if mac_data != '':
open(output_dir + mac_cmd.replace(' ', '_') + ".txt", 'w').write(mac_data)
interfaces_re = "((?:\w+|-|/!)+\d+(?:/\d+)*) is (?:up|down)"
interfaces = device.cmd("show interfaces")
open(output_dir + "show_interfaces.txt", 'w').write(interfaces)
for result in re.findall(interfaces_re, interfaces):
filename = "show_interface_%s_status.txt" % result
filename = filename.replace("/", "+")
open(output_dir + filename, 'w').write(device.cmd("show interface %s status" % result))
|
OSError
|
dataset/ETHPy150Open nickpegg/ciscolib/tests/get_switch_data.py/Grabber.run
|
83
|
def push(self, **options):
# for this size dict & usage pattern, copying turns out to be cheaper
# than directing __getitem__ down through a stack of sparse frames.
self._frames.append(self._frames[-1].copy())
try:
self.update(**options)
except __HOLE__:
self.pop()
raise
|
KeyError
|
dataset/ETHPy150Open jek/flatland/flatland/out/generic.py/Context.push
|
84
|
@property
def _stats_log_template(self):
"""The template for reader responses in the stats log."""
try:
return utils.get_file_contents(os.path.join(
feconf.INTERACTIONS_DIR, self.id, 'stats_response.html'))
except __HOLE__:
return '{{answer}}'
|
IOError
|
dataset/ETHPy150Open oppia/oppia/extensions/interactions/base.py/BaseInteraction._stats_log_template
|
85
|
def get_rule_by_name(self, rule_name):
"""Gets a rule given its name."""
try:
return next(
r for r in self.rules if r.__name__ == rule_name)
except __HOLE__:
raise Exception('Could not find rule with name %s' % rule_name)
|
StopIteration
|
dataset/ETHPy150Open oppia/oppia/extensions/interactions/base.py/BaseInteraction.get_rule_by_name
|
86
|
def sqrtm(A, disp=True, blocksize=64):
"""
Matrix square root.
Parameters
----------
A : (N, N) array_like
Matrix whose square root to evaluate
disp : bool, optional
Print warning if error in the result is estimated large
instead of returning estimated error. (Default: True)
blocksize : integer, optional
If the blocksize is not degenerate with respect to the
size of the input array, then use a blocked algorithm. (Default: 64)
Returns
-------
sqrtm : (N, N) ndarray
Value of the sqrt function at `A`
errest : float
(if disp == False)
Frobenius norm of the estimated error, ||err||_F / ||A||_F
References
----------
.. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
"Blocked Schur Algorithms for Computing the Matrix Square Root,
Lecture Notes in Computer Science, 7782. pp. 171-182.
Examples
--------
>>> from scipy.linalg import sqrtm
>>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
>>> r = sqrtm(a)
>>> r
array([[ 0.75592895, 1.13389342],
[ 0.37796447, 1.88982237]])
>>> r.dot(r)
array([[ 1., 3.],
[ 1., 4.]])
"""
A = _asarray_validated(A, check_finite=True, as_inexact=True)
if len(A.shape) != 2:
raise ValueError("Non-matrix input to matrix function.")
if blocksize < 1:
raise ValueError("The blocksize should be at least 1.")
keep_it_real = np.isrealobj(A)
if keep_it_real:
T, Z = schur(A)
if not np.array_equal(T, np.triu(T)):
T, Z = rsf2csf(T, Z)
else:
T, Z = schur(A, output='complex')
failflag = False
try:
R = _sqrtm_triu(T, blocksize=blocksize)
ZH = np.conjugate(Z).T
X = Z.dot(R).dot(ZH)
except SqrtmError:
failflag = True
X = np.empty_like(A)
X.fill(np.nan)
if disp:
nzeig = np.any(np.diag(T) == 0)
if nzeig:
print("Matrix is singular and may not have a square root.")
elif failflag:
print("Failed to find a square root.")
return X
else:
try:
arg2 = norm(X.dot(X) - A, 'fro')**2 / norm(A, 'fro')
except __HOLE__:
# NaNs in matrix
arg2 = np.inf
return X, arg2
|
ValueError
|
dataset/ETHPy150Open scipy/scipy/scipy/linalg/_matfuncs_sqrtm.py/sqrtm
|
87
|
def show_ui(self, stdscr):
global mainwin
mainwin = stdscr
curses.use_default_colors()
# w/o this for some reason takes 1 cycle to draw wins
stdscr.refresh()
signal.signal(signal.SIGWINCH, sigwinch_handler)
TIMEOUT = 250
stdscr.timeout(TIMEOUT)
server_count = len(self.servers)
maxy, maxx = stdscr.getmaxyx()
uis = (SummaryUI(maxy, maxx, server_count),
ServerUI(maxy, maxx, server_count))
# start the polling threads
pollers = [StatPoller(server) for server in self.servers]
for poller in pollers:
poller.setName("PollerThread:" + server)
poller.setDaemon(True)
poller.start()
LOG.debug("starting main loop")
global resized_sig
flash = None
while True:
try:
if resized_sig:
resized_sig = False
self.resize(uis)
wakeup_poller()
while not q_stats.empty():
zkserver = q_stats.get_nowait()
for ui in uis:
ui.update(zkserver)
ch = stdscr.getch()
if 0 < ch <=255:
if ch == ord('q'):
return
elif ch == ord('h'):
flash = "Help: q:quit r:reset stats spc:refresh"
flash_count = 1000/TIMEOUT * 5
elif ch == ord('r'):
[reset_server_stats(server) for server in self.servers]
flash = "Server stats reset"
flash_count = 1000/TIMEOUT * 5
wakeup_poller()
elif ch == ord(' '):
wakeup_poller()
stdscr.move(1, 0)
if flash:
stdscr.addstr(1, 0, flash)
flash_count -= 1
if flash_count == 0:
flash = None
stdscr.clrtoeol()
curses.doupdate()
except __HOLE__:
break
|
KeyboardInterrupt
|
dataset/ETHPy150Open andreisavu/zookeeper-mq/test_5_trunk/zktop.py/Main.show_ui
|
88
|
def iteratorCreationTiming():
def getIterable(x):
print("Getting iterable", x)
return Iterable(x)
class Iterable:
def __init__(self, x):
self.x = x
self.values = list(range(x))
self.count = 0
def __iter__(self):
print("Giving iterator now", self.x)
return self
def __next__(self):
print("Next of", self.x, "is", self.count)
if len(self.values) > self.count:
self.count += 1
return self.values[ self.count - 1 ]
else:
print("Raising StopIteration for", self.x)
raise StopIteration
# Python2/3 compatibility.
next = __next__
def __del__(self):
print("Deleting", self.x)
gen = ( (y,z) for y in getIterable(3) for z in getIterable(2) )
print("Using generator", gen)
next(gen)
res = tuple(gen)
print(res)
print('*' * 20)
try:
next(gen)
except __HOLE__:
print("Usage past end gave StopIteration exception as expected.")
try:
print("Generator state then is", inspect.getgeneratorstate(gen)) # @UndefinedVariable
except AttributeError:
pass
print("Its frame is now", gen.gi_frame)
print("Early aborting generator:")
gen2 = ( (y,z) for y in getIterable(3) for z in getIterable(2) )
del gen2
|
StopIteration
|
dataset/ETHPy150Open kayhayen/Nuitka/tests/basics/GeneratorExpressions.py/iteratorCreationTiming
|
89
|
def genexprSend():
x = ( x for x in range(9) )
print("Sending too early:")
try:
x.send(3)
except TypeError as e:
print("Gave expected TypeError with text:", e)
z = next(x)
y = x.send(3)
print("Send return value", y)
print("And then next gave", next(x))
print("Throwing an exception to it.")
try:
x.throw(2)
assert False
except TypeError as e:
print("Gave expected TypeError:", e)
print("Throwing an exception to it.")
try:
x.throw(ValueError(2))
except ValueError as e:
print("Gave expected ValueError:", e)
try:
next(x)
print("Next worked even after thrown error")
except __HOLE__ as e:
print("Gave expected stop iteration after throwing exception in it:", e)
print("Throwing another exception from it.")
try:
x.throw(ValueError(5))
except ValueError as e:
print("Gave expected ValueError with text:", e)
|
StopIteration
|
dataset/ETHPy150Open kayhayen/Nuitka/tests/basics/GeneratorExpressions.py/genexprSend
|
90
|
def genexprThrown():
def checked(z):
if z == 3:
raise ValueError
return z
x = ( checked(x) for x in range(9) )
try:
for count, value in enumerate(x):
print(count, value)
except __HOLE__:
print(count+1, ValueError)
try:
next(x)
print("Allowed to do next() after raised exception from the generator expression")
except StopIteration:
print("Exception in generator, disallowed next() afterwards.")
|
ValueError
|
dataset/ETHPy150Open kayhayen/Nuitka/tests/basics/GeneratorExpressions.py/genexprThrown
|
91
|
def __setattr__(self, key, value):
"""Set an attr with protection of class members.
This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to
:exc:`AttributeError`.
Examples
--------
>>> s = Struct()
>>> s.a = 10
>>> s.a
10
>>> try:
... s.get = 10
... except AttributeError:
... print("you can't set a class member")
...
you can't set a class member
"""
# If key is an str it might be a class member or instance var
if isinstance(key, str):
# I can't simply call hasattr here because it calls getattr, which
# calls self.__getattr__, which returns True for keys in
# self._data. But I only want keys in the class and in
# self.__dict__
if key in self.__dict__ or hasattr(Struct, key):
raise AttributeError(
'attr %s is a protected member of class Struct.' % key
)
try:
self.__setitem__(key, value)
except __HOLE__ as e:
raise AttributeError(e)
|
KeyError
|
dataset/ETHPy150Open ipython/ipython-py3k/IPython/utils/ipstruct.py/Struct.__setattr__
|
92
|
def __getattr__(self, key):
"""Get an attr by calling :meth:`dict.__getitem__`.
Like :meth:`__setattr__`, this method converts :exc:`KeyError` to
:exc:`AttributeError`.
Examples
--------
>>> s = Struct(a=10)
>>> s.a
10
>>> type(s.get)
<class 'builtin_function_or_method'>
>>> try:
... s.b
... except AttributeError:
... print("I don't have that key")
...
I don't have that key
"""
try:
result = self[key]
except __HOLE__:
raise AttributeError(key)
else:
return result
|
KeyError
|
dataset/ETHPy150Open ipython/ipython-py3k/IPython/utils/ipstruct.py/Struct.__getattr__
|
93
|
def get_kwargs(self, field, kwargs):
"""
Return extra kwargs based on the field type.
"""
if field.type == 'StringField':
kwargs['data-type'] = 'text'
elif field.type == 'TextAreaField':
kwargs['data-type'] = 'textarea'
kwargs['data-rows'] = '5'
elif field.type == 'BooleanField':
kwargs['data-type'] = 'select'
# data-source = dropdown options
kwargs['data-source'] = json.dumps([
{'value': '', 'text': gettext('No')},
{'value': '1', 'text': gettext('Yes')}
])
kwargs['data-role'] = 'x-editable-boolean'
elif field.type == 'Select2Field':
kwargs['data-type'] = 'select'
choices = [{'value': x, 'text': y} for x, y in field.choices]
# prepend a blank field to choices if allow_blank = True
if getattr(field, 'allow_blank', False):
choices.insert(0, {'value': '__None', 'text': ''})
# json.dumps fixes issue with unicode strings not loading correctly
kwargs['data-source'] = json.dumps(choices)
elif field.type == 'DateField':
kwargs['data-type'] = 'combodate'
kwargs['data-format'] = 'YYYY-MM-DD'
kwargs['data-template'] = 'YYYY-MM-DD'
elif field.type == 'DateTimeField':
kwargs['data-type'] = 'combodate'
kwargs['data-format'] = 'YYYY-MM-DD HH:mm:ss'
kwargs['data-template'] = 'YYYY-MM-DD HH:mm:ss'
# x-editable-combodate uses 1 minute increments
kwargs['data-role'] = 'x-editable-combodate'
elif field.type == 'TimeField':
kwargs['data-type'] = 'combodate'
kwargs['data-format'] = 'HH:mm:ss'
kwargs['data-template'] = 'HH:mm:ss'
kwargs['data-role'] = 'x-editable-combodate'
elif field.type == 'IntegerField':
kwargs['data-type'] = 'number'
elif field.type in ['FloatField', 'DecimalField']:
kwargs['data-type'] = 'number'
kwargs['data-step'] = 'any'
elif field.type in ['QuerySelectField', 'ModelSelectField',
'QuerySelectMultipleField']:
# QuerySelectField and ModelSelectField are for relations
kwargs['data-type'] = 'select'
choices = []
selected_ids = []
for value, label, selected in field.iter_choices():
try:
label = text_type(label)
except __HOLE__:
# unable to display text value
label = ''
choices.append({'value': text_type(value), 'text': label})
if selected:
selected_ids.append(value)
# blank field is already included if allow_blank
kwargs['data-source'] = json.dumps(choices)
if field.type == 'QuerySelectMultipleField':
kwargs['data-type'] = 'select2'
kwargs['data-role'] = 'x-editable-select2-multiple'
# must use id instead of text or prefilled values won't work
separator = getattr(field, 'separator', ',')
kwargs['data-value'] = separator.join(selected_ids)
else:
raise Exception('Unsupported field type: %s' % (type(field),))
return kwargs
|
TypeError
|
dataset/ETHPy150Open flask-admin/flask-admin/flask_admin/model/widgets.py/XEditableWidget.get_kwargs
|
94
|
def stop(botname):
"""
This method of stopping a bot is only required if you have backgrounded
or otherwise daemonized its process, and it would run indefinitely otherwise.
"""
_bot_exists(botname)
cfg = ConfigParser.SafeConfigParser()
cfg.read('%s/settings.cfg' % botname)
pidfile = cfg.get('bot', 'pidfile')
if os.path.exists(pidfile):
# Delete the pidfile. This will message the process
pid = -1
try:
f = open(pidfile, "r")
pid = int(f.readline().strip())
f.close()
os.remove(pidfile)
except __HOLE__:
print 'Unable to read PID file. Perhaps "%s" is not running?' % botname
except OSError, err:
err = str(err)
print err
print 'Sent process %s a halt signal.' % pid
else:
print 'PID file "%s" does not exist. Perhaps "%s" is not running?' % (pidfile, botname)
|
IOError
|
dataset/ETHPy150Open magsol/pybot/pybot/bootstrap.py/stop
|
95
|
def _bot_exists(botname):
"""
Utility method to import a bot.
"""
module = None
try:
module = importlib.import_module('%s.%s' % (botname, botname))
except __HOLE__ as e:
quit('Unable to import bot "%s.%s": %s' % (botname, botname, str(e)))
return module
|
ImportError
|
dataset/ETHPy150Open magsol/pybot/pybot/bootstrap.py/_bot_exists
|
96
|
def test_abs__file__(self):
# Make sure all imported modules have their __file__ attribute
# as an absolute path.
# Handled by abs__file__()
site.abs__file__()
for module in (sys, os, __builtin__):
try:
self.failUnless(os.path.isabs(module.__file__), `module`)
except __HOLE__:
continue
# We could try everything in sys.modules; however, when regrtest.py
# runs something like test_frozen before test_site, then we will
# be testing things loaded *after* test_site did path normalization
|
AttributeError
|
dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test_site.py/ImportSideEffectTests.test_abs__file__
|
97
|
def test_sitecustomize_executed(self):
# If sitecustomize is available, it should have been imported.
if not sys.modules.has_key("sitecustomize"):
try:
import sitecustomize
except __HOLE__:
pass
else:
self.fail("sitecustomize not imported automatically")
|
ImportError
|
dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test_site.py/ImportSideEffectTests.test_sitecustomize_executed
|
98
|
@webapi_check_local_site
@webapi_login_required
@webapi_response_errors(DOES_NOT_EXIST, INVALID_FORM_DATA,
PERMISSION_DENIED, NOT_LOGGED_IN)
@webapi_request_fields(
required=dict({
'file_attachment_id': {
'type': int,
'description': 'The ID of the file attachment being '
'commented on.',
},
}, **BaseFileAttachmentCommentResource.REQUIRED_CREATE_FIELDS),
optional=dict({
'diff_against_file_attachment_id': {
'type': int,
'description': 'The ID of the file attachment that '
'file_attachment_id is diffed. The comment '
'applies to the diff between these two '
'attachments.',
'added_in': '2.0',
},
}, **BaseFileAttachmentCommentResource.OPTIONAL_CREATE_FIELDS),
allow_unknown=True
)
def create(self, request, file_attachment_id=None,
diff_against_file_attachment_id=None, *args, **kwargs):
"""Creates a file comment on a review.
This will create a new comment on a file as part of a review.
The comment contains text only.
"""
try:
review_request = \
resources.review_request.get_object(request, *args, **kwargs)
review = resources.review.get_object(request, *args, **kwargs)
except ObjectDoesNotExist:
return DOES_NOT_EXIST
if not resources.review.has_modify_permissions(request, review):
return self.get_no_access_error(request)
try:
file_attachment = \
FileAttachment.objects.get(pk=file_attachment_id,
review_request=review_request)
except ObjectDoesNotExist:
return INVALID_FORM_DATA, {
'fields': {
'file_attachment_id': ['This is not a valid file '
'attachment ID'],
}
}
diff_against_file_attachment = None
if diff_against_file_attachment_id:
try:
diff_against_file_attachment = FileAttachment.objects.get(
pk=diff_against_file_attachment_id,
review_request=review_request)
except __HOLE__:
return INVALID_FORM_DATA, {
'fields': {
'diff_against_file_attachment_id': [
'This is not a valid file attachment ID'
],
}
}
new_comment = self.create_comment(
review=review,
file_attachment=file_attachment,
diff_against_file_attachment=diff_against_file_attachment,
fields=('file_attachment', 'diff_against_file_attachment'),
**kwargs)
review.file_attachment_comments.add(new_comment)
return 201, {
self.item_result_key: new_comment,
}
|
ObjectDoesNotExist
|
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/webapi/resources/review_file_attachment_comment.py/ReviewFileAttachmentCommentResource.create
|
99
|
@webapi_check_local_site
@webapi_login_required
@webapi_response_errors(DOES_NOT_EXIST, NOT_LOGGED_IN, PERMISSION_DENIED)
@webapi_request_fields(
optional=BaseFileAttachmentCommentResource.OPTIONAL_UPDATE_FIELDS,
allow_unknown=True
)
def update(self, request, *args, **kwargs):
"""Updates a file comment.
This can update the text or region of an existing comment. It
can only be done for comments that are part of a draft review.
"""
try:
resources.review_request.get_object(request, *args, **kwargs)
review = resources.review.get_object(request, *args, **kwargs)
file_comment = self.get_object(request, *args, **kwargs)
except __HOLE__:
return DOES_NOT_EXIST
# Determine whether or not we're updating the issue status.
if self.should_update_issue_status(file_comment, **kwargs):
return self.update_issue_status(request, self, *args, **kwargs)
if not resources.review.has_modify_permissions(request, review):
return self.get_no_access_error(request)
self.update_comment(file_comment, **kwargs)
return 200, {
self.item_result_key: file_comment,
}
|
ObjectDoesNotExist
|
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/webapi/resources/review_file_attachment_comment.py/ReviewFileAttachmentCommentResource.update
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.