Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
7,000
def _test_tags_read(filename=None): import sys if filename is None: if len(sys.argv) != 2: filename = '/tmp/libtiff_tags_write.tiff' if not os.path.isfile (filename): print 'Run `%s <filename>` for testing.' % (__file__) return else: ...
TypeError
dataset/ETHPy150Open pearu/pylibtiff/libtiff/libtiff_ctypes.py/_test_tags_read
7,001
@record def test_message_bytes_fails(self): # Arrange queue_name = self._get_queue_reference() # Action. try: message = b'xyz' self.qs.put_message(queue_name, message) self.fail('Passing binary to text encoder should fail.') except __HOLE_...
TypeError
dataset/ETHPy150Open Azure/azure-storage-python/tests/test_queue_encodings.py/StorageQueueEncodingTest.test_message_bytes_fails
7,002
@record def test_message_text_fails(self): # Arrange qs2 = self._create_storage_service(QueueService, self.settings) qs2.encode_function = QueueMessageFormat.binary_base64encode qs2.decode_function = QueueMessageFormat.binary_base64decode queue_name = self._get_queue_referen...
TypeError
dataset/ETHPy150Open Azure/azure-storage-python/tests/test_queue_encodings.py/StorageQueueEncodingTest.test_message_text_fails
7,003
@record def test_message_base64_decode_fails(self): # Arrange qs2 = self._create_storage_service(QueueService, self.settings) qs2.encode_function = QueueMessageFormat.text_xmlencode qs2.decode_function = QueueMessageFormat.binary_base64decode queue_name = self._create_queue(...
ValueError
dataset/ETHPy150Open Azure/azure-storage-python/tests/test_queue_encodings.py/StorageQueueEncodingTest.test_message_base64_decode_fails
7,004
def read_hdf(path_or_buf, key=None, **kwargs): """ read from the store, close it if we opened it Retrieve pandas object stored in file, optionally based on where criteria Parameters ---------- path_or_buf : path (string), or buffer to read from key : group identifie...
ValueError
dataset/ETHPy150Open pydata/pandas/pandas/io/pytables.py/read_hdf
7,005
def __init__(self, path, mode=None, complevel=None, complib=None, fletcher32=False, **kwargs): try: import tables # noqa except __HOLE__ as ex: # pragma: no cover raise ImportError('HDFStore requires PyTables, "{ex}" problem ' 'imp...
ImportError
dataset/ETHPy150Open pydata/pandas/pandas/io/pytables.py/HDFStore.__init__
7,006
def convert(self, values, nan_rep, encoding): """set the data from this selection (and convert to the correct dtype if we can) """ # values is a recarray if values.dtype.fields is not None: values = values[self.cname] self.set_data(values) # use the...
ValueError
dataset/ETHPy150Open pydata/pandas/pandas/io/pytables.py/DataCol.convert
7,007
def write_array(self, key, value, items=None): if key in self.group: self._handle.remove_node(self.group, key) # Transform needed to interface with pytables row/col notation empty_array = self._is_empty_array(value.shape) transposed = False if com.is_categorical_dty...
ValueError
dataset/ETHPy150Open pydata/pandas/pandas/io/pytables.py/GenericFixed.write_array
7,008
def validate_multiindex(self, obj): """validate that we can store the multi-index; reset and return the new object """ levels = [l if l is not None else "level_{0}".format(i) for i, l in enumerate(obj.index.names)] try: return obj.reset_index(), leve...
ValueError
dataset/ETHPy150Open pydata/pandas/pandas/io/pytables.py/Table.validate_multiindex
7,009
def create_axes(self, axes, obj, validate=True, nan_rep=None, data_columns=None, min_itemsize=None, **kwargs): """ create and return the axes leagcy tables create an indexable column, indexable index, non-indexable fields Parameters: ----------- ...
NotImplementedError
dataset/ETHPy150Open pydata/pandas/pandas/io/pytables.py/Table.create_axes
7,010
def generate(self, where): """ where can be a : dict,list,tuple,string """ if where is None: return None q = self.table.queryables() try: return Expr(where, queryables=q, encoding=self.table.encoding) except __HOLE__: # raise a nice message, s...
NameError
dataset/ETHPy150Open pydata/pandas/pandas/io/pytables.py/Selection.generate
7,011
def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied. """ try: acce...
AttributeError
dataset/ETHPy150Open django/django/django/contrib/sessions/middleware.py/SessionMiddleware.process_response
7,012
def ajax_list(self): field_name = request.args.get('field') prev_page = 0 next_page = 0 try: models = path_to_models(self.model, field_name) except __HOLE__: data = [] else: field = self.model._meta.fields[field_name] rel_m...
AttributeError
dataset/ETHPy150Open coleifer/flask-peewee/flask_peewee/admin.py/ModelAdmin.ajax_list
7,013
def get_model_field(self, model, field): try: attr = getattr(model, field) except AttributeError: model_admin = self.admin[type(model)] try: attr = getattr(model_admin, field) except __HOLE__: raise AttributeError('Could not...
AttributeError
dataset/ETHPy150Open coleifer/flask-peewee/flask_peewee/admin.py/AdminTemplateHelper.get_model_field
7,014
def get_verbose_name(self, model, column_name): try: field = model._meta.fields[column_name] except __HOLE__: return self.fix_underscores(column_name) else: return field.verbose_name
KeyError
dataset/ETHPy150Open coleifer/flask-peewee/flask_peewee/admin.py/AdminTemplateHelper.get_verbose_name
7,015
def uuid_or_400(f): @wraps(f) def wrapper(request, *args, **kwds): try: uuid.UUID(args[0]) except __HOLE__: return HttpResponseBadRequest() return f(request, *args, **kwds) return wrapper
ValueError
dataset/ETHPy150Open healthchecks/healthchecks/hc/api/decorators.py/uuid_or_400
7,016
def check_api_key(f): @wraps(f) def wrapper(request, *args, **kwds): try: data = json.loads(request.body.decode("utf-8")) except __HOLE__: return make_error("could not parse request body") api_key = str(data.get("api_key", "")) if api_key == "": ...
ValueError
dataset/ETHPy150Open healthchecks/healthchecks/hc/api/decorators.py/check_api_key
7,017
def _get_repo_names(project_list): # take a list of project names, like ['anchor', 'barbican'], get the # corresponding repos for each. Return a dictionary with the project # as the key and the repo as the value. project_repos = {key: None for key in project_list} yaml_data = get_yaml("{0}{1}".for...
IndexError
dataset/ETHPy150Open openstack/bandit/tools/openstack_coverage.py/_get_repo_names
7,018
def clone_projects(project_list): # clone all of the projects, return the directory name they are cloned in project_locations = _get_repo_names(project_list) orig_dir = os.path.abspath(os.getcwd()) # create directory for projects try: dir_name = 'project-source-{}'.format(datetime.datetime...
OSError
dataset/ETHPy150Open openstack/bandit/tools/openstack_coverage.py/clone_projects
7,019
def run_bandit(source_dir): # go through each source directory in the directory which contains source, # run Bandit with the established tox job, save results orig_dir = os.path.abspath(os.getcwd()) try: fail_results_dir = os.path.abspath('fail_results') os.mkdir(fail_results_dir) e...
OSError
dataset/ETHPy150Open openstack/bandit/tools/openstack_coverage.py/run_bandit
7,020
def principal(): print('(principal) iniciando...') co = corrotina() print('(principal) invocando next(co)...') next(co) print('(principal) invocando co.send(88)...') co.send(88) try: print('(principal) invocando co.send(99)...') co.send(99) # o print a seguir nunca va...
StopIteration
dataset/ETHPy150Open fluentpython/example-code/attic/control/exemplo0.py/principal
7,021
def handle(self, *args, **options): quiet = options.get('quiet', False) if not quiet: self.stdout.write("Export of DMS MDT's command called.\n") # Try and Fetch all mdts manager = MetaDataTemplateManager() mdts = manager.get_all_mdts() # Validating all OK ...
KeyError
dataset/ETHPy150Open adlibre/Adlibre-DMS/adlibre_dms/couchapps/mdtcouch/management/commands/export_mdts.py/Command.handle
7,022
def tearDown(self): os.chdir(self.test_dir) try: self._rmrf('locale/%s' % LOCALE) except __HOLE__: pass os.chdir(self._cwd)
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/tests/regressiontests/makemessages/extraction.py/ExtractorTests.tearDown
7,023
def tearDown(self): super(SymlinkExtractorTests, self).tearDown() os.chdir(self.test_dir) try: os.remove(self.symlinked_dir) except __HOLE__: pass os.chdir(self._cwd)
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/tests/regressiontests/makemessages/extraction.py/SymlinkExtractorTests.tearDown
7,024
def _url_for_fetch(self, mapping): try: return mapping['pre_processed_url'] except __HOLE__: return mapping['raw_url']
KeyError
dataset/ETHPy150Open openelections/openelections-core/openelex/us/az/datasource.py/Datasource._url_for_fetch
7,025
def unplug_device(conf, device): orig_log_fail_as_error = device.get_log_fail_as_error() device.set_log_fail_as_error(False) try: device.link.delete() except __HOLE__: device.set_log_fail_as_error(orig_log_fail_as_error) # Maybe the device is OVS port, so try to delete ov...
RuntimeError
dataset/ETHPy150Open openstack/neutron/neutron/cmd/netns_cleanup.py/unplug_device
7,026
@staticmethod def create_repo(cwd=TEMP_DIR): try: shell_out(["git", "init"], cwd=cwd) return True except (__HOLE__, CalledProcessError): return False
OSError
dataset/ETHPy150Open hayd/pep8radius/tests/util_vcs.py/MixinGit.create_repo
7,027
@staticmethod def successfully_commit_files(file_names, commit="initial_commit", cwd=TEMP_DIR): try: shell_out(["git", "add"] + file_names, cwd=cwd) shell_out(["git", "commit", "-m", commit], cwd=cwd) wit...
OSError
dataset/ETHPy150Open hayd/pep8radius/tests/util_vcs.py/MixinGit.successfully_commit_files
7,028
@staticmethod def create_repo(cwd=TEMP_DIR): try: shell_out(["hg", "init"], cwd=cwd) return True except (__HOLE__, CalledProcessError): return False
OSError
dataset/ETHPy150Open hayd/pep8radius/tests/util_vcs.py/MixinHg.create_repo
7,029
@staticmethod def successfully_commit_files(file_names, commit="initial_commit", cwd=TEMP_DIR): try: shell_out(["hg", "add"] + file_names, cwd=cwd) shell_out(["hg", "commit", "-m", commit], cwd=cwd) with ...
OSError
dataset/ETHPy150Open hayd/pep8radius/tests/util_vcs.py/MixinHg.successfully_commit_files
7,030
@staticmethod def create_repo(cwd=TEMP_DIR): try: shell_out(["bzr", "init"], cwd=cwd) return True except (__HOLE__, CalledProcessError): return False
OSError
dataset/ETHPy150Open hayd/pep8radius/tests/util_vcs.py/MixinBzr.create_repo
7,031
@staticmethod def successfully_commit_files(file_names, commit="initial_commit", cwd=TEMP_DIR): try: shell_out(["bzr", "add"] + file_names, cwd=cwd) shell_out(["bzr", "commit", "-m", commit], cwd=cwd) wit...
OSError
dataset/ETHPy150Open hayd/pep8radius/tests/util_vcs.py/MixinBzr.successfully_commit_files
7,032
def delete_topic(topic): if topic == 'General': print('Default topic "General" cannot be removed.') exit() try: del d[topic] print('Removed "{}" from your library.'.format(topic)) except __HOLE__: print('"{}" is not in your library!'.format(topic)) exit() # ...
KeyError
dataset/ETHPy150Open iamaziz/TermFeed/termfeed/dbop.py/delete_topic
7,033
def generate_doc(config): docdir = os.path.join(cwd,'documentation') if not os.path.exists(docdir): docdir = os.path.join(cwd,'..','documentation') if not os.path.exists(docdir): print "Couldn't find documentation file at: %s" % docdir return None try: import markdown2 as markdown except __HOLE__: impor...
ImportError
dataset/ETHPy150Open jaraen/TiAccurateTimer/iphone/build.py/generate_doc
7,034
def _format_prefixes(subnetpool): try: return '\n'.join(pool for pool in subnetpool['prefixes']) except (TypeError, __HOLE__): return subnetpool['prefixes']
KeyError
dataset/ETHPy150Open openstack/python-neutronclient/neutronclient/neutron/v2_0/subnetpool.py/_format_prefixes
7,035
def _posix_shell(self, chan, raw=True, initial_input=None): """ Create a loop which redirects sys.stdin/stdout into this channel. The loop ends when channel.recv() returns 0. Code inspired by the Paramiko interactive demo. """ result = [] password_sent = False ...
IOError
dataset/ETHPy150Open jonathanslenders/python-deployer/deployer/host/base.py/Host._posix_shell
7,036
def specification(self, of, defaults=True, via=None): """Build our internal specification of the target callable. Optionally, pre-populate the callbacks for --help/-h and --version/-V. """ cmd = Bunch(target=of) cmd.doc = partitionhelp(getdoc(cmd.target)) if getdoc(cmd.target) ...
TypeError
dataset/ETHPy150Open marrow/script/marrow/script/core.py/Parser.specification
7,037
def update (self, pairs): try: for key, value in pairs.iteritems (): if not self.has_key (key): self._keys.append (key) except __HOLE__: for pair in pairs: if not self.has_key (pair[0]): self._keys.append (pa...
AttributeError
dataset/ETHPy150Open dotskapes/dotSkapes/modules/geo/utils.py/ordered_dict.update
7,038
@staticmethod def chooseBoard(dap_class=DAPAccess, blocking=True, return_first=False, board_id=None, target_override=None, frequency=1000000, init_board=True): """ Allow you to select a board among all boards connected """ all_mbeds = MbedBoard...
ValueError
dataset/ETHPy150Open mbedmicro/pyOCD/pyOCD/board/mbed_board.py/MbedBoard.chooseBoard
7,039
def parse(self, response): if 'news.ycombinator.com' in response.url: soup = bs(response.body) items = [(x[0].text, x[0].get('href')) for x in filter(None, [ x.findChildren() for x in soup.findAll('td', {'class':'title'}) ])] for item in items: print ...
ValueError
dataset/ETHPy150Open mvanveen/hncrawl/news/spiders/hnspider.py/HnspiderSpider.parse
7,040
def mangle_test_address(address): path, possible_open_bracket, params = address.partition('[') names = path.split("::") try: names.remove('()') except __HOLE__: pass # convert file path to dotted path names[0] = names[0].replace("/", '.') names[0] = _py_ext_re.sub("", names[0...
ValueError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/junitxml.py/mangle_test_address
7,041
def capture(self, webcam): """ Capture an image from a webcam Given a webcam, this attempts to capture an image using the subprocess command. Also creates a thumbnail of the image Args: webcam (dict): Entry for the webcam. Example:: { 'na...
OSError
dataset/ETHPy150Open panoptes/POCS/panoptes/environment/webcams.py/Webcams.capture
7,042
def start_capturing(self): """ Starts the capturing loop for all cameras Depending on the number of frames taken for an individual image, capturing can take up to ~30 sec. """ self.is_capturing = True for process in self._processes: self.logger.info("Staring...
AssertionError
dataset/ETHPy150Open panoptes/POCS/panoptes/environment/webcams.py/Webcams.start_capturing
7,043
@property def nicedir(self): try: from os.path import relpath, isabs except __HOLE__: return self.dir else: a = self.dir r = relpath(self.dir) if isabs(a): home = os.environ["HOME"] if a == home: ...
ImportError
dataset/ETHPy150Open trentm/sources/lib/sources.py/Source.nicedir
7,044
def _run(argv, cwd=None): log.debug("run '%s'", ' '.join(argv)) try: return subprocess.check_call(argv, cwd=cwd) except __HOLE__: _, err, _ = sys.exc_info() import errno if err.errno == errno.ENOENT: raise OSError(errno.ENOENT, "'%s' not found" % argv[0]) ...
OSError
dataset/ETHPy150Open trentm/sources/lib/sources.py/_run
7,045
def _parse_time(self, time): try: return int(time) except __HOLE__: return None
ValueError
dataset/ETHPy150Open rbarrois/mpdlcd/mpdlcd/mpdwrapper.py/MPDClient._parse_time
7,046
def google(q): query = quote(q) url = "https://encrypted.google.com/search?q={0}".format(query) soup = BeautifulSoup(requests.get(url).text, "html5lib") answer = soup.findAll("h3", attrs={"class": "r"}) if not answer: return ":crying_cat_face: Sorry, google doesn't have an answer for you :c...
IndexError
dataset/ETHPy150Open llimllib/limbo/limbo/plugins/google.py/google
7,047
def run(req): # tell the client helper the current taskid stackhut.req_id = req['req_id'] iface_name, func_name = req['method'].split('.') params = req['params'] if iface_name in SERVICES: iface_impl = SERVICES[iface_name] try: func = getattr(iface_impl, func_name) ...
AttributeError
dataset/ETHPy150Open StackHut/stackhut/stackhut_toolkit/res/shims/python/runner.py/run
7,048
def to_python(self, value): if not value or value == 'None': return None if isinstance(value, Geoposition): return value if isinstance(value, list): return Geoposition(value[0], value[1]) # default case is string value_parts = value.rsplit(','...
IndexError
dataset/ETHPy150Open philippbosch/django-geoposition/geoposition/fields.py/GeopositionField.to_python
7,049
def get(self, key, *args): try: return self[key] except __HOLE__: if args: return args[0] raise
KeyError
dataset/ETHPy150Open pyjs/pyjs/pyjs/options.py/Mappings.Defaults.get
7,050
def __getitem__(self, key, exc=KeyError): try: return self._cache[key] except __HOLE__: raise exc(key)
KeyError
dataset/ETHPy150Open pyjs/pyjs/pyjs/options.py/Mappings.__getitem__
7,051
def __setitem__(self, key, kwds): if not key: raise TypeError('Malformed name.') n = 'opt' if key.isupper(): n = 'grp' new = '_%s' % n sig = '_%s_sig' % n sig_hash = '_%s_sig_hash' % n try: None in kwds except TypeError:...
TypeError
dataset/ETHPy150Open pyjs/pyjs/pyjs/options.py/Mappings.__setitem__
7,052
def get(self, key, *args): try: return self[key] except __HOLE__: if args: return args[0] raise
KeyError
dataset/ETHPy150Open pyjs/pyjs/pyjs/options.py/Mappings.get
7,053
def runWorkflowQuery(config, vistrail=None, version=None, fromTime=None, toTime=None, user=None, offset=0, limit=100, modules=[], thumbs=None): # returns list of workflows: # (vistrail name, vistrail id, id, name, date, user, thumb) result = [] db = open_db_connection(config) select_...
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/db/services/query.py/runWorkflowQuery
7,054
def runLogQuery(config, vistrail=None, version=None, fromTime=None, toTime=None, user=None, completed=None, offset=0, limit=100, modules=[], thumbs=None): # returns list of workflow executions: # (vistrail name, vistrail id, log id, workflow id, workflow name, # ex...
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/db/services/query.py/runLogQuery
7,055
def collapse_addresses(addresses): """Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network...
AttributeError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/dep/ipaddress.py/collapse_addresses
7,056
def __eq__(self, other): try: return (self._ip == other._ip and self._version == other._version) except __HOLE__: return NotImplemented
AttributeError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/dep/ipaddress.py/_BaseAddress.__eq__
7,057
def __eq__(self, other): try: return (self._version == other._version and self.network_address == other.network_address and int(self.netmask) == int(other.netmask)) except __HOLE__: return NotImplemented
AttributeError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/dep/ipaddress.py/_BaseNetwork.__eq__
7,058
def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. ...
ValueError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/dep/ipaddress.py/_BaseV4._ip_int_from_string
7,059
def _is_valid_netmask(self, netmask): """Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask. """ mask = n...
ValueError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/dep/ipaddress.py/_BaseV4._is_valid_netmask
7,060
def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: ...
ValueError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/dep/ipaddress.py/_BaseV4._is_hostmask
7,061
def __eq__(self, other): address_equal = IPv4Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except __HOLE__: # An interface with an associated network ...
AttributeError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/dep/ipaddress.py/IPv4Interface.__eq__
7,062
def __lt__(self, other): address_less = IPv4Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except __HOLE__: # We *do* allow addresses and interfaces to be sorted. The ...
AttributeError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/dep/ipaddress.py/IPv4Interface.__lt__
7,063
def _ip_int_from_string(self, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ if not ip...
ValueError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/dep/ipaddress.py/_BaseV6._ip_int_from_string
7,064
def __eq__(self, other): address_equal = IPv6Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except __HOLE__: # An interface with an associated network ...
AttributeError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/dep/ipaddress.py/IPv6Interface.__eq__
7,065
def __lt__(self, other): address_less = IPv6Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except __HOLE__: # We *do* allow addresses and interfaces to be sorted. The ...
AttributeError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/dep/ipaddress.py/IPv6Interface.__lt__
7,066
def _is_valid_netmask(self, prefixlen): """Verify that the netmask/prefixlen is valid. Args: prefixlen: A string, the netmask in prefix length format. Returns: A boolean, True if the prefix represents a valid IPv6 netmask. """ try: ...
ValueError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/dep/ipaddress.py/IPv6Network._is_valid_netmask
7,067
def parse_GECKO(cls, agentString): """ Attempt to parse the given User-Agent string as a Gecko-based browser's user-agent. """ identifier = 'Gecko/' start = agentString.find(identifier) if start != -1: end = agentString.find(' ', start) if ...
ValueError
dataset/ETHPy150Open twisted/nevow/nevow/useragent.py/UserAgent.parse_GECKO
7,068
def parse_WEBKIT(cls, agentString): """ Attempt to parse the given User-Agent string as a WebKit-based browser's user-agent. """ identifier = 'WebKit/' start = agentString.find(identifier) if start != -1: end = start + len(identifier) while...
ValueError
dataset/ETHPy150Open twisted/nevow/nevow/useragent.py/UserAgent.parse_WEBKIT
7,069
def parse_OPERA(cls, agentString): """ Attempt to parse an Opera user-agent. """ prefix = 'Opera/' if agentString.startswith(prefix): version = agentString[len(prefix):].split(None, 1)[0] try: version = map(int, version.split('.')) ...
ValueError
dataset/ETHPy150Open twisted/nevow/nevow/useragent.py/UserAgent.parse_OPERA
7,070
def parse_MSIE(cls, agentString): """ Attempt to parse an Internet Explorer user-agent. """ oldPrefix = 'Mozilla/4.0 (compatible; MSIE ' newPrefix = 'Mozilla/5.0 (compatible; MSIE ' for prefix in oldPrefix, newPrefix: if agentString.startswith(prefix): ...
ValueError
dataset/ETHPy150Open twisted/nevow/nevow/useragent.py/UserAgent.parse_MSIE
7,071
def _Exists(self): """Returns true if the service exists.""" show_cmd = [AZURE_PATH, 'service', 'show', '--json', self.name] stdout, _, _ = vm_util.IssueCommand(show_cmd, suppress_warning=True) try: json.loads(stdout) except __HOL...
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/PerfKitBenchmarker/perfkitbenchmarker/providers/azure/azure_virtual_machine.py/AzureService._Exists
7,072
def _Exists(self): """Returns true if the VM exists and attempts to get some data.""" show_cmd = [AZURE_PATH, 'vm', 'show', '--json', self.name] stdout, _, _ = vm_util.IssueCommand(show_cmd, suppress_warning=True) try: json.loads(stdo...
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/PerfKitBenchmarker/perfkitbenchmarker/providers/azure/azure_virtual_machine.py/AzureVirtualMachine._Exists
7,073
def test_logistic_cg(): try: import scipy logistic_cg.cg_optimization_mnist(n_epochs=10) except __HOLE__: from nose.plugins.skip import SkipTest raise SkipTest( 'SciPy not available. Needed for the logistic_cg example.')
ImportError
dataset/ETHPy150Open lisa-lab/DeepLearningTutorials/code/test.py/test_logistic_cg
7,074
def lower_global(self, name, value): """ 1) Check global scope dictionary. 2) Check __builtins__. 2a) is it a dictionary (for non __main__ module) 2b) is it a module (for __main__ module) """ moddict = self.get_module_dict() obj = self.pyapi.dict_g...
TypeError
dataset/ETHPy150Open numba/numba/numba/objmode.py/PyLower.lower_global
7,075
def make_plot(benchmarks, title, adjustment): class Style(DefaultStyle): colors = ["#000000" if row["path"] else DefaultStyle.colors[1] for row in benchmarks] font_family = 'Consolas, "Deja Vu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace' minimum = int(min(...
ImportError
dataset/ETHPy150Open ionelmc/pytest-benchmark/src/pytest_benchmark/histogram.py/make_plot
7,076
def copy_keys_except(dic, *keys): """Return a copy of the dict without the specified items. """ ret = dic.copy() for key in keys: try: del ret[key] except __HOLE__: pass return ret
KeyError
dataset/ETHPy150Open mikeorr/WebHelpers2/webhelpers2/containers.py/copy_keys_except
7,077
def del_keys(dic, *keys): """Delete several keys from a dict, ignoring those that don't exist. This modifies the dict in place. :: >>> d ={"A": 1, "B": 2, "C": 3} >>> del_keys(d, "A", "C") >>> d {'B': 2} """ for key in keys: try: del dic[key...
KeyError
dataset/ETHPy150Open mikeorr/WebHelpers2/webhelpers2/containers.py/del_keys
7,078
def correlate_dicts(dicts, key): """Correlate several dicts under one superdict. If you have several dicts each with a 'name' key, this puts them in a container dict keyed by name. Example:: >>> d1 = {"name": "Fred", "age": 41} >>> d2 = {"name": "Barney", "age": 31} >>> flint...
KeyError
dataset/ETHPy150Open mikeorr/WebHelpers2/webhelpers2/containers.py/correlate_dicts
7,079
def correlate_objects(objects, attr): """Correlate several objects under one dict. If you have several objects each with a 'name' attribute, this puts them in a dict keyed by name. Example:: >>> class Flintstone(DumbObject): ... pass ... >>> fred = Flintstone(name="...
AttributeError
dataset/ETHPy150Open mikeorr/WebHelpers2/webhelpers2/containers.py/correlate_objects
7,080
def run(self, context): try: self.output = self.device.execute(self.command, timeout=self.timeout, check_exit_code=False) except __HOLE__: self.device.killall('dhrystone') raise
KeyboardInterrupt
dataset/ETHPy150Open ARM-software/workload-automation/wlauto/workloads/dhrystone/__init__.py/Dhrystone.run
7,081
def __init__(self, param_info, parent=None): ColorChooserButton.__init__(self, parent) try: r,g,b = [int(float(i) * 255) for i in param_info.value.split(',')] except __HOLE__: r,g,b = (0.0, 0.0, 0.0) self.setColor(QtGui.QColor(r,g,b)) self.setFixedHeight(2...
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/gui/modules/paramexplore.py/PEColorChooserButton.__init__
7,082
def __init__(self, file, align=True, bigendian=True, inclheader=False): import struct self.closed = False self.align = align # whether to align to word (2-byte) boundaries if bigendian: strflag = '>' else: strflag = '<' self.file = fil...
IOError
dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Lib/chunk.py/Chunk.__init__
7,083
def skip(self): """Skip the rest of the chunk. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk. """ if self.closed: raise ValueError, "I/O operation on closed ...
IOError
dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Lib/chunk.py/Chunk.skip
7,084
def check_uid(val): """Return an uid, given a user value. If the value is an integer, make sure it's an existing uid. If the user value is unknown, raises a ValueError. """ if isinstance(val, six.integer_types): try: pwd.getpwuid(val) return val except (KeyEr...
KeyError
dataset/ETHPy150Open benoitc/gaffer/gaffer/util.py/check_uid
7,085
def check_gid(val): """Return a gid, given a group value If the group value is unknown, raises a ValueError. """ if isinstance(val, int): try: grp.getgrgid(val) return val except (__HOLE__, OverflowError): raise ValueError("No such group: %r" % val) ...
KeyError
dataset/ETHPy150Open benoitc/gaffer/gaffer/util.py/check_gid
7,086
def closerange(fd_low, fd_high): # NOQA # Iterate through and close all file descriptors. for fd in range(fd_low, fd_high): try: os.close(fd) except __HOLE__: # ERROR, fd wasn't open to begin with (ignored) pass # http://www.svbug.com/docum...
OSError
dataset/ETHPy150Open benoitc/gaffer/gaffer/util.py/closerange
7,087
def parse_signal_value(sig): if sig is None: raise ValueError("invalid signal") # value passed is a string if isinstance(sig, six.string_types): if sig.isdigit(): # if number in the string, try to parse it try: return int(sig) except Value...
AttributeError
dataset/ETHPy150Open benoitc/gaffer/gaffer/util.py/parse_signal_value
7,088
def upgrade_websocket(self, environ, start_response): """ Attempt to upgrade the socket environ['wsgi.input'] into a websocket enabled connection. """ websocket_version = environ.get('HTTP_SEC_WEBSOCKET_VERSION', '') if not websocket_version: raise UpgradeRequiredErro...
TypeError
dataset/ETHPy150Open jrief/django-websocket-redis/ws4redis/django_runserver.py/WebsocketRunServer.upgrade_websocket
7,089
def testInvalidVisibleColumnIds(self): t = TableGenerator.createTableWithDefaultContainer(3, 10) try: t.setVisibleColumns(['a', 'Property 2', 'Property 3']) self.fail('IllegalArgumentException expected') except __HOLE__: pass # OK, expected self.ass...
ValueError
dataset/ETHPy150Open rwl/muntjac/muntjac/test/server/component/table/table_visible_columns.py/TableVisibleColumns.testInvalidVisibleColumnIds
7,090
def testDuplicateVisibleColumnIds(self): t = TableGenerator.createTableWithDefaultContainer(3, 10) try: t.setVisibleColumns(['Property 0', 'Property 1', 'Property 2', 'Property 1']) # FIXME: Multiple properties in the Object array should be detected ...
ValueError
dataset/ETHPy150Open rwl/muntjac/muntjac/test/server/component/table/table_visible_columns.py/TableVisibleColumns.testDuplicateVisibleColumnIds
7,091
def write_result(self, buf): indent = 0 frame = self.frame _classes = ['dataframe'] # Default class. if self.classes is not None: if isinstance(self.classes, str): self.classes = self.classes.split() if not isinstance(self.classes, (list, tuple))...
ImportError
dataset/ETHPy150Open pydata/pandas/pandas/formats/format.py/HTMLFormatter.write_result
7,092
def detect_console_encoding(): """ Try to find the most capable encoding supported by the console. slighly modified from the way IPython handles the same issue. """ import locale global _initial_defencoding encoding = None try: encoding = sys.stdout.encoding or sys.stdin.encodin...
AttributeError
dataset/ETHPy150Open pydata/pandas/pandas/formats/format.py/detect_console_encoding
7,093
def ask_around(self, service_name, payload, operator=None): """Ask all handlers of a given service name, return list of answers. Handlers connected through the optionally given operator are skipped, so that partyline applications do not call themselves. """ answers = [] ...
KeyError
dataset/ETHPy150Open rduplain/wsgi_party/wsgi_party.py/WSGIParty.ask_around
7,094
def _get_login_token(self, email, password): """ Passes email and password to base api and returns login token. """ auth_url = 'authentication.json' params = urllib.urlencode({ 'email': email, 'password': password, }) try: data...
KeyError
dataset/ETHPy150Open npinger/base-crm-api-client/base_client.py/BaseAPIService._get_login_token
7,095
def update_deal_tags(self, deal_id, tags, action='add'): """ Adds, removes, or relplaces tags for a deal. Returns a json or xml response. Arguments: deal_id: The base id of the deal that we want to work with tags: comma separated string of tags. Eg. 'platinum,trial_period' ...
ValueError
dataset/ETHPy150Open npinger/base-crm-api-client/base_client.py/BaseAPIService.update_deal_tags
7,096
def update_contact_tags(self, contact_id, tags, action='add'): """ Adds, removes, or relplaces tags for a contact. Returns a json or xml response. Arguments: contact_id: The base id of the contact that we want to work with tags: comma separated string of tags. Eg. 'platinum,tria...
ValueError
dataset/ETHPy150Open npinger/base-crm-api-client/base_client.py/BaseAPIService.update_contact_tags
7,097
def dispatch(self, parameterName, value): """ When called in dispatch, do the coerce for C{value} and save the returned value. """ if value is None: raise UsageError("Parameter '%s' requires an argument." % (parameterName,)) try: ...
ValueError
dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/python/usage.py/CoerceParameter.dispatch
7,098
def parseOptions(self, options=None): """ The guts of the command-line parser. """ if options is None: options = sys.argv[1:] # we really do need to place the shell completion check here, because # if we used an opt_shell_completion method then it would be p...
TypeError
dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/python/usage.py/Options.parseOptions
7,099
def main(): parser = ArgumentParser(description='Download videos from some video platforms via http requests using youtube-dl', formatter_class=RawTextHelpFormatter) parser.add_argument('-v', '--version', action='version', version=__version__) parser.add_argument('-u', '--update', action='store_true', help=...
KeyboardInterrupt
dataset/ETHPy150Open r4mos/youtube-dl-simple-server/youtube_dl_simple_server/__init__.py/main