Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
3,600
def Get(self, limit, offset=0): """Get results of the query with a limit on the number of results. Args: limit: maximum number of values to return. offset: offset requested -- if nonzero, this will override the offset in the original query Returns: A list of entities with a...
StopIteration
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/datastore.py/MultiQuery.Get
3,601
def __init__(self, entity_iterator, orderings): """Ctor. Args: entity_iterator: an iterator of entities which will be wrapped. orderings: an iterable of (identifier, order) pairs. order should be either Query.ASCENDING or Query.DESCENDING. """ self.__entity_iterator = ...
StopIteration
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/datastore.py/MultiQuery.SortOrderEntity.__init__
3,602
def __delitem__(self, query_filter): """Delete a filter by deleting it from all subqueries. If a KeyError is raised during the attempt, it is ignored, unless every subquery raised a KeyError. If any other exception is raised, any deletes will be rolled back. Args: query_filter: the filter to...
KeyError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/datastore.py/MultiQuery.__delitem__
3,603
def next(self): if not self.__buffer: self.__buffer = self._Next(self.__batch_size) try: return self.__buffer.pop(0) except __HOLE__: raise StopIteration
IndexError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/datastore.py/Iterator.next
3,604
def has_migration_started(self,): from region_migration.models import DatabaseRegionMigrationDetail try: migration = self.migration.get() except __HOLE__: return False if migration.is_migration_finished(): return False if migration.current_st...
ObjectDoesNotExist
dataset/ETHPy150Open globocom/database-as-a-service/dbaas/logical/models.py/Database.has_migration_started
3,605
def get_field_type(values): """ Determines the type of every item in the value list or dictionary, then consolidates that into a single output type. This is used to determine what type to convert an entire field into - often within a database. Input - a list or dictionar...
TypeError
dataset/ETHPy150Open kenfar/DataGristle/gristle/field_type.py/get_field_type
3,606
def is_string(value): """ Returns True if the value is a string, subject to false-negatives if the string is all numeric. 'b' is True '' is True ' ' is True '$3' is True '4,333' is True '33.22' is False '3' is False '...
ValueError
dataset/ETHPy150Open kenfar/DataGristle/gristle/field_type.py/is_string
3,607
def is_integer(value): """ Returns True if the input consists soley of digits and represents an integer rather than character data or a float. '3' is True '-3' is True 3 is True -3 is True 3.3 is False '33.22' is False ...
TypeError
dataset/ETHPy150Open kenfar/DataGristle/gristle/field_type.py/is_integer
3,608
def is_float(value): """ Returns True if the input consists soley of digits and represents a float rather than character data or an integer. 44.55 is True '33.22' is True 6 is False '3' is False '-3' is False '4,333' is False '$3' is ...
ValueError
dataset/ETHPy150Open kenfar/DataGristle/gristle/field_type.py/is_float
3,609
def is_unknown(value): """ Returns True if the value is a common unknown indicator: '' is True ' ' is True 'na' is True 'NA' is True 'n/a' is True 'N/A' is True 'unk' is True 'unknown' is True '3' is Fal...
TypeError
dataset/ETHPy150Open kenfar/DataGristle/gristle/field_type.py/is_unknown
3,610
def is_timestamp(time_str): """ Determine if arg is a timestamp and if so what format Args: time_str - character string that may be a date, time, epoch or combo Returns: status - True if date/time False if not scope - kind of timestamp pattern - dat...
ValueError
dataset/ETHPy150Open kenfar/DataGristle/gristle/field_type.py/is_timestamp
3,611
def setdefault(self, key, value): """We may not always be connected to an app, but we still need to provide a way to the base environment to set it's defaults. """ try: super(FlaskConfigStorage, self).setdefault(key, value) except __HOLE__: self._defaults....
RuntimeError
dataset/ETHPy150Open miracle2k/flask-assets/src/flask_assets.py/FlaskConfigStorage.setdefault
3,612
def split_prefix(self, ctx, item): """See if ``item`` has blueprint prefix, return (directory, rel_path). """ app = ctx._app try: if hasattr(app, 'blueprints'): blueprint, name = item.split('/', 1) directory = get_static_folder(app.blueprints[b...
ValueError
dataset/ETHPy150Open miracle2k/flask-assets/src/flask_assets.py/FlaskResolver.split_prefix
3,613
def search_for_source(self, ctx, item): # If a load_path is set, use it instead of the Flask static system. # # Note: With only env.directory set, we don't go to default; # Setting env.directory only makes the output directory fixed. if self.use_webassets_system_for_sources(ctx):...
IOError
dataset/ETHPy150Open miracle2k/flask-assets/src/flask_assets.py/FlaskResolver.search_for_source
3,614
def convert_item_to_flask_url(self, ctx, item, filepath=None): """Given a relative reference like `foo/bar.css`, returns the Flask static url. By doing so it takes into account blueprints, i.e. in the aformentioned example, ``foo`` may reference a blueprint. If an absolute path ...
ImportError
dataset/ETHPy150Open miracle2k/flask-assets/src/flask_assets.py/FlaskResolver.convert_item_to_flask_url
3,615
@property def _app(self): """The application object to work with; this is either the app that we have been bound to, or the current application. """ if self.app is not None: return self.app ctx = _request_ctx_stack.top if ctx is not None: retu...
ImportError
dataset/ETHPy150Open miracle2k/flask-assets/src/flask_assets.py/Environment._app
3,616
def get_file(file_name): try: f = open(file_name, "rb") f_content = f.read() f.close() except __HOLE__, e: sys.stderr.write("[-] Error reading file %s.\n" % e) sys.exit(ERR) sys.stdout.write("[+] File is ready and is in memory.\n") return base64.b64encode(f_conten...
IOError
dataset/ETHPy150Open ytisf/PyExfil/pyexfil/pop_exfil_client.py/get_file
3,617
def author_addon_clicked(f): """Decorator redirecting clicks on "Other add-ons by author".""" @functools.wraps(f) def decorated(request, *args, **kwargs): redirect_id = request.GET.get('addons-author-addons-select', None) if not redirect_id: return f(request, *args, **kwargs) ...
ValueError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/addons/views.py/author_addon_clicked
3,618
@addon_valid_disabled_pending_view @non_atomic_requests def addon_detail(request, addon): """Add-ons details page dispatcher.""" if addon.is_deleted or (addon.is_pending() and not addon.is_persona()): # Allow pending themes to be listed. raise http.Http404 if addon.is_disabled: retur...
IndexError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/addons/views.py/addon_detail
3,619
@mobile_template('addons/{mobile/}persona_detail.html') @non_atomic_requests def persona_detail(request, addon, template=None): """Details page for Personas.""" if not (addon.is_public() or addon.is_pending()): raise http.Http404 persona = addon.persona # This persona's categories. categor...
IndexError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/addons/views.py/persona_detail
3,620
def _parse_file_contents(self, selector_file_contents): try: selector_input_json = json.loads(selector_file_contents) except __HOLE__: raise SelectorParseError('MalformedJSON') self._validate_selector_input(selector_input_json) selectors = self._parse_input_for_...
ValueError
dataset/ETHPy150Open m-lab/telescope/telescope/selector.py/SelectorFileParser._parse_file_contents
3,621
def _parse_start_time(self, start_time_string): """Parse the time window start time. Parse the start time from the expected timestamp format to Python datetime format. Must be in UTC time. Args: start_time_string: (str) Timestamp in format YYYY-MM-DDTHH-mm-SS. Retu...
ValueError
dataset/ETHPy150Open m-lab/telescope/telescope/selector.py/SelectorFileParser._parse_start_time
3,622
def _parse_ip_translation(self, ip_translation_dict): """Parse the ip_translation field into an IPTranslationStrategySpec object. Args: ip_translation_dict: (dict) An unprocessed dictionary of ip_translation data from the input selector file. Returns: IP...
KeyError
dataset/ETHPy150Open m-lab/telescope/telescope/selector.py/SelectorFileParser._parse_ip_translation
3,623
@property def last_results(self): """The last result that was produced.""" try: return self.results[-1][0] except __HOLE__: exc.raise_with_cause(exc.NotFound, "Last results not found")
IndexError
dataset/ETHPy150Open openstack/taskflow/taskflow/persistence/models.py/RetryDetail.last_results
3,624
@property def last_failures(self): """The last failure dictionary that was produced. NOTE(harlowja): This is **not** the same as the local ``failure`` attribute as the obtained failure dictionary in the ``results`` attribute (which is what this returns) is from associated at...
IndexError
dataset/ETHPy150Open openstack/taskflow/taskflow/persistence/models.py/RetryDetail.last_failures
3,625
def atom_detail_class(atom_type): try: return _NAME_TO_DETAIL[atom_type] except __HOLE__: raise TypeError("Unknown atom type '%s'" % (atom_type))
KeyError
dataset/ETHPy150Open openstack/taskflow/taskflow/persistence/models.py/atom_detail_class
3,626
def atom_detail_type(atom_detail): try: return _DETAIL_TO_NAME[type(atom_detail)] except __HOLE__: raise TypeError("Unknown atom '%s' (%s)" % (atom_detail, type(atom_detail)))
KeyError
dataset/ETHPy150Open openstack/taskflow/taskflow/persistence/models.py/atom_detail_type
3,627
def handle_noargs(self, develop, **options): call_command('sync_and_migrate') try: from molly.wurfl import wurfl_data except __HOLE__: no_wurfl = True else: no_wurfl = False if no_wurfl or not develop: call_command('update_wurfl') ...
ImportError
dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/management/commands/deploy.py/Command.handle_noargs
3,628
def _main(): import re import sys args = sys.argv[1:] inFileName = args and args[0] or "Include/token.h" outFileName = "Lib/token.py" if len(args) > 1: outFileName = args[1] try: fp = open(inFileName) except IOError as err: sys.stdout.write("I/O error: %s\n" % str...
IOError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/token.py/_main
3,629
def is_valid_url(uri): try: urlvalidate(uri) except __HOLE__: return False return True
ValidationError
dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/main/models/meta_data.py/is_valid_url
3,630
def _set_hash(self): if not self.data_file: return None file_exists = self.data_file.storage.exists(self.data_file.name) if (file_exists and self.data_file.name != '') \ or (not file_exists and self.data_file): try: self.data_file.seek(os...
IOError
dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/main/models/meta_data.py/MetaData._set_hash
3,631
def setUp(self): super(GRRBaseTest, self).setUp() tmpdir = os.environ.get("TEST_TMPDIR") or config_lib.CONFIG["Test.tmpdir"] # Make a temporary directory for test files. self.temp_dir = tempfile.mkdtemp(dir=tmpdir) config_lib.CONFIG.SetWriteBack( os.path.join(self.temp_dir, "writeback.yam...
AttributeError
dataset/ETHPy150Open google/grr/grr/lib/test_lib.py/GRRBaseTest.setUp
3,632
def run(self, result=None): # pylint: disable=g-bad-name """Run the test case. This code is basically the same as the standard library, except that when there is an exception, the --debug flag allows us to drop into the raising function for interactive inspection of the test failure. Args: ...
KeyboardInterrupt
dataset/ETHPy150Open google/grr/grr/lib/test_lib.py/GRRBaseTest.run
3,633
def RunForTimeWithNoExceptions(self, cmd, argv, timeout=10, should_exit=False, check_exit_code=False): """Run a command line argument and check for python exceptions raised. Args: cmd: The command to run as a string. argv: The args. timeout: How long to let th...
OSError
dataset/ETHPy150Open google/grr/grr/lib/test_lib.py/GRRBaseTest.RunForTimeWithNoExceptions
3,634
def _GetActionInstance(self, action_name, arg=None, grr_worker=None, action_worker_cls=None): """Run an action and generate responses. This basically emulates GRRClientWorker.HandleMessage(). Args: action_name: The action to run. arg: A protobuf to pass the action. ...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/test_lib.py/EmptyActionTest._GetActionInstance
3,635
def Start(self): for k, v in self._overrides.iteritems(): self._saved_values[k] = config_lib.CONFIG.Get(k) try: config_lib.CONFIG.Set.old_target(k, v) except __HOLE__: config_lib.CONFIG.Set(k, v)
AttributeError
dataset/ETHPy150Open google/grr/grr/lib/test_lib.py/ConfigOverrider.Start
3,636
def Stop(self): for k, v in self._saved_values.iteritems(): try: config_lib.CONFIG.Set.old_target(k, v) except __HOLE__: config_lib.CONFIG.Set(k, v)
AttributeError
dataset/ETHPy150Open google/grr/grr/lib/test_lib.py/ConfigOverrider.Stop
3,637
def __enter__(self): self.old_datetime = datetime.datetime class FakeDateTime(object): def __init__(self, time_val, increment, orig_datetime): self.time = time_val self.increment = increment self.orig_datetime = orig_datetime def __getattribute__(self, name): try: ...
AttributeError
dataset/ETHPy150Open google/grr/grr/lib/test_lib.py/FakeDateTimeUTC.__enter__
3,638
def _FindElement(self, selector): try: selector_type, effective_selector = selector.split("=", 1) except __HOLE__: effective_selector = selector selector_type = None if selector_type == "css": elems = self.driver.execute_script( "return $(\"" + effective_selector.replace("...
ValueError
dataset/ETHPy150Open google/grr/grr/lib/test_lib.py/GRRSeleniumTest._FindElement
3,639
def loadTestsFromName(self, name, module=None): """Load the tests named.""" parts = name.split(".") try: test_cases = self.loadTestsFromTestCase(self.base_class.classes[parts[0]]) except __HOLE__: raise RuntimeError("Unable to find test %r - is it registered?" % name) # Specifies the wh...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/test_lib.py/GRRTestLoader.loadTestsFromName
3,640
def __init__(self, run, stdout, stderr, stdin, env=None): _ = env Popen.running_args = run Popen.stdout = stdout Popen.stderr = stderr Popen.stdin = stdin Popen.returncode = 0 try: # Store the content of the executable file. Popen.binary = open(run[0]).read() except __HOLE__...
IOError
dataset/ETHPy150Open google/grr/grr/lib/test_lib.py/Popen.__init__
3,641
def CheckFlowErrors(total_flows, token=None): # Check that all the flows are complete. for session_id in total_flows: try: flow_obj = aff4.FACTORY.Open(session_id, aff4_type="GRRFlow", mode="r", token=token) except __HOLE__: continue if flow_obj.state.cont...
IOError
dataset/ETHPy150Open google/grr/grr/lib/test_lib.py/CheckFlowErrors
3,642
def GetProfileByName(self, profile_name, version="v1.0"): try: profile_data = open(os.path.join( config_lib.CONFIG["Test.data_dir"], "profiles", version, profile_name + ".gz"), "rb").read() self.profiles_served += 1 return rdf_rekall_types.RekallProfile(name=profile_name, ...
IOError
dataset/ETHPy150Open google/grr/grr/lib/test_lib.py/TestRekallRepositoryProfileServer.GetProfileByName
3,643
def get_prog(): try: if os.path.basename(sys.argv[0]) in ('__main__.py', '-c'): return "%s -m pip" % sys.executable except (__HOLE__, TypeError, IndexError): pass return 'pip'
AttributeError
dataset/ETHPy150Open balanced/status.balancedpayments.com/venv/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg/pip/util.py/get_prog
3,644
def renames(old, new): """Like os.renames(), but handles renaming across devices.""" # Implementation borrowed from os.renames(). head, tail = os.path.split(new) if head and tail and not os.path.exists(head): os.makedirs(head) shutil.move(old, new) head, tail = os.path.split(old) i...
OSError
dataset/ETHPy150Open balanced/status.balancedpayments.com/venv/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg/pip/util.py/renames
3,645
def untar_file(filename, location): """Untar the file (tar file located at filename) to the destination location""" if not os.path.exists(location): os.makedirs(location) if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'): mode = 'r:gz' elif filename.lower().endswit...
KeyError
dataset/ETHPy150Open balanced/status.balancedpayments.com/venv/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg/pip/util.py/untar_file
3,646
def ReadMatrix(file, separator="\t", numeric_type=numpy.float, take="all", headers=False ): """read a matrix. There probably is a routine for this in Numpy, which I haven't found yet. """ lines = filter(lambda x: x[0] != "#", fi...
ValueError
dataset/ETHPy150Open CGATOxford/cgat/CGAT/MatlabTools.py/ReadMatrix
3,647
def readMatrix(infile, format="full", separator="\t", numeric_type=numpy.float, take="all", headers=True, missing=None, ): """read a matrix from file ane return a numpy matrix. formats accepted are: * f...
IndexError
dataset/ETHPy150Open CGATOxford/cgat/CGAT/MatlabTools.py/readMatrix
3,648
def main(): parser = argparse.ArgumentParser() parser.add_argument('-d', '--delay', type=int, default=0) args = parser.parse_args() if sys.stdin.isatty(): parser.error('no input, pipe another btc command output into this command') torrents = sys.stdin.read() if len(torrents.strip()) ==...
ValueError
dataset/ETHPy150Open bittorrent/btc/btc/btc_stop.py/main
3,649
def initlog(*allargs): """Write a log message, if there is a log file. Even though this function is called initlog(), you should always use log(); log is a variable that is set either to initlog (initially), to dolog (once the log file has been opened), or to nolog (when logging is disabled). ...
IOError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/cgi.py/initlog
3,650
def parse_multipart(fp, pdict): """Parse multipart input. Arguments: fp : input file pdict: dictionary containing other parameters of content-type header Returns a dictionary just like parse_qs(): keys are the field names, each value is a list of values for that field. This is easy to use b...
ValueError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/cgi.py/parse_multipart
3,651
def __init__(self, fp=None, headers=None, outerboundary="", environ=os.environ, keep_blank_values=0, strict_parsing=0): """Constructor. Read multipart/* until last part. Arguments, all optional: fp : file pointer; default: sys.stdin (not used when the...
ValueError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/cgi.py/FieldStorage.__init__
3,652
def __getitem__(self, key): v = SvFormContentDict.__getitem__(self, key) if v[0] in '0123456789+-.': try: return int(v) except __HOLE__: try: return float(v) except ValueError: pass return v.strip()
ValueError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/cgi.py/InterpFormContentDict.__getitem__
3,653
def values(self): result = [] for key in self.keys(): try: result.append(self[key]) except __HOLE__: result.append(self.dict[key]) return result
IndexError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/cgi.py/InterpFormContentDict.values
3,654
def items(self): result = [] for key in self.keys(): try: result.append((key, self[key])) except __HOLE__: result.append((key, self.dict[key])) return result
IndexError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/cgi.py/InterpFormContentDict.items
3,655
def GetHashDigest(filename): """ Get the sha1 digest of `filename`)""" try: fp = open(filename, mode='rb') digest = hashlib.sha1(fp.read()).hexdigest() fp.close() return digest except __HOLE__ as e: sys.stderr.write(str(e)) sys.exit(1) return
IOError
dataset/ETHPy150Open spranesh/Redhawk/redhawk/utils/util.py/GetHashDigest
3,656
def GuessLanguage(filename): """ Attempts to Guess Langauge of `filename`. Essentially, we do a filename.rsplit('.', 1), and a lookup into a dictionary of extensions.""" try: (_, extension) = filename.rsplit('.', 1) except __HOLE__: raise ValueError("Could not guess language as '%s' does not have an \ ...
ValueError
dataset/ETHPy150Open spranesh/Redhawk/redhawk/utils/util.py/GuessLanguage
3,657
def StartShell(local_vars, banner='', try_ipython=True): """ Start a shell, with the given local variables. It prints the given banner as a welcome message.""" def IPythonShell(namespace, banner): from IPython.Shell import IPShell ipshell = IPShell(user_ns = namespace) ipshell.mainloop(banner=banner)...
ImportError
dataset/ETHPy150Open spranesh/Redhawk/redhawk/utils/util.py/StartShell
3,658
def get_from_clause(self): """ Returns a list of strings that are joined together to go after the "FROM" part of the query, as well as a list any extra parameters that need to be included. Sub-classes, can override this to create a from-clause via a "select". This should...
KeyError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/addons/query.py/IndexCompiler.get_from_clause
3,659
def inlines(value, return_list=False): try: from BeautifulSoup import BeautifulStoneSoup except __HOLE__: from beautifulsoup import BeautifulStoneSoup content = BeautifulStoneSoup(value, selfClosingTags=['inline', 'img', 'br', 'input'...
ImportError
dataset/ETHPy150Open pigmonkey/django-inlineobjects/inlines/parser.py/inlines
3,660
def render_inline(inline): """ Replace inline markup with template markup that matches the appropriate app and model. """ # Look for inline type, 'app.model' try: app_label, model_name = inline['type'].split('.') except: if settings.DEBUG: raise TemplateSyntaxErr...
KeyError
dataset/ETHPy150Open pigmonkey/django-inlineobjects/inlines/parser.py/render_inline
3,661
def get_user_model(): """ Get the user model that is being used. If the `get_user_model` method is not available, default back to the standard User model provided through `django.contrib.auth`. """ try: from django.contrib.auth import get_user_model return get_user_mod...
ImportError
dataset/ETHPy150Open Rediker-Software/doac/doac/compat.py/get_user_model
3,662
def test_bad_traceback(self): result = "JJackson's SSN: 555-55-5555" try: # copied from couchdbkit/client.py assert isinstance(result, dict), 'received an invalid ' \ 'response of type %s: %s' % (type(result), repr(result)) except __HOLE__ as e: ...
AssertionError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/util/tests/test_log.py/TestLogging.test_bad_traceback
3,663
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 timothycrosley/jiphy/jiphy/pie_slice.py/OrderedDict.__init__
3,664
def load_config_file(self, suppress_errors=True): """Load the config file. By default, errors in loading config are handled, and a warning printed on screen. For testing, the suppress_errors option is set to False, so errors will make tests fail. """ base_config = 'ipyth...
IOError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/core/application.py/BaseIPythonApplication.load_config_file
3,665
def init_profile_dir(self): """initialize the profile dir""" try: # location explicitly specified: location = self.config.ProfileDir.location except __HOLE__: # location not specified, find by profile name try: p = ProfileDir.find_p...
AttributeError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/core/application.py/BaseIPythonApplication.init_profile_dir
3,666
@property def env(self): raw_env = self.settings['raw_env'].get() env = {} if not raw_env: return env for e in raw_env: s = _compat.bytes_to_str(e) try: k, v = s.split('=', 1) except __HOLE__: raise Run...
ValueError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/gunicorn/config.py/Config.env
3,667
def validate_callable(arity): def _validate_callable(val): if isinstance(val, six.string_types): try: mod_name, obj_name = val.rsplit(".", 1) except __HOLE__: raise TypeError("Value '%s' is not import string. " "Format: ...
ValueError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/gunicorn/config.py/validate_callable
3,668
def validate_user(val): if val is None: return os.geteuid() if isinstance(val, int): return val elif val.isdigit(): return int(val) else: try: return pwd.getpwnam(val).pw_uid except __HOLE__: raise ConfigError("No such user: '%s'" % val)
KeyError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/gunicorn/config.py/validate_user
3,669
def validate_group(val): if val is None: return os.getegid() if isinstance(val, int): return val elif val.isdigit(): return int(val) else: try: return grp.getgrnam(val).gr_gid except __HOLE__: raise ConfigError("No such group: '%s'" % val)
KeyError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/gunicorn/config.py/validate_group
3,670
def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0, link=None, verbose=1, dry_run=0): """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is copied there with the same name; otherwise, it must be a filename. (If the file exists, it will be ruthlessly clobb...
KeyError
dataset/ETHPy150Open ctxis/canape/CANAPE.Scripting/Lib/distutils/file_util.py/copy_file
3,671
def main(): """ azurectl - invoke the Application """ docopt.__dict__['extras'] = extras logger.init() try: App() except AzureError as e: # known exception, log information and exit logger.log.error('%s: %s', type(e).__name__, format(e)) sys.exit(1) ex...
SystemExit
dataset/ETHPy150Open SUSE/azurectl/azurectl/azurectl.py/main
3,672
def _delete_conntrack_state(self, device_info_list, rule, remote_ip=None): conntrack_cmds = self._get_conntrack_cmds(device_info_list, rule, remote_ip) for cmd in conntrack_cmds: try: self.execute(list(cmd), run_as_root=True, ...
RuntimeError
dataset/ETHPy150Open openstack/neutron/neutron/agent/linux/ip_conntrack.py/IpConntrackManager._delete_conntrack_state
3,673
def _to_int_with_arithmetics(self, item): item = str(item) try: return int(item) except __HOLE__: return int(eval(item))
ValueError
dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/running/keywords.py/ForLoop._to_int_with_arithmetics
3,674
def get_all_layers(layer, treat_as_input=None): """ This function gathers all layers below one or more given :class:`Layer` instances, including the given layer(s). Its main use is to collect all layers of a network just given the output layer(s). The layers are guaranteed to be returned in a topolo...
TypeError
dataset/ETHPy150Open Lasagne/Lasagne/lasagne/layers/helper.py/get_all_layers
3,675
def get_output(layer_or_layers, inputs=None, **kwargs): """ Computes the output of the network at one or more given layers. Optionally, you can define the input(s) to propagate through the network instead of using the input variable(s) associated with the network's input layer(s). Parameters ...
TypeError
dataset/ETHPy150Open Lasagne/Lasagne/lasagne/layers/helper.py/get_output
3,676
def get_output_shape(layer_or_layers, input_shapes=None): """ Computes the output shape of the network at one or more given layers. Parameters ---------- layer_or_layers : Layer or list the :class:`Layer` instance for which to compute the output shapes, or a list of :class:`Layer` i...
TypeError
dataset/ETHPy150Open Lasagne/Lasagne/lasagne/layers/helper.py/get_output_shape
3,677
def main(): #args = GetArgs() try: si = None try: print "Trying to connect to VCENTER SERVER . . ." si = connect.Connect(inputs['vcenter_ip'], 443, inputs['vcenter_user'], inputs['vcenter_password']) except __HOLE__, e: pass atexit.register...
IOError
dataset/ETHPy150Open rreubenur/vmware-pyvmomi-examples/network_configure.py/main
3,678
def loadTagDict(dirPath): d = {} try: files = os.listdir(dirPath) except __HOLE__: return {} for path in files: # ignore hidden files if path.startswith('.'): continue c = TagFile(os.path.join(dirPath, path)) d[c.tag] = c return d
OSError
dataset/ETHPy150Open sassoftware/conary/conary/build/tags.py/loadTagDict
3,679
def get_sd_auth(val, sd_auth_pillar_name='serverdensity'): ''' Returns requested Server Density authentication value from pillar. CLI Example: .. code-block:: bash salt '*' serverdensity_device.get_sd_auth <val> ''' sd_pillar = __pillar__.get(sd_auth_pillar_name) log.debug('Server...
KeyError
dataset/ETHPy150Open saltstack/salt/salt/modules/serverdensity_device.py/get_sd_auth
3,680
def create(name, **params): ''' Function to create device in Server Density. For more info, see the `API docs`__. .. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating CLI Example: .. code-block:: bash salt '*' serverdensity_device.create lama salt '*' serverden...
ValueError
dataset/ETHPy150Open saltstack/salt/salt/modules/serverdensity_device.py/create
3,681
def delete(device_id): ''' Delete a device from Server Density. For more information, see the `API docs`__. .. __: https://apidocs.serverdensity.com/Inventory/Devices/Deleting CLI Example: .. code-block:: bash salt '*' serverdensity_device.delete 51f7eafcdba4bb235e000ae4 ''' ...
ValueError
dataset/ETHPy150Open saltstack/salt/salt/modules/serverdensity_device.py/delete
3,682
def ls(**params): ''' List devices in Server Density Results will be filtered by any params passed to this function. For more information, see the API docs on listing_ and searching_. .. _listing: https://apidocs.serverdensity.com/Inventory/Devices/Listing .. _searching: https://apidocs.server...
ValueError
dataset/ETHPy150Open saltstack/salt/salt/modules/serverdensity_device.py/ls
3,683
def update(device_id, **params): ''' Updates device information in Server Density. For more information see the `API docs`__. .. __: https://apidocs.serverdensity.com/Inventory/Devices/Updating CLI Example: .. code-block:: bash salt '*' serverdensity_device.update 51f7eafcdba4bb235e0...
ValueError
dataset/ETHPy150Open saltstack/salt/salt/modules/serverdensity_device.py/update
3,684
def get_win_certfile(): global _wincerts if _wincerts is not None: return _wincerts.name try: from wincertstore import CertFile except __HOLE__: return None class MyCertFile(CertFile): def __init__(self, stores=(), certs=()): CertFile.__init__(self) ...
ImportError
dataset/ETHPy150Open GeekTrainer/Flask/Work/Trivia - Module 5/env/Lib/site-packages/setuptools/ssl_support.py/get_win_certfile
3,685
def find_ca_bundle(): """Return an existing CA bundle path, or None""" if os.name=='nt': return get_win_certfile() else: for cert_path in cert_paths: if os.path.isfile(cert_path): return cert_path try: return pkg_resources.resource_filename('certifi', ...
ImportError
dataset/ETHPy150Open GeekTrainer/Flask/Work/Trivia - Module 5/env/Lib/site-packages/setuptools/ssl_support.py/find_ca_bundle
3,686
def profileFormulaMenuCommand(cntlr): # save DTS menu item has been invoked if cntlr.modelManager is None or cntlr.modelManager.modelXbrl is None: cntlr.addToLog("No taxonomy loaded.") return # get file name into which to save log file while in foreground thread profileReportFile = cntl...
ValueError
dataset/ETHPy150Open Arelle/Arelle/arelle/plugin/profileFormula.py/profileFormulaMenuCommand
3,687
def _check_extension(self, extension): """Checks for required methods in extension objects.""" try: LOG.debug('Ext name: %s', extension.get_name()) LOG.debug('Ext alias: %s', extension.get_alias()) LOG.debug('Ext description: %s', extension.get_description()) ...
AttributeError
dataset/ETHPy150Open openstack/neutron/neutron/api/extensions.py/ExtensionManager._check_extension
3,688
def get_plugin_supported_extension_aliases(self, plugin): """Return extension aliases supported by a given plugin""" aliases = set() # we also check all classes that the plugins inherit to see if they # directly provide support for an extension for item in [plugin] + plugin.__cla...
TypeError
dataset/ETHPy150Open openstack/neutron/neutron/api/extensions.py/PluginAwareExtensionManager.get_plugin_supported_extension_aliases
3,689
def get_extensions_path(service_plugins=None): paths = collections.OrderedDict() # Add Neutron core extensions paths[neutron.extensions.__path__[0]] = 1 if service_plugins: # Add Neutron *-aas extensions for plugin in service_plugins.values(): neutron_mod = provider_configur...
AttributeError
dataset/ETHPy150Open openstack/neutron/neutron/api/extensions.py/get_extensions_path
3,690
def authenticate(self, username, password): user = None # try Debian PAM module (PyPAM) try: auth = PAM.pam() # pam callback def pam_conv(auth, query_list, userData): response = [] for i in range(len(query_list)): ...
NameError
dataset/ETHPy150Open claudyus/LXC-Web-Panel/lwp/authenticators/pam.py/pam.authenticate
3,691
def updateLabelWidget(self): try: self.myInteractionProgressBar.setVisible(False) self.parent.labelWidget.repaint() except __HOLE__: pass
IndexError
dataset/ETHPy150Open ilastik/ilastik-0.5/ilastik/modules/classification/gui/guiThreads.py/ClassificationInteractive.updateLabelWidget
3,692
def send(self, response_decoder=None): """ Creates and sends a request to the OAuth server, decodes the response and returns the resulting token object. response_decoder - A custom callable can be supplied to override the default method of extracting AccessToken parame...
HTTPError
dataset/ETHPy150Open ryanhorn/tyoiOAuth2/tyoi/oauth2/__init__.py/AccessTokenRequest.send
3,693
def try_utf8_decode(value): """Try to decode an object. :param value: :return: """ if not is_string(value): return value elif PYTHON3 and not isinstance(value, bytes): return value elif not PYTHON3 and not isinstance(value, unicode): return value try: re...
AttributeError
dataset/ETHPy150Open eandersson/amqpstorm/amqpstorm/compatibility.py/try_utf8_decode
3,694
def joined(self, a, b): """ Returns True if a and b are members of the same set. """ mapping = self._mapping try: return mapping[a] is mapping[b] except __HOLE__: return False
KeyError
dataset/ETHPy150Open tanghaibao/jcvi/utils/grouper.py/Grouper.joined
3,695
def match(self, response): try: self._actual = response.json except __HOLE__: self._actual = json.loads(response.data) return self._actual == self._expected
AttributeError
dataset/ETHPy150Open obmarg/flask-should-dsl/flask_should_dsl/matchers.py/JsonMatcher.match
3,696
def __call__(self, *pargs): if len(pargs) == 1: # One argument - this is either just the header name, # or the full header text expected = pargs[0].split(':') elif len(pargs) == 2: # Two arguments - should be header name & header value expected...
IndexError
dataset/ETHPy150Open obmarg/flask-should-dsl/flask_should_dsl/matchers.py/HeaderMatcher.__call__
3,697
def global_env(): """Gets the global Elo environment.""" try: global_env.__elo__ except __HOLE__: # setup the default environment setup() return global_env.__elo__
AttributeError
dataset/ETHPy150Open sublee/elo/elo.py/global_env
3,698
@handle_request_errors def run(self): params = self.args.get('<params>') if params == '-': params = sys.stdin.read() body = json.loads(params) try: timeout = float(self.args.get('--timeout')) except __HOLE__: print("--timeout requires a num...
ValueError
dataset/ETHPy150Open deliveryhero/lymph/lymph/cli/request.py/RequestCommand.run
3,699
def download(self): self._printStartDownloadMessage() response = requests.get(self.url, stream=True) response.raise_for_status() try: contentLength = int(response.headers['content-length']) self.fileSize = contentLength except __HOLE__: # chunk...
KeyError
dataset/ETHPy150Open ga4gh/server/scripts/utils.py/HttpFileDownloader.download