Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
3,700
def _unlock_cache(w_lock): ''' Unlock a FS file/dir based lock ''' if not os.path.exists(w_lock): return try: if os.path.isdir(w_lock): os.rmdir(w_lock) elif os.path.isfile(w_lock): os.unlink(w_lock) except (OSError, __HOLE__) as exc: log.trace('Error removing lockfile {0}: {1}'.format(w_lock, exc))
IOError
dataset/ETHPy150Open saltstack/salt/salt/fileserver/__init__.py/_unlock_cache
3,701
def _lock_cache(w_lock): try: os.mkdir(w_lock) except __HOLE__ as exc: if exc.errno != errno.EEXIST: raise return False else: log.trace('Lockfile {0} created'.format(w_lock)) return True
OSError
dataset/ETHPy150Open saltstack/salt/salt/fileserver/__init__.py/_lock_cache
3,702
def check_env_cache(opts, env_cache): ''' Returns cached env names, if present. Otherwise returns None. ''' if not os.path.isfile(env_cache): return None try: with salt.utils.fopen(env_cache, 'rb') as fp_: log.trace('Returning env cache data from {0}'.format(env_cache)) serial = salt.payload.Serial(opts) return serial.load(fp_) except (__HOLE__, OSError): pass return None
IOError
dataset/ETHPy150Open saltstack/salt/salt/fileserver/__init__.py/check_env_cache
3,703
def generate_mtime_map(path_map): ''' Generate a dict of filename -> mtime ''' file_map = {} for saltenv, path_list in six.iteritems(path_map): for path in path_list: for directory, dirnames, filenames in os.walk(path): for item in filenames: try: file_path = os.path.join(directory, item) file_map[file_path] = os.path.getmtime(file_path) except (OSError, __HOLE__): # skip dangling symlinks log.info( 'Failed to get mtime on {0}, ' 'dangling symlink ?'.format(file_path)) continue return file_map
IOError
dataset/ETHPy150Open saltstack/salt/salt/fileserver/__init__.py/generate_mtime_map
3,704
def reap_fileserver_cache_dir(cache_base, find_func): ''' Remove unused cache items assuming the cache directory follows a directory convention: cache_base -> saltenv -> relpath ''' for saltenv in os.listdir(cache_base): env_base = os.path.join(cache_base, saltenv) for root, dirs, files in os.walk(env_base): # if we have an empty directory, lets cleanup # This will only remove the directory on the second time # "_reap_cache" is called (which is intentional) if len(dirs) == 0 and len(files) == 0: # only remove if empty directory is older than 60s if time.time() - os.path.getctime(root) > 60: os.rmdir(root) continue # if not, lets check the files in the directory for file_ in files: file_path = os.path.join(root, file_) file_rel_path = os.path.relpath(file_path, env_base) try: filename, _, hash_type = file_rel_path.rsplit('.', 2) except __HOLE__: log.warning(( 'Found invalid hash file [{0}] when attempting to reap' ' cache directory.' ).format(file_)) continue # do we have the file? ret = find_func(filename, saltenv=saltenv) # if we don't actually have the file, lets clean up the cache # object if ret['path'] == '': os.unlink(file_path)
ValueError
dataset/ETHPy150Open saltstack/salt/salt/fileserver/__init__.py/reap_fileserver_cache_dir
3,705
def _gen_back(self, back): ''' Return the backend list ''' if not back: back = self.opts['fileserver_backend'] else: try: back = back.split(',') except __HOLE__: back = six.text_type(back).split(',') ret = [] if not isinstance(back, list): return ret try: subtract_only = all((x.startswith('-') for x in back)) except AttributeError: pass else: if subtract_only: # Only subtracting backends from enabled ones ret = self.opts['fileserver_backend'] for sub in back: if '{0}.envs'.format(sub[1:]) in self.servers: ret.remove(sub[1:]) elif '{0}.envs'.format(sub[1:-2]) in self.servers: ret.remove(sub[1:-2]) return ret for sub in back: if '{0}.envs'.format(sub) in self.servers: ret.append(sub) elif '{0}.envs'.format(sub[:-2]) in self.servers: ret.append(sub[:-2]) return ret
AttributeError
dataset/ETHPy150Open saltstack/salt/salt/fileserver/__init__.py/Fileserver._gen_back
3,706
def update_opts(self): # This fix func monkey patching by pillar for name, func in self.servers.items(): try: if '__opts__' in func.__globals__: func.__globals__['__opts__'].update(self.opts) except __HOLE__: pass
AttributeError
dataset/ETHPy150Open saltstack/salt/salt/fileserver/__init__.py/Fileserver.update_opts
3,707
def __get_value(self, name): """Get a BlobInfo value, loading entity if necessary. This method allows lazy loading of the underlying datastore entity. It should never be invoked directly. Args: name: Name of property to get value for. Returns: Value of BlobInfo property from entity. """ if self.__entity is None: self.__entity = datastore.Get( datastore_types.Key.from_path( self.kind(), str(self.__key), namespace='')) try: return self.__entity[name] except __HOLE__: raise AttributeError(name)
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/blobstore/blobstore.py/BlobInfo.__get_value
3,708
def _parse_upload_info(field_storage, error_class): """Parse the upload info from file upload field_storage. Args: field_storage: cgi.FieldStorage that represents uploaded blob. error_class: error to raise. Returns: A dictionary containing the parsed values. None if there was no field_storage. Raises: error_class when provided a field_storage that does not contain enough information. """ if field_storage is None: return None field_name = field_storage.name def get_value(dict, name): value = dict.get(name, None) if value is None: raise error_class( 'Field %s has no %s.' % (field_name, name)) return value filename = get_value(field_storage.disposition_options, 'filename') blob_key = field_storage.type_options.get('blob-key', None) upload_content = email.message_from_file(field_storage.file) field_storage.file.seek(0) content_type = get_value(upload_content, 'content-type') size = get_value(upload_content, 'content-length') creation_string = get_value(upload_content, UPLOAD_INFO_CREATION_HEADER) md5_hash_encoded = get_value(upload_content, 'content-md5') md5_hash = base64.urlsafe_b64decode(md5_hash_encoded) gs_object_name = upload_content.get(CLOUD_STORAGE_OBJECT_HEADER, None) try: size = int(size) except (TypeError, __HOLE__): raise error_class( '%s is not a valid value for %s size.' % (size, field_name)) try: creation = blobstore._parse_creation(creation_string, field_name) except blobstore._CreationFormatError, err: raise error_class(str(err)) return {'blob_key': blob_key, 'content_type': content_type, 'creation': creation, 'filename': filename, 'size': size, 'md5_hash': md5_hash, 'gs_object_name': gs_object_name, }
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/blobstore/blobstore.py/_parse_upload_info
3,709
@contextlib.contextmanager def filelock(name, wait_delay=.1): path = os.path.join(tempfile.gettempdir(), name) while True: try: fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR) except __HOLE__ as e: if e.errno != errno.EEXIST: raise time.sleep(wait_delay) continue else: break try: yield fd finally: os.close(fd) os.unlink(path)
OSError
dataset/ETHPy150Open fcurella/django-recommends/recommends/utils.py/filelock
3,710
def _attached_volume_for_container( self, container, path_to_manifestations ): """ Infer the Flocker manifestation which is in use by the given container. :param flocker.node._docker.Unit container: The container to inspect. :param dict path_to_manifestations: A mapping from mount points (as ``FilePath``) to identifiers (as ``unicode``) of the datasets that are mounted there. :return: ``None`` if no Flocker manifestation can be associated with the container state. Otherwise an ``AttachedVolume`` referring to that manifestation and the location in the container where it is mounted. """ if container.volumes: # XXX https://clusterhq.atlassian.net/browse/FLOC-49 # we only support one volume per container # at this time # XXX https://clusterhq.atlassian.net/browse/FLOC-773 # we assume all volumes are datasets docker_volume = list(container.volumes)[0] try: manifestation = path_to_manifestations[ docker_volume.node_path] except __HOLE__: # Apparently not a dataset we're managing, give up. return None else: return AttachedVolume( manifestation=manifestation, mountpoint=docker_volume.container_path, ) return None
KeyError
dataset/ETHPy150Open ClusterHQ/flocker/flocker/node/_container.py/ApplicationNodeDeployer._attached_volume_for_container
3,711
def _environment_for_container(self, container): """ Get the custom environment specified for the container and infer its links. It would be nice to do these two things separately but links are only represented in the container's environment so both steps involve inspecting the environment. :param flocker.node._docker.Unit container: The container to inspect. :return: A two-tuple of the container's links and environment. Links are given as a ``list`` of ``Link`` instances. Environment is given as a ``list`` of two-tuples giving the environment variable name and value (as ``bytes``). """ # Improve the factoring of this later. Separate it into two methods. links = [] environment = [] if container.environment: environment_dict = container.environment.to_dict() for label, value in environment_dict.items(): # <ALIAS>_PORT_<PORTNUM>_TCP_PORT=<value> parts = label.rsplit(b"_", 4) try: alias, pad_a, port, pad_b, pad_c = parts local_port = int(port) except ValueError: # <ALIAS>_PORT_<PORT>_TCP parts = label.rsplit(b"_", 3) try: alias, pad_a, port, pad_b = parts except __HOLE__: environment.append((label, value)) continue if not (pad_a, pad_b) == (b"PORT", b"TCP"): environment.append((label, value)) continue if (pad_a, pad_b, pad_c) == (b"PORT", b"TCP", b"PORT"): links.append(Link( local_port=local_port, remote_port=int(value), alias=alias, )) return links, environment
ValueError
dataset/ETHPy150Open ClusterHQ/flocker/flocker/node/_container.py/ApplicationNodeDeployer._environment_for_container
3,712
def showfiles(args): """Writes out the input and output files. Works both for a pack file and for an extracted directory. """ def parse_run(runs, s): for i, run in enumerate(runs): if run['id'] == s: return i try: r = int(s) except __HOLE__: logging.critical("Error: Unknown run %s", s) raise UsageError if r < 0 or r >= len(runs): logging.critical("Error: Expected 0 <= run <= %d, got %d", len(runs) - 1, r) sys.exit(1) return r show_inputs = args.input or not args.output show_outputs = args.output or not args.input def file_filter(fio): if file_filter.run is None: return ((show_inputs and fio.read_runs) or (show_outputs and fio.write_runs)) else: return ((show_inputs and file_filter.run in fio.read_runs) or (show_outputs and file_filter.run in fio.write_runs)) file_filter.run = None pack = Path(args.pack[0]) if not pack.exists(): logging.critical("Pack or directory %s does not exist", pack) sys.exit(1) if pack.is_dir(): # Reads info from an unpacked directory config = load_config_file(pack / 'config.yml', canonical=True) # Filter files by run if args.run is not None: file_filter.run = parse_run(config.runs, args.run) # The '.reprounzip' file is a pickled dictionary, it contains the name # of the files that replaced each input file (if upload was used) unpacked_info = metadata_read(pack, None) assigned_input_files = unpacked_info.get('input_files', {}) if show_inputs: shown = False for input_name, f in sorted(iteritems(config.inputs_outputs)): if f.read_runs and file_filter(f): if not shown: print("Input files:") shown = True if args.verbosity >= 2: print(" %s (%s)" % (input_name, f.path)) else: print(" %s" % input_name) assigned = assigned_input_files.get(input_name) if assigned is None: assigned = "(original)" elif assigned is False: assigned = "(not created)" elif assigned is True: assigned = "(generated)" else: assert isinstance(assigned, (bytes, unicode_)) print(" %s" % assigned) if not shown: print("Input files: none") if show_outputs: shown = False for output_name, f in sorted(iteritems(config.inputs_outputs)): if f.write_runs and file_filter(f): if not shown: print("Output files:") shown = True if args.verbosity >= 2: print(" %s (%s)" % (output_name, f.path)) else: print(" %s" % output_name) if not shown: print("Output files: none") else: # pack.is_file() # Reads info from a pack file config = load_config(pack) # Filter files by run if args.run is not None: file_filter.run = parse_run(config.runs, args.run) if any(f.read_runs for f in itervalues(config.inputs_outputs)): print("Input files:") for input_name, f in sorted(iteritems(config.inputs_outputs)): if f.read_runs and file_filter(f): if args.verbosity >= 2: print(" %s (%s)" % (input_name, f.path)) else: print(" %s" % input_name) else: print("Input files: none") if any(f.write_runs for f in itervalues(config.inputs_outputs)): print("Output files:") for output_name, f in sorted(iteritems(config.inputs_outputs)): if f.write_runs and file_filter(f): if args.verbosity >= 2: print(" %s (%s)" % (output_name, f.path)) else: print(" %s" % output_name) else: print("Output files: none")
ValueError
dataset/ETHPy150Open ViDA-NYU/reprozip/reprounzip/reprounzip/pack_info.py/showfiles
3,713
def parse(self, response): # x_path test checker = response.request.meta['checker'] rpt = response.request.meta['rpt'] if checker.checker_type == '4': self.log("No 404 ({c}).".format(c=str(checker)), logging.INFO) return if rpt.content_type == 'J': json_resp = json.loads(response.body_as_unicode()) try: jsonpath_expr = parse(checker.checker_x_path) except JsonPathLexerError: raise CloseSpider("Invalid checker JSONPath ({c})!".format(c=str(checker))) test_select = [match.value for match in jsonpath_expr.find(json_resp)] #self.log(unicode(test_select), logging.INFO) else: try: test_select = response.xpath(checker.checker_x_path).extract() except __HOLE__: self.log("Invalid checker XPath ({c})!".format(c=str(checker)), logging.ERROR) return if len(test_select) > 0 and checker.checker_x_path_result == '': self.log("Elements for XPath found on page (no result string defined) ({c}). Delete reason.".format(c=str(checker)), logging.INFO) if self.conf['DO_ACTION']: self._del_ref_object() return elif len(test_select) > 0 and test_select[0] == checker.checker_x_path_result: self.log("XPath result string '{s}' found on page ({c}). Delete reason.".format(s=checker.checker_x_path_result, c=str(checker)), logging.INFO) if self.conf['DO_ACTION']: self._del_ref_object() return else: self.log("XPath result string not found ({c}).".format(c=str(checker)), logging.INFO) return
ValueError
dataset/ETHPy150Open holgerd77/django-dynamic-scraper/dynamic_scraper/spiders/django_checker.py/DjangoChecker.parse
3,714
def unload_module(module): if "plugin_unloaded" in module.__dict__: module.plugin_unloaded() # Check unload_handler too, for backwards compat if "unload_handler" in module.__dict__: module.unload_handler() # Unload the old plugins if "plugins" in module.__dict__: for p in module.plugins: for cmd_cls_list in all_command_classes: try: cmd_cls_list.remove(p) except __HOLE__: pass for c in all_callbacks.values(): try: c.remove(p) except ValueError: pass
ValueError
dataset/ETHPy150Open spywhere/Javatar/tests/stubs/sublime_plugin.py/unload_module
3,715
def reload_plugin(modulename): print("reloading plugin", modulename) if modulename in sys.modules: m = sys.modules[modulename] unload_module(m) m = imp.reload(m) else: m = importlib.import_module(modulename) module_plugins = [] on_activated_targets = [] for type_name in dir(m): try: t = m.__dict__[type_name] if t.__bases__: is_plugin = False if issubclass(t, ApplicationCommand): application_command_classes.append(t) is_plugin = True if issubclass(t, WindowCommand): window_command_classes.append(t) is_plugin = True if issubclass(t, TextCommand): text_command_classes.append(t) is_plugin = True if is_plugin: module_plugins.append(t) if issubclass(t, EventListener): obj = t() for p in all_callbacks.items(): if p[0] in dir(obj): p[1].append(obj) if "on_activated" in dir(obj): on_activated_targets.append(obj) module_plugins.append(obj) except __HOLE__: pass if len(module_plugins) > 0: m.plugins = module_plugins if api_ready: if "plugin_loaded" in m.__dict__: try: m.plugin_loaded() except: traceback.print_exc() # Synthesize any required on_activated calls for el in on_activated_targets: w = sublime.active_window() if w: v = w.active_view() if v: try: el.on_activated(v) except: traceback.print_exc()
AttributeError
dataset/ETHPy150Open spywhere/Javatar/tests/stubs/sublime_plugin.py/reload_plugin
3,716
def create_text_commands(view_id): view = sublime.View(view_id) cmds = [] for class_ in text_command_classes: try: cmds.append(class_(view)) except __HOLE__: print(class_) raise return cmds
TypeError
dataset/ETHPy150Open spywhere/Javatar/tests/stubs/sublime_plugin.py/create_text_commands
3,717
def is_enabled_(self, args): ret = None try: if args: if 'event' in args: del args['event'] ret = self.is_enabled(**args) else: ret = self.is_enabled() except __HOLE__: ret = self.is_enabled() if not isinstance(ret, bool): raise ValueError("is_enabled must return a bool", self) return ret
TypeError
dataset/ETHPy150Open spywhere/Javatar/tests/stubs/sublime_plugin.py/Command.is_enabled_
3,718
def is_visible_(self, args): ret = None try: if args: ret = self.is_visible(**args) else: ret = self.is_visible() except __HOLE__: ret = self.is_visible() if not isinstance(ret, bool): raise ValueError("is_visible must return a bool", self) return ret
TypeError
dataset/ETHPy150Open spywhere/Javatar/tests/stubs/sublime_plugin.py/Command.is_visible_
3,719
def is_checked_(self, args): ret = None try: if args: ret = self.is_checked(**args) else: ret = self.is_checked() except __HOLE__: ret = self.is_checked() if not isinstance(ret, bool): raise ValueError("is_checked must return a bool", self) return ret
TypeError
dataset/ETHPy150Open spywhere/Javatar/tests/stubs/sublime_plugin.py/Command.is_checked_
3,720
def description_(self, args): try: if args != None: return self.description(**args) else: return self.description() except __HOLE__ as e: return ""
TypeError
dataset/ETHPy150Open spywhere/Javatar/tests/stubs/sublime_plugin.py/Command.description_
3,721
def __init__(self, zippath): self.zippath = zippath self.name = os.path.splitext(os.path.basename(zippath))[0] self.contents = {"":""} self.packages = {""} z = zipfile.ZipFile(zippath, 'r') files = [i.filename for i in z.infolist()] for f in files: base, ext = os.path.splitext(f) if ext != ".py": continue paths = base.split('/') if len(paths) > 0 and paths[len(paths) - 1] == "__init__": paths.pop() self.packages.add('.'.join(paths)) try: self.contents['.'.join(paths)] = z.read(f).decode('utf-8') except __HOLE__: print(f, "in", zippath, "is not utf-8 encoded, unable to load plugin") continue while len(paths) > 1: paths.pop() parent = '.'.join(paths) if parent not in self.contents: self.contents[parent] = "" self.packages.add(parent) z.close()
UnicodeDecodeError
dataset/ETHPy150Open spywhere/Javatar/tests/stubs/sublime_plugin.py/ZipLoader.__init__
3,722
@staticmethod def open_using_pefile(input_name, input_bytes): ''' Open the PE File using the Python pefile module. ''' try: pef = pefile.PE(data=input_bytes, fast_load=False) except (__HOLE__, pefile.PEFormatError), error: print 'warning: pe_fail (with exception from pefile module) on file: %s' % input_name error_str = '(Exception):, %s' % (str(error)) return None, error_str # Now test to see if the features are there/extractable if not return FAIL flag if pef.PE_TYPE is None or pef.OPTIONAL_HEADER is None or len(pef.OPTIONAL_HEADER.DATA_DIRECTORY) < 7: print 'warning: pe_fail on file: %s' % input_name error_str = 'warning: pe_fail on file: %s' % input_name return None, error_str # Success return pef, None # Extract various set of features using PEfile module
AttributeError
dataset/ETHPy150Open SuperCowPowers/workbench/workbench/workers/pe_features.py/PEFileWorker.open_using_pefile
3,723
def extract_features_using_pefile(self, pef): ''' Process the PE File using the Python pefile module. ''' # Store all extracted features into feature lists extracted_dense = {} extracted_sparse = {} # Now slog through the info and extract the features feature_not_found_flag = -99 feature_default_value = 0 self._warnings = [] # Set all the dense features and sparse features to 'feature not found' # value and then check later to see if it was found for feature in self._dense_feature_list: extracted_dense[feature] = feature_not_found_flag for feature in self._sparse_feature_list: extracted_sparse[feature] = feature_not_found_flag # Check to make sure all the section names are standard std_sections = ['.text', '.bss', '.rdata', '.data', '.rsrc', '.edata', '.idata', '.pdata', '.debug', '.reloc', '.stab', '.stabstr', '.tls', '.crt', '.gnu_deb', '.eh_fram', '.exptbl', '.rodata'] for i in range(200): std_sections.append('/'+str(i)) std_section_names = 1 extracted_sparse['section_names'] = [] for section in pef.sections: name = convert_to_ascii_null_term(section.Name).lower() extracted_sparse['section_names'].append(name) if name not in std_sections: std_section_names = 0 extracted_dense['std_section_names'] = std_section_names extracted_dense['debug_size'] = pef.OPTIONAL_HEADER.DATA_DIRECTORY[6].Size extracted_dense['major_version'] = pef.OPTIONAL_HEADER.MajorImageVersion extracted_dense['minor_version'] = pef.OPTIONAL_HEADER.MinorImageVersion extracted_dense['iat_rva'] = pef.OPTIONAL_HEADER.DATA_DIRECTORY[1].VirtualAddress extracted_dense['export_size'] = pef.OPTIONAL_HEADER.DATA_DIRECTORY[0].Size extracted_dense['check_sum'] = pef.OPTIONAL_HEADER.CheckSum try: extracted_dense['generated_check_sum'] = pef.generate_checksum() except ValueError: extracted_dense['generated_check_sum'] = 0 if len(pef.sections) > 0: extracted_dense['virtual_address'] = pef.sections[0].VirtualAddress extracted_dense['virtual_size'] = pef.sections[0].Misc_VirtualSize extracted_dense['number_of_sections'] = pef.FILE_HEADER.NumberOfSections extracted_dense['compile_date'] = pef.FILE_HEADER.TimeDateStamp extracted_dense['number_of_rva_and_sizes'] = pef.OPTIONAL_HEADER.NumberOfRvaAndSizes extracted_dense['total_size_pe'] = len(pef.__data__) # Number of import and exports if hasattr(pef, 'DIRECTORY_ENTRY_IMPORT'): extracted_dense['number_of_imports'] = len(pef.DIRECTORY_ENTRY_IMPORT) num_imported_symbols = 0 for module in pef.DIRECTORY_ENTRY_IMPORT: num_imported_symbols += len(module.imports) extracted_dense['number_of_import_symbols'] = num_imported_symbols if hasattr(pef, 'DIRECTORY_ENTRY_BOUND_IMPORT'): extracted_dense['number_of_bound_imports'] = len(pef.DIRECTORY_ENTRY_BOUND_IMPORT) num_imported_symbols = 0 for module in pef.DIRECTORY_ENTRY_BOUND_IMPORT: num_imported_symbols += len(module.entries) extracted_dense['number_of_bound_import_symbols'] = num_imported_symbols if hasattr(pef, 'DIRECTORY_ENTRY_EXPORT'): try: extracted_dense['number_of_export_symbols'] = len(pef.DIRECTORY_ENTRY_EXPORT.symbols) symbol_set = set() for symbol in pef.DIRECTORY_ENTRY_EXPORT.symbols: symbol_info = 'unknown' if not symbol.name: symbol_info = 'ordinal=' + str(symbol.ordinal) else: symbol_info = 'name=' + symbol.name symbol_set.add(convert_to_utf8('%s' % (symbol_info)).lower()) # Now convert set to list and add to features extracted_sparse['ExportedSymbols'] = list(symbol_set) except AttributeError: extracted_sparse['ExportedSymbols'] = ['AttributeError'] # Specific Import info (Note this will be a sparse field woo hoo!) if hasattr(pef, 'DIRECTORY_ENTRY_IMPORT'): symbol_set = set() for module in pef.DIRECTORY_ENTRY_IMPORT: for symbol in module.imports: symbol_info = 'unknown' if symbol.import_by_ordinal is True: symbol_info = 'ordinal=' + str(symbol.ordinal) else: symbol_info = 'name=' + symbol.name # symbol_info['hint'] = symbol.hint if symbol.bound: symbol_info += ' bound=' + str(symbol.bound) symbol_set.add(convert_to_utf8('%s:%s' % (module.dll, symbol_info)).lower()) # Now convert set to list and add to features extracted_sparse['imported_symbols'] = list(symbol_set) # Do we have a second section if len(pef.sections) >= 2: extracted_dense['virtual_size_2'] = pef.sections[1].Misc_VirtualSize extracted_dense['size_image'] = pef.OPTIONAL_HEADER.SizeOfImage extracted_dense['size_code'] = pef.OPTIONAL_HEADER.SizeOfCode extracted_dense['size_initdata'] = pef.OPTIONAL_HEADER.SizeOfInitializedData extracted_dense['size_uninit'] = pef.OPTIONAL_HEADER.SizeOfUninitializedData extracted_dense['pe_majorlink'] = pef.OPTIONAL_HEADER.MajorLinkerVersion extracted_dense['pe_minorlink'] = pef.OPTIONAL_HEADER.MinorLinkerVersion extracted_dense['pe_driver'] = 1 if pef.is_driver() else 0 extracted_dense['pe_exe'] = 1 if pef.is_exe() else 0 extracted_dense['pe_dll'] = 1 if pef.is_dll() else 0 extracted_dense['pe_i386'] = 1 if pef.FILE_HEADER.Machine != 0x014c: extracted_dense['pe_i386'] = 0 extracted_dense['pe_char'] = pef.FILE_HEADER.Characteristics # Data directory features!! datadirs = { 0: 'IMAGE_DIRECTORY_ENTRY_EXPORT', 1: 'IMAGE_DIRECTORY_ENTRY_IMPORT', 2: 'IMAGE_DIRECTORY_ENTRY_RESOURCE', 5: 'IMAGE_DIRECTORY_ENTRY_BASERELOC', 12: 'IMAGE_DIRECTORY_ENTRY_IAT'} for idx, datadir in datadirs.items(): datadir = pefile.DIRECTORY_ENTRY[idx] if len(pef.OPTIONAL_HEADER.DATA_DIRECTORY) <= idx: continue directory = pef.OPTIONAL_HEADER.DATA_DIRECTORY[idx] extracted_dense['datadir_%s_size' % datadir] = directory.Size # Section features section_flags = ['IMAGE_SCN_MEM_EXECUTE', 'IMAGE_SCN_CNT_CODE', 'IMAGE_SCN_MEM_WRITE', 'IMAGE_SCN_MEM_READ'] rawexecsize = 0 vaexecsize = 0 for sec in pef.sections: if not sec: continue for char in section_flags: # does the section have one of our attribs? if hasattr(sec, char): rawexecsize += sec.SizeOfRawData vaexecsize += sec.Misc_VirtualSize break # Take out any weird characters in section names secname = convert_to_ascii_null_term(sec.Name).lower() secname = secname.replace('.', '') if secname in std_sections: extracted_dense['sec_entropy_%s' % secname] = sec.get_entropy() extracted_dense['sec_rawptr_%s' % secname] = sec.PointerToRawData extracted_dense['sec_rawsize_%s' % secname] = sec.SizeOfRawData extracted_dense['sec_vasize_%s' % secname] = sec.Misc_VirtualSize extracted_dense['sec_va_execsize'] = vaexecsize extracted_dense['sec_raw_execsize'] = rawexecsize # Imphash (implemented in pefile 1.2.10-139 or later) try: extracted_sparse['imp_hash'] = pef.get_imphash() except __HOLE__: extracted_sparse['imp_hash'] = 'Not found: Install pefile 1.2.10-139 or later' # Register if there were any pe warnings warnings = pef.get_warnings() if warnings: extracted_dense['pe_warnings'] = 1 extracted_sparse['pe_warning_strings'] = warnings else: extracted_dense['pe_warnings'] = 0 # Issue a warning if the feature isn't found for feature in self._dense_feature_list: if extracted_dense[feature] == feature_not_found_flag: extracted_dense[feature] = feature_default_value if (self._verbose): print 'info: Feature: %s not found! Setting to %d' % (feature, feature_default_value) # Issue a warning if the feature isn't found for feature in self._sparse_feature_list: if extracted_sparse[feature] == feature_not_found_flag: extracted_sparse[feature] = [] # For sparse data probably best default if (self._verbose): print 'info: Feature: %s not found! Setting to %d' % (feature, feature_default_value) # Set the features for the class var self._dense_features = extracted_dense self._sparse_features = extracted_sparse return self.get_dense_features(), self.get_sparse_features() # Helper functions
AttributeError
dataset/ETHPy150Open SuperCowPowers/workbench/workbench/workers/pe_features.py/PEFileWorker.extract_features_using_pefile
3,724
def convert_to_utf8(string): ''' Convert string to UTF8 ''' if (isinstance(string, unicode)): return string.encode('utf-8') try: u = unicode(string, 'utf-8') except __HOLE__: return str(string) utf8 = u.encode('utf-8') return utf8
TypeError
dataset/ETHPy150Open SuperCowPowers/workbench/workbench/workers/pe_features.py/convert_to_utf8
3,725
def __init__(self, **kwargs): """ Match inputs with vars """ super(CommonData, self).__init__(**kwargs) if self.validate() is False: raise TypeError("\n".join("'%s' <- %s" % (x, y) for x, y in six.iteritems(self.errors))) # Add extra vars from modules try: module_name = kwargs['module_name'] fake_kwargs = dict(kwargs) # Add metavars: action / subactions self.action = fake_kwargs.pop('module_name') self.sub_action = None # Is a sub-action selected for x, y in six.iteritems(fake_kwargs): if x.startswith("module_"): self.sub_action = fake_kwargs.pop(x) break module_model = getattr(AppSettings.modules[module_name], "__model__", None) if module_model is not None: # Load module model to check parameters module_model(**fake_kwargs) # If not errors, set vars and values for x, v in six.iteritems(fake_kwargs): if x not in self.vars: setattr(self, x, v) except __HOLE__: # No module name available -> not an error. Class must be loading from another locations pass # ----------------------------------------------------------------------
KeyError
dataset/ETHPy150Open cr0hn/enteletaor/enteletaor_lib/libs/core/structs.py/CommonData.__init__
3,726
def __repr__(self): r = [] for x, v in six.iteritems(self.vars): try: r.append("%s: %s" % (x, str(v))) except __HOLE__: r.append("%s: %s" % (x, str(v.data))) return "\n".join(r) # --------------------------------------------------------------------------
TypeError
dataset/ETHPy150Open cr0hn/enteletaor/enteletaor_lib/libs/core/structs.py/CommonData.__repr__
3,727
def has_value(key, value=None): ''' Determine whether the key exists in the current salt process environment dictionary. Optionally compare the current value of the environment against the supplied value string. key Must be a string. Used as key for environment lookup. value: Optional. If key exists in the environment, compare the current value with this value. Return True if they are equal. CLI Example: .. code-block:: bash salt '*' environ.has_value foo ''' if not isinstance(key, six.string_types): log.debug( '{0}: \'key\' argument is not a string type: \'{1}\'' .format(__name__, key) ) return False try: cur_val = os.environ[key] if value is not None: if cur_val == value: return True else: return False except __HOLE__: return False return True
KeyError
dataset/ETHPy150Open saltstack/salt/salt/modules/environ.py/has_value
3,728
def __init__(self, *args, **kwds): if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__end except __HOLE__: self.clear() self.update(*args, **kwds)
AttributeError
dataset/ETHPy150Open jkbrzt/httpie/httpie/compat.py/OrderedDict.__init__
3,729
def __init__(self, *a, **kw): try: import json except __HOLE__: import simplejson as json self.json = json self.storage = ManifestStaticFilesStorage() self._load_manifest()
ImportError
dataset/ETHPy150Open miracle2k/django-assets/django_assets/manifest.py/DjangoManifest.__init__
3,730
def load(self): self.models = {} self.cmds = {} self.settings = Settings() try: load = self.mod.load except __HOLE__: pass else: load(self)
AttributeError
dataset/ETHPy150Open natano/tiget/tiget/plugins/__init__.py/Plugin.load
3,731
def unload(self): try: unload = self.mod.unload except __HOLE__: pass else: unload(self)
AttributeError
dataset/ETHPy150Open natano/tiget/tiget/plugins/__init__.py/Plugin.unload
3,732
@periodic_task.periodic_task def _heal_instances(self, ctxt): """Periodic task to send updates for a number of instances to parent cells. On every run of the periodic task, we will attempt to sync 'CONF.cells.instance_update_num_instances' number of instances. When we get the list of instances, we shuffle them so that multiple nova-cells services aren't attempting to sync the same instances in lockstep. If CONF.cells.instance_update_at_threshold is set, only attempt to sync instances that have been updated recently. The CONF setting defines the maximum number of seconds old the updated_at can be. Ie, a threshold of 3600 means to only update instances that have modified in the last hour. """ if not self.state_manager.get_parent_cells(): # No need to sync up if we have no parents. return info = {'updated_list': False} def _next_instance(): try: instance = next(self.instances_to_heal) except __HOLE__: if info['updated_list']: return threshold = CONF.cells.instance_updated_at_threshold updated_since = None if threshold > 0: updated_since = timeutils.utcnow() - datetime.timedelta( seconds=threshold) self.instances_to_heal = cells_utils.get_instances_to_sync( ctxt, updated_since=updated_since, shuffle=True, uuids_only=True) info['updated_list'] = True try: instance = next(self.instances_to_heal) except StopIteration: return return instance rd_context = ctxt.elevated(read_deleted='yes') for i in range(CONF.cells.instance_update_num_instances): while True: # Yield to other greenthreads time.sleep(0) instance_uuid = _next_instance() if not instance_uuid: return try: instance = objects.Instance.get_by_uuid(rd_context, instance_uuid) except exception.InstanceNotFound: continue self._sync_instance(ctxt, instance) break
StopIteration
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/cells/manager.py/CellsManager._heal_instances
3,733
def connection_memoize(key): """Decorator, memoize a function in a connection.info stash. Only applicable to functions which take no arguments other than a connection. The memo will be stored in ``connection.info[key]``. """ @util.decorator def decorated(fn, self, connection): connection = connection.connect() try: return connection.info[key] except __HOLE__: connection.info[key] = val = fn(self, connection) return val return decorated
KeyError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/engine/util.py/connection_memoize
3,734
def query_bugs(self, query): bugs = [] def __api_call(offset=None): query_results = self.jira.jql(query, offset) if query_results: issues = query_results["issues"] for issue in issues: bug = self.from_search_json(issue) bugs.append(bug) try: starts_at = query_results.get("startAt") max_results = query_results.get("maxResults") total = query_results.get("total") ends_at = int(starts_at) + int(max_results) if ends_at < int(total): __api_call(offset=ends_at) except __HOLE__: pass __api_call(); return bugs
TypeError
dataset/ETHPy150Open SalesforceEng/Providence/Empire/bugsystems/jira/__init__.py/JiraBugSystem.query_bugs
3,735
def ensure_domain(name, purgeable=False, inherit_soa=False, force=False): """This function will take ``domain_name`` and make sure that a domain with that name exists. If this function creates a domain it will set the domain's purgeable flag to the value of the named arguement ``purgeable``. See the doc page about Labels and Domains for other information about this function. This function will attempt to prevent you from: * creating a new TLD * creating a domain that would be a child of a delegated domain * creating a domain that wouldn't exist in an existing zone (it wouldn't have an SOA) You can override these constrains by setting the ``force`` named argument to ``True``. By default if a domain's parent has an SOA, the new domain will not inherit that SOA. You can cause the domain to inherit the SOA by passing the named argument ``inherit_soa`` as ``True``. For example, the function :func:`ensure_label_domain` passes ``inherit_soa=True``. If a domain already exists with a name equal to ``name`` it is immediately returned. It is up to the caller to ensure that ``purgeable`` is set if it is needed. """ try: domain = Domain.objects.get(name=name) return domain except __HOLE__: pass # Looks like we are creating some domains. Make sure the first domain we # create is under a domain that has a non-None SOA reference. parts = list(reversed(name.split('.'))) if not force: domain_name = '' leaf_domain = None # Find the leaf domain. for i in range(len(parts)): domain_name = parts[i] + '.' + domain_name domain_name = domain_name.strip('.') try: tmp_domain = Domain.objects.get(name=domain_name) # It got here so we know we found a domain. leaf_domain = tmp_domain except ObjectDoesNotExist: continue if not leaf_domain: raise ValidationError( "Creating this record would cause the " "creation of a new TLD. Please contact " "http://www.icann.org/ for more information.") if leaf_domain.delegated: raise ValidationError( "Creating this record would cause the " "creation of a domain that would be a child of a " "delegated domain.") if not leaf_domain.soa: raise ValidationError( "Creating this record would cause the " "creation of a domain that would not be in an existing " "DNS zone.") domain_name = '' # We know the end domain doesn't exist, so we build it up incrementally # starting at the very right most parent domain. If we find that a parent # domain already exists we continue until we find the domain that doesn't # exist. for i in range(len(parts)): domain_name = parts[i] + '.' + domain_name domain_name = domain_name.strip('.') if Domain.objects.filter(name=domain_name).exists(): continue # We are about to create a domain that previously didn't exist! clobber_querysets = get_clobbered(domain_name) # Don't use get_or_create here because we need to pass certain kwargs # to clean() domain = Domain(name=domain_name) # we know the clobber_querysets may conflict, but we will handle # resolving the conflict later in this function if purgeable: domain.purgeable = True domain.clean(ignore_conflicts=True) # master domain is set here if (inherit_soa and domain.master_domain and domain.master_domain.soa is not None): domain.soa = domain.master_domain.soa # get the domain in the db so we can save the clobbered objects domain.save(do_full_clean=False) # update the objects that initially conflicted with this domain for qs in clobber_querysets: qs.update(domain=domain, label='') # full_clean() wasn't called on this domain but clean() was. Calling # clean_feilds() will ensure we have done the equivalent of a # full_clean() on the domain. domain.clean_fields() return domain
ObjectDoesNotExist
dataset/ETHPy150Open mozilla/inventory/mozdns/utils.py/ensure_domain
3,736
def ensure_label_domain(fqdn, force=False): """Returns a label and domain object.""" if fqdn == '': raise ValidationError("FQDN cannot be the emptry string.") try: domain = Domain.objects.get(name=fqdn) if not domain.soa and not force: raise ValidationError("You must create a record inside an " "existing zones.") return '', domain except __HOLE__: pass fqdn_partition = fqdn.split('.') if len(fqdn_partition) == 1: raise ValidationError("Creating this record would force the creation " "of a new TLD '{0}'!".format(fqdn)) else: label, domain_name = fqdn_partition[0], '.'.join(fqdn_partition[1:]) domain = ensure_domain(domain_name, purgeable=True, inherit_soa=True) if not domain.soa and not force: raise ValidationError("You must create a record inside an " "existing zones.") return label, domain
ObjectDoesNotExist
dataset/ETHPy150Open mozilla/inventory/mozdns/utils.py/ensure_label_domain
3,737
def getData(filename, name): global discover_tests try: file_tests = discover_tests[filename] except __HOLE__: file_tests = discover_tests[filename] = readTests(filename) return file_tests[name]
KeyError
dataset/ETHPy150Open necaris/python3-openid/openid/test/discoverdata.py/getData
3,738
def generateSample(test_name, base_url, example_xrds=example_xrds, filename=default_test_file): try: template = getData(filename, test_name) except __HOLE__ as why: import errno if int(why) == errno.ENOENT: raise KeyError(filename) else: raise return fillTemplate(test_name, template, base_url, example_xrds)
IOError
dataset/ETHPy150Open necaris/python3-openid/openid/test/discoverdata.py/generateSample
3,739
def export(self, request): self.full_clean() format = 'yaml' selected = [] include_images = False include_categories = False for name, value in self.cleaned_data.items(): if name == 'format': format = value continue if name == 'include_images': include_images = value continue if name == 'include_categories': include_categories = value continue opt, key = name.split('__') if opt=='export': if value: selected.append(key) try: serializers.get_serializer(format) except __HOLE__: raise CommandError("Unknown serialization format: %s" % format) objects = [] images = [] categories = {} for slug in selected: product = Product.objects.get(slug=slug) objects.append(product) for subtype in product.get_subtypes(): objects.append(getattr(product,subtype.lower())) objects.extend(list(product.price_set.all())) objects.extend(list(product.productimage_set.all())) if include_images: for image in product.productimage_set.all(): images.append(image.picture) if include_categories: for category in product.category.all(): if category not in categories: categories[category] = 1 # Export all categories, translations. Export images,translations if # desired. if include_categories: for category in categories.keys(): objects.append(category) objects.extend(list(category.translations.all())) if include_images: for image in category.images.all(): objects.append(image) objects.extend(list(image.translations.all())) try: raw = serializers.serialize(format, objects, indent=False) except Exception, e: raise CommandError("Unable to serialize database: %s" % e) if include_images: filedir = settings.MEDIA_ROOT buf = StringIO() zf = zipfile.ZipFile(buf, 'a', zipfile.ZIP_STORED) export_file = 'products.%s' % format zf.writestr(str(export_file), raw) zinfo = zf.getinfo(str(export_file)) # Caution, highly magic number, chmods the file to 644 zinfo.external_attr = 2175008768L image_dir = config_value('PRODUCT', 'IMAGE_DIR') config = "PRODUCT.IMAGE_DIR=%s\nEXPORT_FILE=%s" % (image_dir, export_file) zf.writestr('VARS', config) zinfo = zf.getinfo('VARS') # Caution, highly magic number, chmods the file to 644 zinfo.external_attr = 2175008768L for image in images: f = os.path.join(filedir, image) if os.path.exists(f): zf.write(f, str(image)) zf.close() raw = buf.getvalue() mimetype = "application/zip" format = "zip" else: mimetype = "text/" + format response = HttpResponse(mimetype=mimetype, content=raw) response['Content-Disposition'] = 'attachment; filename="products-%s.%s"' % (time.strftime('%Y%m%d-%H%M'), format) return response
KeyError
dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/product/forms.py/ProductExportForm.export
3,740
def _save(self, request): self.full_clean() data = self.cleaned_data optiondict = _get_optiondict() #dirty is a comma delimited list of groupid__optionid strings dirty = self.cleaned_data['dirty'].split(',') if dirty: for key in dirty: # this is the keep/create checkbox field try: keep = data["pv__" + key] opts = _get_options_for_key(key, optiondict) if opts: if keep: self._create_variation(opts, key, data, request) else: self._delete_variation(opts, request) except __HOLE__: pass
KeyError
dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/product/forms.py/VariationManagerForm._save
3,741
def _get_options_for_key(key, optiondict): ids = key.split('__') opts = [] for work in ids: grpid, optid = work.split('_') try: opts.append(optiondict[int(grpid)][int(optid)]) except __HOLE__: log.warn('Could not find option for group id=%s, option id=%s', grpid, optid) return opts
KeyError
dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/product/forms.py/_get_options_for_key
3,742
def test_constructor(self): a = Rat(10, 15) self.assertEqual(a.num, 2) self.assertEqual(a.den, 3) a = Rat(10L, 15L) self.assertEqual(a.num, 2) self.assertEqual(a.den, 3) a = Rat(10, -15) self.assertEqual(a.num, -2) self.assertEqual(a.den, 3) a = Rat(-10, 15) self.assertEqual(a.num, -2) self.assertEqual(a.den, 3) a = Rat(-10, -15) self.assertEqual(a.num, 2) self.assertEqual(a.den, 3) a = Rat(7) self.assertEqual(a.num, 7) self.assertEqual(a.den, 1) try: a = Rat(1, 0) except ZeroDivisionError: pass else: self.fail("Rat(1, 0) didn't raise ZeroDivisionError") for bad in "0", 0.0, 0j, (), [], {}, None, Rat, unittest: try: a = Rat(bad) except TypeError: pass else: self.fail("Rat(%r) didn't raise TypeError" % bad) try: a = Rat(1, bad) except __HOLE__: pass else: self.fail("Rat(1, %r) didn't raise TypeError" % bad)
TypeError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_binop.py/RatTestCase.test_constructor
3,743
def test_check_errors(): wc = WordCloud() assert_raises(NotImplementedError, wc.to_html) try: np.array(wc) raise AssertionError("np.array(wc) didn't raise") except __HOLE__ as e: assert_true("call generate" in str(e)) try: wc.recolor() raise AssertionError("wc.recolor didn't raise") except ValueError as e: assert_true("call generate" in str(e))
ValueError
dataset/ETHPy150Open amueller/word_cloud/test/test_wordcloud.py/test_check_errors
3,744
def __exit__(self, exc_type, exc_value, tb): if self.expected is None: if exc_type is None: return True else: raise if exc_type is None: try: exc_name = self.expected.__name__ except __HOLE__: exc_name = str(self.expected) raise AssertionError("{0} not raised".format(exc_name)) if not issubclass(exc_type, self.expected): raise if self.expected_regex is None: return True expected_regex = self.expected_regex expected_regex = re.compile(expected_regex) if not expected_regex.search(str(exc_value)): raise AssertionError("'{0}' does not match '{1}'".format(expected_regex.pattern, str(exc_value))) return True
AttributeError
dataset/ETHPy150Open ros-infrastructure/bloom/test/utils/common.py/AssertRaisesContext.__exit__
3,745
def user_bloom(cmd, args=None, directory=None, auto_assert=True, return_io=True, silent=False): """Runs the given bloom cmd ('git-bloom-{cmd}') with the given args""" assert type(cmd) == str, \ "user_bloom cmd takes str only, got " + str(type(cmd)) if args is None: args = cmd.split()[1:] cmd = cmd.split()[0] assert type(args) in [list, tuple, str], \ "user_bloom args takes [list, tuple, str] only, got " + \ str(type(args)) from pkg_resources import load_entry_point from bloom import __version__ as ver if not cmd.startswith('git-bloom-'): cmd = 'git-bloom-' + cmd if type(args) != list: if type(args) == str: args = args.split() args = list(args) with change_directory(directory if directory is not None else os.getcwd()): with redirected_stdio() as (out, err): func = load_entry_point('bloom==' + ver, 'console_scripts', cmd) try: ret = func(args) or 0 except __HOLE__ as e: ret = e.code if ret != 0 and auto_assert: raise if not silent: print("Command '{0}' returned '{1}':".format(cmd, ret)) print(out.getvalue(), file=sys.stdout, end='') print(err.getvalue(), file=sys.stderr, end='') if return_io: return ret, out.getvalue(), err.getvalue() return ret
SystemExit
dataset/ETHPy150Open ros-infrastructure/bloom/test/utils/common.py/user_bloom
3,746
def load_creds(self): print(" > Loading access token..."), try: stored_creds = open(self.TOKEN_FILE).read() self.set_token(*stored_creds.split('|')) print(" [OK]") except __HOLE__: print(" [FAILED]") print(" x Access token not found. Beginning new session.") self.link()
IOError
dataset/ETHPy150Open ksiazkowicz/orphilia-dropbox/orphiliaclient/client.py/StoredSession.load_creds
3,747
def GetTSKVsPartByPathSpec(tsk_volume, path_spec): """Retrieves the TSK volume system part object from the TSK volume object. Args: tsk_volume: a TSK volume object (instance of pytsk3.Volume_Info). path_spec: the path specification (instance of PathSpec). Returns: A tuple of the TSK volume system part object (instance of pytsk3.TSK_VS_PART_INFO) and the partition index. The partition index is None when not available. The function return or (None, None) on error. """ location = getattr(path_spec, u'location', None) part_index = getattr(path_spec, u'part_index', None) start_offset = getattr(path_spec, u'start_offset', None) partition_index = None if part_index is None: if location is not None: if location.startswith(u'/p'): try: partition_index = int(location[2:], 10) - 1 except __HOLE__: pass if partition_index is None or partition_index < 0: location = None if location is None and start_offset is None: return None, None bytes_per_sector = TSKVolumeGetBytesPerSector(tsk_volume) current_part_index = 0 current_partition_index = 0 tsk_vs_part = None # pytsk3 does not handle the Volume_Info iterator correctly therefore # the explicit cast to list is needed to prevent the iterator terminating # too soon or looping forever. tsk_vs_part_list = list(tsk_volume) number_of_tsk_vs_parts = len(tsk_vs_part_list) if number_of_tsk_vs_parts > 0: if (part_index is not None and (part_index < 0 or part_index >= number_of_tsk_vs_parts)): return None, None for tsk_vs_part in tsk_vs_part_list: if TSKVsPartIsAllocated(tsk_vs_part): if partition_index is not None: if partition_index == current_partition_index: break current_partition_index += 1 if part_index is not None and part_index == current_part_index: break if start_offset is not None: start_sector = TSKVsPartGetStartSector(tsk_vs_part) if start_sector is not None: start_sector *= bytes_per_sector if start_sector == start_offset: break current_part_index += 1 # Note that here we cannot solely rely on testing if tsk_vs_part is set # since the for loop will exit with tsk_vs_part set. if tsk_vs_part is None or current_part_index >= number_of_tsk_vs_parts: return None, None if not TSKVsPartIsAllocated(tsk_vs_part): current_partition_index = None return tsk_vs_part, current_partition_index
ValueError
dataset/ETHPy150Open log2timeline/dfvfs/dfvfs/lib/tsk_partition.py/GetTSKVsPartByPathSpec
3,748
def form_valid(self, request, form): new_user = self.register(request, **form.cleaned_data) success_url = self.get_success_url(request, new_user) # success_url may be a simple string, or a tuple providing the # full argument set for redirect(). Attempting to unpack it # tells us which one it is. try: to, args, kwargs = success_url return redirect(to, *args, **kwargs) except __HOLE__: return redirect(success_url)
ValueError
dataset/ETHPy150Open codesters/codesters/registration/views.py/RegistrationView.form_valid
3,749
def get(self, request, *args, **kwargs): activated_user = self.activate(request, *args, **kwargs) if activated_user: signals.user_activated.send(sender=self.__class__, user=activated_user, request=request) success_url = self.get_success_url(request, activated_user) try: to, args, kwargs = success_url return redirect(to, *args, **kwargs) except __HOLE__: return redirect(success_url) return super(ActivationView, self).get(request, *args, **kwargs)
ValueError
dataset/ETHPy150Open codesters/codesters/registration/views.py/ActivationView.get
3,750
@classmethod def init_conn(cls): try: vertica_python except __HOLE__: raise DbError('Vertica module not found/loaded. Please make sure all dependencies are installed\n') cls.conn = cls.conn() cls.cursor = cls.conn.cursor() cls.conn_initialized = True return cls
NameError
dataset/ETHPy150Open appnexus/schema-tool/schematool/db/_vertica.py/VerticaDb.init_conn
3,751
@classmethod def conn(cls): """ return the vertica connection handle to the configured server """ config = cls.config try: conn_driver_dict = {} conf_to_driver_map = {'host':'host', 'username':'user', 'password':'password', 'revision_db_name':'database', 'port':'port'} for conf_key, conf_value in config.iteritems(): try: driver_key = conf_to_driver_map[conf_key] driver_value = conf_value # NOTE: Vertica Python driver requires non-unicode strings if isinstance(driver_value, unicode): driver_value = str(driver_value) conn_driver_dict[driver_key] = driver_value except __HOLE__: pass conn = vertica_python.connect(conn_driver_dict) except Exception, e: raise DbError("Cannot connect to Vertica Db: %s\n" "Ensure that the server is running and you can connect normally" % e.message) return conn
KeyError
dataset/ETHPy150Open appnexus/schema-tool/schematool/db/_vertica.py/VerticaDb.conn
3,752
@classmethod def as_text(cls, slug, username, key): filepath = join(cls.datapath, slug, username, '%s.txt' % key) headers = [('Content-Type', 'text/plain'), ('Content-Disposition', 'attachment; filename=%s' % key) ] try: text = forward(FileApp(filepath, headers)) except __HOLE__: abort(404, 'Game does not exist: %s' % slug) else: return text
OSError
dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/controllers/localv1/userdata.py/UserdataController.as_text
3,753
def on_consume_ready(self, connection, channel, consumers, **kwargs): """ Kombu callback when consumers are ready to accept messages. Called after any (re)connection to the broker. """ if not self._consumers_ready.ready(): _log.debug('consumer started %s', self) self._consumers_ready.send(None) for provider in self._providers: try: callback = provider.on_consume_ready except __HOLE__: pass else: callback()
AttributeError
dataset/ETHPy150Open onefinestay/nameko/nameko/messaging.py/QueueConsumer.on_consume_ready
3,754
def extract_token_from_cookie(request): """Given a Request object, return a csrf_token. """ try: token = request.headers.cookie['csrf_token'].value except __HOLE__: token = None else: token = _sanitize_token(token) # Don't set a CSRF cookie on assets, to avoid busting the cache. # Don't set it on callbacks, because we don't need it there. if request.path.raw.startswith('/assets/') or request.path.raw.startswith('/callbacks/'): token = None else: token = token or _get_new_token() return {'csrf_token': token}
KeyError
dataset/ETHPy150Open gratipay/gratipay.com/gratipay/security/csrf.py/extract_token_from_cookie
3,755
def __getattribute__(self, attr): get = lambda name: object.__getattribute__(self, name) try: results = get('_results') except AttributeError: pass try: return get(attr) except __HOLE__: pass obj = getattr(results, attr) data = results.model.data how = self._wrap_attrs.get(attr) if how and isinstance(how, tuple): obj = data.wrap_output(obj, how[0], *how[1:]) elif how: obj = data.wrap_output(obj, how=how) return obj
AttributeError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/base/wrapper.py/ResultsWrapper.__getattribute__
3,756
def _Encode(self, value): """Encode the value for the attribute.""" try: return value.SerializeToString().encode("hex") except __HOLE__: if isinstance(value, (int, long)): return str(value).encode("hex") else: # Types "string" and "bytes" are stored as strings here. return utils.SmartStr(value).encode("hex")
AttributeError
dataset/ETHPy150Open google/grr/grr/lib/data_stores/mysql_advanced_data_store.py/MySQLAdvancedDataStore._Encode
3,757
def remote_createContainer(self, uid, data): """ Create a new Container. @param uid: Unique ID which the environment process inside the container needs to login to the Master process. @type uid: str @param data: Extra data which is used to configure the container. @type data: dict @return: New Container instance. @rtype: rce.container.RCEContainer """ try: nr = self._nrs.pop() except __HOLE__: raise MaxNumberExceeded('Can not manage any additional container.') container = RCEContainer(self, nr, uid, data) return container.start().addCallback(lambda _: container)
KeyError
dataset/ETHPy150Open rapyuta/rce/rce-core/rce/container.py/ContainerClient.remote_createContainer
3,758
def __get_live_version(self): """ Get a live version string using versiontools """ try: import versiontools except __HOLE__: return None else: return str(versiontools.Version.from_expression(self.name))
ImportError
dataset/ETHPy150Open coderanger/pychef/versiontools_support.py/VersiontoolsEnchancedDistributionMetadata.__get_live_version
3,759
def __get_frozen_version(self): """ Get a fixed version string using an existing PKG-INFO file """ try: return self.__base("PKG-INFO").version except __HOLE__: return None
IOError
dataset/ETHPy150Open coderanger/pychef/versiontools_support.py/VersiontoolsEnchancedDistributionMetadata.__get_frozen_version
3,760
def non_string_iterable(obj): try: iter(obj) except __HOLE__: return False else: return not isinstance(obj, basestring)
TypeError
dataset/ETHPy150Open beville/ComicStreamer/comicstreamerlib/gui_win.py/non_string_iterable
3,761
@classmethod def setupClass(cls): global numpy global assert_equal global assert_almost_equal try: import numpy import scipy from numpy.testing import assert_equal,assert_almost_equal except __HOLE__: raise SkipTest('SciPy not available.')
ImportError
dataset/ETHPy150Open networkx/networkx/networkx/linalg/tests/test_spectrum.py/TestSpectrum.setupClass
3,762
def open_for_reading(self): if self.verified is True: file_handle = None try: file_handle = open(self.file_path, 'rb') self.readers += 1 return file_handle except __HOLE__: self.close_read_handle(file_handle) return None
IOError
dataset/ETHPy150Open lbryio/lbry/lbrynet/core/HashBlob.py/BlobFile.open_for_reading
3,763
def nwfilterLookupByName(self, name): try: return self._nwfilters[name] except __HOLE__: raise make_libvirtError( libvirtError, "no nwfilter with matching name %s" % name, error_code=VIR_ERR_NO_NWFILTER, error_domain=VIR_FROM_NWFILTER)
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/tests/unit/virt/libvirt/fakelibvirt.py/Connection.nwfilterLookupByName
3,764
def nodeDeviceLookupByName(self, name): try: return self._nodedevs[name] except __HOLE__: raise make_libvirtError( libvirtError, "no nodedev with matching name %s" % name, error_code=VIR_ERR_NO_NODE_DEVICE, error_domain=VIR_FROM_NODEDEV)
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/tests/unit/virt/libvirt/fakelibvirt.py/Connection.nodeDeviceLookupByName
3,765
@contextmanager def make_target_directory(self, path): here = os.path.abspath(os.getcwd()) path = os.path.abspath(path) if here != path: try: os.makedirs(path) except OSError as e: self.abort('Could not create target folder: %s' % e) if os.path.isdir(path): try: if len(os.listdir(path)) != 0: raise OSError('Directory not empty') except __HOLE__ as e: self.abort('Bad target folder: %s' % e) scratch = os.path.join(tempfile.gettempdir(), uuid.uuid4().hex) os.makedirs(scratch) try: yield scratch except: shutil.rmtree(scratch) raise else: # Use shutil.move here in case we move across a file system # boundary. for filename in os.listdir(scratch): if isinstance(path, text_type): filename = filename.decode(fs_enc) shutil.move(os.path.join(scratch, filename), os.path.join(path, filename)) os.rmdir(scratch)
OSError
dataset/ETHPy150Open lektor/lektor/lektor/quickstart.py/Generator.make_target_directory
3,766
def run(self, ctx, path): with self.make_target_directory(path) as scratch: for template in self.jinja_env.list_templates(): if not template.endswith('.in'): continue fn = self.expand_filename(scratch, ctx, template) tmpl = self.jinja_env.get_template(template) rv = tmpl.render(ctx).strip('\r\n') if rv: directory = os.path.dirname(fn) try: os.makedirs(directory) except __HOLE__: pass with open(fn, 'w') as f: f.write(rv.encode('utf-8') + '\n')
OSError
dataset/ETHPy150Open lektor/lektor/lektor/quickstart.py/Generator.run
3,767
def project_quickstart(defaults=None): if not defaults: defaults = {} g = Generator('project') g.title('Lektor Quickstart') g.text( 'This wizard will generate a new basic project with some sensible ' 'defaults for getting started quickly. We just need to go through ' 'a few questions so that the project is set up correctly for you.' ) name = defaults.get('name') if name is None: name = g.prompt('Project Name', None, 'A project needs a name. The name is primarily used for the admin ' 'UI and some other places to refer to your project to not get ' 'confused if multiple projects exist. You can change this at ' 'any later point.') author_name = g.prompt('Author Name', get_default_author(), 'Your name. This is used in a few places in the default template ' 'to refer to in the default copyright messages.') path = defaults.get('path') if path is None: here = os.path.abspath(os.getcwd()) default_project_path = None try: if len(os.listdir(here)) == []: default_project_path = here except __HOLE__: pass if default_project_path is None: default_project_path = os.path.join(os.getcwd(), name) path = g.prompt('Project Path', default_project_path, 'This is the path where the project will be located. You can ' 'move a project around later if you do not like the path. If ' 'you provide a relative path it will be relative to the working ' 'directory.') path = os.path.expanduser(path) with_blog = g.prompt('Add Basic Blog', True, 'Do you want to generate a basic blog module? If you enable this ' 'the models for a very basic blog will be generated.') g.confirm('That\'s all. Create project?') g.run({ 'project_name': name, 'project_slug': slugify(name), 'project_path': path, 'with_blog': with_blog, 'this_year': datetime.utcnow().year, 'today': datetime.utcnow().strftime('%Y-%m-%d'), 'author_name': author_name, }, path)
OSError
dataset/ETHPy150Open lektor/lektor/lektor/quickstart.py/project_quickstart
3,768
def _fixed_getinnerframes(etb, context=1,tb_offset=0): import linecache LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) # If the error is at the console, don't build any context, since it would # otherwise produce 5 blank lines printed out (there is no file at the # console) rec_check = records[tb_offset:] try: rname = rec_check[0][1] if rname == '<ipython console>' or rname.endswith('<string>'): return rec_check except __HOLE__: pass aux = traceback.extract_tb(etb) assert len(records) == len(aux) for i, (file, lnum, _, _) in zip(list(range(len(records))), aux): maybeStart = lnum-1 - context//2 start = max(maybeStart, 0) end = start + context lines = linecache.getlines(file)[start:end] buf = list(records[i]) buf[LNUM_POS] = lnum buf[INDEX_POS] = lnum - 1 - start buf[LINES_POS] = lines records[i] = tuple(buf) return records[tb_offset:] # Helper function -- largely belongs to VerboseTB, but we need the same # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they # can be recognized properly by ipython.el's py-traceback-line-re # (SyntaxErrors have to be treated specially because they have no traceback)
IndexError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/core/ultratb.py/_fixed_getinnerframes
3,769
def _format_exception_only(self, etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.exc_info()[:2]. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list. Also lifted nearly verbatim from traceback.py """ have_filedata = False Colors = self.Colors list = [] try: stype = Colors.excName + etype.__name__ + Colors.Normal except __HOLE__: stype = etype # String exceptions don't get special coloring if value is None: list.append( str(stype) + '\n') else: if etype is SyntaxError: if not value.text: # Don't know if this could actually still occur. have_filedata = False else: have_filedata = True #print 'filename is',value.filename # dbg filename = value.filename if not filename: filename = "<string>" list.append('%s File %s"%s"%s, line %s%d%s\n' % \ (Colors.normalEm, Colors.filenameEm, filename, Colors.normalEm, Colors.linenoEm, value.lineno, Colors.Normal )) if value.text is not None: i = 0 while i < len(value.text) and value.text[i].isspace(): i = i+1 list.append('%s %s%s\n' % (Colors.line, value.text.strip(), Colors.Normal)) if value.offset is not None: s = ' ' for c in value.text[i:value.offset-1]: if c.isspace(): s = s + c else: s = s + ' ' list.append('%s%s^%s\n' % (Colors.caret, s, Colors.Normal) ) try: s = self._some_str(value.msg) except AttributeError: s = self._some_str(value) if s: list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, Colors.Normal, s)) else: list.append('%s\n' % str(stype)) # sync with user hooks if have_filedata: ipinst = ipapi.get() if ipinst is not None: ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) return list
AttributeError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/core/ultratb.py/ListTB._format_exception_only
3,770
def structured_traceback(self, etype, evalue, etb, tb_offset=None, context=5): """Return a nice text document describing the traceback.""" tb_offset = self.tb_offset if tb_offset is None else tb_offset # some locals try: etype = etype.__name__ except AttributeError: pass Colors = self.Colors # just a shorthand + quicker name lookup ColorsNormal = Colors.Normal # used a lot col_scheme = self.color_scheme_table.active_scheme_name indent = ' '*INDENT_SIZE em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) undefined = '%sundefined%s' % (Colors.em, ColorsNormal) exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) # some internal-use functions def text_repr(value): """Hopefully pretty robust repr equivalent.""" # this is pretty horrible but should always return *something* try: return pydoc.text.repr(value) except KeyboardInterrupt: raise except: try: return repr(value) except KeyboardInterrupt: raise except: try: # all still in an except block so we catch # getattr raising name = getattr(value, '__name__', None) if name: # ick, recursion return text_repr(name) klass = getattr(value, '__class__', None) if klass: return '%s instance' % text_repr(klass) except KeyboardInterrupt: raise except: return 'UNRECOVERABLE REPR FAILURE' def eqrepr(value, repr=text_repr): return '=%s' % repr(value) def nullrepr(value, repr=text_repr): return '' # meat of the code begins try: etype = etype.__name__ except __HOLE__: pass if self.long_header: # Header with the exception type, python version, and date pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable date = time.ctime(time.time()) head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, exc, ' '*(75-len(str(etype))-len(pyver)), pyver, date.rjust(75) ) head += "\nA problem occured executing Python code. Here is the sequence of function"\ "\ncalls leading up to the error, with the most recent (innermost) call last." else: # Simplified header head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, 'Traceback (most recent call last)'.\ rjust(75 - len(str(etype)) ) ) frames = [] # Flush cache before calling inspect. This helps alleviate some of the # problems with python 2.3's inspect.py. ##self.check_cache() # Drop topmost frames if requested try: # Try the default getinnerframes and Alex's: Alex's fixes some # problems, but it generates empty tracebacks for console errors # (5 blanks lines) where none should be returned. #records = inspect.getinnerframes(etb, context)[tb_offset:] #print 'python records:', records # dbg records = _fixed_getinnerframes(etb, context, tb_offset) #print 'alex records:', records # dbg except: # FIXME: I've been getting many crash reports from python 2.3 # users, traceable to inspect.py. If I can find a small test-case # to reproduce this, I should either write a better workaround or # file a bug report against inspect (if that's the real problem). # So far, I haven't been able to find an isolated example to # reproduce the problem. inspect_error() traceback.print_exc(file=self.ostream) info('\nUnfortunately, your original traceback can not be constructed.\n') return '' # build some color string templates outside these nested loops tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ (Colors.vName, Colors.valEm, ColorsNormal) tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, Colors.vName, ColorsNormal) tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, ColorsNormal) # now, loop over all records printing context and info abspath = os.path.abspath for frame, file, lnum, func, lines, index in records: #print '*** record:',file,lnum,func,lines,index # dbg try: file = file and abspath(file) or '?' except OSError: # if file is '<console>' or something not in the filesystem, # the abspath call will throw an OSError. Just ignore it and # keep the original file string. pass link = tpl_link % file try: args, varargs, varkw, locals = inspect.getargvalues(frame) except: # This can happen due to a bug in python2.3. We should be # able to remove this try/except when 2.4 becomes a # requirement. Bug details at http://python.org/sf/1005466 inspect_error() traceback.print_exc(file=self.ostream) info("\nIPython's exception reporting continues...\n") if func == '?': call = '' else: # Decide whether to include variable details or not var_repr = self.include_vars and eqrepr or nullrepr try: call = tpl_call % (func,inspect.formatargvalues(args, varargs, varkw, locals,formatvalue=var_repr)) except KeyError: # This happens in situations like errors inside generator # expressions, where local variables are listed in the # line, but can't be extracted from the frame. I'm not # 100% sure this isn't actually a bug in inspect itself, # but since there's no info for us to compute with, the # best we can do is report the failure and move on. Here # we must *not* call any traceback construction again, # because that would mess up use of %debug later on. So we # simply report the failure and move on. The only # limitation will be that this frame won't have locals # listed in the call signature. Quite subtle problem... # I can't think of a good way to validate this in a unit # test, but running a script consisting of: # dict( (k,v.strip()) for (k,v) in range(10) ) # will illustrate the error, if this exception catch is # disabled. call = tpl_call_fail % func # Initialize a list of names on the current line, which the # tokenizer below will populate. names = [] def tokeneater(token_type, token, start, end, line): """Stateful tokeneater which builds dotted names. The list of names it appends to (from the enclosing scope) can contain repeated composite names. This is unavoidable, since there is no way to disambguate partial dotted structures until the full list is known. The caller is responsible for pruning the final list of duplicates before using it.""" # build composite names if token == '.': try: names[-1] += '.' # store state so the next token is added for x.y.z names tokeneater.name_cont = True return except IndexError: pass if token_type == tokenize.NAME and token not in keyword.kwlist: if tokeneater.name_cont: # Dotted names names[-1] += token tokeneater.name_cont = False else: # Regular new names. We append everything, the caller # will be responsible for pruning the list later. It's # very tricky to try to prune as we go, b/c composite # names can fool us. The pruning at the end is easy # to do (or the caller can print a list with repeated # names if so desired. names.append(token) elif token_type == tokenize.NEWLINE: raise IndexError # we need to store a bit of state in the tokenizer to build # dotted names tokeneater.name_cont = False def linereader(file=file, lnum=[lnum], getline=linecache.getline): line = getline(file, lnum[0]) lnum[0] += 1 return line # Build the list of names on this line of code where the exception # occurred. try: # This builds the names list in-place by capturing it from the # enclosing scope. # We're using _tokenize because tokenize expects bytes, and # attempts to find an encoding cookie, which can go wrong # e.g. if the traceback line includes "encoding=encoding". # N.B. _tokenize is undocumented. An official API for # tokenising strings is proposed in Python Issue 9969. for atoken in tokenize._tokenize(linereader, None): tokeneater(*atoken) except IndexError: # signals exit of tokenizer pass except UnicodeDecodeError: pass except tokenize.TokenError as msg: _m = ("An unexpected error occurred while tokenizing input\n" "The following traceback may be corrupted or invalid\n" "The error message is: %s\n" % msg) error(_m) # prune names list of duplicates, but keep the right order unique_names = uniq_stable(names) # Start loop over vars lvals = [] if self.include_vars: for name_full in unique_names: name_base = name_full.split('.',1)[0] if name_base in frame.f_code.co_varnames: if name_base in locals: try: value = repr(eval(name_full,locals)) except: value = undefined else: value = undefined name = tpl_local_var % name_full else: if name_base in frame.f_globals: try: value = repr(eval(name_full,frame.f_globals)) except: value = undefined else: value = undefined name = tpl_global_var % name_full lvals.append(tpl_name_val % (name,value)) if lvals: lvals = '%s%s' % (indent,em_normal.join(lvals)) else: lvals = '' level = '%s %s\n' % (link,call) if index is None: frames.append(level) else: frames.append('%s%s' % (level,''.join( _format_traceback_lines(lnum,index,lines,Colors,lvals, col_scheme)))) # Get (safely) a string form of the exception info try: etype_str,evalue_str = list(map(str,(etype,evalue))) except: # User exception is improperly defined. etype,evalue = str,sys.exc_info()[:2] etype_str,evalue_str = list(map(str,(etype,evalue))) # ... and format it exception = ['%s%s%s: %s' % (Colors.excName, etype_str, ColorsNormal, evalue_str)] # vds: >> if records: filepath, lnum = records[-1][1:3] #print "file:", str(file), "linenb", str(lnum) # dbg filepath = os.path.abspath(filepath) ipinst = ipapi.get() if ipinst is not None: ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) # vds: << # return all our info assembled as a single string # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) return [head] + frames + [''.join(exception[0])]
AttributeError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/core/ultratb.py/VerboseTB.structured_traceback
3,771
def __call__(self, etype=None, evalue=None, etb=None): """This hook can replace sys.excepthook (for Python 2.1 or higher).""" if etb is None: self.handler() else: self.handler((etype, evalue, etb)) try: self.debugger() except __HOLE__: print("\nKeyboardInterrupt") #----------------------------------------------------------------------------
KeyboardInterrupt
dataset/ETHPy150Open ipython/ipython-py3k/IPython/core/ultratb.py/VerboseTB.__call__
3,772
def __call__(self,etype=None,evalue=None,etb=None, out=None,tb_offset=None): """Print out a formatted exception traceback. Optional arguments: - out: an open file-like object to direct output to. - tb_offset: the number of frames to skip over in the stack, on a per-call basis (this overrides temporarily the instance's tb_offset given at initialization time. """ if out is None: out = self.ostream out.flush() out.write(self.text(etype, evalue, etb, tb_offset)) out.write('\n') out.flush() # FIXME: we should remove the auto pdb behavior from here and leave # that to the clients. try: self.debugger() except __HOLE__: print("\nKeyboardInterrupt")
KeyboardInterrupt
dataset/ETHPy150Open ipython/ipython-py3k/IPython/core/ultratb.py/AutoFormattedTB.__call__
3,773
@vm_util.Retry(max_retries=10) def AddPubKeyToHost(host_ip, password, keyfile, username): public_key = str() if keyfile: keyfile = os.path.expanduser(keyfile) if not paramiko: raise Exception('`paramiko` is required for pushing keyfile to ecs.') with open(keyfile, 'r') as f: public_key = f.read() ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect( host_ip, username=ROOT, # We should use root to add pubkey to host password=password, ) if username == ROOT: command_list = [ 'mkdir .ssh; echo "%s" >> ~/.ssh/authorized_keys' % public_key ] else: command_list = [ 'echo "{0} ALL = NOPASSWD: ALL" >> /etc/sudoers'.format(username), 'useradd {0} --home /home/{0} --shell /bin/bash -m'.format(username), 'mkdir /home/{0}/.ssh'.format(username), 'echo "{0}" >> /home/{1}/.ssh/authorized_keys' .format(public_key, username), 'chown -R {0}:{0} /home/{0}/.ssh'.format(username)] command = ';'.join(command_list) ssh.exec_command(command) ssh.close() return True except __HOLE__: raise IOError
IOError
dataset/ETHPy150Open GoogleCloudPlatform/PerfKitBenchmarker/perfkitbenchmarker/providers/alicloud/util.py/AddPubKeyToHost
3,774
def convert_to_datetime_object(timestr): try: date_object = parse_datetime(timestr) except __HOLE__ as e: raise ParamError("There was an error while parsing the date from %s -- Error: %s" % (timestr, e.message)) return date_object
ValueError
dataset/ETHPy150Open adlnet/ADL_LRS/lrs/utils/__init__.py/convert_to_datetime_object
3,775
def get_lang(langdict, lang): if lang: if lang == 'all': return langdict else: # Return where key = lang try: return {lang:langdict[lang]} except __HOLE__: pass first = langdict.iteritems().next() return {first[0]:first[1]}
KeyError
dataset/ETHPy150Open adlnet/ADL_LRS/lrs/utils/__init__.py/get_lang
3,776
def geocode(api_key, address, timeout=2): ''' returns (longtitude, latitude,) tuple for given address ''' try: xml = _get_geocode_xml(api_key, address, timeout) return _get_coords(xml) except __HOLE__: return None, None
IOError
dataset/ETHPy150Open kmike/yandex-maps/yandex_maps/api.py/geocode
3,777
def _get_coords(response): try: dom = xml.dom.minidom.parseString(response) pos_elem = dom.getElementsByTagName('pos')[0] pos_data = pos_elem.childNodes[0].data return tuple(pos_data.split()) except __HOLE__: return None, None
IndexError
dataset/ETHPy150Open kmike/yandex-maps/yandex_maps/api.py/_get_coords
3,778
def check_image_file_format(self, f): # Check file extension extension = os.path.splitext(f.name)[1].lower()[1:] if extension not in ALLOWED_EXTENSIONS: raise ValidationError(self.error_messages['invalid_image'], code='invalid_image') if hasattr(f, 'image'): # Django 1.8 annotates the file object with the PIL image image = f.image elif not f.closed: # Open image file file_position = f.tell() f.seek(0) try: image = Image.open(f) except __HOLE__: # Uploaded file is not even an image file (or corrupted) raise ValidationError(self.error_messages['invalid_image_known_format'], code='invalid_image_known_format') f.seek(file_position) else: # Couldn't get the PIL image, skip checking the internal file format return image_format = extension.upper() if image_format == 'JPG': image_format = 'JPEG' internal_image_format = image.format.upper() if internal_image_format == 'MPO': internal_image_format = 'JPEG' # Check that the internal format matches the extension # It is possible to upload PSD files if their extension is set to jpg, png or gif. This should catch them out if internal_image_format != image_format: raise ValidationError(self.error_messages['invalid_image_known_format'] % ( image_format, ), code='invalid_image_known_format')
IOError
dataset/ETHPy150Open torchbox/wagtail/wagtail/wagtailimages/fields.py/WagtailImageField.check_image_file_format
3,779
def dropIndex(self, table, name, check = True): if check: assert(table in self.tables) if name not in self.tables[table]: return False self._dropIndexSql(table, name) try: self.tables[table].remove(name) except __HOLE__, e: pass return True # since not all databases handle renaming and dropping columns the # same way, we provide a more generic interface in here
ValueError
dataset/ETHPy150Open sassoftware/conary/conary/dbstore/base_drv.py/BaseDatabase.dropIndex
3,780
def _guess_type(value): if value == '': return TYPE_STRING try: val = int(value) return TYPE_INTEGER except ValueError: pass try: val = float(value) return TYPE_FLOAT except __HOLE__: pass if str(value).lower() in ('true', 'false'): return TYPE_BOOLEAN try: val = parser.parse(value) return TYPE_DATETIME except ValueError: pass return TYPE_STRING
ValueError
dataset/ETHPy150Open getredash/redash/redash/query_runner/google_spreadsheets.py/_guess_type
3,781
def _value_eval_list(value): value_list = [] for member in value: if member == '' or member == None: val = None value_list.append(val) continue try: val = int(member) value_list.append(val) continue except ValueError: pass try: val = float(member) value_list.append(val) continue except __HOLE__: pass if str(member).lower() in ('true', 'false'): val = bool(member) value_list.append(val) continue try: val = parser.parse(member) value_list.append(val) continue except ValueError: pass value_list.append(member) return value_list
ValueError
dataset/ETHPy150Open getredash/redash/redash/query_runner/google_spreadsheets.py/_value_eval_list
3,782
@staticmethod def get_pack(ref): try: return ref.split(PACK_SEPARATOR, 1)[0] except (__HOLE__, AttributeError): raise InvalidResourceReferenceError(ref=ref)
IndexError
dataset/ETHPy150Open StackStorm/st2/st2common/st2common/models/system/common.py/ResourceReference.get_pack
3,783
@staticmethod def get_name(ref): try: return ref.split(PACK_SEPARATOR, 1)[1] except (__HOLE__, AttributeError): raise InvalidResourceReferenceError(ref=ref)
IndexError
dataset/ETHPy150Open StackStorm/st2/st2common/st2common/models/system/common.py/ResourceReference.get_name
3,784
def clean(self, value): super(KWCivilIDNumberField, self).clean(value) if value in EMPTY_VALUES: return '' if not re.match(r'^\d{12}$', value): raise ValidationError(self.error_messages['invalid']) match = re.match(id_re, value) if not match: raise ValidationError(self.error_messages['invalid']) gd = match.groupdict() try: d = date(int(gd['yy']), int(gd['mm']), int(gd['dd'])) except __HOLE__: raise ValidationError(self.error_messages['invalid']) if not self.has_valid_checksum(value): raise ValidationError(self.error_messages['invalid']) return value
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/localflavor/kw/forms.py/KWCivilIDNumberField.clean
3,785
def get_output_file(output): if output == sys.stdout: return output else: try: return open(output, "w") except __HOLE__ as error: logging.warning(error) exit(1)
IOError
dataset/ETHPy150Open IceCTF/ctf-platform/api/api_manager.py/get_output_file
3,786
def load_problems(args): problem_dir = args.problems_directory[0] grader_dir = args.graders_directory[0] static_dir = args.static_directory[0] if not path.exists(static_dir): logging.debug("No directory {}. Creating...".format(static_dir)) makedirs(static_dir) if not path.exists(problem_dir): logging.critical("No such directory: {}".format(problem_dir)) return for (dirpath, dirnames, filenames) in walk(problem_dir): if "problem.json" in filenames: json_file = path.join(dirpath, 'problem.json') contents = open(json_file, "r").read() try: data = json_util.loads(contents) except __HOLE__ as e: logging.warning("Invalid JSON format in file {filename} ({exception})".format(filename=json_file, exception=e)) continue if not isinstance(data, dict): logging.warning("Invalid JSON format in file {}".format(json_file)) continue if 'name' not in data: logging.warning("Invalid problem format in file {}".format(json_file)) continue problem_name = data['name'] relative_path = path.relpath(dirpath, problem_dir) logging.info("Found problem '{}'".format(problem_name)) if 'grader' not in dirnames: logging.warning("Problem '{}' appears to have no grader folder. Skipping...".format(problem_name)) continue grader_path = path.join(grader_dir, relative_path) if path.exists(grader_path): shutil.rmtree(grader_path) shutil.copytree(path.join(dirpath, 'grader'), grader_path) logging.info("Graders updated for problem {}".format(problem_name)) try: if api.common.safe_fail(api.problem.get_problem, pid=api.common.hash(problem_name)): api.problem.update_problem(api.common.hash(problem_name), data) else: api.problem.insert_problem(data) except api.common.WebException as e: logging.info("Problem '{}' was not added to the database. Reason: {}".format(problem_name, e)) if 'static' in dirnames: logging.info("Found a static directory for '{}'. Copying...".format(problem_name)) static_path = path.join(static_dir, relative_path) if path.exists(static_path): shutil.rmtree(static_path) shutil.copytree(path.join(dirpath, 'static'), static_path) errors = api.problem.analyze_problems() for error in errors: logging.warning(error)
ValueError
dataset/ETHPy150Open IceCTF/ctf-platform/api/api_manager.py/load_problems
3,787
def test_bogus_units(self): try: uf = Float(0., iotype='in', units='bogus') except __HOLE__, err: self.assertEqual(str(err), "Units of 'bogus' are invalid") else: self.fail('ValueError expected')
ValueError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/datatypes/test/test_float.py/FloatTestCase.test_bogus_units
3,788
def test_range_violations(self): try: self.hobj.float1 = 124 except __HOLE__, err: self.assertEqual(str(err), ": Variable 'float1' must be a float in the range [0.0, 99.0], but a value of 124 <type 'int'> was specified.") else: self.fail('ValueError expected') try: self.hobj.float1 = -3 except ValueError, err: self.assertEqual(str(err), ": Variable 'float1' must be a float in the range [0.0, 99.0], but a value of -3 <type 'int'> was specified.") else: self.fail('ValueError exception')
ValueError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/datatypes/test/test_float.py/FloatTestCase.test_range_violations
3,789
def test_exclusions(self): self.hobj.add('float4', Float(low=3.0, high=4.0, \ exclude_low=True, exclude_high=True, \ iotype='in', units='kg')) try: self.hobj.float4 = 3.0 except __HOLE__, err: self.assertEqual(str(err), ": Variable 'float4' must be a float in the range (3.0, 4.0), but a value of 3.0 <type 'float'> was specified.") else: self.fail('ValueError expected')
ValueError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/datatypes/test/test_float.py/FloatTestCase.test_exclusions
3,790
def test_default_value_type(self): try: self.hobj.add('bad_default', Float('Bad Wolf')) except __HOLE__, err: self.assertEqual(str(err), "Default value should be a float.") else: self.fail('ValueError expected')
ValueError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/datatypes/test/test_float.py/FloatTestCase.test_default_value_type
3,791
def test_default_value(self): try: self.hobj.add('out_of_bounds', Float(5.0, low=3, high=4)) except __HOLE__, err: self.assertEqual(str(err), "Default value is outside of bounds [3.0, 4.0].") else: self.fail('ValueError expected')
ValueError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/datatypes/test/test_float.py/FloatTestCase.test_default_value
3,792
def __init__(self, **kwargs): self.kwargs = kwargs try: self.message = self.msg_fmt % kwargs except __HOLE__: exc_info = sys.exc_info() # kwargs doesn't match a variable in the message # log the issue and the kwargs LOG.exception(_LE('Exception in string format operation')) for name, value in six.iteritems(kwargs): LOG.error(_LE("%(name)s: %(value)s"), {'name': name, 'value': value}) # noqa if _FATAL_EXCEPTION_FORMAT_ERRORS: raise_(exc_info[0], exc_info[1], exc_info[2])
KeyError
dataset/ETHPy150Open openstack/tripleo-common/tripleo_common/core/exception.py/TripleoCommonException.__init__
3,793
def test_pure_python_math_module(self): vals = [1, -.5, 1.5, 0, 0.0, -2, -2.2, .2] # not being tested: math.asinh, math.atanh, math.lgamma, math.erfc, math.acos def f(): functions = [ math.sqrt, math.cos, math.sin, math.tan, math.asin, math.atan, math.acosh, math.cosh, math.sinh, math.tanh, math.ceil, math.erf, math.exp, math.expm1, math.factorial, math.floor, math.log, math.log10, math.log1p ] tr = [] for idx1 in range(len(vals)): v1 = vals[idx1] for funIdx in range(len(functions)): function = functions[funIdx] try: tr = tr + [function(v1)] except __HOLE__ as ex: pass return tr r1 = self.evaluateWithExecutor(f) r2 = f() self.assertGreater(len(r1), 100) self.assertTrue(numpy.allclose(r1, r2, 1e-6))
ValueError
dataset/ETHPy150Open ufora/ufora/ufora/FORA/python/PurePython/MathTestCases.py/MathTestCases.test_pure_python_math_module
3,794
def wait(self): try: self.event.wait() except __HOLE__: msg = _("Daemon Shutdown on KeyboardInterrupt") logger.info(msg)
KeyboardInterrupt
dataset/ETHPy150Open rcbops/glance-buildpackage/glance/store/scrubber.py/Daemon.wait
3,795
def get_strategy(self): try: return utils.get_object_backup_strategy(self.backup_source) except __HOLE__: six.reraise(exceptions.BackupStrategyNotFoundError, exceptions.BackupStrategyNotFoundError())
KeyError
dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/backup/models.py/Backup.get_strategy
3,796
def stringReceived(self, frame): tr = TTransport.TMemoryBuffer(frame) iprot = self._iprot_factory.getProtocol(tr) (fname, mtype, rseqid) = iprot.readMessageBegin() try: method = self.recv_map[fname] except __HOLE__: method = getattr(self.client, 'recv_' + fname) self.recv_map[fname] = method method(iprot, mtype, rseqid)
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/thrift-0.9.1/src/transport/TTwisted.py/ThriftClientProtocol.stringReceived
3,797
def __init__(self): super(RewritePlugin, self).__init__() self.config.add({}) # Gather all the rewrite rules for each field. rules = defaultdict(list) for key, view in self.config.items(): value = view.get(unicode) try: fieldname, pattern = key.split(None, 1) except __HOLE__: raise ui.UserError(u"invalid rewrite specification") if fieldname not in library.Item._fields: raise ui.UserError(u"invalid field name (%s) in rewriter" % fieldname) self._log.debug(u'adding template field {0}', key) pattern = re.compile(pattern.lower()) rules[fieldname].append((pattern, value)) if fieldname == 'artist': # Special case for the artist field: apply the same # rewrite for "albumartist" as well. rules['albumartist'].append((pattern, value)) # Replace each template field with the new rewriter function. for fieldname, fieldrules in rules.iteritems(): getter = rewriter(fieldname, fieldrules) self.template_fields[fieldname] = getter if fieldname in library.Album._fields: self.album_template_fields[fieldname] = getter
ValueError
dataset/ETHPy150Open beetbox/beets/beetsplug/rewrite.py/RewritePlugin.__init__
3,798
def for_model(self, model): try: return self._models[model] except __HOLE__: return
KeyError
dataset/ETHPy150Open thoas/django-sequere/sequere/registry.py/SequereRegistry.for_model
3,799
def run_code(code, code_path, ns=None, function_name=None): """ Import a Python module from a path, and run the function given by name, if function_name is not None. """ # Change the working directory to the directory of the example, so # it can get at its data files, if any. Add its path to sys.path # so it can import any helper modules sitting beside it. if six.PY2: pwd = os.getcwdu() else: pwd = os.getcwd() old_sys_path = list(sys.path) if setup.config.plot_working_directory is not None: try: os.chdir(setup.config.plot_working_directory) except __HOLE__ as err: raise OSError(str(err) + '\n`plot_working_directory` option in' 'Sphinx configuration file must be a valid ' 'directory path') except TypeError as err: raise TypeError(str(err) + '\n`plot_working_directory` option in ' 'Sphinx configuration file must be a string or ' 'None') sys.path.insert(0, setup.config.plot_working_directory) elif code_path is not None: dirname = os.path.abspath(os.path.dirname(code_path)) os.chdir(dirname) sys.path.insert(0, dirname) # Reset sys.argv old_sys_argv = sys.argv sys.argv = [code_path] # Redirect stdout stdout = sys.stdout if six.PY3: sys.stdout = io.StringIO() else: sys.stdout = cStringIO.StringIO() # Assign a do-nothing print function to the namespace. There # doesn't seem to be any other way to provide a way to (not) print # that works correctly across Python 2 and 3. def _dummy_print(*arg, **kwarg): pass try: try: code = unescape_doctest(code) if ns is None: ns = {} if not ns: if setup.config.plot_pre_code is None: six.exec_(six.text_type("import numpy as np\n" + "from matplotlib import pyplot as plt\n"), ns) else: six.exec_(six.text_type(setup.config.plot_pre_code), ns) ns['print'] = _dummy_print if "__main__" in code: six.exec_("__name__ = '__main__'", ns) code = remove_coding(code) six.exec_(code, ns) if function_name is not None: six.exec_(function_name + "()", ns) except (Exception, SystemExit) as err: raise PlotError(traceback.format_exc()) finally: os.chdir(pwd) sys.argv = old_sys_argv sys.path[:] = old_sys_path sys.stdout = stdout return ns
OSError
dataset/ETHPy150Open mwaskom/seaborn/doc/sphinxext/plot_directive.py/run_code