Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
2,500
def no_jump_into_finally_block(output): try: try: output.append(3) x = 1 finally: output.append(6) except __HOLE__ as e: output.append('finally' in str(e))
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/no_jump_into_finally_block
2,501
def no_jump_out_of_finally_block(output): try: try: output.append(3) finally: output.append(5) output.append(6) except __HOLE__ as e: output.append('finally' in str(e))
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/no_jump_out_of_finally_block
2,502
def no_jump_to_non_integers(output): try: output.append(2) except __HOLE__ as e: output.append('integer' in str(e))
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/no_jump_to_non_integers
2,503
def no_jump_without_trace_function(): try: previous_frame = sys._getframe().f_back previous_frame.f_lineno = previous_frame.f_lineno except __HOLE__ as e: # This is the exception we wanted; make sure the error message # talks about trace functions. if 'trace' not in str(e...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_sys_settrace.py/no_jump_without_trace_function
2,504
def now_playing(self, cardinal, user, channel, msg): # Before we do anything, let's make sure we'll be able to query Last.fm if self.api_key is None: cardinal.sendMsg( channel, "Last.fm plugin is not configured. Please set API key." ) s...
IndexError
dataset/ETHPy150Open JohnMaguire/Cardinal/plugins/lastfm/plugin.py/LastfmPlugin.now_playing
2,505
def compare(self, cardinal, user, channel, msg): # Before we do anything, let's make sure we'll be able to query Last.fm if self.api_key is None: cardinal.sendMsg( channel, "Last.fm plugin is not configured correctly. " "Please set API key." ...
KeyError
dataset/ETHPy150Open JohnMaguire/Cardinal/plugins/lastfm/plugin.py/LastfmPlugin.compare
2,506
def _check_imports(): """ Dynamically remove optimizers we don't have """ optlist = ['ALPSO', 'CONMIN', 'FSQP', 'IPOPT', 'NLPQLP', 'NSGA2', 'PSQP', 'SLSQP', 'SNOPT', 'NLPY_AUGLAG', 'NOMAD'] for optimizer in optlist[:]: try: exec('from pyoptsparse import %s' % optimiz...
ImportError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/drivers/pyoptsparse_driver.py/_check_imports
2,507
def run(self, problem): """pyOpt execution. Note that pyOpt controls the execution, and the individual optimizers (i.e., SNOPT) control the iteration. Args ---- problem : `Problem` Our parent `Problem`. """ self.pyopt_solution = None rel = pr...
ImportError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/drivers/pyoptsparse_driver.py/pyOptSparseDriver.run
2,508
def parse(self, field, data): try: return FieldParser.parse(self, field, data) except __HOLE__: return InvalidValue(data)
ValueError
dataset/ETHPy150Open olemb/dbfread/examples/print_invalid_values.py/MyFieldParser.parse
2,509
def mkdir_p(path): # Python doesn't have an analog to `mkdir -p` < Python 3.2. try: os.makedirs(path) except __HOLE__ as e: if e.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
OSError
dataset/ETHPy150Open zulip/zulip/zulip_tools.py/mkdir_p
2,510
def get_deployment_lock(error_rerun_script): start_time = time.time() got_lock = False while time.time() - start_time < 300: try: os.mkdir(LOCK_DIR) got_lock = True break except __HOLE__: print(WARNING + "Another deployment in progress; waiting...
OSError
dataset/ETHPy150Open zulip/zulip/zulip_tools.py/get_deployment_lock
2,511
def cleanup(self): # This code sometimes runs when the rest of this module # has already been deleted, so it can't use any globals # or import anything. if self.__tempfiles: for file in self.__tempfiles: try: self.__unlink(file) ...
OSError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/URLopener.cleanup
2,512
def retrieve(self, url, filename=None, reporthook=None, data=None): """retrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.""" url = unwrap(toBytes(url)) if self.tempcache and url in self.tempcache: return self.tempcache...
IOError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/URLopener.retrieve
2,513
def open_local_file(self, url): """Use local file.""" import mimetypes, mimetools, email.Utils try: from cStringIO import StringIO except __HOLE__: from StringIO import StringIO host, file = splithost(url) localname = url2pathname(file) try...
ImportError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/URLopener.open_local_file
2,514
def open_ftp(self, url): """Use FTP protocol.""" if not isinstance(url, str): raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented') import mimetypes, mimetools try: from cStringIO import StringIO except __HOLE__: ...
ImportError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/URLopener.open_ftp
2,515
def open_data(self, url, data=None): """Use "data" URL.""" if not isinstance(url, str): raise IOError, ('data error', 'proxy support for data protocol currently not implemented') # ignore POSTed data # # syntax of data URLs: # dataurl := "data:" [ mediatype ...
ValueError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/URLopener.open_data
2,516
def prompt_user_passwd(self, host, realm): """Override this in a GUI environment!""" import getpass try: user = raw_input("Enter username for %s at %s: " % (realm, host)) passwd = getpass.getpass("Enter passw...
KeyboardInterrupt
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/FancyURLopener.prompt_user_passwd
2,517
def noheaders(): """Return an empty mimetools.Message object.""" global _noheaders if _noheaders is None: import mimetools try: from cStringIO import StringIO except __HOLE__: from StringIO import StringIO _noheaders = mimetools.Message(StringIO(), 0) ...
ImportError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/noheaders
2,518
def splitnport(host, defport=-1): """Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number.""" global _nportprog if _nportprog is None: ...
ValueError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/splitnport
2,519
def unquote(s): """unquote('abc%20def') -> 'abc def'.""" res = s.split('%') for i in xrange(1, len(res)): item = res[i] try: res[i] = _hextochr[item[:2]] + item[2:] except KeyError: res[i] = '%' + item except __HOLE__: res[i] = unichr(int(i...
UnicodeDecodeError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/unquote
2,520
def quote(s, safe = '/'): """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists the following reserved characters. reserved ...
KeyError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/quote
2,521
def urlencode(query,doseq=0): """Encode a sequence of two-element tuples or dictionary into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of...
TypeError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/urlencode
2,522
def getproxies_internetconfig(): """Return a dictionary of scheme -> proxy server URL mappings. By convention the mac uses Internet Config to store proxies. An HTTP proxy, for instance, is stored under the HttpProxy key. """ try: import ic except __...
ImportError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/getproxies_internetconfig
2,523
def getproxies_registry(): """Return a dictionary of scheme -> proxy server URL mappings. Win32 uses the registry to store proxies. """ proxies = {} try: import _winreg except __HOLE__: # Std module, so should be around - but you never know! ...
ImportError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/getproxies_registry
2,524
def proxy_bypass(host): try: import _winreg import re except __HOLE__: # Std modules, so should be around - but you never know! return 0 try: internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, r'Software\Micro...
ImportError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/urllib.py/proxy_bypass
2,525
def error(self, obj, name, value): """Returns an informative and descriptive error string.""" wtype = "value" wvalue = value info = "an array-like object" # pylint: disable=E1101 if self.shape and hasattr(value, 'shape') and value.shape: if self.shape != val...
AttributeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/datatypes/array.py/Array.error
2,526
def _validate_with_metadata(self, obj, name, value, src_units): """Perform validation and unit conversion using metadata from the source trait. """ # pylint: disable=E1101 dst_units = self.units try: pq = PhysicalQuantity(1.0, src_units) except __HOL...
NameError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/datatypes/array.py/Array._validate_with_metadata
2,527
def main(): args = parse_args() warnings.simplefilter('always') resolver_kwargs = {} if args.order is not None: resolver_kwargs['order'] = args.order.split(',') if args.options is not None: resolver_kwargs['options'] = json.loads(args.options) resolver = get_resolver(**resolver_k...
ValueError
dataset/ETHPy150Open Kitware/minerva/server/libs/carmen/cli.py/main
2,528
def __main_loop(self): """The main program loop, reads JSON requests from stdin, writes JSON responses to stdout """ while(True): # reset result and log self.result = False self.log = [] # get the request string, strip the ending "\n" ...
AttributeError
dataset/ETHPy150Open polaris-gslb/polaris-gslb/polaris_pdns/core/remotebackend.py/RemoteBackend.__main_loop
2,529
def __get(self, name, obj, default=None): try: attr = getattr(self, name) except __HOLE__: return default if callable(attr): return attr(obj) return attr
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/sitemaps/__init__.py/Sitemap.__get
2,530
def _sync_from_artifact_store(jobstep): """Checks and creates new artifacts from the artifact store.""" url = '{base}/buckets/{jobstep_id}/artifacts/'.format( base=current_app.config.get('ARTIFACTS_SERVER'), jobstep_id=jobstep.id.hex, ) job = jobstep.job try: res = requests....
HTTPError
dataset/ETHPy150Open dropbox/changes/changes/jobs/sync_job_step.py/_sync_from_artifact_store
2,531
def verify(self, mhash, S): """Verify that a certain PKCS#1 PSS signature is authentic. This function checks if the party holding the private half of the given RSA key has really signed the message. This function is called ``RSASSA-PSS-VERIFY``, and is specified in section ...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pycrypto-2.6.1/lib/Crypto/Signature/PKCS1_PSS.py/PSS_SigScheme.verify
2,532
def ApplyPluginsToBatch(self, hunt_urn, plugins, batch, batch_index): exceptions_by_plugin = {} for plugin_def, plugin in plugins: logging.debug("Processing hunt %s with %s, batch %d", hunt_urn, plugin_def.plugin_name, batch_index) try: plugin.ProcessResponses(batch) ...
IOError
dataset/ETHPy150Open google/grr/grr/lib/hunts/standard.py/ProcessHuntResultsCronFlow.ApplyPluginsToBatch
2,533
def delete_user(email, profile="splunk"): ''' Delete a splunk user by email CLI Example: salt myminion splunk_user.delete 'user@example.com' ''' client = _get_splunk(profile) user = list_users(profile).get(email) if user: try: client.users.delete(user.name) ...
HTTPError
dataset/ETHPy150Open saltstack/salt/salt/modules/splunk.py/delete_user
2,534
def __init__(self, *args, **kwargs): try: del kwargs['name'] del kwargs['expected_type'] except __HOLE__: pass super().__init__(*args, name='dart_sdk_path', expected_type=str, **kwargs)
KeyError
dataset/ETHPy150Open guillermooo/dart-sublime-bundle/lib/sdk.py/DartSdkPathSetting.__init__
2,535
def __init__(self, *args, **kwargs): try: del kwargs['name'] del kwargs['expected_type'] except __HOLE__: pass super().__init__(*args, name='dart_dartium_path', expected_type=str, **kwargs)
KeyError
dataset/ETHPy150Open guillermooo/dart-sublime-bundle/lib/sdk.py/DartiumPathSetting.__init__
2,536
def add(self, repo_url=None, ppa=None): """ This function used to add apt repositories and or ppa's If repo_url is provided adds repo file to /etc/apt/sources.list.d/ If ppa is provided add apt-repository using add-apt-repository command. """ ...
IOError
dataset/ETHPy150Open EasyEngine/easyengine/ee/core/apt_repo.py/EERepo.add
2,537
def remove(self, ppa=None, repo_url=None): """ This function used to remove ppa's If ppa is provided adds repo file to /etc/apt/sources.list.d/ command. """ if ppa: EEShellExec.cmd_exec(self, "add-apt-repository -y " ...
IOError
dataset/ETHPy150Open EasyEngine/easyengine/ee/core/apt_repo.py/EERepo.remove
2,538
def undeployed(name, url='http://localhost:8080/manager', timeout=180): ''' Enforce that the WAR will be un-deployed from the server name the context path to deploy url : http://localhost:8080/manager the URL of the server manager webapp timeout : 1...
KeyError
dataset/ETHPy150Open saltstack/salt/salt/states/tomcat.py/undeployed
2,539
def _colorize(text, colorize=True): if not colorize or not sys.stdout.isatty(): return text try: from pygments import highlight from pygments.formatters import TerminalFormatter from pygments.lexers import PythonLexer return highlight(text, PythonLexer(), TerminalFormatte...
ImportError
dataset/ETHPy150Open scrapy/scrapy/scrapy/utils/display.py/_colorize
2,540
def main(): usagestr = "usage: %prog [-h] [options] [args]" parser = optparse.OptionParser(usage = usagestr) parser.set_defaults(numnodes = 5) parser.add_option("-n", "--numnodes", dest = "numnodes", type = int, help = "number of nodes") def usage(msg = None, err = 0): ...
ValueError
dataset/ETHPy150Open coreemu/core/daemon/examples/netns/emane80211.py/main
2,541
def test_connect_in_mocking(self): """Ensure that the connect() method works properly in mocking. """ try: import mongomock except __HOLE__: raise SkipTest('you need mongomock installed to run this testcase') connect('mongoenginetest', host='mongomock://l...
ImportError
dataset/ETHPy150Open MongoEngine/mongoengine/tests/test_connection.py/ConnectionTest.test_connect_in_mocking
2,542
def __init__(self, rradir, rrdcache=None): if rrdtool is None: raise errors.InitError( "The python module 'rrdtool' is not installed") if not os.path.exists(rradir): try: os.makedirs(rradir) except __HOLE__, ex: rai...
OSError
dataset/ETHPy150Open marineam/nagcat/python/nagcat/trend.py/TrendMaster.__init__
2,543
def __init__(self, conf, rradir, start=None, rrdapi=None, private=False): self._step = util.Interval(conf.get("repeat", "1m")).seconds self._ds_list = {'_state': {'type': "GAUGE", 'min': None, 'max': None}} # _ds_order is the order in the actual file and is set in validate() self._ds_ord...
OSError
dataset/ETHPy150Open marineam/nagcat/python/nagcat/trend.py/Trend.__init__
2,544
@urlmatch(netloc=r'(.*\.)?api\.weixin\.qq\.com$') def wechat_api_mock(url, request): path = url.path.replace('/cgi-bin/component/', '').replace('/', '_') res_file = os.path.join(_FIXTURE_PATH, '%s.json' % path) content = { 'errcode': 99999, 'errmsg': 'can not find fixture %s' % res_file, ...
IOError
dataset/ETHPy150Open jxtech/wechatpy/tests/test_component_api.py/wechat_api_mock
2,545
@contextmanager def patch_os_environment(remove=None, **values): """ Context manager for patching the operating system environment. """ old_values = {} remove = remove or [] for key in remove: old_values[key] = os.environ.pop(key) for key, value in values.iteritems(): old_val...
KeyError
dataset/ETHPy150Open quantopian/zipline/zipline/testing/core.py/patch_os_environment
2,546
def _update_metrics(self, slug, game): metrics = MetricsSession.get_metrics(slug) inverse_mapping = get_inverse_mapping_table(game) for session in metrics: try: s = _Session(session['timestamp']) fileDict = {} for entry in session['en...
TypeError
dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/controllers/localv1/metrics.py/MetricsController._update_metrics
2,547
@classmethod def as_csv(cls, slug, timestamp): timestamp_format = '%Y-%m-%d_%H-%M-%S' try: filename = '%s-%s.csv' % (slug, time.strftime(timestamp_format, time.gmtime(float(timestamp)))) except __HOLE__: abort(404, 'Invalid timestamp: %s' % timestamp) respons...
ValueError
dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/controllers/localv1/metrics.py/MetricsController.as_csv
2,548
@classmethod @jsonify def as_json(cls, slug, timestamp): timestamp_format = '%Y-%m-%d_%H-%M-%S' try: filename = '%s-%s.json' % (slug, time.strftime(timestamp_format, time.gmtime(float(timestamp)))) except __HOLE__: abort(404, 'Invalid timestamp: %s' % timestamp) ...
ValueError
dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/controllers/localv1/metrics.py/MetricsController.as_json
2,549
def serve_forever(self): """ Run the DAAP server. Start by advertising the server via Bonjour. Then serve requests until CTRL + C is received. """ # Verify that the provider has a server. if self.provider.server is None: raise ValueError( "Can...
KeyboardInterrupt
dataset/ETHPy150Open basilfx/flask-daapserver/daapserver/__init__.py/DaapServer.serve_forever
2,550
def __contains__(self, shape): try: return shape.in_sphere(self) except __HOLE__: raise TypeError( "No 'in_sphere' method supplied by %s" % type(shape) )
AttributeError
dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/gameobjects/sphere.py/Sphere.__contains__
2,551
def intersects(self, shape): try: return shape.intersects_sphere(self) except __HOLE__: raise TypeError( "No 'intersects_sphere' method supplied by %s" % type(shape) )
AttributeError
dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/gameobjects/sphere.py/Sphere.intersects
2,552
def parse_bytesio(bytesio): """Parse the shebang from a file opened for reading binary.""" if bytesio.read(2) != b'#!': return () first_line = bytesio.readline() try: first_line = first_line.decode('US-ASCII') except __HOLE__: return () # Require only printable ascii ...
UnicodeDecodeError
dataset/ETHPy150Open pre-commit/pre-commit/pre_commit/parse_shebang.py/parse_bytesio
2,553
def _extract_error_json(body): """Return error_message from the HTTP response body.""" error_json = {} try: body_json = json.loads(body) if 'error_message' in body_json: raw_msg = body_json['error_message'] error_json = json.loads(raw_msg) else: er...
ValueError
dataset/ETHPy150Open openstack/python-magnumclient/magnumclient/common/httpclient.py/_extract_error_json
2,554
def json_request(self, method, url, **kwargs): kwargs.setdefault('headers', {}) kwargs['headers'].setdefault('Content-Type', 'application/json') kwargs['headers'].setdefault('Accept', 'application/json') if 'body' in kwargs: kwargs['body'] = json.dumps(kwargs['body']) ...
ValueError
dataset/ETHPy150Open openstack/python-magnumclient/magnumclient/common/httpclient.py/HTTPClient.json_request
2,555
def json_request(self, method, url, **kwargs): kwargs.setdefault('headers', {}) kwargs['headers'].setdefault('Content-Type', 'application/json') kwargs['headers'].setdefault('Accept', 'application/json') if 'body' in kwargs: kwargs['data'] = json.dumps(kwargs.pop('body')) ...
ValueError
dataset/ETHPy150Open openstack/python-magnumclient/magnumclient/common/httpclient.py/SessionClient.json_request
2,556
def description(self, test): try: # Wrapped _ErrorHolder objects have their own description return trim_docstring(test.description) except __HOLE__: # Fall back to the docstring on the method itself. if test._testMethodDoc: return trim_docs...
AttributeError
dataset/ETHPy150Open pybee/cricket/cricket/pipes.py/PipedTestResult.description
2,557
def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None): """Constructor, takes a WebDriver instance and timeout in seconds. :Args: - driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote) - timeout - Number of seconds before timing ...
TypeError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/selenium/webdriver/support/wait.py/WebDriverWait.__init__
2,558
@classmethod def get_first_root_node(cls): """ :returns: The first root node in the tree or ``None`` if it is empty. """ try: return cls.get_root_nodes()[0] except __HOLE__: return None
IndexError
dataset/ETHPy150Open tabo/django-treebeard/treebeard/models.py/Node.get_first_root_node
2,559
@classmethod def get_last_root_node(cls): """ :returns: The last root node in the tree or ``None`` if it is empty. """ try: return cls.get_root_nodes().reverse()[0] except __HOLE__: return None
IndexError
dataset/ETHPy150Open tabo/django-treebeard/treebeard/models.py/Node.get_last_root_node
2,560
def get_first_child(self): """ :returns: The leftmost node's child, or None if it has no children. """ try: return self.get_children()[0] except __HOLE__: return None
IndexError
dataset/ETHPy150Open tabo/django-treebeard/treebeard/models.py/Node.get_first_child
2,561
def get_last_child(self): """ :returns: The rightmost node's child, or None if it has no children. """ try: return self.get_children().reverse()[0] except __HOLE__: return None
IndexError
dataset/ETHPy150Open tabo/django-treebeard/treebeard/models.py/Node.get_last_child
2,562
def __new__(cls, name, bases, attrs): try: PrefixedSettings except __HOLE__: # Creating the PrefixedSettings class. Continue. pass else: if PrefixedSettings in bases: prefix = get_prefix(attrs, name) attrs = prefix_a...
NameError
dataset/ETHPy150Open matthewwithanm/django-classbasedsettings/cbsettings/settings.py/PrefixedSettingsBase.__new__
2,563
def __new__(cls, name, bases, attrs): try: AppSettings except __HOLE__: # Creating the AppSettings class. Continue. pass else: if AppSettings in bases: prefix = get_prefix(attrs, name, use_app_name=True) attrs = pref...
NameError
dataset/ETHPy150Open matthewwithanm/django-classbasedsettings/cbsettings/settings.py/AppSettingsBase.__new__
2,564
def load(self, bytes, base_url=None): """ Takes a bytestring and returns a document. """ try: data = json.loads(bytes.decode('utf-8')) except __HOLE__ as exc: raise ParseError('Malformed JSON. %s' % exc) doc = _parse_document(data, base_url) ...
ValueError
dataset/ETHPy150Open core-api/python-client/coreapi/codecs/hal.py/HALCodec.load
2,565
def serve(self): while self._event.is_set(): try: self.handle_request() except __HOLE__: # When server is being closed, while loop can run once # after setting self._event = False depending on how it # is scheduled. ...
TypeError
dataset/ETHPy150Open pydy/pydy/pydy/viz/server.py/StoppableHTTPServer.serve
2,566
def __init__(self): # pragma: no cover libraw = util.find_library('raw') try: if libraw is not None: super(LibRaw, self).__init__(libraw) else: raise ImportError except (ImportError, AttributeError, __HOLE__, IOError): raise Im...
OSError
dataset/ETHPy150Open photoshell/rawkit/libraw/bindings.py/LibRaw.__init__
2,567
@login_required @permission_required("waitinglist.manage_cohorts") def cohort_member_add(request, pk): cohort = Cohort.objects.get(pk=pk) if "invite_next" in request.POST: try: N = int(request.POST["invite_next"]) except __HOLE__: return redirect("waitinglist_cohort_det...
ValueError
dataset/ETHPy150Open pinax/django-waitinglist/waitinglist/views.py/cohort_member_add
2,568
def _update_workflow_nodes_json(workflow, json_nodes, id_map, user): """Ideally would get objects from form validation instead.""" nodes = [] for json_node in json_nodes: node = get_or_create_node(workflow, json_node, save=False) if node.node_type == 'subworkflow': try: node.sub_workflow =...
TypeError
dataset/ETHPy150Open cloudera/hue/apps/oozie/src/oozie/views/api.py/_update_workflow_nodes_json
2,569
def extract_panel_definitions_from_model_class(model, exclude=None): if hasattr(model, 'panels'): return model.panels panels = [] _exclude = [] if exclude: _exclude.extend(exclude) fields = fields_for_model(model, exclude=_exclude, formfield_callback=formfield_for_dbfield) fo...
AttributeError
dataset/ETHPy150Open torchbox/wagtail/wagtail/wagtailadmin/edit_handlers.py/extract_panel_definitions_from_model_class
2,570
def classes(self): """ Additional CSS classnames to add to whatever kind of object this is at output. Subclasses of EditHandler should override this, invoking super(B, self).classes() to append more classes specific to the situation. """ classes = [] try: ...
AttributeError
dataset/ETHPy150Open torchbox/wagtail/wagtail/wagtailadmin/edit_handlers.py/EditHandler.classes
2,571
@cached_classmethod def target_models(cls): if cls.page_type: target_models = [] for page_type in cls.page_type: try: target_models.append(resolve_model_string(page_type)) except LookupError: raise ImproperlyCon...
ValueError
dataset/ETHPy150Open torchbox/wagtail/wagtail/wagtailadmin/edit_handlers.py/BasePageChooserPanel.target_models
2,572
def mount(location, access='rw', root=None): ''' Mount an image CLI Example: .. code-block:: bash salt '*' guest.mount /srv/images/fedora.qcow ''' if root is None: root = os.path.join( tempfile.gettempdir(), 'guest', location.lstrip(os.sep)....
OSError
dataset/ETHPy150Open saltstack/salt/salt/modules/guestfs.py/mount
2,573
def run(self): """ fetch artefacts """ source_path = self.workflow.source.path sources_file_path = os.path.join(source_path, 'sources') artefacts = "" try: with open(sources_file_path, 'r') as f: artefacts = f.read() sel...
IOError
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/plugins/pre_pyrpkg_fetch_artefacts.py/DistgitFetchArtefactsPlugin.run
2,574
def unicode_strings(buf, n=4): reg = b"((?:[%s]\x00){4,})" % (ASCII_BYTE) ascii_re = re.compile(reg) for match in ascii_re.finditer(buf): try: if isinstance(match.group(), array.array): yield match.group().tostring().decode("utf-16") else: yiel...
UnicodeDecodeError
dataset/ETHPy150Open williballenthin/INDXParse/get_file_info.py/unicode_strings
2,575
def create_safe_datetime(fn): try: return fn() except __HOLE__: return datetime.datetime(1970, 1, 1, 0, 0, 0)
ValueError
dataset/ETHPy150Open williballenthin/INDXParse/get_file_info.py/create_safe_datetime
2,576
def main(): parser = argparse.ArgumentParser(description='Inspect ' 'a given MFT file record.') parser.add_argument('-a', action="store", metavar="cache_size", type=int, dest="cache_size", default=1024, help="Size of cache.") ...
ValueError
dataset/ETHPy150Open williballenthin/INDXParse/get_file_info.py/main
2,577
def zip_longest(*args, **kwds): # noqa fillvalue = kwds.get("fillvalue") def sentinel(counter=([fillvalue] * (len(args) - 1)).pop): yield counter() # yields the fillvalue, or raises IndexError fillers = itertools.repeat(fillvalue) iters = [itertools.chain(it, sentinel(...
IndexError
dataset/ETHPy150Open aparo/pyes/pyes/utils/compat.py/zip_longest
2,578
def handle_noargs(self, **options): self.set_options(**options) found_files = SortedDict() manifest = ConfiguredStaticFilesManifest() manifest.clear() ignore_patterns = getattr(settings, 'ECSTATIC_MANIFEST_EXCLUDES', []) for finder in finders.get_finders(): ...
AttributeError
dataset/ETHPy150Open hzdg/django-ecstatic/ecstatic/management/commands/createstaticmanifest.py/Command.handle_noargs
2,579
def __init__(self, xfm, reference): self.xfm = xfm self.reference = None if isstr(reference): import nibabel try: self.reference = nibabel.load(reference) self.shape = self.reference.shape[:3][::-1] except __HOLE__: ...
IOError
dataset/ETHPy150Open gallantlab/pycortex/cortex/xfm.py/Transform.__init__
2,580
def __repr__(self): try: path, fname = os.path.split(self.reference.get_filename()) return "<Transform into %s space>"%fname except __HOLE__: return "<Reference free affine transform>"
AttributeError
dataset/ETHPy150Open gallantlab/pycortex/cortex/xfm.py/Transform.__repr__
2,581
@classmethod def from_fsl(cls, xfm, func_nii, anat_nii): """Converts an fsl transform to a pycortex transform. Converts a transform computed using FSL's FLIRT to a transform ("xfm") object in pycortex. The transform must have been computed FROM the nifti volume specified in `func_nii` TO th...
AttributeError
dataset/ETHPy150Open gallantlab/pycortex/cortex/xfm.py/Transform.from_fsl
2,582
def to_fsl(self, anat_nii, direction='func>anat'): """Converts a pycortex transform to an FSL transform. Uses the stored "reference" file provided when the transform was created (usually a functional data or statistical volume) and the supplied anatomical file to create an FSL transfo...
AttributeError
dataset/ETHPy150Open gallantlab/pycortex/cortex/xfm.py/Transform.to_fsl
2,583
def isstr(obj): """Check for stringy-ness in python 2.7 or 3""" try: return isinstance(obj, basestring) except __HOLE__: return isinstance(obj, str)
NameError
dataset/ETHPy150Open gallantlab/pycortex/cortex/xfm.py/isstr
2,584
def createException(service_exception, provider_nsa): # nsiconnection.ServiceException (binding) -> error.NSIError try: exception_type = error.lookup(service_exception.errorId) variables = [ (tvp.type, tvp.value) for tvp in service_exception.variables ] if service_exception.variables else None ...
AssertionError
dataset/ETHPy150Open NORDUnet/opennsa/opennsa/protocols/nsi2/helper.py/createException
2,585
def parseLabel(label_part): if not '=' in label_part: raise error.PayloadError('No = in urn label part (%s)' % label_part) label_short_type, label_value = label_part.split('=') try: label_type = LABEL_MAP[label_short_type] except __HOLE__: raise error.PayloadError('Label type %s...
KeyError
dataset/ETHPy150Open NORDUnet/opennsa/opennsa/protocols/nsi2/helper.py/parseLabel
2,586
def get_actual_status_img(request, output_format='png', width=600, height=600): if reportlab is None: messages.error(request, _("Module") + " reportlab " + _("is not available")) try: redirect_to = request.META['HTTP_REFERER'] except __HOLE__: redirect_to = '/' ...
KeyError
dataset/ETHPy150Open lukaszb/django-projector/projector/views/reports.py/get_actual_status_img
2,587
def handle_accept(self): if _debug: TCPServerDirector._debug("handle_accept") try: client, addr = self.accept() except socket.error: TCPServerDirector._warning('accept() threw an exception') return except __HOLE__: TCPServerDirector._warni...
TypeError
dataset/ETHPy150Open JoelBender/bacpypes/py27/bacpypes/tcp.py/TCPServerDirector.handle_accept
2,588
def remove_actor(self, actor): if _debug: TCPServerDirector._debug("remove_actor %r", actor) try: del self.servers[actor.peer] except __HOLE__: TCPServerDirector._warning("remove_actor: %r not an actor", actor) # tell the ASE the server has gone away if ...
KeyError
dataset/ETHPy150Open JoelBender/bacpypes/py27/bacpypes/tcp.py/TCPServerDirector.remove_actor
2,589
def _is_compute_port(self, port): try: if (port['device_id'] and uuidutils.is_uuid_like(port['device_id']) and port['device_owner'].startswith( constants.DEVICE_OWNER_COMPUTE_PREFIX)): return True except (__HOLE__, AttributeError): ...
KeyError
dataset/ETHPy150Open openstack/neutron/neutron/notifiers/nova.py/Notifier._is_compute_port
2,590
def send_events(self, batched_events): LOG.debug("Sending events: %s", batched_events) try: response = self.nclient.server_external_events.create( batched_events) except nova_exceptions.NotFound: LOG.debug("Nova returned NotFound for event: %s", ...
KeyError
dataset/ETHPy150Open openstack/neutron/neutron/notifiers/nova.py/Notifier.send_events
2,591
def run_upgrade_script(app, script_name): try: cur_script = __import__('datamigrations.%s' % script_name) except __HOLE__: # return if the script doesn't exist return print "Running %s.upgrade" % script_name script = getattr(cur_script, script_name) script.upgrade(app)
ImportError
dataset/ETHPy150Open jkossen/imposter/datamigrations/__init__.py/run_upgrade_script
2,592
def run_downgrade_script(app, script_name): try: cur_script = __import__('datamigrations.%s' % script_name) except __HOLE__: # return if the script doesn't exist return print "Running %s.downgrade" % script_name script = getattr(cur_script, script_name) script.downgrade(app)
ImportError
dataset/ETHPy150Open jkossen/imposter/datamigrations/__init__.py/run_downgrade_script
2,593
def setUp(self): """ Patch the L{ls} module's time function so the results of L{lsLine} are deterministic. """ self.now = 123456789 def fakeTime(): return self.now self.patch(ls, 'time', fakeTime) # Make sure that the timezone ends up the same...
KeyError
dataset/ETHPy150Open twisted/twisted/twisted/conch/test/test_cftp.py/ListingTests.setUp
2,594
def __init__(self, data, subject, xfmname, mask=None, **kwargs): """Three possible variables: raw, volume, movie, vertex. Enumerated with size: raw volume movie: (t, z, y, x, c) raw volume image: (z, y, x, c) reg volume movie: (t, z, y, x) reg volume image: (z, y, x) raw ...
NameError
dataset/ETHPy150Open gallantlab/pycortex/cortex/dataset.py/VolumeData.__init__
2,595
def __init__(self, data, subject, **kwargs): """Vertex Data possibilities raw linear movie: (t, v, c) reg linear movie: (t, v) raw linear image: (v, c) reg linear image: (v,) where t is the number of time points, c is colors (i.e. RGB), and v is the number of ve...
NameError
dataset/ETHPy150Open gallantlab/pycortex/cortex/dataset.py/VertexData.__init__
2,596
def _hdf_write(h5, data, name="data", group="/datasets"): import tables atom = tables.Atom.from_dtype(data.dtype) filt = tables.filters.Filters(complevel=9, complib='blosc', shuffle=True) create = False try: ds = h5.getNode("%s/%s"%(group, name)) ds[:] = data except tables.NoSuch...
ValueError
dataset/ETHPy150Open gallantlab/pycortex/cortex/dataset.py/_hdf_write
2,597
def _real_extract(self, url): track_id = self._match_id(url) data = {'ax': 1, 'ts': time.time()} data_encoded = compat_urllib_parse.urlencode(data) complete_url = url + "?" + data_encoded request = compat_urllib_request.Request(complete_url) response, urlh = self._downlo...
ValueError
dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/extractor/hypem.py/HypemIE._real_extract
2,598
def _from_class_value(self, value, value_type): type_factory = self._type_factory collation = self._collation bytes_to_unicode = self._bytes_to_unicode allow_tz = self._allow_tz if issubclass(value_type, bool): return type_factory.BitN elif issubclass(value_t...
StopIteration
dataset/ETHPy150Open denisenkom/pytds/pytds/tds_types.py/TdsTypeInferrer._from_class_value
2,599
def test_fast_dot(): # Check fast dot blas wrapper function if fast_dot is np.dot: return rng = np.random.RandomState(42) A = rng.random_sample([2, 10]) B = rng.random_sample([2, 10]) try: linalg.get_blas_funcs(['gemm'])[0] has_blas = True except (__HOLE__, ValueErr...
AttributeError
dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/utils/tests/test_extmath.py/test_fast_dot