Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
7,600
def init_repo(self): if os.path.exists(self.config_path): raise errors.Error("repository '%s' already initialized" % ( self.root_dir)) try: if not os.path.exists(self.system_root): os.makedirs(self.system_root) util.json_dump({}, ...
IOError
dataset/ETHPy150Open ohmu/poni/poni/core.py/ConfigMan.init_repo
7,601
def _query(self, method, path, data=None, page=False, retry=0): """ Fetch an object from the Graph API and parse the output, returning a tuple where the first item is the object yielded by the Graph API and the second is the URL for the next page of results, or ``None`` if results have b...
KeyError
dataset/ETHPy150Open jgorset/facepy/facepy/graph_api.py/GraphAPI._query
7,602
def _parse(self, data): """ Parse the response from Facebook's Graph API. :param data: A string describing the Graph API's response. """ # tests seems to pass a str, while real usage bytes which should be expected if type(data) == type(bytes()): data = data.d...
ValueError
dataset/ETHPy150Open jgorset/facepy/facepy/graph_api.py/GraphAPI._parse
7,603
def handle(self, listener, client, addr): req = None try: if self.cfg.is_ssl: client = ssl.wrap_socket(client, server_side=True, **self.cfg.ssl_options) parser = http.RequestParser(self.cfg, client) req = six.next(parser) ...
StopIteration
dataset/ETHPy150Open benoitc/gunicorn/gunicorn/workers/sync.py/SyncWorker.handle
7,604
def render_GET(self, request): """ This method is called by the twisted framework when a GET request was received. """ # First check if the version is ok try: version = request.args['version'] except __HOLE__: request.setResponseCode(httpstatus...
KeyError
dataset/ETHPy150Open rapyuta/rce/rce-comm/rce/comm/server.py/RobotResource.render_GET
7,605
def onConnect(self, req): """ Method is called by the Autobahn engine when a request to establish a connection has been received. @param req: Connection Request object. @type req: autobahn.websocket.ConnectionRequest @return: Deferred which fires...
KeyError
dataset/ETHPy150Open rapyuta/rce/rce-comm/rce/comm/server.py/RobotWebSocketProtocol.onConnect
7,606
def processCompleteMessage(self, msg): """ Process complete messages by calling the appropriate handler for the manager. (Called by rce.comm.assembler.MessageAssembler) """ try: msgType = msg['type'] data = msg['data'] except __HOLE__ as e: ...
KeyError
dataset/ETHPy150Open rapyuta/rce/rce-comm/rce/comm/server.py/RobotWebSocketProtocol.processCompleteMessage
7,607
def _process_createContainer(self, data): """ Internally used method to process a request to create a container. """ try: self._avatar.createContainer(data['containerTag'], data.get('containerData', {})) except __HOLE__ as e: ...
KeyError
dataset/ETHPy150Open rapyuta/rce/rce-comm/rce/comm/server.py/RobotWebSocketProtocol._process_createContainer
7,608
def _process_destroyContainer(self, data): """ Internally used method to process a request to destroy a container. """ try: self._avatar.destroyContainer(data['containerTag']) except __HOLE__ as e: raise InvalidRequest("Can not process 'DestroyContainer' request. ...
KeyError
dataset/ETHPy150Open rapyuta/rce/rce-comm/rce/comm/server.py/RobotWebSocketProtocol._process_destroyContainer
7,609
def _process_configureComponent(self, data): """ Internally used method to process a request to configure components. """ for node in data.pop('addNodes', []): try: self._avatar.addNode(node['containerTag'], node['nodeT...
KeyError
dataset/ETHPy150Open rapyuta/rce/rce-comm/rce/comm/server.py/RobotWebSocketProtocol._process_configureComponent
7,610
def _process_configureConnection(self, data): """ Internally used method to process a request to configure connections. """ for conf in data.pop('connect', []): try: self._avatar.addConnection(conf['tagA'], conf['tagB']) except KeyError as e: ...
KeyError
dataset/ETHPy150Open rapyuta/rce/rce-comm/rce/comm/server.py/RobotWebSocketProtocol._process_configureConnection
7,611
def _process_DataMessage(self, data): """ Internally used method to process a data message. """ try: iTag = str(data['iTag']) mType = str(data['type']) msgID = str(data['msgID']) msg = data['msg'] except __HOLE__ as e: raise Inv...
KeyError
dataset/ETHPy150Open rapyuta/rce/rce-comm/rce/comm/server.py/RobotWebSocketProtocol._process_DataMessage
7,612
def parse_ticket(secret, ticket, ip, digest_algo=DEFAULT_DIGEST): """ Parse the ticket, returning (timestamp, userid, tokens, user_data). If the ticket cannot be parsed, ``BadTicket`` will be raised with an explanation. """ if isinstance(digest_algo, str): # correct specification of dig...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/auth/auth_tkt.py/parse_ticket
7,613
def setup(self, gen): Node.setup(self, gen) try: self.target = gen.rules[self.name] if self.accepts_epsilon != self.target.accepts_epsilon: self.accepts_epsilon = self.target.accepts_epsilon gen.changed() except __HOLE__: # Oops, it's nonex...
KeyError
dataset/ETHPy150Open smurfix/yapps/yapps/parsetree.py/NonTerminal.setup
7,614
def track_event(request, event): """ Simple view that receives and stores an event in the backend (celery queue or dummy). """ params = request.GET.get('params') if params: try: params = anyjson.deserialize(params) except __HOLE__, e: return HttpResponseBa...
ValueError
dataset/ETHPy150Open ella/django-event-tracker/eventtracker/views.py/track_event
7,615
def rollback(self): """ Rolls back the database to last """ try: shutil.copy2(self.db_path + "/BACKUP_codedict_db.DB", self.db_path + "/codedict_db.DB") except (shutil.Error, IOError, __HOLE__) as error: print "Error while rolling back database.\n", error...
OSError
dataset/ETHPy150Open BastiPaeltz/codedict/source/database.py/Database.rollback
7,616
def add_content(self, values, lang_name, insert_type="normal"): """ Adds content to the database. Tries to insert and updates if row already exists. """ # backup database file if insert_type == "from_file": try: shutil.copy2(self.db_path + "...
IOError
dataset/ETHPy150Open BastiPaeltz/codedict/source/database.py/Database.add_content
7,617
def dependencies(package_json, version_number=None): '''Get the list of package names of dependencies for a package.''' versions = package_json['versions'] if version_number is None: # Get the maximum version number if the caller didn't provide one explicity. version_number = sorted(versions...
KeyError
dataset/ETHPy150Open zsck/npm-to-git/n2g.py/dependencies
7,618
def repository_url(package_json): '''Get the URL of a package's repository''' try: return package_json['repository']['url'] except __HOLE__: return None
KeyError
dataset/ETHPy150Open zsck/npm-to-git/n2g.py/repository_url
7,619
def recursively_replace_dependencies(node_modules_path, kind, memo={}): '''Recursively traverse into node_modules/ and then each dependency's node_modules/ directory, replacing dependencies as we go.''' package_json_filename = os.sep.join([node_modules_path, 'package.json']) if os.path.isfile(package_json_f...
IOError
dataset/ETHPy150Open zsck/npm-to-git/n2g.py/recursively_replace_dependencies
7,620
def convert(ctx, filename, setup_args, monkey_patch_mode, verbose, output, log, show_output=True): if monkey_patch_mode == "automatic": try: if verbose: pprint("PINK", "Catching monkey (this may take a while) ...") monkey_patch_mode = detect_mon...
ValueError
dataset/ETHPy150Open cournape/Bento/bento/convert/commands.py/convert
7,621
def loadfile(filename): try: fp = file(filename, 'r') try: obj = simplejson.load(fp) finally: fp.close() except __HOLE__: raise InvalidClientSecretsError('File not found: "%s"' % filename) return _validate_clientsecrets(obj)
IOError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/google-api-python-client/oauth2client/clientsecrets.py/loadfile
7,622
def get_user_for_response(id, request, include_products=True): id_type = unicode(request.args.get("id_type", "url_slug")) try: logged_in = unicode(getattr(current_user, id_type)) == id except __HOLE__: logged_in = False retrieved_user = get_profile_from_id( id, id_type,...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/views.py/get_user_for_response
7,623
def abort_if_user_not_logged_in(profile): allowed = True try: if current_user.id != profile.id: abort_json(401, "You can't do this because it's not your profile.") except __HOLE__: abort_json(405, "You can't do this because you're not logged in.")
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/views.py/abort_if_user_not_logged_in
7,624
def current_user_owns_profile(profile): try: return current_user.id == profile.id except __HOLE__: #Anonymous return False
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/views.py/current_user_owns_profile
7,625
def current_user_owns_tiid(tiid): try: profile_for_current_user = db.session.query(Profile).get(int(current_user.id)) db.session.expunge(profile_for_current_user) return tiid in profile_for_current_user.tiids except __HOLE__: #Anonymous return False
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/views.py/current_user_owns_tiid
7,626
def current_user_must_own_tiid(tiid): try: if not current_user_owns_tiid(tiid): abort_json(401, "You have to own this product to modify it.") except __HOLE__: abort_json(405, "You must be logged in to modify products.") ############################################################...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/views.py/current_user_must_own_tiid
7,627
@app.before_request def redirect_to_https(): try: if request.headers["X-Forwarded-Proto"] == "https": pass else: return redirect(request.url.replace("http://", "https://"), 301) # permanent except __HOLE__: #logger.debug(u"There's no X-Forwarded-Proto header; ass...
KeyError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/views.py/redirect_to_https
7,628
@app.before_request def load_globals(): g.user = current_user try: g.user_id = current_user.id except __HOLE__: g.user_id = None g.api_key = os.getenv("API_KEY") g.webapp_root = os.getenv("WEBAPP_ROOT_PRETTY", os.getenv("WEBAPP_ROOT"))
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/views.py/load_globals
7,629
@app.route("/profile/current") def get_current_user(): local_sleep(1) try: user_info = g.user.dict_about() except __HOLE__: # anon user has no as_dict() user_info = None return json_resp_from_thing({"user": user_info})
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/views.py/get_current_user
7,630
@app.route("/profile/<profile_id>/pinboard", methods=["GET", "POST"]) def pinboard_endpoint(profile_id): profile = get_user_for_response(profile_id, request) if request.method == "GET": board = Pinboard.query.filter_by(profile_id=profile.id).first() try: resp = board.contents ...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/views.py/pinboard_endpoint
7,631
@app.route("/product/<tiid>/pdf", methods=['GET']) def product_pdf(tiid): if request.method == "GET": try: product = get_product(tiid) pdf = product.get_pdf() db.session.merge(product) # get pdf might have cached the pdf commit(db) if pdf: ...
IndexError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/views.py/product_pdf
7,632
@app.route("/product/<tiid>/file", methods=['GET', 'POST']) def product_file(tiid): if request.method == "GET": try: product = get_product(tiid) if not product: return abort_json(404, "product not found") if product.has_file: my_file = pr...
IndexError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/views.py/product_file
7,633
@app.route("/top.js") def get_js_top(): try: current_user_dict = current_user.dict_about() except __HOLE__: current_user_dict = None return make_js_response( "top.js.tpl", segmentio_key=os.getenv("SEGMENTIO_KEY"), mixpanel_token=os.getenv("MIXPANEL_TOKEN"), s...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/views.py/get_js_top
7,634
def _interpret_args(self, args, kwargs): f, gradient = None, self.gradient atoms, lists = self._sort_args(args) s = self._pop_symbol_list(lists) s = self._fill_in_vars(s) # prepare the error message for lambdification failure f_str = ', '.join(str(fa) for fa in atoms) ...
TypeError
dataset/ETHPy150Open sympy/sympy/sympy/plotting/pygletplot/color_scheme.py/ColorScheme._interpret_args
7,635
def _test_color_function(self): if not callable(self.f): raise ValueError("Color function is not callable.") try: result = self.f(0, 0, 0, 0, 0) if len(result) != 3: raise ValueError("length should be equal to 3") except TypeError as te: ...
AssertionError
dataset/ETHPy150Open sympy/sympy/sympy/plotting/pygletplot/color_scheme.py/ColorScheme._test_color_function
7,636
def so_bindtodevice_supported(): try: if hasattr(IN, 'SO_BINDTODEVICE'): return True except __HOLE__: pass return False
NameError
dataset/ETHPy150Open circus-tent/circus/circus/tests/test_sockets.py/so_bindtodevice_supported
7,637
def safe_import(name): try: mod = __import__(name, None, None, "*") except __HOLE__: mod = MissingModule(name) except Exception: # issue 72: IronPython on Mono if sys.platform == "cli" and name == "signal": #os.name == "posix": mod = MissingModule(name) el...
ImportError
dataset/ETHPy150Open sccn/SNAP/src/rpyc/lib/__init__.py/safe_import
7,638
def _purge_consumer_by_tag(self, consumer_tag): '''Purge consumer entry from this basic instance NOTE: this protected method may be called by derived classes :param str consumer_tag: ''' try: del self._consumer_cb[consumer_tag] except __HOLE__: s...
KeyError
dataset/ETHPy150Open agoragames/haigha/haigha/classes/basic_class.py/BasicClass._purge_consumer_by_tag
7,639
def run(self): # pylint: disable=too-many-branches self._send(signal.RUN_START) self._initialize_run() try: while self.job_queue: try: self._init_job() self._run_job() except __HOLE__: self....
KeyboardInterrupt
dataset/ETHPy150Open ARM-software/workload-automation/wlauto/core/execution.py/Runner.run
7,640
def _run_job(self): # pylint: disable=too-many-branches spec = self.current_job.spec if not spec.enabled: self.logger.info('Skipping workload %s (iteration %s)', spec, self.context.current_iteration) self.current_job.result.status = IterationResult.SKIPPED return ...
KeyboardInterrupt
dataset/ETHPy150Open ARM-software/workload-automation/wlauto/core/execution.py/Runner._run_job
7,641
@contextmanager def _handle_errors(self, action, on_error_status=IterationResult.FAILED): try: if action is not None: self.logger.debug(action) yield except (__HOLE__, DeviceNotRespondingError): raise except (WAError, TimeoutError), we: ...
KeyboardInterrupt
dataset/ETHPy150Open ARM-software/workload-automation/wlauto/core/execution.py/Runner._handle_errors
7,642
def _output_to_dict(cmdoutput, values_mapper=None): ''' Convert rabbitmqctl output to a dict of data cmdoutput: string output of rabbitmqctl commands values_mapper: function object to process the values part of each line ''' ret = {} if values_mapper is None: values_mapper = lambda s...
ValueError
dataset/ETHPy150Open saltstack/salt/salt/modules/rabbitmq.py/_output_to_dict
7,643
def test_turns_into_unicode(self): unicode_str = b''.decode('utf-8') try: assert unicode(self.instance) == unicode_str except __HOLE__: assert str(self.instance) == unicode_str
NameError
dataset/ETHPy150Open sigmavirus24/github3.py/tests/unit/test_null.py/TestNullObject.test_turns_into_unicode
7,644
def testUploadAccount(self): hash_algorithm = gitkitclient.ALGORITHM_HMAC_SHA256 try: hash_key = bytes('key123', 'utf-8') except __HOLE__: hash_key = 'key123' upload_user = gitkitclient.GitkitUser.FromDictionary({ 'email': self.email, 'localId': self.user_id, 'dis...
TypeError
dataset/ETHPy150Open google/identity-toolkit-python-client/tests/test_gitkitclient.py/GitkitClientTestCase.testUploadAccount
7,645
def get_histogram(self, database, table, column, nested=None): """ Returns the results of an Impala SELECT histogram() FROM query for a given column or nested type. Assumes that the column/nested type is scalar. """ results = [] hql = self.get_histogram_query(database, table, column, nested) ...
IndexError
dataset/ETHPy150Open cloudera/hue/apps/impala/src/impala/dbms.py/ImpalaDbms.get_histogram
7,646
def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_quadopt', [dirname(__file__)]) except __HOLE__: import _quadopt return _quadopt if fp is not None: ...
ImportError
dataset/ETHPy150Open googlefonts/fontcrunch/fontcrunch/quadopt.py/swig_import_helper
7,647
@access.admin @describeRoute( Description('Set the value for a system setting, or a list of them.') .notes("""Must be a system administrator to call this. If the value passed is a valid JSON object, it will be parsed and stored as an object.""") .param('key', 'T...
ValueError
dataset/ETHPy150Open girder/girder/girder/api/v1/system.py/System.setSetting
7,648
@access.admin(scope=TokenScope.SETTINGS_READ) @describeRoute( Description('Get the value of a system setting, or a list of them.') .notes('Must be a system administrator to call this.') .param('key', 'The key identifying this setting.', required=False) .param('list', 'A JSON list of ...
ValueError
dataset/ETHPy150Open girder/girder/girder/api/v1/system.py/System.getSetting
7,649
@access.admin @describeRoute( Description('Set the list of enabled plugins for the system.') .responseClass('Setting') .notes('Must be a system administrator to call this.') .param('plugins', 'JSON array of plugins to enable.') .errorResponse('Required dependencies do not exi...
ValueError
dataset/ETHPy150Open girder/girder/girder/api/v1/system.py/System.enablePlugins
7,650
@access.admin(scope=TokenScope.PARTIAL_UPLOAD_CLEAN) @describeRoute( Description('Discard uploads that have not been finished.') .notes("""Must be a system administrator to call this. This frees resources that were allocated for the uploads and clears the uploads from d...
OSError
dataset/ETHPy150Open girder/girder/girder/api/v1/system.py/System.discardPartialUploads
7,651
def _run_worker(): LOG.info('(PID=%s) Exporter started.', os.getpid()) export_worker = worker.get_worker() try: export_worker.start(wait=True) except (KeyboardInterrupt, __HOLE__): LOG.info('(PID=%s) Exporter stopped.', os.getpid()) export_worker.shutdown() except: re...
SystemExit
dataset/ETHPy150Open StackStorm/st2/st2exporter/st2exporter/cmd/st2exporter_starter.py/_run_worker
7,652
def main(): try: _setup() return _run_worker() except __HOLE__ as exit_code: sys.exit(exit_code) except: LOG.exception('(PID=%s) Exporter quit due to exception.', os.getpid()) return 1 finally: _teardown()
SystemExit
dataset/ETHPy150Open StackStorm/st2/st2exporter/st2exporter/cmd/st2exporter_starter.py/main
7,653
def reorder(fname): """ Reorder fields in a configuration file so that assignments of variables comes before use. """ fp = open(fname, 'r+') options = Options() configresult = {} section = "" configresult[section] = Options() for line in fp.readlines(): line = line.strip...
ValueError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/confsort.py/reorder
7,654
def facebook_decorator(func): def wrapper(request, *args, **kwargs): user = request.user # User must me logged via FB backend in order to ensure we talk about # the same person if not is_complete_authentication(request): try: user = social_complete(reques...
ValueError
dataset/ETHPy150Open omab/django-social-auth/example/app/facebook.py/facebook_decorator
7,655
def format_message(self, message): message = self.normalize_message(message) username = message['n_user'] kind = message.get('kind') created = None group = message['n_group'] topic = message['n_topic'] message_body = message['n_message'] try: c...
KeyError
dataset/ETHPy150Open ptone/notifyore/notifyore/notifiers/stream.py/StreamNotifier.format_message
7,656
def collapse_address_list(addresses): """Collapse a list of IP objects. Example: collapse_address_list([IPv4Network('1.1.0.0/24'), IPv4Network('1.1.1.0/24')]) -> [IPv4Network('1.1.0.0/23')] Args: addresses: A list of IPv4Network ...
AttributeError
dataset/ETHPy150Open uwdata/termite-data-server/web2py/gluon/contrib/ipaddr.py/collapse_address_list
7,657
def __eq__(self, other): try: return (self._ip == other._ip and self._version == other._version) except __HOLE__: return NotImplemented
AttributeError
dataset/ETHPy150Open uwdata/termite-data-server/web2py/gluon/contrib/ipaddr.py/_BaseAddress.__eq__
7,658
def __eq__(self, other): try: return (self._version == other._version and self.network_address == other.network_address and int(self.netmask) == int(other.netmask)) except __HOLE__: if isinstance(other, _BaseAddress): return...
AttributeError
dataset/ETHPy150Open uwdata/termite-data-server/web2py/gluon/contrib/ipaddr.py/_BaseInterface.__eq__
7,659
def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. ...
ValueError
dataset/ETHPy150Open uwdata/termite-data-server/web2py/gluon/contrib/ipaddr.py/_BaseV4._ip_int_from_string
7,660
def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: ...
ValueError
dataset/ETHPy150Open uwdata/termite-data-server/web2py/gluon/contrib/ipaddr.py/IPv4Interface._is_hostmask
7,661
def _is_valid_netmask(self, netmask): """Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask. """ mask = n...
ValueError
dataset/ETHPy150Open uwdata/termite-data-server/web2py/gluon/contrib/ipaddr.py/IPv4Interface._is_valid_netmask
7,662
def _ip_int_from_string(self, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: A long, the IPv6 ip_str. Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ parts = i...
ValueError
dataset/ETHPy150Open uwdata/termite-data-server/web2py/gluon/contrib/ipaddr.py/_BaseV6._ip_int_from_string
7,663
def _is_valid_netmask(self, prefixlen): """Verify that the netmask/prefixlen is valid. Args: prefixlen: A string, the netmask in prefix length format. Returns: A boolean, True if the prefix represents a valid IPv6 netmask. """ try: ...
ValueError
dataset/ETHPy150Open uwdata/termite-data-server/web2py/gluon/contrib/ipaddr.py/IPv6Interface._is_valid_netmask
7,664
def test_describe_instances(self): i = InfrastructureManager() params1 = {} result1 = i.describe_instances(params1, 'secret1') self.assertFalse(result1['success']) self.assertEquals(result1['reason'], InfrastructureManager.REASON_BAD_SECRET) # test the scenario where we fail to give descr...
TypeError
dataset/ETHPy150Open AppScale/appscale/InfrastructureManager/tests/test_infrastructure_manager.py/TestInfrastructureManager.test_describe_instances
7,665
def load_object(path): """Load an object given its absolute object path, and return it. object can be a class, function, variable or an instance. path ie: 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware' """ try: dot = path.rindex('.') except ValueError: raise ValueEr...
AttributeError
dataset/ETHPy150Open scrapy/scrapy/scrapy/utils/misc.py/load_object
7,666
def get_default_status(self, status=None, request=request): try: return request.headers[self.requested_response_status_header] except (__HOLE__, RuntimeError): return super(API, self).get_default_status()
KeyError
dataset/ETHPy150Open salsita/flask-raml/flask_raml.py/API.get_default_status
7,667
def metadata(self, name): """ Returns the metadata for the named variable. Args ---- name : str Name of variable to get the metadata for. Returns ------- dict The metadata dict for the named variable. Raises -----...
KeyError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/core/vec_wrapper.py/VecWrapper.metadata
7,668
def _get_local_idxs(self, name, idx_dict, get_slice=False): """ Returns all of the indices for the named variable in this vector. Args ---- name : str Name of variable to get the indices for. get_slice : bool, optional If True, return the idxs as...
KeyError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/core/vec_wrapper.py/VecWrapper._get_local_idxs
7,669
def setup(self, parent_params_vec, params_dict, srcvec, my_params, connections, relevance=None, var_of_interest=None, store_byobjs=False, shared_vec=None, alloc_complex=False): """ Configure this vector to store a flattened array of the variables in params_dict. Varia...
KeyError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/core/vec_wrapper.py/TgtVecWrapper.setup
7,670
def test_strings(self): assert_that('').is_not_none() assert_that('').is_empty() assert_that('').is_false() assert_that('').is_type_of(str) assert_that('').is_instance_of(str) assert_that('foo').is_length(3) assert_that('foo').is_not_empty() assert_that('...
AssertionError
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_readme.py/TestReadme.test_strings
7,671
def test_custom_error_message(self): try: assert_that(1+2).is_equal_to(2) fail('should have raised error') except AssertionError as e: assert_that(str(e)).is_equal_to('Expected <3> to be equal to <2>, but was not.') try: assert_that(1+2).described...
AssertionError
dataset/ETHPy150Open ActivisionGameScience/assertpy/tests/test_readme.py/TestReadme.test_custom_error_message
7,672
def get_minpad(self, axis): try: return self._minpad[axis] except __HOLE__: return self._minpad
TypeError
dataset/ETHPy150Open glue-viz/glue/glue/external/wcsaxes/axislabels.py/AxisLabels.get_minpad
7,673
def check_x_scale(x_scale, x0): if isinstance(x_scale, string_types) and x_scale == 'jac': return x_scale try: x_scale = np.asarray(x_scale, dtype=float) valid = np.all(np.isfinite(x_scale)) and np.all(x_scale > 0) except (__HOLE__, TypeError): valid = False if not vali...
ValueError
dataset/ETHPy150Open scipy/scipy/scipy/optimize/_lsq/least_squares.py/check_x_scale
7,674
def getStreamedConstant(constant_value): # Note: The marshal module cannot persist all unicode strings and # therefore cannot be used. Instead we use pickle. try: saved = cpickle.dumps( constant_value, protocol = 0 if type(constant_value) is unicode else pickle_protocol ...
TypeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/codegen/Pickling.py/getStreamedConstant
7,675
def do_deletes(): while True: f = _get_delete_path() if f is None: break try: if os.path.isfile(f): os.remove(f) elif os.path.isdir(f): rm_full_dir(f) except __HOLE__: log.error("Failed to delete: %s", f)
OSError
dataset/ETHPy150Open blackberry/ALF/alf/local.py/do_deletes
7,676
def main(proj_name, project_inst, run_folder, template_fn, iters, aggr_min, aggr_max, keep, timeout, write_pickle, reduce, reduce_n): "main loop" ext = os.path.splitext(os.path.basename(template_fn))[1] results = 0 iterno = 0 is_replay = (iters == 1 and aggr_min == 0 and aggr_max == 0) ...
KeyboardInterrupt
dataset/ETHPy150Open blackberry/ALF/alf/local.py/main
7,677
def load_project(project_name): # load project and check that it looks okay try: importlib.import_module(project_name) except ImportError as e: try: #TODO: relative module imports in a projects/Project will fail for some reason importlib.import_module("projects.%s" % ...
ImportError
dataset/ETHPy150Open blackberry/ALF/alf/local.py/load_project
7,678
def _internal_increment(self, namespace, request): """Internal function for incrementing from a MemcacheIncrementRequest. Args: namespace: A string containing the namespace for the request, if any. Pass an empty string if there is no namespace. request: A MemcacheIncrementRequest instance. ...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/memcache/memcache_stub.py/MemcacheServiceStub._internal_increment
7,679
def unthe(self, text, pattern): """Moves pattern in the path format string or strips it text -- text to handle pattern -- regexp pattern (case ignore is already on) strip -- if True, pattern will be removed """ if text: r = re.compile(pattern, flags=re.IGNORE...
IndexError
dataset/ETHPy150Open beetbox/beets/beetsplug/the.py/ThePlugin.unthe
7,680
@access.user @loadmodel(model='collection', level=AccessType.ADMIN) @filtermodel(model='collection', addFields={'access'}) @describeRoute( Description('Set the access control list for a collection.') .param('id', 'The ID of the collection.', paramType='path') .param('access', 'The ac...
ValueError
dataset/ETHPy150Open girder/girder/girder/api/v1/collection.py/Collection.updateCollectionAccess
7,681
def encrypt(claims, jwk, adata='', add_header=None, alg='RSA-OAEP', enc='A128CBC-HS256', rng=get_random_bytes, compression=None): """ Encrypts the given claims and produces a :class:`~jose.JWE` :param claims: A `dict` representing the claims for this :class:`~jose.JWE`. :param jw...
KeyError
dataset/ETHPy150Open Demonware/jose/jose.py/encrypt
7,682
def spec_compliant_encrypt(claims, jwk, add_header=None, alg='RSA-OAEP', enc='A128CBC-HS256', rng=get_random_bytes): """ Encrypts the given claims and produces a :class:`~jose.JWE` :param claims: A `dict` representing the claims for this :class:`~jose.JWE`. :pa...
KeyError
dataset/ETHPy150Open Demonware/jose/jose.py/spec_compliant_encrypt
7,683
def legacy_decrypt(jwe, jwk, adata='', validate_claims=True, expiry_seconds=None): """ Decrypts a deserialized :class:`~jose.JWE` :param jwe: An instance of :class:`~jose.JWE` :param jwk: A `dict` representing the JWK required to decrypt the content of the :class:`~jose.J...
KeyError
dataset/ETHPy150Open Demonware/jose/jose.py/legacy_decrypt
7,684
def spec_compliant_decrypt(jwe, jwk, validate_claims=True, expiry_seconds=None): """ Decrypts a deserialized :class:`~jose.JWE` :param jwe: An instance of :class:`~jose.JWE` :param jwk: A `dict` representing the JWK required to decrypt the content of the :class:`~...
KeyError
dataset/ETHPy150Open Demonware/jose/jose.py/spec_compliant_decrypt
7,685
def decrypt(*args, **kwargs): """ Decrypts legacy or spec-compliant JOSE token. First attempts to decrypt the token in a legacy mode (https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-19). If it is not a valid legacy token then attempts to decrypt it in a spec-compliant way (http://tools.i...
ValueError
dataset/ETHPy150Open Demonware/jose/jose.py/decrypt
7,686
def b64decode_url(istr): """ JWT Tokens may be truncated without the usual trailing padding '=' symbols. Compensate by padding to the nearest 4 bytes. """ istr = encode_safe(istr) try: return urlsafe_b64decode(istr + '=' * (4 - (len(istr) % 4))) except __HOLE__ as e: raise Er...
TypeError
dataset/ETHPy150Open Demonware/jose/jose.py/b64decode_url
7,687
def encode_safe(istr, encoding='utf8'): try: return istr.encode(encoding) except __HOLE__: # this will fail if istr is already encoded pass return istr
UnicodeDecodeError
dataset/ETHPy150Open Demonware/jose/jose.py/encode_safe
7,688
def decrypt_oaep(ciphertext, jwk): try: return PKCS1_OAEP.new(RSA.importKey(jwk['k'])).decrypt(ciphertext) except __HOLE__ as e: raise Error(e.args[0])
ValueError
dataset/ETHPy150Open Demonware/jose/jose.py/decrypt_oaep
7,689
def _compound_from_key(self, key): try: enc, hash = key.split('+') return enc, hash except ValueError: pass try: enc, hash = key.split('-') return enc, hash except __HOLE__: pass raise Error('Unsupported al...
ValueError
dataset/ETHPy150Open Demonware/jose/jose.py/_JWA._compound_from_key
7,690
def _validate(claims, validate_claims, expiry_seconds): """ Validate expiry related claims. If validate_claims is False, do nothing. Otherwise, validate the exp and nbf claims if they are present, and validate the iat claim if expiry_seconds is provided. """ if not validate_claims: ret...
KeyError
dataset/ETHPy150Open Demonware/jose/jose.py/_validate
7,691
def execute_from_command_line(): try: cmd = sys.argv[1] except __HOLE__: cmd = "help" try: subcmd = sys.argv[2:] except: print "error" if cmd == "help": sys.stdout.write(help_text()) else: exe = get_command(cmd) if exe: exe.ex...
IndexError
dataset/ETHPy150Open CelloCello/flask-go/flask_go/management.py/execute_from_command_line
7,692
def consume(self): try: if self.data[self.p] == 10: # \n self.line += 1 self.charPositionInLine = 0 else: self.charPositionInLine += 1 self.p += 1 except __HOLE__: # happend when we reached EOF ...
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/antlr3/antlr3/streams.py/ANTLRStringStream.consume
7,693
def LA(self, i): if i == 0: return 0 # undefined if i < 0: i += 1 # e.g., translate LA(-1) to use offset i=0; then data[p+0-1] try: return self.data[self.p+i-1] except __HOLE__: return EOF
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/antlr3/antlr3/streams.py/ANTLRStringStream.LA
7,694
def LT(self, i): if i == 0: return 0 # undefined if i < 0: i += 1 # e.g., translate LA(-1) to use offset i=0; then data[p+0-1] try: return self.strdata[self.p+i-1] except __HOLE__: return EOF
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/antlr3/antlr3/streams.py/ANTLRStringStream.LT
7,695
def mark(self): state = (self.p, self.line, self.charPositionInLine) try: self._markers[self.markDepth] = state except __HOLE__: self._markers.append(state) self.markDepth += 1 self.lastMarker = self.markDepth return self.lastMark...
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/antlr3/antlr3/streams.py/ANTLRStringStream.mark
7,696
def fillBuffer(self): """ Load all tokens from the token source and put in tokens. This is done upon first LT request because you might want to set some token type / channel overrides before filling buffer. """ index = 0 t = self.tokenSource.nextToken() ...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/antlr3/antlr3/streams.py/CommonTokenStream.fillBuffer
7,697
def skipOffTokenChannels(self, i): """ Given a starting index, return the index of the first on-channel token. """ try: while self.tokens[i].channel != self.channel: i += 1 except __HOLE__: # hit the end of token stream ...
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/antlr3/antlr3/streams.py/CommonTokenStream.skipOffTokenChannels
7,698
def LT(self, k): """ Get the ith token from the current position 1..n where k=1 is the first symbol of lookahead. """ if self.p == -1: self.fillBuffer() if k == 0: return None if k < 0: return self.LB(-k) ...
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/antlr3/antlr3/streams.py/CommonTokenStream.LT
7,699
def toString(self, *args): if len(args) == 0: programName = self.DEFAULT_PROGRAM_NAME start = self.MIN_TOKEN_INDEX end = self.size() - 1 elif len(args) == 1: programName = args[0] start = self.MIN_TOKEN_INDEX end = self...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/antlr3/antlr3/streams.py/TokenRewriteStream.toString