Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
2,700
def _request(self, line, f): args = line.split(None, 2) try: peer = args[0] method = args[1] params = eval(args[2]) except: print("argument error") return try: p = peers[peer] except __HOLE__: pri...
KeyError
dataset/ETHPy150Open osrg/ryu/ryu/cmd/rpc_cli.py/Cmd._request
2,701
@messaging.expected_exceptions(exception.InstanceNotFound) def get_instance_nw_info(self, context, instance_id, rxtx_factor, host, instance_uuid=None, **kwargs): """Creates network info list for instance. called by allocate_for_instance and network_api context n...
TypeError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/network/manager.py/NetworkManager.get_instance_nw_info
2,702
def _allocate_mac_addresses(self, context, instance_uuid, networks, macs): """Generates mac addresses and creates vif rows in db for them.""" # make a copy we can mutate if macs is not None: available_macs = set(macs) for network in networks: if macs is None: ...
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/network/manager.py/NetworkManager._allocate_mac_addresses
2,703
@staticmethod def _convert_int_args(kwargs): int_args = ("network_size", "num_networks", "vlan_start", "vpn_start") for key in int_args: try: value = kwargs.get(key) if value is None: continue kwargs[...
ValueError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/network/manager.py/NetworkManager._convert_int_args
2,704
def create_networks(self, context, **kwargs): """Create networks based on parameters.""" self._convert_int_args(kwargs) kwargs["vlan_start"] = kwargs.get("vlan_start") or CONF.vlan_start kwargs["num_networks"] = (kwargs.get("num_networks") or CONF.num_n...
ValueError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/network/manager.py/VlanManager.create_networks
2,705
def getProcessResourceUsage(self, pid_list): try: results = {} for pid in pid_list: result = {} results[str(pid)] = result try: proc = psutil.Process(pid) except: LOG.exception("Proces...
AttributeError
dataset/ETHPy150Open GambitResearch/suponoff/suponoff-monhelper.py/MonHelperRPCInterface.getProcessResourceUsage
2,706
def tailFile(filename, offset, length): """ Read length bytes from the file named by filename starting at offset, automatically increasing offset and setting overflow flag if log size has grown beyond (offset + length). If length bytes are not available, as many bytes as are available are returned....
IOError
dataset/ETHPy150Open GambitResearch/suponoff/suponoff-monhelper.py/tailFile
2,707
def __init__(self, master): self.master = master self.emulator = None self.conf_dict = {} self.conf_name = tk.StringVar() self.conf_frame = None master.title("Wireless Network Reproduction") master.protocol("WM_DELETE_WINDOW", self.exit_func) # first ch...
OSError
dataset/ETHPy150Open FinalTheory/wireless-network-reproduction/macdivert/emulator.py/EmulatorGUI.__init__
2,708
def encode(self, domain, attribute, value): try: field = self.fields[attribute] except __HOLE__: return value else: return field.encode(value)
KeyError
dataset/ETHPy150Open saymedia/python-simpledb/simpledb/models.py/FieldEncoder.encode
2,709
def decode(self, domain, attribute, value): try: field = self.fields[attribute] except __HOLE__: return value else: return field.decode(value)
KeyError
dataset/ETHPy150Open saymedia/python-simpledb/simpledb/models.py/FieldEncoder.decode
2,710
def _get_service_file(squadron_dir, service_name, service_ver, filename, on_error=None, config=None): """ Grabs the named service file in a service directory Keyword arguments: squadron_dir -- base directory service_name -- the name of the service service_ver -- the version of the s...
OSError
dataset/ETHPy150Open gosquadron/squadron/squadron/commit.py/_get_service_file
2,711
def _get_config(conf_dir, service): """ Gets the service configuration Keyword arguments: conf_dir -- the location of the configuration directory service -- the name of the service """ ex = None for ext in extensions: try: with open(os.path.join(conf_dir, ser...
OSError
dataset/ETHPy150Open gosquadron/squadron/squadron/commit.py/_get_config
2,712
def has_key(self, key): try: value = self[key] except __HOLE__: return False return True
KeyError
dataset/ETHPy150Open babble/babble/include/jython/Lib/UserDict.py/DictMixin.has_key
2,713
def setdefault(self, key, default=None): try: return self[key] except __HOLE__: self[key] = default return default
KeyError
dataset/ETHPy150Open babble/babble/include/jython/Lib/UserDict.py/DictMixin.setdefault
2,714
def pop(self, key, *args): if len(args) > 1: raise TypeError, "pop expected at most 2 arguments, got "\ + repr(1 + len(args)) try: value = self[key] except __HOLE__: if args: return args[0] raise ...
KeyError
dataset/ETHPy150Open babble/babble/include/jython/Lib/UserDict.py/DictMixin.pop
2,715
def popitem(self): try: k, v = self.iteritems().next() except __HOLE__: raise KeyError, 'container is empty' del self[k] return (k, v)
StopIteration
dataset/ETHPy150Open babble/babble/include/jython/Lib/UserDict.py/DictMixin.popitem
2,716
def get(self, key, default=None): try: return self[key] except __HOLE__: return default
KeyError
dataset/ETHPy150Open babble/babble/include/jython/Lib/UserDict.py/DictMixin.get
2,717
def delete_files(main_window, forever): """Delete the selected files.""" iconview = main_window.iconview selected = iconview.get_selected_items() if selected and len(selected)>1: if forever: message = _('Would you like to permanently delete the ' 'selected ima...
OSError
dataset/ETHPy150Open thesamet/webilder/src/webilder/WebilderDesktop.py/delete_files
2,718
def import_files(files): success_count = 0 for afile in files: try: success_count += wbz_handler.handle_file(afile) except (__HOLE__, KeyError, ValueError), e: mbox = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK) ...
IOError
dataset/ETHPy150Open thesamet/webilder/src/webilder/WebilderDesktop.py/import_files
2,719
def test_lastWriteReceived(self): """ Verify that a write made directly to stdout using L{os.write} after StandardIO has finished is reliably received by the process reading that stdout. """ p = StandardIOTestProcessProtocol() # Note: the OS X bug which prompted ...
ValueError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/test/test_stdio.py/StandardInputOutputTestCase.test_lastWriteReceived
2,720
def _lookup_obs(): c = None for mod, cls in OBS_PROVIDERS: m_name = 'watchdog.observers.%s' % mod try: c = import_module(cls, m_name) except (ImportError, __HOLE__): # more exceptions? continue return c
AttributeError
dataset/ETHPy150Open yildizberkay/MongoApp/libs/watchdog/observers/__init__.py/_lookup_obs
2,721
def crowding_replacement(random, population, parents, offspring, args): """Performs crowding replacement as a form of niching. This function performs crowding replacement, which means that the members of the population are replaced one-at-a-time with each of the offspring. A random sample of `...
KeyError
dataset/ETHPy150Open aarongarrett/inspyred/inspyred/ec/replacers.py/crowding_replacement
2,722
def simulated_annealing_replacement(random, population, parents, offspring, args): """Replaces population using the simulated annealing schedule. This function performs simulated annealing replacement based on a temperature and a cooling rate. These can be specified by the keyword arguments `t...
KeyError
dataset/ETHPy150Open aarongarrett/inspyred/inspyred/ec/replacers.py/simulated_annealing_replacement
2,723
def execute(self, argv): options, args = self.parseOptions(argv) self.setUp(options) if options.interactive: while True: try: input = raw_input(">>> ") except (EOFError, KeyboardInterrupt): self.stdout....
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/antlr3/antlr3/main.py/_Main.execute
2,724
def populate_obj(self, obj, name): values = getattr(obj, name, None) try: ivalues = iter(values) except __HOLE__: ivalues = iter([]) candidates = itertools.chain(ivalues, itertools.repeat(None)) _fake = type(str('_fake'), (object, ), {}) output =...
TypeError
dataset/ETHPy150Open flask-admin/flask-admin/flask_admin/model/fields.py/InlineFieldList.populate_obj
2,725
def __getitem__(self, x): try: return DataUser.__getitem__(self, x) except __HOLE__: raise Exception( "You attempted to get the value `%s' from `%s'. It isn't here." " Perhaps you misspelled the name of a Property?" % (x, self))
KeyError
dataset/ETHPy150Open openworm/PyOpenWorm/PyOpenWorm/dataObject.py/DataObject.__getitem__
2,726
def oid(identifier_or_rdf_type, rdf_type=None): """ Create an object from its rdf type Parameters ---------- identifier_or_rdf_type : :class:`str` or :class:`rdflib.term.URIRef` If `rdf_type` is provided, then this value is used as the identifier for the newly created object. Otherwise,...
KeyError
dataset/ETHPy150Open openworm/PyOpenWorm/PyOpenWorm/dataObject.py/oid
2,727
def get_most_specific_rdf_type(types): """ Gets the most specific rdf_type. Returns the URI corresponding to the lowest in the DataObject class hierarchy from among the given URIs. """ most_specific_type = DataObject for x in types: try: class_object = RDFTypeTable[x] ...
KeyError
dataset/ETHPy150Open openworm/PyOpenWorm/PyOpenWorm/dataObject.py/get_most_specific_rdf_type
2,728
def dbworker(self): quoteDbName = self.connection.quoteIdentifier(self.db) self.progress.emit(0, 100, "Starting...") if self.compression == "": opener = open elif self.compression == "zip": opener = ZipFile elif self.compression == "gz": opene...
UnicodeDecodeError
dataset/ETHPy150Open mtorromeo/sqlantaresia/sqlantaresia/DumpTab.py/DumpThread.dbworker
2,729
def __init__(self, number): self.number = number # FIXME: need to make sure we're really getting a number and not any non-number characters. try: self.digits = [int(digit) for digit in str(self.number).strip()] self.region_code = int(str(self.digits[0]) + str(self.digits[...
ValueError
dataset/ETHPy150Open wesabe/fixofx/lib/ofx/validators.py/RoutingNumber.__init__
2,730
def resolve(self, context, quiet=True): """ Return an object described by the accessor by traversing the attributes of context. """ try: obj = context for level in self.levels: if isinstance(obj, dict): obj = ...
KeyError
dataset/ETHPy150Open shymonk/django-datatable/table/utils.py/Accessor.resolve
2,731
def render(self, context): try: expire_time = self.expire_time_var.resolve(context) except VariableDoesNotExist: raise TemplateSyntaxError('"cache" tag got an unknown variable: %r' % self.expire_time_var.var) try: expire_time = int(expire_time) except ...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/templatetags/cache.py/CacheNode.render
2,732
def _real_main(argv=None): # Compatibility fixes for Windows if sys.platform == 'win32': # https://github.com/rg3/youtube-dl/issues/820 codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None) workaround_optparse_bug9161() setproctitle('youtube-dl') pars...
ValueError
dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/__init__.py/_real_main
2,733
def main(argv=None): try: _real_main(argv) except DownloadError: sys.exit(1) except SameFileError: sys.exit('ERROR: fixed output name but more than one file to download') except __HOLE__: sys.exit('\nERROR: Interrupted by user')
KeyboardInterrupt
dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/__init__.py/main
2,734
def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv # setup command line parser parser = E.OptionParser(version="%prog version: $Id$", usage=globals()["__doc__"]) par...
KeyError
dataset/ETHPy150Open CGATOxford/cgat/scripts/clusters2metrics.py/main
2,735
def _Dynamic_Unsubscribe(self, request, response): """Unsubscribe a query. Args: request: UnsubscribeRequest response: UnsubscribeResponse (not used) """ ValidateSubscriptionId(request.sub_id()) ValidateTopic(request.topic()) try: del self.topics[request.topic()][request.sub_i...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/prospective_search/prospective_search_stub.py/ProspectiveSearchStub._Dynamic_Unsubscribe
2,736
@handle_response_format @treeio_login_required @module_admin_required() def settings_view(request, response_format='html'): "Settings view" # default permissions try: conf = ModuleSetting.get_for_module( 'treeio.core', 'default_permissions')[0] default_permissions = conf.value ...
IndexError
dataset/ETHPy150Open treeio/treeio/treeio/core/administration/views.py/settings_view
2,737
def move_or_copy(src, dst): try: os.rename(src, dst) except __HOLE__ as e: if e.errno == ERRNO_INVALID_CROSS_DEVICE_LINK: try: shutil.copy(src, dst) finally: os.unlink(src) else: raise
OSError
dataset/ETHPy150Open eallik/spinoff/spinoff/contrib/filetransfer/fileref.py/move_or_copy
2,738
def _find_comp(self, dt): if len(self._comps) == 1: return self._comps[0] dt = dt.replace(tzinfo=None) try: return self._cachecomp[self._cachedate.index(dt)] except __HOLE__: pass lastcomp = None lastcompdt = None for comp in se...
ValueError
dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/dateutil/tz.py/_tzicalvtz._find_comp
2,739
def gettz(name=None): tz = None if not name: try: name = os.environ["TZ"] except __HOLE__: pass if name is None or name == ":": for filepath in TZFILES: if not os.path.isabs(filepath): filename = filepath for path in...
KeyError
dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/dateutil/tz.py/gettz
2,740
def segment_axis(a, length, overlap=0, axis=None, end='cut', endvalue=0): """Generate a new array that chops the given array along the given axis into overlapping frames. Parameters ---------- a : array-like The array to segment length : int The length of each frame overlap ...
TypeError
dataset/ETHPy150Open jfsantos/ift6266h14/old/pylearn2_timit/segmentaxis.py/segment_axis
2,741
def __next__(self): try: if not self._origin_iter: self._origin_iter = self._origin.__iter__() n = next(self._origin_iter) except __HOLE__ as e: self._finished = True raise e else: self._state.append(n) retur...
StopIteration
dataset/ETHPy150Open graphql-python/graphene/graphene/utils/lazylist.py/LazyList.__next__
2,742
def read_events(self, timeout=None): if timeout is not None: rs, ws, xs = select.select([self.__fd], [], [], timeout) if self.__fd not in rs: return [] while True: try: s = os.read(self.__fd, 1024) break exc...
KeyError
dataset/ETHPy150Open shaurz/fsmonitor/fsmonitor/linux.py/FSMonitor.read_events
2,743
def run(self, doc): marker_found = False div = etree.Element("div") div.attrib["class"] = "toc" last_li = None # Add title to the div if self.config["title"]: header = etree.SubElement(div, "span") header.attrib["class"] = "toctitle" ...
IndexError
dataset/ETHPy150Open darcyliu/storyboard/markdown/extensions/toc.py/TocTreeprocessor.run
2,744
def GetKindsForAllNamespaces(self, deadline): """Obtain a list of all kind names from the datastore. Pulls kinds from all namespaces. The result is deduped and alphabetized. Args: deadline: maximum number of seconds to spend getting kinds. Returns: kinds: an alphabetized list of kinds for...
StopIteration
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/ext/datastore_admin/main.py/RouteByActionHandler.GetKindsForAllNamespaces
2,745
def make_word_list(): print "making word list..." word_list = [] for i in w: try: d[i.lower()] except __HOLE__: pass else: if i.lower() == "'s": pass elif i[-1] == ".": pass else: word_list.append((i.lower(), d[i.lower()][0])) return word_list
KeyError
dataset/ETHPy150Open rossgoodwin/sonnetizer/sonnetizer_m.py/make_word_list
2,746
def sylcount(s): try: d[s] except __HOLE__: return None else: if len(d[s]) <= 1: sj = ''.join(d[s][0]) sl = re.split('0|1|2', sj) return len(sl) - 1 else: sj0 = ''.join(d[s][0]) sl0 = re.split('0|1|2', sj0) sj1 = ''.join(d[s][1]) sl1 = re.split('0|1|2', sj1) if len(sl1) < len(sl0): ...
KeyError
dataset/ETHPy150Open rossgoodwin/sonnetizer/sonnetizer_m.py/sylcount
2,747
def fs_cleanup(filename, suppress_exceptions=True): """ Tries to remove the given filename. Ignores non-existent files """ try: os.remove(filename) except __HOLE__: if suppress_exceptions: pass else: raise
OSError
dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/common/utils.py/fs_cleanup
2,748
def get_descriptor(file_input, read=True): try: # Is it a file like object? file_input.seek(0) except __HOLE__: # If not, try open it. if read: return open(file_input, 'rb') else: return open(file_input, 'wb') else: return file_input
AttributeError
dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/common/utils.py/get_descriptor
2,749
def _collect_files_being_pushed(ref_list, remote): """Collect modified files and filter those that need linting. Parameter: ref_list: list of references to parse (provided by git in stdin) remote: the remote being pushed to Returns: dict: Dict mapping branch names to 2-tuples of the ...
ValueError
dataset/ETHPy150Open oppia/oppia/scripts/pre_push_hook.py/_collect_files_being_pushed
2,750
def _install_hook(): # install script ensures that oppia is root oppia_dir = os.getcwd() hooks_dir = os.path.join(oppia_dir, '.git', 'hooks') pre_push_file = os.path.join(hooks_dir, 'pre-push') if os.path.islink(pre_push_file): print 'Symlink already exists' return try: o...
AttributeError
dataset/ETHPy150Open oppia/oppia/scripts/pre_push_hook.py/_install_hook
2,751
def test_truncate(self): "Sequence truncate" assert str(self.seq[-202020202:5]) == 'atttg' assert self.seq[-202020202:5] == self.seq[0:5] assert self.seq[-2020202:] == self.seq assert str(self.seq[-202020202:-5]) == 'atttgactatgc' assert str(self.seq[-5:2029]) == 'tccag' ...
IndexError
dataset/ETHPy150Open cjlee112/pygr/tests/sequence_test.py/Sequence_Test.test_truncate
2,752
def test_rctruncate(self): "Sequence reverse complement truncate" seq= -self.seq assert str(seq[-202020202:5]) == 'ctgga' assert seq[-202020202:5] == seq[0:5] assert seq[-2020202:] == seq assert str(seq[-202020202:-5]) == 'ctggagcatagt' assert str(seq[-5:2029]) ==...
IndexError
dataset/ETHPy150Open cjlee112/pygr/tests/sequence_test.py/Sequence_Test.test_rctruncate
2,753
def __init__(self, bootstrap, timeout=60, debug=False, token=None): self.debug = debug self.timeout = timeout self.domainname = None self.token = token self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUS...
KeyboardInterrupt
dataset/ETHPy150Open denizalti/concoord/concoord/blockingclientproxy.py/ClientProxy.__init__
2,754
def discoverbootstrap(self, givenbootstrap): tmpbootstraplist = [] try: for bootstrap in givenbootstrap.split(","): bootstrap = bootstrap.strip() # The bootstrap list is read only during initialization if bootstrap.find(":") >= 0: ...
ValueError
dataset/ETHPy150Open denizalti/concoord/concoord/blockingclientproxy.py/ClientProxy.discoverbootstrap
2,755
def invoke_command(self, *args): # create a request descriptor reqdesc = ReqDesc(self, args, self.token) self.pendingops[reqdesc.commandnumber] = reqdesc # send the request with self.writelock: self.conn.send(reqdesc.cm) with self.lock: try: ...
KeyboardInterrupt
dataset/ETHPy150Open denizalti/concoord/concoord/blockingclientproxy.py/ClientProxy.invoke_command
2,756
def recv_loop(self, *args): socketset = [self.socket] while True: try: needreconfig = False inputready,outputready,exceptready = select.select(socketset, [], socketset, 0) for s in inputready: reply = self.conn.receive() ...
KeyboardInterrupt
dataset/ETHPy150Open denizalti/concoord/concoord/blockingclientproxy.py/ClientProxy.recv_loop
2,757
def parse(self, text, maxwidth=None, maxheight=None, template_dir=None, context=None, urlize_all_links=CONSUMER_URLIZE_ALL): """ Scans a block of text, replacing anything matching a provider pattern with an OEmbed html snippet, if possible. Templates should be stor...
UnicodeDecodeError
dataset/ETHPy150Open worldcompany/djangoembed/oembed/parsers/base.py/BaseParser.parse
2,758
def Parse(rc_name, h_name = None): if h_name: h_file = open(h_name, "rU") else: # See if same basename as the .rc h_name = rc_name[:-2]+"h" try: h_file = open(h_name, "rU") except __HOLE__: # See if MSVC default of 'resource.h' in the same...
IOError
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/lib/win32rcparser.py/Parse
2,759
def getimage(self, size=None): if size is None: size = self.bestsize() channels = self.dataforsize(size) im = channels.get("RGB").copy() try: im.putalpha(channels["A"]) except __HOLE__: pass return im ## # Image plugin for Mac OS icons...
KeyError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/IcnsImagePlugin.py/IcnsFile.getimage
2,760
def __init__(self, pkg='', rev='', address=None, payload=None, **kwargs): """ :param str pkg: The package import path within the remote library; by default the root package path (equivalent to passing `pkg='.'` or `pkg=''`). :param str rev: Identifies which version of the remote library ...
ValueError
dataset/ETHPy150Open pantsbuild/pants/contrib/go/src/python/pants/contrib/go/targets/go_remote_library.py/GoRemoteLibrary.__init__
2,761
def get_alias_strings(aliases): alias_strings = [] for alias in aliases: alias = item_module.canonical_alias_tuple(alias) (namespace, nid) = alias try: alias_strings += [namespace+":"+nid] except __HOLE__: # jsonify the biblio dicts alias_strin...
TypeError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/collection.py/get_alias_strings
2,762
def get_items_for_client(tiids, myrefsets, myredis, most_recent_metric_date=None, most_recent_diff_metric_date=None): item_metric_dicts = get_readonly_item_metric_dicts(tiids, most_recent_metric_date, most_recent_diff_metric_date) dict_of_item_docs = {} for tiid in item_metric_dicts: try: ...
TypeError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/collection.py/get_items_for_client
2,763
def get_collection_with_items_for_client(cid, myrefsets, myredis, mydao, include_history=False): collection_obj = Collection.query.get(cid) collection_doc = get_collection_doc_from_object(collection_obj) if not collection_doc: return (None, None) collection_doc["items"] = [] tiids = collect...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/collection.py/get_collection_with_items_for_client
2,764
def clean_value_for_csv(value_to_store): try: value_to_store = value_to_store.encode("utf-8").strip() except __HOLE__: pass return value_to_store
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/collection.py/clean_value_for_csv
2,765
def make_csv_rows(items): header_metric_names = [] for item in items: header_metric_names += item["metrics"].keys() header_metric_names = sorted(list(set(header_metric_names))) header_alias_names = ["title", "doi"] # make header row header_list = ["tiid"] + header_alias_names + header_...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/collection.py/make_csv_rows
2,766
def build_all_reference_lookups(myredis, mydao): # for expediency, assuming all reference collections are this size # risky assumption, but run with it for now! size_of_reference_collections = 100 confidence_interval_level = 0.95 percentiles = range(100) confidence_interval_table = myredis.get_...
ValueError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/collection.py/build_all_reference_lookups
2,767
@patch('corehq.apps.userreports.specs.datetime') def test_indicators(self, datetime_mock): fake_time_now = datetime.datetime(2015, 4, 24, 12, 30, 8, 24886) datetime_mock.utcnow.return_value = fake_time_now # indicators sample_doc, expected_indicators = get_sample_doc_and_indicators(f...
AssertionError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/userreports/tests/test_data_source_config.py/DataSourceConfigurationTest.test_indicators
2,768
def _wait_synchronous(self): # Wait to finish, but cancel if KeyboardInterrupt from impala.hiveserver2 import OperationalError loop_start = time.time() def _sleep_interval(start_time): elapsed = time.time() - start_time if elapsed < 0.05: return 0...
KeyboardInterrupt
dataset/ETHPy150Open cloudera/ibis/ibis/impala/client.py/ImpalaCursor._wait_synchronous
2,769
def choose_boundary(): """Return a string usable as a multipart boundary. The string chosen is unique within a single program run, and incorporates the user id (if available), process id (if available), and current time. So it's very unlikely the returned string appears in message text, but there'...
AttributeError
dataset/ETHPy150Open babble/babble/include/jython/Lib/mimetools.py/choose_boundary
2,770
def ustr(s, encoding="utf-8"): """ Convert argument to unicode string. """ if isinstance(s, str): return s try: return s.decode(encoding) except __HOLE__: return str(s)
AttributeError
dataset/ETHPy150Open nigelsmall/httpstream/httpstream/util.py/ustr
2,771
def get_video_dims(fname): """ Pull out the frame length, spatial height and spatial width of a video file using ffmpeg. Parameters ---------- fname : str Path to video file to be inspected. Returns ------- shape : tuple The spatiotemporal dimensions of the video ...
ImportError
dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/utils/video.py/get_video_dims
2,772
def copy_to_clipboard(text): # reliable on mac if sys.platform == 'darwin': os.system('echo "{0}" | pbcopy'.format(text)) return # okay we'll try cross-platform way try: from Tkinter import Tk except __HOLE__: return r = Tk() r.withdraw() r.clipboard_cle...
ImportError
dataset/ETHPy150Open zeekay/soundcloud-cli/soundcloud_cli/utils.py/copy_to_clipboard
2,773
def escape_list(mylist, escape_func): """Escape a list of arguments by running the specified escape_func on every object in the list that has an escape() method.""" def escape(obj, escape_func=escape_func): try: e = obj.escape except __HOLE__: return obj else:...
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Subst.py/escape_list
2,774
def __getattr__(self, attr): nl = self.nl._create_nodelist() try: nl0 = nl[0] except __HOLE__: # If there is nothing in the list, then we have no attributes to # pass through, so raise AttributeError for everything. raise AttributeError("NodeList h...
IndexError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Subst.py/Target_or_Source.__getattr__
2,775
def subst_dict(target, source): """Create a dictionary for substitution of special construction variables. This translates the following special arguments: target - the target (object or array of objects), used to generate the TARGET and TARGETS construction variables so...
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Subst.py/subst_dict
2,776
def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None): """Expand a string or list containing construction variable substitutions. This is the work-horse function for substitutions in file names and the like. The companion scons_subst_list() function (b...
IndexError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Subst.py/scons_subst
2,777
def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None): """Substitute construction variables in a string (or list or other object) and separate the arguments into a command list. The companion scons_subst() function (above) handles basic substitutio...
IndexError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Subst.py/scons_subst_list
2,778
@instance_synchronized def get_console_output(self, instance_name): console_log_paths = self._pathutils.get_vm_console_log_paths( instance_name) try: log = b'' # Start with the oldest console log file. for log_path in console_log_paths[::-1]: ...
IOError
dataset/ETHPy150Open openstack/compute-hyperv/hyperv/nova/serialconsoleops.py/SerialConsoleOps.get_console_output
2,779
def test_bugdown_fixtures(self): format_tests, linkify_tests = self.load_bugdown_tests() self.maxDiff = None for name, test in six.iteritems(format_tests): converted = bugdown_convert(test['input']) print("Running Bugdown test %s" % (name,)) self.assertEqual...
TypeError
dataset/ETHPy150Open zulip/zulip/zerver/tests/test_bugdown.py/BugdownTest.test_bugdown_fixtures
2,780
def connect(self,dupe=None): """ Starts connection. Connects to proxy, supplies login and password to it (if were specified while creating instance). Instructs proxy to make connection to the target server. Returns non-empty sting on success. """ if not TCPsocket.connect(self,(se...
IOError
dataset/ETHPy150Open kuri65536/python-for-android/python-build/python-libs/xmpppy/xmpp/transports.py/HTTPPROXYsocket.connect
2,781
def watch(self, args): from_date = None while True: from_date = self.query(args, from_date) try: time.sleep(2) except (KeyboardInterrupt, __HOLE__): sys.exit(0)
SystemExit
dataset/ETHPy150Open alerta/python-alerta/alerta/shell.py/AlertCommand.watch
2,782
def top(self, args): screen = Screen(endpoint=args.endpoint, key=args.key) try: screen.run() except __HOLE__ as e: screen._reset() print(e) sys.exit(1) except (KeyboardInterrupt, SystemExit): screen.w.running = False ...
RuntimeError
dataset/ETHPy150Open alerta/python-alerta/alerta/shell.py/AlertCommand.top
2,783
def keys(self, args): response = self._keys() keys = response['keys'] print('{:<40} {:<24} {:<20} {:<16} {:<10} {:19} {:19} {:4}'.format('API KEY', 'USER', 'DESCRIPTION', 'CUSTOMER', 'RO / RW', 'EXPIRES', 'LAST USED', 'COUNT')) for key in keys: expire_time = datetime.strpt...
TypeError
dataset/ETHPy150Open alerta/python-alerta/alerta/shell.py/AlertCommand.keys
2,784
def main(): logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s") # Only mangle the terminal if using Python 2.x if sys.version_info[0] == 2: sys.stdout = codecs.getwriter('utf-8')(sys.stdout) try: AlertaShell().run() except (__HOLE__, KeyboardInterrup...
SystemExit
dataset/ETHPy150Open alerta/python-alerta/alerta/shell.py/main
2,785
def range_usage_text(request): start = request.GET.get('start', None) end = request.GET.get('end', None) format = request.GET.get('format', 'human_readable') if not (start and end): return HttpResponse(json.dumps({ 'success': False, 'error_messages': 'Provide a start and ...
ValidationError
dataset/ETHPy150Open mozilla/inventory/core/range/views.py/range_usage_text
2,786
def redirect_to_range_from_ip(request): ip_str = request.GET.get('ip_str') ip_type = request.GET.get('ip_type') if not (ip_str and ip_type): return HttpResponse(json.dumps({'failure': "Slob"})) if ip_type == '4': try: ip_upper, ip_lower = 0, int(ipaddr.IPv4Address(ip_str)) ...
ValidationError
dataset/ETHPy150Open mozilla/inventory/core/range/views.py/redirect_to_range_from_ip
2,787
def find_related(request): """ Given a list of site, vlan, and network primary keys, help a user make choices about where to put an IP address A user can select from choices: Networks Vlans Sites The goal of the UI is to help a user choose a range -- which for this func...
ValueError
dataset/ETHPy150Open mozilla/inventory/core/range/views.py/find_related
2,788
def _join_if_needed(self, value): if isinstance(value, (list, tuple)): try: return self._join_multivalued.join(value) except __HOLE__: # list in value may not contain strings pass return value
TypeError
dataset/ETHPy150Open scrapy/scrapy/scrapy/exporters.py/CsvItemExporter._join_if_needed
2,789
def _build_row(self, values): for s in values: try: yield to_native_str(s) except __HOLE__: yield s
TypeError
dataset/ETHPy150Open scrapy/scrapy/scrapy/exporters.py/CsvItemExporter._build_row
2,790
@property def size(self): try: return int(self.data['details'].get('filesize')) except __HOLE__: return None
ValueError
dataset/ETHPy150Open picklepete/pyicloud/pyicloud/services/photos.py/PhotoAsset.size
2,791
def __contains__(self, item): try: wr = ref(item) except __HOLE__: return False return wr in self.data
TypeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/_weakrefset.py/WeakSet.__contains__
2,792
def pop(self): if self._pending_removals: self._commit_removals() while True: try: itemref = self.data.pop() except __HOLE__: raise KeyError('pop from empty WeakSet') item = itemref() if item is not None...
KeyError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/_weakrefset.py/WeakSet.pop
2,793
def __init__(self, parent): parent.title = "Interactive Lobe Segmentation" # TODO make this more human readable by adding spaces parent.categories = ["Chest Imaging Platform"] parent.dependencies = [] parent.contributors = ["Pietro Nardelli (UCC/SPL) and Applied Chest Imaging Laboratory, Brigham and Wom...
AttributeError
dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/InteractiveLobeSegmentation/InteractiveLobeSegmentation.py/InteractiveLobeSegmentation.__init__
2,794
def onReload(self,moduleName="InteractiveLobeSegmentation"): """Generic reload method for any scripted module. ModuleWizard will subsitute correct default moduleName. """ import imp, sys, os, slicer widgetName = moduleName + "Widget" # reload the source code # - set source file path # ...
AttributeError
dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/InteractiveLobeSegmentation/InteractiveLobeSegmentation.py/InteractiveLobeSegmentationWidget.onReload
2,795
def job_script_kwargs(self, ofile, efile, job_name): pbsargs = {'-o': ofile, '-e': efile, '-N': job_name} for k, v in self.params.items(): if k == 'plugin': continue try: if not k.startswith('-'): ...
KeyError
dataset/ETHPy150Open galaxyproject/pulsar/pulsar/managers/util/cli/job/torque.py/Torque.job_script_kwargs
2,796
def _get_job_state(self, state): try: return { 'E': job_states.RUNNING, 'R': job_states.RUNNING, 'Q': job_states.QUEUED, 'C': job_states.OK }.get(state) except __HOLE__: raise KeyError("Failed to map torq...
KeyError
dataset/ETHPy150Open galaxyproject/pulsar/pulsar/managers/util/cli/job/torque.py/Torque._get_job_state
2,797
@classmethod def get_row_by_pk(self, ar, pk): """Implements :meth:`get_row_by_pk <lino.core.actors.Actor.get_row_by_pk>` for a database table. """ try: return self.model.objects.get(pk=pk) except __HOLE__: return None except self.model...
ValueError
dataset/ETHPy150Open lsaffre/lino/lino/core/dbtables.py/Table.get_row_by_pk
2,798
def apply(self, transform, pvalueish=None): """Applies a custom transform using the pvalueish specified. Args: transform: the PTranform (or callable) to apply. pvalueish: the input for the PTransform (typically a PCollection). Raises: TypeError: if the transform object extracted from the...
TypeError
dataset/ETHPy150Open GoogleCloudPlatform/DataflowPythonSDK/google/cloud/dataflow/pipeline.py/Pipeline.apply
2,799
def tearDown(self): try: shutil.rmtree(self.tempdir) except __HOLE__: pass self.top = None
OSError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/casehandlers/test/test_jsonrecorder.py/TestCase.tearDown