Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
2,900
def _k8s_object_to_st2_trigger(self, k8s_object): # Define some variables try: resource_type = k8s_object['type'] object_kind = k8s_object['object']['kind'] name = k8s_object['object']['metadata']['name'] namespace = k8s_object['object']['metadata']['names...
KeyError
dataset/ETHPy150Open StackStorm/st2contrib/packs/kubernetes/sensors/third_party_resource.py/ThirdPartyResource._k8s_object_to_st2_trigger
2,901
@classmethod def get_size(cls, value): """ Predefined sizes: ======== ======== ========= size width height ======== ======== ========= tiny 420 315 small 480 360 medium 640 480 large 960 720 huge ...
AttributeError
dataset/ETHPy150Open yetty/django-embed-video/embed_video/templatetags/embed_video_tags.py/VideoNode.get_size
2,902
def test_file_isatty(name): if not os.path.exists(name): return try: test_isatty(name, file(name)) except __HOLE__, e: print e # XXX Jython prints 'no such file or directory' - probably # 'permission denied' but Java doesn't understand?
IOError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_isatty.py/test_file_isatty
2,903
def __iter__(self): self.generator = self.readlines('\n') has_next = True while has_next: try: chunk = six.next(self.generator) yield chunk except __HOLE__: has_next = False self.close()
StopIteration
dataset/ETHPy150Open spotify/luigi/luigi/contrib/webhdfs.py/ReadableWebHdfsFile.__iter__
2,904
def memo_key(args, kwargs): result = (args, frozenset(kwargs.items())) try: hash(result) except __HOLE__: result = tuple(map(id, args)), str(kwargs) return result
TypeError
dataset/ETHPy150Open blaze/cachey/cachey/cache.py/memo_key
2,905
def get(self, item, default=None): # overloading this method is needed to force the dict to go through # the timetable check try: return self[item] except __HOLE__: return default
KeyError
dataset/ETHPy150Open phaethon/scapy/scapy/config.py/CacheInstance.get
2,906
def __setitem__(self, item, v): try: self._timetable[item] = time.time() except __HOLE__: pass dict.__setitem__(self, item,v)
AttributeError
dataset/ETHPy150Open phaethon/scapy/scapy/config.py/CacheInstance.__setitem__
2,907
def first(self): """Returns the first element from the database result or None. """ try: return next(self) except __HOLE__: return None
StopIteration
dataset/ETHPy150Open anandology/broadgauge/broadgauge/models.py/ResultSet.first
2,908
def get_value(self, key, args, kwargs): # Try standard formatting, then return 'unknown key' try: return Formatter.get_value(self, key, args, kwargs) except __HOLE__: return self.default
KeyError
dataset/ETHPy150Open artirix/logcabin/logcabin/event.py/DefaultFormatter.get_value
2,909
def __init__(self, path, update_cache): self.fullpath = os.path.join(path, 'cache') self.update_cache = update_cache self.expire_after = timedelta(days=180).total_seconds() self.time = time.time() self.dirty = False self.cache = {} # this new set is to avoid doing...
IOError
dataset/ETHPy150Open YetAnotherNerd/whatlastgenre/wlg/dataprovider.py/Cache.__init__
2,910
def save(self): '''Save the cache dict as json string to a file. Clean expired entries before saving and use a temporary file to avoid data loss on interruption. ''' if not self.dirty: return self.clean() print("Saving cache... ", end='') dirn...
KeyboardInterrupt
dataset/ETHPy150Open YetAnotherNerd/whatlastgenre/wlg/dataprovider.py/Cache.save
2,911
def _request_json(self, url, params, method='GET'): '''Return a json response from a request.''' res = self._request(url, params, method=method) try: return res.json() except __HOLE__ as err: self.log.debug(res.text) raise DataProviderError("json reque...
ValueError
dataset/ETHPy150Open YetAnotherNerd/whatlastgenre/wlg/dataprovider.py/DataProvider._request_json
2,912
def query(self, query): '''Perform a real DataProvider query.''' res = None if query.type == 'artist': try: # query by mbid if query.mbid_artist: res = self.query_by_mbid(query.type, query.mbid_artist) except NotImplementedError: ...
NotImplementedError
dataset/ETHPy150Open YetAnotherNerd/whatlastgenre/wlg/dataprovider.py/DataProvider.query
2,913
def __init__(self, conf): super(Discogs, self).__init__() # http://www.discogs.com/developers/#header:home-rate-limiting self.rate_limit = 3.0 # OAuth1 authentication import rauth discogs = rauth.OAuth1Service( consumer_key='sYGBZLljMPsYUnmGOzTX', ...
KeyError
dataset/ETHPy150Open YetAnotherNerd/whatlastgenre/wlg/dataprovider.py/Discogs.__init__
2,914
def _request_html(self, url, params, method='GET'): '''Return a html response from a request.''' from lxml import html res = self._request(url, params, method=method) if res.status_code == 404: return None try: return html.fromstring(res.text) exce...
ValueError
dataset/ETHPy150Open YetAnotherNerd/whatlastgenre/wlg/dataprovider.py/RateYourMusic._request_html
2,915
def _query(self, type_, searchterm): '''Search RateYourMusic.''' def match(str_a, str_b): '''Return True if str_a and str_b are quite similar.''' import difflib return difflib.SequenceMatcher( None, str_a.lower(), str_b.lower()).quick_ratio() > 0.9 ...
IndexError
dataset/ETHPy150Open YetAnotherNerd/whatlastgenre/wlg/dataprovider.py/RateYourMusic._query
2,916
def _query(self, params): '''Query What.CD API.''' self.login() try: result = self._request_json('https://what.cd/ajax.php', params) except requests.exceptions.TooManyRedirects: # whatcd session expired self.session.cookies.set('session', None) ...
KeyError
dataset/ETHPy150Open YetAnotherNerd/whatlastgenre/wlg/dataprovider.py/WhatCD._query
2,917
def is_numeric(s): try: int(s) return True except __HOLE__: return False
ValueError
dataset/ETHPy150Open duydao/Text-Pastry/text_pastry_selection.py/is_numeric
2,918
def _watch_file(self, filepath, trigger_event=True): """Adds the file's modified time into its internal watchlist.""" is_new = filepath not in self._watched_files if trigger_event: if is_new: self.trigger_created(filepath) else: self.trigge...
OSError
dataset/ETHPy150Open jeffh/sniffer/sniffer/scanner/base.py/PollingScanner._watch_file
2,919
def __init__(self, initlist=[]): """ Items in initlist can either be - tuples of (key,values) - or plain values Keys can be None or empty strings in item tuples. """ self.values = [] self.keys = [] for idx, item in enumerate(initlist): ...
ValueError
dataset/ETHPy150Open ralhei/pyRserve/pyRserve/taggedContainers.py/TaggedList.__init__
2,920
def __getitem__(self, idx_or_name): try: return numpy.ndarray.__getitem__(self, idx_or_name) except: pass try: return numpy.ndarray.__getitem__(self, self.attr.index(idx_or_name)) except __HOLE__: ...
ValueError
dataset/ETHPy150Open ralhei/pyRserve/pyRserve/taggedContainers.py/TaggedArray.__getitem__
2,921
def is_correct(self): try: abs_path = get_absolute_path(self.__str__()) return access(abs_path, W_OK) except (AttributeError, __HOLE__): # TODO: These are thrown by get_absolute_path when called on None and probably shouldn't be needed return False
TypeError
dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/models/gamedetails.py/PathDetail.is_correct
2,922
def is_correct(self): try: path = get_absolute_path(self.game.path) path = join_path(path, self.image_path) except (AttributeError, __HOLE__): # TODO: These are thrown by get_absolute_path when called on None and probably shouldn't be needed return None ...
TypeError
dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/models/gamedetails.py/ImageDetail.is_correct
2,923
def _has_changed(self, initial, data): try: input_format = formats.get_format('DATE_INPUT_FORMATS')[0] initial = datetime.datetime.strptime(initial, input_format).date() except (__HOLE__, ValueError): pass return super(DateInput, self)....
TypeError
dataset/ETHPy150Open gregmuellegger/django-floppyforms/floppyforms/widgets.py/DateInput._has_changed
2,924
def _has_changed(self, initial, data): try: input_format = formats.get_format('DATETIME_INPUT_FORMATS')[0] initial = datetime.datetime.strptime(initial, input_format) except (TypeError, __HOLE__): pass return super(DateTimeInput, self)....
ValueError
dataset/ETHPy150Open gregmuellegger/django-floppyforms/floppyforms/widgets.py/DateTimeInput._has_changed
2,925
def _has_changed(self, initial, data): try: input_format = formats.get_format('TIME_INPUT_FORMATS')[0] initial = datetime.datetime.strptime(initial, input_format).time() except (__HOLE__, ValueError): pass return super(TimeInput, self)....
TypeError
dataset/ETHPy150Open gregmuellegger/django-floppyforms/floppyforms/widgets.py/TimeInput._has_changed
2,926
def _format_value(self, value): value = value[0] try: value = {True: '2', False: '3', '2': '2', '3': '3'}[value] except __HOLE__: value = '1' return value
KeyError
dataset/ETHPy150Open gregmuellegger/django-floppyforms/floppyforms/widgets.py/NullBooleanSelect._format_value
2,927
def render(self, name, value, attrs=None, extra_context={}): try: year_val, month_val, day_val = value.year, value.month, value.day except __HOLE__: year_val = month_val = day_val = None if isinstance(value, six.string_types): if settings.USE_L10N: ...
AttributeError
dataset/ETHPy150Open gregmuellegger/django-floppyforms/floppyforms/widgets.py/SelectDateWidget.render
2,928
def value_from_datadict(self, data, files, name): y = data.get(self.year_field % name) m = data.get(self.month_field % name) d = data.get(self.day_field % name) if y == m == d == "0": return None if y and m and d: if settings.USE_L10N: inpu...
ValueError
dataset/ETHPy150Open gregmuellegger/django-floppyforms/floppyforms/widgets.py/SelectDateWidget.value_from_datadict
2,929
def _wait_for_container_running(self, name): # we bump to 20 minutes here to match the timeout on the router and in the app unit files try: self._wait_for_job_state(name, JobState.up) except __HOLE__: raise RuntimeError('container failed to start')
RuntimeError
dataset/ETHPy150Open deis/deis/controller/scheduler/fleet.py/FleetHTTPClient._wait_for_container_running
2,930
def state(self, name): """Display the given job's running state.""" systemdActiveStateMap = { 'active': 'up', 'reloading': 'down', 'inactive': 'created', 'failed': 'crashed', 'activating': 'down', 'deactivating': 'down', } ...
KeyError
dataset/ETHPy150Open deis/deis/controller/scheduler/fleet.py/FleetHTTPClient.state
2,931
def matchBlocks(self, blocks, threshold=.5, *args, **kwargs): """ Partitions blocked data and returns a list of clusters, where each cluster is a tuple of record ids Keyword arguments: blocks -- Sequence of tuples of records, where each tuple is a set of recor...
AttributeError
dataset/ETHPy150Open datamade/dedupe/dedupe/api.py/Matching.matchBlocks
2,932
def __init__(self, settings_file, num_cores=None): # pragma : no cover """ Initialize from a settings file #### Example usage # initialize from a settings file with open('my_learned_settings', 'rb') as f: deduper = dedup...
AttributeError
dataset/ETHPy150Open datamade/dedupe/dedupe/api.py/StaticMatching.__init__
2,933
def _checkDataSample(self, data_sample): try: len(data_sample) except __HOLE__: raise ValueError("data_sample must be a sequence") if len(data_sample): self._checkRecordPairType(data_sample[0]) else: warnings.warn("You submitted an empty ...
TypeError
dataset/ETHPy150Open datamade/dedupe/dedupe/api.py/ActiveMatching._checkDataSample
2,934
def unindex(self, data): # pragma : no cover for field in self.blocker.index_fields: self.blocker.unindex((record[field] for record in viewvalues(data)), field) for block_key, record_id in...
KeyError
dataset/ETHPy150Open datamade/dedupe/dedupe/api.py/GazetteerMatching.unindex
2,935
def __init__(self, *args, **kwargs): super(StaticGazetteer, self).__init__(*args, **kwargs) settings_file = args[0] try: self.blocked_records = pickle.load(settings_file) except EOFError: self.blocked_records = OrderedDict({}) except (__HOLE__, Attribute...
KeyError
dataset/ETHPy150Open datamade/dedupe/dedupe/api.py/StaticGazetteer.__init__
2,936
def delete_column_constraints(func): """ Decorates column operation functions for MySQL. Deletes the constraints from the database and clears local cache. """ def _column_rm(self, table_name, column_name, *args, **opts): # Delete foreign key constraints try: self.delete_f...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/South-1.0.2/south/db/mysql.py/delete_column_constraints
2,937
def copy_column_constraints(func): """ Decorates column operation functions for MySQL. Determines existing constraints and copies them to a new column """ def _column_cp(self, table_name, column_old, column_new, *args, **opts): # Copy foreign key constraint try: constrain...
IndexError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/South-1.0.2/south/db/mysql.py/copy_column_constraints
2,938
def _fill_constraint_cache(self, db_name, table_name): # for MySQL grab all constraints for this database. It's just as cheap as a single column. self._constraint_cache[db_name] = {} self._constraint_cache[db_name][table_name] = {} self._reverse_cache[db_name] = {} self._constra...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/South-1.0.2/south/db/mysql.py/DatabaseOperations._fill_constraint_cache
2,939
def _lookup_constraint_references(self, table_name, cname): """ Provided an existing table and constraint, returns tuple of (foreign table, column) """ db_name = self._get_setting('NAME') try: return self._constraint_references[db_name][(table_name, cname)] ...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/South-1.0.2/south/db/mysql.py/DatabaseOperations._lookup_constraint_references
2,940
def _lookup_reverse_constraint(self, table_name, column_name=None): """Look for the column referenced by a foreign constraint""" db_name = self._get_setting('NAME') if self.dry_run: raise DryRunError("Cannot get constraints for columns.") if not self._is_valid_cache(db_name,...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/South-1.0.2/south/db/mysql.py/DatabaseOperations._lookup_reverse_constraint
2,941
def create(vm_): ''' Create a single VM from a data dict CLI Example: .. code-block:: bash salt-cloud -p profile_name vm_name ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured(__opts__, ...
AttributeError
dataset/ETHPy150Open saltstack/salt/salt/cloud/clouds/joyent.py/create
2,942
def clean(self, value): value = super(ITSocialSecurityNumberField, self).clean(value) if value in EMPTY_VALUES: return '' value = re.sub('\s', '', value).upper() try: check_digit = ssn_check_digit(value) except __HOLE__: raise ValidationError(s...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/localflavor/it/forms.py/ITSocialSecurityNumberField.clean
2,943
def clean(self, value): value = super(ITVatNumberField, self).clean(value) if value in EMPTY_VALUES: return '' try: vat_number = int(value) except __HOLE__: raise ValidationError(self.error_messages['invalid']) vat_number = str(vat_number).zfil...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/localflavor/it/forms.py/ITVatNumberField.clean
2,944
def updateMessages(self, parameters): # Modify messages created by internal validation for each parameter. # This method is called after internal validation. class_ = self.__class__ dataset_parameter = parameters[0] variables_parameter = parameters[1] output_f...
RuntimeError
dataset/ETHPy150Open Esri/solutions-geoprocessing-toolbox/suitability/toolboxes/scripts/MultidimensionSupplementalTools/MultidimensionSupplementalTools/Scripts/mds/tools/opendap_to_netcdf.py/OPeNDAPtoNetCDF.updateMessages
2,945
def execute(self, parameters, messages): dataset_name = parameters[0].valueAsText variable_names = mds.OrderedSet(parameters[1].values) output_filename = parameters[2].valueAsText extent = None if parameters[3].value is not None: extent = [flo...
RuntimeError
dataset/ETHPy150Open Esri/solutions-geoprocessing-toolbox/suitability/toolboxes/scripts/MultidimensionSupplementalTools/MultidimensionSupplementalTools/Scripts/mds/tools/opendap_to_netcdf.py/OPeNDAPtoNetCDF.execute
2,946
def mftest(): cam = Camera() img = cam.getImage() d = Display(img.size()) bb1 = getBBFromUser(cam,d) fs1=[] img = cam.getImage() while True: try: img1 = cam.getImage() fs1 = img1.track("mftrack",fs1,img,bb1, numM=10, numN=10, winsize=10) print fs1[...
KeyboardInterrupt
dataset/ETHPy150Open sightmachine/SimpleCV/SimpleCV/examples/tracking/mftrack.py/mftest
2,947
def getBBFromUser(cam, d): p1 = None p2 = None img = cam.getImage() while d.isNotDone(): try: img = cam.getImage() img.save(d) dwn = d.leftButtonDownPosition() up = d.leftButtonUpPosition() if dwn: p1 = dwn ...
KeyboardInterrupt
dataset/ETHPy150Open sightmachine/SimpleCV/SimpleCV/examples/tracking/mftrack.py/getBBFromUser
2,948
def bump_version(version): try: parts = map(int, version.split('.')) except __HOLE__: fail('Current version is not numeric') parts[-1] += 1 return '.'.join(map(str, parts))
ValueError
dataset/ETHPy150Open espeed/bulbs/scripts/make-release.py/bump_version
2,949
def simplify_value(value): if hasattr(value, 'simplify_for_render'): return value.simplify_for_render(simplify_value, simplify_model) elif isinstance(value, dict): out = {} for key in value: new_key = key if isinstance(key, (basestring, int)) else str(key) try: ...
NotImplementedError
dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/simplify.py/simplify_value
2,950
def simplify_model(obj, terse=False): if obj is None: return None # It's a Model instance # "expose_fields" is never used if hasattr(obj._meta, 'expose_fields'): expose_fields = obj._meta.expose_fields else: expose_fields = [f.name for f in obj._meta.fields] out = { ...
NotImplementedError
dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/simplify.py/simplify_model
2,951
def serialize_to_xml(value): if value is None: node = etree.Element('null') elif isinstance(value, bool): node = etree.Element('literal') node.text = 'true' if value else 'false' node.attrib['type'] = 'boolean' elif isinstance(value, (basestring, int, float)): node = ...
UnicodeDecodeError
dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/simplify.py/serialize_to_xml
2,952
def main(unused_argv): if not FLAGS.discovery: raise app.UsageError('You must specify --discovery') if not (FLAGS.output_dir or FLAGS.output_file): raise app.UsageError( 'You must specify one of --output_dir or --output_file') if not FLAGS.templates: raise app.UsageError('You must specify --te...
ValueError
dataset/ETHPy150Open google/apis-client-generator/src/googleapis/codegen/expand_templates.py/main
2,953
def __getattr__(self, name): try: # Return 1 if value in day_of_week is True, 0 otherwise return (self.day_of_week[self._DAYS_OF_WEEK.index(name)] and 1 or 0) except __HOLE__: pass except ValueError: # not a day of the week pass raise AttributeError(name)
KeyError
dataset/ETHPy150Open google/transitfeed/transitfeed/serviceperiod.py/ServicePeriod.__getattr__
2,954
def ValidateDate(self, date, field_name, problems, context=None): if date is None: # No exception is issued because ServicePeriods can be created using only # calendar_dates.txt. In that case we have a ServicePeriod consisting # entirely of service exceptions, and with no start_date or end_date. ...
ValueError
dataset/ETHPy150Open google/transitfeed/transitfeed/serviceperiod.py/ServicePeriod.ValidateDate
2,955
def get(self, request, *args, **kwargs): # Get the data from the session try: key = self.request.session[self.session_key_name] del self.request.session[self.session_key_name] except __HOLE__: raise Http404() # Get data for qrcode image_factor...
KeyError
dataset/ETHPy150Open Bouke/django-two-factor-auth/two_factor/views/core.py/QRGeneratorView.get
2,956
def test_random_location(self, domain): """ Execute a test for the given domain at a random location. Optional key is required for Google's public instance. """ locations = self.list_locations() test = self.request_test(domain, random.choice(locations)) try: ...
KeyError
dataset/ETHPy150Open StackStorm/st2contrib/packs/webpagetest/actions/lib/webpagetest.py/WebPageTestAction.test_random_location
2,957
@task def build_form_multimedia_zip(domain, xmlns, startdate, enddate, app_id, export_id, zip_name, download_id): def find_question_id(form, value): for k, v in form.iteritems(): if isinstance(v, dict): ret = find_question_id(v, value) if ret: ...
TypeError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/reports/tasks.py/build_form_multimedia_zip
2,958
def _buffer_recv_worker(ft_client): """Worker thread that constantly receives buffers.""" try: for raw_buffer in ft_client.iter_raw_buffers(): ft_client._push_raw_buffer(raw_buffer) except __HOLE__ as err: # something is wrong, the server stopped (or something) ft_client...
RuntimeError
dataset/ETHPy150Open mne-tools/mne-python/mne/realtime/fieldtrip_client.py/_buffer_recv_worker
2,959
def draw(self): self.plot._render_lock.acquire() self.camera.apply_transformation() calc_verts_pos, calc_verts_len = 0, 0 calc_cverts_pos, calc_cverts_len = 0, 0 should_update_caption = (clock() - self.last_caption_update > self.caption_update_i...
ValueError
dataset/ETHPy150Open sympy/sympy/sympy/plotting/pygletplot/plot_window.py/PlotWindow.draw
2,960
def validateJSON(): style=unicode(js.toPlainText()) if not style.strip(): #no point in validating an empty string return pos=None try: json.loads(style) except __HOLE__, e: s=str(e) print s if s == 'No JSON object could ...
ValueError
dataset/ETHPy150Open rst2pdf/rst2pdf/gui/codeeditor.py/validateJSON
2,961
def process_request(self, request): latitude = None longitude = None accuracy = None # If the request has latitude and longitude query params, use those if 'latitude' in request.GET and 'longitude' in request.GET: latitude = request.GET['latitude'] longit...
ValueError
dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/middleware.py/LocationMiddleware.process_request
2,962
def get(self): recording.dont_record() lineno = self.request.get('n') try: lineno = int(lineno) except: lineno = 0 filename = self.request.get('f') or '' orig_filename = filename match = re.match('<path\[(\d+)\]>(.*)', filename) if match: index, tail = match.groups()...
IOError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/appstats/ui.py/FileHandler.get
2,963
def run(self, no_ipython): """ Runs the shell. Unless no_ipython is True or use_python is False then runs IPython shell if that is installed. """ context = self.get_context() if not no_ipython: try: import IPython sh = IPython...
ImportError
dataset/ETHPy150Open danjac/Flask-Script/flaskext/script.py/Shell.run
2,964
def handle(self, prog, name, args=None): args = list(args or []) try: command = self._commands[name] except __HOLE__: raise InvalidCommand, "Command %s not found" % name help_args = ('-h', '--help') # remove -h from args if present, and add to remainin...
KeyError
dataset/ETHPy150Open danjac/Flask-Script/flaskext/script.py/Manager.handle
2,965
def run(self, commands=None, default_command=None): """ Prepares manager to receive command line input. Usually run inside "if __name__ == "__main__" block in a Python script. :param commands: optional dict of commands. Appended to any commands added u...
IndexError
dataset/ETHPy150Open danjac/Flask-Script/flaskext/script.py/Manager.run
2,966
def read_edl(self, path): """Reads the content of the edl in the given path :param path: A string showing the EDL path :return: str """ try: with open(path) as f: edl_content = f.read() except __HOLE__: edl_content = '' re...
IOError
dataset/ETHPy150Open eoyilmaz/anima/anima/ui/edl_importer.py/MainDialog.read_edl
2,967
def store_media_file_path(self, path): """stores the given path as the avid media file path in anima cache folder. :param str path: The path to be stored :return: """ # make dirs first try: os.makedirs(os.path.dirname(self.cache_file_full_path)) ...
OSError
dataset/ETHPy150Open eoyilmaz/anima/anima/ui/edl_importer.py/MainDialog.store_media_file_path
2,968
def restore_media_file_path(self): """restores the media file path """ try: with open(self.cache_file_full_path) as f: media_file_path = f.read() self.media_files_path_lineEdit.setText(media_file_path) except __HOLE__: pass # not stor...
IOError
dataset/ETHPy150Open eoyilmaz/anima/anima/ui/edl_importer.py/MainDialog.restore_media_file_path
2,969
def get_namespace(self, schema): try: namespace = make_safe(schema._namespace) except __HOLE__: namespace = None return namespace
AttributeError
dataset/ETHPy150Open spotify/pyschema/pyschema/source_generation.py/PackageBuilder.get_namespace
2,970
def __contains__(self, key): try: if dict.__contains__(self, key): state = dict.__getitem__(self, key) o = state.obj() else: return False except __HOLE__: return False else: return o is not None
KeyError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/orm/identity.py/WeakInstanceDict.__contains__
2,971
def add(self, state): key = state.key # inline of self.__contains__ if dict.__contains__(self, key): try: existing_state = dict.__getitem__(self, key) if existing_state is not state: o = existing_state.obj() if o...
KeyError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/orm/identity.py/WeakInstanceDict.add
2,972
def __init__(self, shell=None): super(BuiltinTrap, self).__init__(shell=shell, config=None) self._orig_builtins = {} # We define this to track if a single BuiltinTrap is nested. # Only turn off the trap when the outermost call to __exit__ is made. self._nested_level = 0 s...
ImportError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/core/builtin_trap.py/BuiltinTrap.__init__
2,973
def remove_builtin(self, key): """Remove an added builtin and re-set the original.""" try: orig = self._orig_builtins.pop(key) except __HOLE__: pass else: if orig is BuiltinUndefined: del builtins.__dict__[key] else: ...
KeyError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/core/builtin_trap.py/BuiltinTrap.remove_builtin
2,974
def deactivate(self): """Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.""" # Note: must iterate over a static keys() list because we'll be # mutating the dict itself remove_builtin = self.remove_builtin ...
KeyError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/core/builtin_trap.py/BuiltinTrap.deactivate
2,975
def get_auth(self, username, password, authoritative_source, auth_options=None): """ Returns an authentication object. Examines the auth backend given after the '@' in the username and returns a suitable instance of a subclass of the BaseAuth class. * `username` [string...
KeyError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap/nipap/authlib.py/AuthFactory.get_auth
2,976
def authenticate(self): """ Verify authentication. Returns True/False dependant on whether the authentication succeeded or not. """ # if authentication has been performed, return last result if self._authenticated is not None: return self._authentica...
IndexError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap/nipap/authlib.py/LdapAuth.authenticate
2,977
def main(): '''CGI entry point.''' config = ConfigParser.ConfigParser() config.read('/etc/edeploy.conf') def config_get(section, name, default): 'Secured config getter.' try: return config.get(section, name) except (ConfigParser.NoOptionError, ConfigParser.NoSection...
AttributeError
dataset/ETHPy150Open redhat-cip/edeploy/server/upload-health.py/main
2,978
def run(self): """main loop waiting for keyboard interrupt i.e. do nothing until user press 'X' or CTRL-C""" try: while(self.controller.__class__.running): sleep(1) except (__HOLE__, SystemExit): pass
KeyboardInterrupt
dataset/ETHPy150Open ericgibert/supersid/supersid/textsidviewer.py/textSidViewer.run
2,979
def handle_noargs(self, **options): if not settings.PWD_ALGORITHM == 'bcrypt': return for user in User.objects.all(): pwd = user.password if pwd.startswith('hh$') or pwd.startswith('bcrypt$'): continue # Password has already been strengthened. ...
ValueError
dataset/ETHPy150Open fwenzel/django-sha2/django_sha2/management/commands/strengthen_user_passwords.py/Command.handle_noargs
2,980
@staticmethod def _open_file(filename): """Attempt to open the the file at ``filename`` for reading. Raises: DataSourceError, if the file cannot be opened. """ if filename is None: raise DataSourceError("Trace filename is not defined") try: ...
IOError
dataset/ETHPy150Open openxc/openxc-python/openxc/sources/trace.py/TraceDataSource._open_file
2,981
def GetNetworkGateway(network): """Get the gateway for a network. Uses "netstat -nr" on Darwin and "ip route" on Linux to read the routing table. It searches for a route with destination exactly matching the network parameter! Args: network: str, likely in CIDR format or default gateway, e.g....
OSError
dataset/ETHPy150Open google/simian/src/simian/mac/client/network_detect.py/GetNetworkGateway
2,982
def IsOnWwan(): """"Checks WWAN device connection status. Note: this may produce false-positives, and may not catch all WWAN devices. Several Sprint and Verizon devices were tested, all of which create ppp0 upon connection. However, L2TP VPN also creates ppp0 (Google no longer uses this as of Q2-2010...
OSError
dataset/ETHPy150Open google/simian/src/simian/mac/client/network_detect.py/IsOnWwan
2,983
def GetNetworkName(): """Return network name (SSID for WLANs) a device is connected to. Returns: name of the matching network name if possible, None otherwise. """ this_platform = _GetPlatform() if this_platform == LINUX: cmdline = '/usr/bin/nmcli -t -f NAME,DEVICES conn status' # Ignore "Auto " ...
OSError
dataset/ETHPy150Open google/simian/src/simian/mac/client/network_detect.py/GetNetworkName
2,984
def IsOnAndroidWap(): """Checks if Android WiFi or Bluetooth tethering is connected. Returns: Boolean. True if Android tethering is connected, False otherwise. """ # ifconfig output looks a little bit different on Darwin vs Linux. # # Darwin: # inet 169.254.135.20 netmask 0xffff0000 broadcast 169.254...
OSError
dataset/ETHPy150Open google/simian/src/simian/mac/client/network_detect.py/IsOnAndroidWap
2,985
def check_group_whitelist(self, username): if not self.group_whitelist: return False for grnam in self.group_whitelist: try: group = getgrnam(grnam) except __HOLE__: self.log.error('No such group: [%s]' % grnam) continue...
KeyError
dataset/ETHPy150Open jupyterhub/jupyterhub/jupyterhub/auth.py/LocalAuthenticator.check_group_whitelist
2,986
@staticmethod def system_user_exists(user): """Check if the user exists on the system""" try: pwd.getpwnam(user.name) except __HOLE__: return False else: return True
KeyError
dataset/ETHPy150Open jupyterhub/jupyterhub/jupyterhub/auth.py/LocalAuthenticator.system_user_exists
2,987
def cloneFile(infile, outfile): '''create a clone of ``infile`` named ``outfile`` by creating a soft-link. ''' # link via relative paths, otherwise it # fails if infile and outfile are in different # directories or in a subdirectory if os.path.dirname(infile) != os.path.dirname(outfile): ...
OSError
dataset/ETHPy150Open CGATOxford/cgat/CGAT/IOTools.py/cloneFile
2,988
def val2str(val, format="%5.2f", na="na"): '''return a formatted value. If value does not fit format string, return "na" ''' if type(val) == int: return format % val elif type(val) == float: return format % val try: x = format % val except (ValueError, __HOLE__): ...
TypeError
dataset/ETHPy150Open CGATOxford/cgat/CGAT/IOTools.py/val2str
2,989
def str2val(val, format="%5.2f", na="na", list_detection=False): """guess type (int, float) of value. If `val` is neither int nor float, the value itself is returned. """ if val is None: return val def _convert(v): try: x = int(v) except __HOLE__: ...
ValueError
dataset/ETHPy150Open CGATOxford/cgat/CGAT/IOTools.py/str2val
2,990
def prettyPercent(numerator, denominator, format="%5.2f", na="na"): """output a percent value or "na" if not defined""" try: x = format % (100.0 * numerator / denominator) except (__HOLE__, ZeroDivisionError): x = "na" return x
ValueError
dataset/ETHPy150Open CGATOxford/cgat/CGAT/IOTools.py/prettyPercent
2,991
def convertDictionary(d, map={}): """convert string values in a dictionary to numeric types. Arguments d : dict The dictionary to convert map : dict If map contains 'default', a default conversion is enforced. For example, to force int for every column but column ``id``, sup...
TypeError
dataset/ETHPy150Open CGATOxford/cgat/CGAT/IOTools.py/convertDictionary
2,992
def write(self, identifier, line): """write `line` to file specified by `identifier`""" filename = self.getFilename(identifier) if filename not in self.mFiles: if self.maxopen and len(self.mFiles) > self.maxopen: for f in self.mFiles.values(): f....
ValueError
dataset/ETHPy150Open CGATOxford/cgat/CGAT/IOTools.py/FilePool.write
2,993
def readList(infile, column=0, map_function=str, map_category={}, with_title=False): """read a list of values from infile. Arguments --------- infile : File File object to read from columns : int Column to take from the file. map...
ValueError
dataset/ETHPy150Open CGATOxford/cgat/CGAT/IOTools.py/readList
2,994
def readMultiMap(infile, columns=(0, 1), map_functions=(str, str), both_directions=False, has_header=False, dtype=dict): """read a map (pairs of values) from infile. In contrast to :func:`readMap`, this method permits multiple...
IndexError
dataset/ETHPy150Open CGATOxford/cgat/CGAT/IOTools.py/readMultiMap
2,995
def readTable(file, separator="\t", numeric_type=numpy.float, take="all", headers=True, truncate=None, cumulate_out_of_range=True, ): """read a table of values. If cumulate_out_of_range is set to true, the termina...
ValueError
dataset/ETHPy150Open CGATOxford/cgat/CGAT/IOTools.py/readTable
2,996
def __init__(self, game_json, appid): """ This sets member variables for the various values that the game object should have. Not all of these exist on all appids, so there's some defaults whenever there is a key error. TODO: This is so awful. Rewrite this whole ugly method into...
KeyError
dataset/ETHPy150Open naiyt/steamapiwrapper/steamapiwrapper/SteamGames.py/Game.__init__
2,997
@protocol.commands.add('count') def count(context, *args): """ *musicpd.org, music database section:* ``count {TAG} {NEEDLE}`` Counts the number of songs and their total playtime in the db matching ``TAG`` exactly. *GMPC:* - use multiple tag-needle pairs to make more specific...
ValueError
dataset/ETHPy150Open mopidy/mopidy/mopidy/mpd/protocol/music_db.py/count
2,998
@protocol.commands.add('find') def find(context, *args): """ *musicpd.org, music database section:* ``find {TYPE} {WHAT}`` Finds songs in the db that are exactly ``WHAT``. ``TYPE`` can be any tag supported by MPD, or one of the two special parameters - ``file`` to search by ful...
ValueError
dataset/ETHPy150Open mopidy/mopidy/mopidy/mpd/protocol/music_db.py/find
2,999
@protocol.commands.add('findadd') def findadd(context, *args): """ *musicpd.org, music database section:* ``findadd {TYPE} {WHAT}`` Finds songs in the db that are exactly ``WHAT`` and adds them to current playlist. Parameters have the same meaning as for ``find``. """ try: ...
ValueError
dataset/ETHPy150Open mopidy/mopidy/mopidy/mpd/protocol/music_db.py/findadd