Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
1,900
def lookup_level(level): """Return the integer representation of a logging level.""" if isinstance(level, integer_types): return level try: return _reverse_level_names[level] except __HOLE__: raise LookupError('unknown level name %s' % level)
KeyError
dataset/ETHPy150Open getlogbook/logbook/logbook/base.py/lookup_level
1,901
def get_level_name(level): """Return the textual representation of logging level 'level'.""" try: return _level_names[level] except __HOLE__: raise LookupError('unknown level')
KeyError
dataset/ETHPy150Open getlogbook/logbook/logbook/base.py/get_level_name
1,902
@cached_property def message(self): """The formatted message.""" if not (self.args or self.kwargs): return self.msg try: try: return self._format_message(self.msg, *self.args, **self.kwargs) excep...
AttributeError
dataset/ETHPy150Open getlogbook/logbook/logbook/base.py/LogRecord.message
1,903
def enable(self): """Convenience method to enable this logger. :raises AttributeError: The disabled property is read-only, typically because it was overridden in a subclass. .. versionadded:: 1.0 """ try: self.disabled = False ...
AttributeError
dataset/ETHPy150Open getlogbook/logbook/logbook/base.py/LoggerMixin.enable
1,904
def disable(self): """Convenience method to disable this logger. :raises AttributeError: The disabled property is read-only, typically because it was overridden in a subclass. .. versionadded:: 1.0 """ try: self.disabled = True ...
AttributeError
dataset/ETHPy150Open getlogbook/logbook/logbook/base.py/LoggerMixin.disable
1,905
def main(argv): global _PROG, _VERBOSE _PROG = argv[0] try: opts, args = getopt.getopt( argv[1:], 'hvu:g:m:', ( 'help', 'verbose', 'user=', 'group=', 'mode=', )) except getopt.GetoptError,...
ValueError
dataset/ETHPy150Open axialmarket/fsq/libexec/fsq/down.py/main
1,906
def validate_value_type(value_type, value): try: return _VALIDATOR_MAP[value_type](value) except (__HOLE__, TypeError) as err: raise ValidationError(err) ### attribute base type validation and conversion
ValueError
dataset/ETHPy150Open kdart/pycopia/storage/pycopia/db/types.py/validate_value_type
1,907
def date_trunc_sql(self, lookup_type, field_name): fields = ['year', 'month', 'day', 'hour', 'minute', 'second'] format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape. format_def = ('0000-', '01', '-01', ' 00:', '00', ':00') try: i = fields....
ValueError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/backends/mysql/base.py/DatabaseOperations.date_trunc_sql
1,908
def main(): resampler = apiai.Resampler(source_samplerate=RATE) vad = apiai.VAD() ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN) request = ai.voice_request() request.lang = 'en' # optional, default value equal 'en' def callback(in_data, frame_count, time_info, status): frames, data = resampl...
KeyboardInterrupt
dataset/ETHPy150Open api-ai/api-ai-python/examples/pyaudio_example.py/main
1,909
def import_tags(sess, store): for tag in sess.query(Tag).all(): try: repos_name = tag.repository.name tag_name = tag.name repos_namespace = tag.repository.user.username image_id = tag.revision.id path = store.tag_path(repos_namespace, repos_name, t...
AttributeError
dataset/ETHPy150Open docker/docker-registry/scripts/import_old_tags.py/import_tags
1,910
def addRecentFile( application, fileName ) : if isinstance( application, Gaffer.Application ) : applicationRoot = application.root() else : applicationRoot = application try : applicationRoot.__recentFiles except __HOLE__ : applicationRoot.__recentFiles = [] if fileName in applicationRoot.__recentFiles ...
AttributeError
dataset/ETHPy150Open ImageEngine/gaffer/python/GafferUI/FileMenu.py/addRecentFile
1,911
def clean(self, value): super(SIEMSOField, self).clean(value) if value in EMPTY_VALUES: return u'' value = value.strip() m = self.emso_regex.match(value) if m is None: raise ValidationError(self.default_error_messages['invalid']) # Validate EMSO...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/localflavor/si/forms.py/SIEMSOField.clean
1,912
@classmethod def from_config(cls, cloud_config, region): try: backend = cloud_config['BACKEND'] except __HOLE__: raise LookupError("No backend specified!") try: backend_cls = backends[backend] except KeyError: raise LookupError( ...
KeyError
dataset/ETHPy150Open onefinestay/gonzo/gonzo/clouds/compute.py/Cloud.from_config
1,913
def get_next_az(self, environment, server_type): available_azs = self.list_availability_zones() try: newest_instance_az = self.list_instances_by_type( environment, server_type)[-1].extra['gonzo_az'] except __HOLE__: return available_azs[0] ...
IndexError
dataset/ETHPy150Open onefinestay/gonzo/gonzo/clouds/compute.py/Cloud.get_next_az
1,914
def querycrawler(self, path=None, curdepth=0, maxdepth=1): self.log.debug('Crawler is visiting %s' % path) localcrawlpaths = list() if curdepth > maxdepth: self.log.info('maximum depth %s reached' % maxdepth) return r = self.request(path=path) if r is None...
KeyError
dataset/ETHPy150Open sandrogauci/wafw00f/wafw00f/lib/evillib.py/waftoolsengine.querycrawler
1,915
def _parse_proxy(self, proxy): parts = urlparse(proxy) if not parts.scheme or not parts.netloc: raise Exception("Invalid proxy specified, scheme required") netloc = parts.netloc.split(":") if len(netloc) != 2: raise Exception("Proxy port unspecified") ...
ValueError
dataset/ETHPy150Open sandrogauci/wafw00f/wafw00f/lib/evillib.py/waftoolsengine._parse_proxy
1,916
def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is already acquired. IOError: if ...
IOError
dataset/ETHPy150Open google/oauth2client/oauth2client/contrib/_fcntl_opener.py/_FcntlOpener.open_and_lock
1,917
def _open(self): # read the OLE directory and see if this is a likely # to be a Microsoft Image Composer file try: self.ole = OleFileIO(self.fp) except __HOLE__: raise SyntaxError, "not an MIC file; invalid OLE file" # find ACI subfiles with Image membe...
IOError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/MicImagePlugin.py/MicImageFile._open
1,918
def seek(self, frame): try: filename = self.images[frame] except __HOLE__: raise EOFError, "no such frame" self.fp = self.ole.openstream(filename) TiffImagePlugin.TiffImageFile._open(self) self.frame = frame
IndexError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/MicImagePlugin.py/MicImageFile.seek
1,919
def __getattr__(self, key): if key in self.__pushed_up: owner = self.__pushed_up[key] value = getattr(getattr(self, owner), key) setattr(self, key, value) return value elif key in self.__all__: module = __import__( self.__name__...
AttributeError
dataset/ETHPy150Open jek/flatland/flatland/util/deferred.py/deferred_module.__getattr__
1,920
def get_price(self, currency=None, orderitem=None): """ This method is part of the public, required API of products. It returns either a price instance or raises a ``DoesNotExist`` exception. If you need more complex pricing schemes, override this method with your own implementa...
IndexError
dataset/ETHPy150Open matthiask/plata/plata/product/models.py/ProductBase.get_price
1,921
def testAFakeZlib(self): # # This could cause a stack overflow before: importing zlib.py # from a compressed archive would cause zlib to be imported # which would find zlib.py in the archive, which would... etc. # # This test *must* be executed first: it must be the first...
ImportError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_zipimport.py/UncompressedZipImportTestCase.testAFakeZlib
1,922
def testBadMagic2(self): # make pyc magic word invalid, causing an ImportError badmagic_pyc = bytearray(test_pyc) badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit files = {TESTMOD + pyc_ext: (NOW, badmagic_pyc)} try: self.doTest(".py", files, TESTMOD) except _...
ImportError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_zipimport.py/UncompressedZipImportTestCase.testBadMagic2
1,923
def reRepl(m): ansiTypes = { 'clear': ansiFormatter.cmdReset(), 'hashtag': ansiFormatter.cmdBold(), 'profile': ansiFormatter.cmdUnderline(), } s = None try: mkey = m.lastgroup if m.group(mkey): s = '%s%s%s' % (ansiTypes[mkey], m.group(mkey), ans...
IndexError
dataset/ETHPy150Open sixohsix/twitter/twitter/cmdline.py/reRepl
1,924
def __call__(self, twitter, options): action = actions.get(options['action'], NoSuchAction)() try: doAction = lambda: action(twitter, options) if options['refresh'] and isinstance(action, StatusAction): while True: doAction() ...
KeyboardInterrupt
dataset/ETHPy150Open sixohsix/twitter/twitter/cmdline.py/Action.__call__
1,925
def __call__(self, twitter, options): prompt = self.render_prompt(options.get('prompt', 'twitter> ')) while True: options['action'] = "" try: args = input(prompt).split() parse_args(args, options) if not options['action']: ...
KeyboardInterrupt
dataset/ETHPy150Open sixohsix/twitter/twitter/cmdline.py/TwitterShell.__call__
1,926
def _key(self, rawresult): """ Returns a string that uniquely identifies a raw result from a particular source. """ bits = [rawresult.contest_slug, rawresult.candidate_slug, slugify(rawresult.jurisdiction)] if rawresult.district: bits.append(r...
AttributeError
dataset/ETHPy150Open openelections/openelections-core/openelex/us/fl/load.py/LoadResults._key
1,927
@background.setter def background(self, value): self._color = value self.refresh() # propagate changes to every clone if self.editor: for clone in self.editor.clones: try: clone.modes.get(self.__class__).background = value ...
KeyError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/modes/caret_line_highlight.py/CaretLineHighlighterMode.background
1,928
def test_illegal_mode(): try: builder.QRCodeBuilder('test', 1, mode='murks', error='M') raise Exception('Expected an error for illegal mode') except __HOLE__ as ex: ok_('murks' in str(ex))
ValueError
dataset/ETHPy150Open mnooner256/pyqrcode/tests/test_builder.py/test_illegal_mode
1,929
def test_illegal_error(): try: builder.QRCodeBuilder('123', version=40, mode='numeric', error='R') raise Exception('Expected an error for illegal mode') except __HOLE__ as ex: ok_('R' in str(ex))
ValueError
dataset/ETHPy150Open mnooner256/pyqrcode/tests/test_builder.py/test_illegal_error
1,930
def test_illegal_version(): try: builder.QRCodeBuilder('123', version=41, mode='numeric', error='M') raise Exception('Expected an error for illegal mode') except __HOLE__ as ex: ok_('41' in str(ex))
ValueError
dataset/ETHPy150Open mnooner256/pyqrcode/tests/test_builder.py/test_illegal_version
1,931
def get_urls(self): urlpatterns = super(RedisServerAdmin, self).get_urls() try: from django.conf.urls import patterns, url except __HOLE__: from django.conf.urls.defaults import patterns, url def wrap(view): def wrapper(*args, **kwargs): ...
ImportError
dataset/ETHPy150Open ionelmc/django-redisboard/src/redisboard/admin.py/RedisServerAdmin.get_urls
1,932
def update_ipaddress(self): ''' Updates the scheduler so it knows its own ip address ''' # assign local ip in case of exception self.old_ip = self.my_ip self.my_ip = '127.0.0.1' try: obj = urllib2.urlopen(settings.get('PUBLIC_IP_URL', ...
IOError
dataset/ETHPy150Open istresearch/scrapy-cluster/crawler/crawling/distributed_scheduler.py/DistributedScheduler.update_ipaddress
1,933
def next_request(self): ''' Logic to handle getting a new url request, from a bunch of different queues ''' t = time.time() # update the redis queues every so often if t - self.update_time > self.update_interval: self.update_time = t self.c...
ValueError
dataset/ETHPy150Open istresearch/scrapy-cluster/crawler/crawling/distributed_scheduler.py/DistributedScheduler.next_request
1,934
def __write_data(self): while len(self.write_buffer) > 0: try: buffer = self.write_buffer[0] self.socket.sendall(buffer) except __HOLE__ as e: self.cleanup() return self.write_buffer.pop(0) self.net_wri...
IOError
dataset/ETHPy150Open adamb70/CSGO-Market-Float-Finder/pysteamkit/steam3/connection.py/TCPConnection.__write_data
1,935
def __read_data(self): while self.socket: try: data = self.socket.recv(4096) except __HOLE__ as e: self.cleanup() return if len(data) == 0: self.cleanup() return self.data_received(d...
IOError
dataset/ETHPy150Open adamb70/CSGO-Market-Float-Finder/pysteamkit/steam3/connection.py/TCPConnection.__read_data
1,936
def __call__(self, bundles=None, output=None, directory=None, no_cache=None, manifest=None, production=None): """Build assets. ``bundles`` A list of bundle names. If given, only this list of bundles should be built. ``output`` List of (bundle, ...
ValueError
dataset/ETHPy150Open miracle2k/webassets/src/webassets/script.py/BuildCommand.__call__
1,937
def __call__(self, loop=None): """Watch assets for changes. ``loop`` A callback, taking no arguments, to be called once every loop iteration. Can be useful to integrate the command with other code. If not specified, the loop wil call ``time.sleep()``. """ ...
KeyboardInterrupt
dataset/ETHPy150Open miracle2k/webassets/src/webassets/script.py/WatchCommand.__call__
1,938
def invoke(self, command, args): """Invoke ``command``, or throw a CommandError. This is essentially a simple validation mechanism. Feel free to call the individual command methods manually. """ try: function = self.commands[command] except __HOLE__ as e: ...
KeyError
dataset/ETHPy150Open miracle2k/webassets/src/webassets/script.py/CommandLineEnvironment.invoke
1,939
def __init__(self, env=None, log=None, prog=None, no_global_options=False): try: import argparse except __HOLE__: raise RuntimeError( 'The webassets command line now requires the ' '"argparse" library on Python versions <= 2.6.') else: ...
ImportError
dataset/ETHPy150Open miracle2k/webassets/src/webassets/script.py/GenericArgparseImplementation.__init__
1,940
def run_with_argv(self, argv): try: ns = self.parser.parse_args(argv) except __HOLE__ as e: # We do not want the main() function to exit the program. # See run() instead. return e.args[0] return self.run_with_ns(ns)
SystemExit
dataset/ETHPy150Open miracle2k/webassets/src/webassets/script.py/GenericArgparseImplementation.run_with_argv
1,941
def __call__(self, sid, *args, **kwargs): """ Return a token. :return: """ try: _sinfo = kwargs['sinfo'] except KeyError: exp = self.do_exp(**kwargs) _tid = kwargs['target_id'] else: if 'lifetime' in kwargs: ...
KeyError
dataset/ETHPy150Open rohe/pyoidc/src/oic/extension/token.py/JWTToken.__call__
1,942
def do_exp(self, **kwargs): try: lifetime = kwargs['lifetime'] except KeyError: try: rt = ' '.join(kwargs['response_type']) except KeyError: rt = ' '.join(kwargs['grant_type']) try: lifetime = self.lt_patter...
KeyError
dataset/ETHPy150Open rohe/pyoidc/src/oic/extension/token.py/JWTToken.do_exp
1,943
def invalidate(self, token): info = self.unpack(token) try: del self.db[info['jti']] except __HOLE__: return False return True
KeyError
dataset/ETHPy150Open rohe/pyoidc/src/oic/extension/token.py/JWTToken.invalidate
1,944
def handle_noargs(self, **options): db = options.get('database') connection = connections[db] verbosity = int(options.get('verbosity')) interactive = options.get('interactive') self.style = no_style() # Import the 'management' module within each installed app, to regist...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/management/commands/flush.py/Command.handle_noargs
1,945
def _v1_auth(self, token_url): creds = self.creds headers = {} headers['X-Auth-User'] = creds['username'] headers['X-Auth-Key'] = creds['password'] tenant = creds.get('tenant') if tenant: headers['X-Auth-Tenant'] = tenant resp, resp_body = self._do_...
KeyError
dataset/ETHPy150Open openstack-dev/heat-cfnclient/heat_cfnclient/common/auth.py/KeystoneStrategy._v1_auth
1,946
def _v2_auth(self, token_url): def get_endpoint(service_catalog): """ Select an endpoint from the service catalog We search the full service catalog for services matching both type and region. If the client supplied no region then any endpoint for the...
ValueError
dataset/ETHPy150Open openstack-dev/heat-cfnclient/heat_cfnclient/common/auth.py/KeystoneStrategy._v2_auth
1,947
def call(self, files): """ This function pulls a ``FileInfo`` or ``TaskInfo`` object from a list ``files``. Each object is then deemed if it will be a multipart operation and add the necessary attributes if so. Each object is then wrapped with a ``BasicTask`` object which is ...
KeyboardInterrupt
dataset/ETHPy150Open aws/aws-cli/awscli/customizations/s3/s3handler.py/S3Handler.call
1,948
@property def raw_sensor_value(self): """ Returns the raw sensor value :returns: the raw value read from the sensor :rtype: int :raises NoSensorFoundError: if the sensor could not be found :raises SensorNotReadyError: if the sensor is not ready y...
IOError
dataset/ETHPy150Open timofurrer/w1thermsensor/w1thermsensor/core.py/W1ThermSensor.raw_sensor_value
1,949
@classmethod def _get_unit_factor(cls, unit): """ Returns the unit factor depending on the unit constant :param int unit: the unit of the factor requested :returns: a function to convert the raw sensor value to the given unit :rtype: lambda function ...
KeyError
dataset/ETHPy150Open timofurrer/w1thermsensor/w1thermsensor/core.py/W1ThermSensor._get_unit_factor
1,950
def data(item=None, show_doc=False): """loads a datasaet (from in-modules datasets) in a dataframe data structure. Args: item (str) : name of the dataset to load. show_doc (bool) : to show the dataset's documentation. Examples: >>> iris = data('iris') >>> data('titanic', sh...
KeyError
dataset/ETHPy150Open iamaziz/PyDataset/pydataset/__init__.py/data
1,951
def connected(self, client): """Call this method when a client connected.""" self.clients.add(client) self._log_connected(client) self._start_watching(client) self.send_msg(client, WELCOME, (self.pickle_protocol, __version__), pickle_protocol=0) prof...
AttributeError
dataset/ETHPy150Open what-studio/profiling/profiling/remote/__init__.py/ProfilingServer.connected
1,952
def possibly_quarantine(self, exc_type, exc_value, exc_traceback): """ Checks the exception info to see if it indicates a quarantine situation (malformed or corrupted database). If not, the original exception will be reraised. If so, the database will be quarantined and a new sql...
OSError
dataset/ETHPy150Open openstack/swift/swift/common/db.py/DatabaseBroker.possibly_quarantine
1,953
def put_record(self, record): if self.db_file == ':memory:': self.merge_items([record]) return if not os.path.exists(self.db_file): raise DatabaseConnectionError(self.db_file, "DB doesn't exist") with lock_parent_directory(self.pending_file, self.pending_timeo...
OSError
dataset/ETHPy150Open openstack/swift/swift/common/db.py/DatabaseBroker.put_record
1,954
def _commit_puts(self, item_list=None): """ Scan for .pending files and commit the found records by feeding them to merge_items(). Assume that lock_parent_directory has already been called. :param item_list: A list of items to commit in addition to .pending """ i...
OSError
dataset/ETHPy150Open openstack/swift/swift/common/db.py/DatabaseBroker._commit_puts
1,955
def download_file(url, location, name_of_file, correct_hash): """Attempts to download a file from the internet to the specified location. If the file is not found, or the retrieval of the file failed, the exception will be caught and the system will exit. Args: url: A string of the URL to be retrieved. ...
IOError
dataset/ETHPy150Open google/fplutil/setuputil/util.py/download_file
1,956
def wait_for_installation(program, command=False, search=False, basedir=""): """Once installation has started, poll until completion. Once an asynchronous installation has started, wait for executable to exist. Poll every second, until executable is found or user presses ctrl-c. Args: program: A string re...
KeyboardInterrupt
dataset/ETHPy150Open google/fplutil/setuputil/util.py/wait_for_installation
1,957
def test_dtypes(): batch_size = 2 dtype_is_none_msg = ("self.dtype is None, so you must provide a " "non-None dtype argument to this method.") all_scalar_dtypes = tuple(t.dtype for t in theano.scalar.all_types) def underspecifies_dtypes(from_spac...
TypeError
dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/space/tests/test_space.py/test_dtypes
1,958
def parse_encoding(fp): """Deduce the encoding of a source file from magic comment. It does this in the same way as the `Python interpreter`__ .. __: http://docs.python.org/ref/encodings.html The ``fp`` argument should be a seekable file object. (From Jeff Dairiki) """ pos = f...
ImportError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Babel-0.9.6/babel/util.py/parse_encoding
1,959
def check_dependencies(self, obj, failed): for dep in self.dependencies: peer_name = dep[0].lower() + dep[1:] # django names are camelCased with the first letter lower try: peer_object = deepgetattr(obj, peer_name) try: peer_objec...
AttributeError
dataset/ETHPy150Open open-cloud/xos/xos/synchronizers/base/syncstep-portal.py/SyncStep.check_dependencies
1,960
@staticmethod def _extract_from_file(file_pattern, file_description, extract_function): """Extract metadata from a file. Returns the result of running extract_function on the opened file, or None if the file cannot be found. file_pattern is a glob pattern for the file: the first fil...
IOError
dataset/ETHPy150Open GeoscienceAustralia/agdc/src/landsat_ingester/landsat_dataset.py/LandsatDataset._extract_from_file
1,961
def get_start_datetime(self): """The start of the acquisition. This is a datetime without timezone in UTC. """ # Use the alternate time if available (from EODS_DATASET metadata). try: start_dt = self._ds.scene_alt_start_datetime except __HOLE__: ...
AttributeError
dataset/ETHPy150Open GeoscienceAustralia/agdc/src/landsat_ingester/landsat_dataset.py/LandsatDataset.get_start_datetime
1,962
def get_end_datetime(self): """The end of the acquisition. This is a datatime without timezone in UTC. """ # Use the alternate time if available (from EODS_DATASET metadata). try: end_dt = self._ds.scene_alt_end_datetime except __HOLE__: end_dt =...
AttributeError
dataset/ETHPy150Open GeoscienceAustralia/agdc/src/landsat_ingester/landsat_dataset.py/LandsatDataset.get_end_datetime
1,963
def get_pq_tests_run(self): """The tests run for a Pixel Quality dataset. This is a 16 bit integer with the bits acting as flags. 1 indicates that the test was run, 0 that it was not. """ # None value provided for pq_tests_run value in case PQA metadata # extraction fai...
AttributeError
dataset/ETHPy150Open GeoscienceAustralia/agdc/src/landsat_ingester/landsat_dataset.py/LandsatDataset.get_pq_tests_run
1,964
def log_entry( self, logger, entry ): # check to see if redis truncated the command match = MORE_BYTES.search( entry['command'] ) if match: pos, length = match.span() pos -= 1 # find the first byte which is not a 'middle' byte in utf8 # middle byte...
UnicodeDecodeError
dataset/ETHPy150Open scalyr/scalyr-agent-2/scalyr_agent/builtin_monitors/redis_monitor.py/RedisHost.log_entry
1,965
def inject_config(consumer, properties): for prop in properties: try: if ":" in prop: property_name, value = prop.split(':')[1], _section_value_map[prop] else: property_name, value = prop, _value_map[prop] except KeyError: log.error...
AttributeError
dataset/ETHPy150Open genzgd/Lampost-Mud/lampost/context/config.py/inject_config
1,966
def calculate_scenario_stats(self, nth_pctile=95, format_numbers=True): """Compute various statistics from worker job result dicts. :param nth_pctile: Use this percentile when calculating the stats :param format_numbers: Should various floating-point numbers be formatted as strings or l...
KeyError
dataset/ETHPy150Open swiftstack/ssbench/ssbench/reporter.py/Reporter.calculate_scenario_stats
1,967
def _compute_latency_stats(self, stat_dict, nth_pctile, format_numbers): try: for latency_type in ('first_byte_latency', 'last_byte_latency'): stat_dict[latency_type] = self._series_stats( stat_dict.get(latency_type, []), nth_pctile, format_num...
KeyError
dataset/ETHPy150Open swiftstack/ssbench/ssbench/reporter.py/Reporter._compute_latency_stats
1,968
def _compute_req_per_sec(self, stat_dict): try: sd_start = stat_dict['start'] except __HOLE__: stat_dict['avg_req_per_sec'] = 0.0 else: delta_t = stat_dict['stop'] - sd_start if delta_t != 0: stat_dict['avg_req_per_sec'] = round( ...
KeyError
dataset/ETHPy150Open swiftstack/ssbench/ssbench/reporter.py/Reporter._compute_req_per_sec
1,969
def _add_result_to(self, stat_dict, result): if 'errors' not in stat_dict: stat_dict['errors'] = 0 try: res_start = result['start'] except KeyError: pass else: try: sd_start = stat_dict['start'] except __HOLE__: ...
KeyError
dataset/ETHPy150Open swiftstack/ssbench/ssbench/reporter.py/Reporter._add_result_to
1,970
def download(url, server_fname, local_fname=None, progress_update_percentage=5, bypass_certificate_check=False): """ An internet download utility modified from http://stackoverflow.com/questions/22676/ how-do-i-download-a-file-over-http-using-python/22776#22776 """ if bypass_certifi...
TypeError
dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/datasets/base.py/download
1,971
def get_trans_id_time(trans_id): """ Returns the time.time() embedded in the trans_id or None if no time information is embedded. Copied from the Swift codebase. Copyright (c) 2010-2012 OpenStack Foundation """ if len(trans_id) >= 34 and trans_id[:2] == 'tx' and trans_id[23] == '-': ...
ValueError
dataset/ETHPy150Open gholt/swiftly/swiftly/client/utils.py/get_trans_id_time
1,972
def _unregister_event(self, event): try: self._evrd.remove(event) except __HOLE__: pass try: self._evwr.remove(event) except KeyError: pass try: self._ioevents.remove(event) except KeyError: pass
KeyError
dataset/ETHPy150Open couchbase/couchbase-python-client/couchbase/iops/select.py/SelectIOPS._unregister_event
1,973
def update_event(self, event, action, flags, fd=None): if action == PYCBC_EVACTION_UNWATCH: self._unregister_event(event) return elif action == PYCBC_EVACTION_WATCH: if flags & LCB_READ_EVENT: self._evrd.add(event) else: tr...
KeyError
dataset/ETHPy150Open couchbase/couchbase-python-client/couchbase/iops/select.py/SelectIOPS.update_event
1,974
@app.task(bind=True) def execute_scheduled_maintenance(self, maintenance_id): LOG.debug("Maintenance id: {}".format(maintenance_id)) maintenance = models.Maintenance.objects.get(id=maintenance_id) models.Maintenance.objects.filter(id=maintenance_id, ).update(status=mai...
ObjectDoesNotExist
dataset/ETHPy150Open globocom/database-as-a-service/dbaas/maintenance/tasks.py/execute_scheduled_maintenance
1,975
def default(self, obj): if hasattr(obj, 'json_repr'): return self.default(obj.json_repr()) if isinstance(obj, datetime.datetime): return obj.isoformat() if isinstance(obj, collections.Iterable) and not is_stringy(obj): try: return {k: self.de...
AttributeError
dataset/ETHPy150Open thefactory/marathon-python/marathon/util.py/MarathonJsonEncoder.default
1,976
def default(self, obj): if hasattr(obj, 'json_repr'): return self.default(obj.json_repr(minimal=True)) if isinstance(obj, datetime.datetime): return obj.isoformat() if isinstance(obj, collections.Iterable) and not is_stringy(obj): try: return...
AttributeError
dataset/ETHPy150Open thefactory/marathon-python/marathon/util.py/MarathonMinimalJsonEncoder.default
1,977
def load_backends(): backends = [] for medium_id, bits in enumerate(getattr(settings, "NOTIFICATION_BACKENDS", default_backends)): if len(bits) == 2: label, backend_path = bits spam_sensitivity = None elif len(bits) == 3: label, backend_path, spam_sensitivity ...
ImportError
dataset/ETHPy150Open brosner/django-notification/notification/backends/__init__.py/load_backends
1,978
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914 requirements=None, env=None, bin_env=None, use_wheel=False, no_use_wheel=False, log=None, proxy=None, timeout=None, editable=None, find_link...
ValueError
dataset/ETHPy150Open saltstack/salt/salt/modules/pip.py/install
1,979
def uninstall(pkgs=None, requirements=None, bin_env=None, log=None, proxy=None, timeout=None, user=None, no_chown=False, cwd=None, saltenv='base', use_vt=False): ''' Uninst...
OSError
dataset/ETHPy150Open saltstack/salt/salt/modules/pip.py/uninstall
1,980
def version(bin_env=None): ''' .. versionadded:: 0.17.0 Returns the version of pip. Use ``bin_env`` to specify the path to a virtualenv and get the version of pip in that virtualenv. If unable to detect the pip version, returns ``None``. CLI Example: .. code-block:: bash salt '*...
AttributeError
dataset/ETHPy150Open saltstack/salt/salt/modules/pip.py/version
1,981
def _valueForName(obj, name, executeCallables=False): nameChunks=name.split('.') for i in range(len(nameChunks)): key = nameChunks[i] if hasattr(obj, 'has_key') and key in obj: nextObj = obj[key] else: try: nextObj = getattr(obj, key) e...
AttributeError
dataset/ETHPy150Open binhex/moviegrabber/lib/site-packages/Cheetah/NameMapper.py/_valueForName
1,982
def __new__(cls, name, bases, attrs): attrs['base_fields'] = {} declared_fields = {} # Inherit any fields from parent(s). try: parents = [b for b in bases if issubclass(b, Resource)] # Simulate the MRO. parents.reverse() for p in parents:...
NameError
dataset/ETHPy150Open toastdriven/piecrust/piecrust/resources.py/DeclarativeMetaclass.__new__
1,983
def wrap_view(self, view): """ Wraps methods so they can be called in a more functional way as well as handling exceptions better. Note that if ``BadRequest`` or an exception with a ``response`` attr are seen, there is special handling to either present a message back to...
ValidationError
dataset/ETHPy150Open toastdriven/piecrust/piecrust/resources.py/Resource.wrap_view
1,984
def remove_api_resource_names(self, url_dict): """ Given a dictionary of regex matches from a URLconf, removes ``api_name`` and/or ``resource_name`` if found. This is useful for converting URLconf matches into something suitable for data lookup. For example:: Model....
KeyError
dataset/ETHPy150Open toastdriven/piecrust/piecrust/resources.py/Resource.remove_api_resource_names
1,985
def dehydrate_resource_uri(self, bundle): """ For the automatically included ``resource_uri`` field, dehydrate the URI for the given bundle. Returns empty string if no URI can be generated. """ try: return self.get_resource_uri(bundle) except __HOLE__...
NotImplementedError
dataset/ETHPy150Open toastdriven/piecrust/piecrust/resources.py/Resource.dehydrate_resource_uri
1,986
def convert_post_to_VERB(self, request, verb): """ Force Django to process the VERB. """ # Based off of ``piston.utils.coerce_put_post``. Similarly BSD-licensed. # And no, the irony is not lost on me. if request.method == verb: if hasattr(request, '_post'): ...
AttributeError
dataset/ETHPy150Open toastdriven/piecrust/piecrust/resources.py/Resource.convert_post_to_VERB
1,987
def get_detail(self, request, **kwargs): """ Returns a single serialized resource. Calls ``cached_obj_get/obj_get`` to provide the data, then handles that result set and serializes it. Should return a HttpResponse (200 OK). """ try: obj = self.cached...
ObjectDoesNotExist
dataset/ETHPy150Open toastdriven/piecrust/piecrust/resources.py/Resource.get_detail
1,988
def patch_list(self, request, **kwargs): """ Updates a collection in-place. The exact behavior of ``PATCH`` to a list resource is still the matter of some debate in REST circles, and the ``PATCH`` RFC isn't standard. So the behavior this method implements (described below) is so...
ObjectDoesNotExist
dataset/ETHPy150Open toastdriven/piecrust/piecrust/resources.py/Resource.patch_list
1,989
def patch_detail(self, request, **kwargs): """ Updates a resource in-place. Calls ``obj_update``. If the resource is updated, return ``HttpAccepted`` (202 Accepted). If the resource did not exist, return ``HttpNotFound`` (404 Not Found). """ request = self.conve...
ObjectDoesNotExist
dataset/ETHPy150Open toastdriven/piecrust/piecrust/resources.py/Resource.patch_detail
1,990
def get_multiple(self, request, **kwargs): """ Returns a serialized list of resources based on the identifiers from the URL. Calls ``obj_get`` to fetch only the objects requested. This method only responds to HTTP GET. Should return a HttpResponse (200 OK). """ ...
ObjectDoesNotExist
dataset/ETHPy150Open toastdriven/piecrust/piecrust/resources.py/Resource.get_multiple
1,991
def setup(): top_dir = dirname(dirname(abspath(__file__))) lib_dir = join(top_dir, "lib") sys.path.insert(0, lib_dir) # Attempt to get 'pygments' on the import path. try: # If already have it, use that one. import pygments except __HOLE__: pygments_dir = join(top_dir, "d...
ImportError
dataset/ETHPy150Open an0/Letterpress/code/markdown2/test/test.py/setup
1,992
def init(driverName=None, debug=False): ''' Constructs a new TTS engine instance or reuses the existing instance for the driver name. @param driverName: Name of the platform specific driver to use. If None, selects the default driver for the operating system. @type: str @param debug: De...
KeyError
dataset/ETHPy150Open parente/pyttsx/pyttsx/__init__.py/init
1,993
def clear_opts_related_cache(model_class): """ Clear the specified model and its children opts related cache. """ opts = model_class._meta if hasattr(opts, '_related_objects_cache'): children = [ related_object.model for related_object ...
AttributeError
dataset/ETHPy150Open charettes/django-mutant/mutant/compat.py/clear_opts_related_cache
1,994
def setDocExample(self, collector, metrics, defaultpath=None): if not len(metrics): return False filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'docs', 'collectors-' + collector + '.md') if not os.path.exists(filePath): ...
IOError
dataset/ETHPy150Open BrightcoveOS/Diamond/test.py/CollectorTestCase.setDocExample
1,995
def _sun_jce_pbe_derive_key_and_iv(password, salt, iteration_count): if len(salt) != 8: raise ValueError("Expected 8-byte salt for PBEWithMD5AndTripleDES (OID %s), found %d bytes" % (".".join(str(i) for i in SUN_JCE_ALGO_ID), len(salt))) # Note: unlike JKS, the PBEWithMD5AndTripleDES algorithm as imple...
UnicodeDecodeError
dataset/ETHPy150Open doublereedkurt/pyjks/jks/jks.py/_sun_jce_pbe_derive_key_and_iv
1,996
def onTabChanged(self, event, *args): try: widgetIndex = event.widget.index("current") tabId = event.widget.tabs()[widgetIndex] for widget in event.widget.winfo_children(): if str(widget) == tabId: self.currentView = widget.view ...
TypeError
dataset/ETHPy150Open Arelle/Arelle/arelle/CntlrWinMain.py/CntlrWinMain.onTabChanged
1,997
def getViewAndModelXbrl(self): view = getattr(self, "currentView", None) if view: modelXbrl = None try: modelXbrl = view.modelXbrl return (view, modelXbrl) except __HOLE__: return (view, None) return (None, None)
AttributeError
dataset/ETHPy150Open Arelle/Arelle/arelle/CntlrWinMain.py/CntlrWinMain.getViewAndModelXbrl
1,998
def okayToContinue(self): view, modelXbrl = self.getViewAndModelXbrl() documentIsModified = False if view is not None: try: # What follows only exists in ViewWinRenderedGrid view.updateInstanceFromFactPrototypes() except __HOLE__: ...
AttributeError
dataset/ETHPy150Open Arelle/Arelle/arelle/CntlrWinMain.py/CntlrWinMain.okayToContinue
1,999
def fileSave(self, event=None, view=None, fileType=None, filenameFromInstance=False, *ignore): if view is None: view = getattr(self, "currentView", None) if view is not None: filename = None modelXbrl = None try: modelXbrl = view.modelXbrl ...
IOError
dataset/ETHPy150Open Arelle/Arelle/arelle/CntlrWinMain.py/CntlrWinMain.fileSave