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 Non...
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.fie...
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...
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 ...
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(t...
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 ret...
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_PROXI...
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, ...
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. ...
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(...
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 r...
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...
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_...
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...
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__...
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] ...
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...
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 m...
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))) ...
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...
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__: ...
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 insta...
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 wil...
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.uni...
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...
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) ...
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 # should...
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 ...
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) els...
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: ...
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...
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]...
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] = {...
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 ...
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...
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 o...
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 hasa...
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('Attrib...
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, f...
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...
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, ...
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, **...
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.ho...
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 ...
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.setp...
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__: ...
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 = pa...
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) ...
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: ...
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 ...
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 a...
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( ...
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 migrat...
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, ...
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['p...
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_LE...
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: ...
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 contain...
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 = { D...
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') ...
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 cas...
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_i...
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[i...
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() ...
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__: s...
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: T...
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) ...
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 iter...
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("Thr...
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) ...
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 >>>...
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) <...
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'] ...
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....
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__), `...
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("sitecust...
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, 'descripti...
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): ...
ObjectDoesNotExist
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/webapi/resources/review_file_attachment_comment.py/ReviewFileAttachmentCommentResource.update