Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
4,400
def verifyFileOnlyWritableByMunkiAndRoot(file_path): """ Check the permissions on a given file path; fail if owner or group does not match the munki process (default: root/admin) or the group is not 'wheel', or if other users are able to write to the file. This prevents escalated execution of arbitr...
OSError
dataset/ETHPy150Open munki/munki/code/client/munkilib/utils.py/verifyFileOnlyWritableByMunkiAndRoot
4,401
def runExternalScript(script, allow_insecure=False, script_args=()): """Run a script (e.g. preflight/postflight) and return its exit status. Args: script: string path to the script to execute. allow_insecure: bool skip the permissions check of executable. args: args to pass to the script. ...
OSError
dataset/ETHPy150Open munki/munki/code/client/munkilib/utils.py/runExternalScript
4,402
def getPIDforProcessName(processname): '''Returns a process ID for processname''' cmd = ['/bin/ps', '-eo', 'pid=,command='] try: proc = subprocess.Popen(cmd, shell=False, bufsize=-1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr...
ValueError
dataset/ETHPy150Open munki/munki/code/client/munkilib/utils.py/getPIDforProcessName
4,403
def _parse_white_list_from_config(self, whitelists): """Parse and validate the pci whitelist from the nova config.""" specs = [] for jsonspec in whitelists: try: dev_spec = jsonutils.loads(jsonspec) except __HOLE__: raise exception.PciConfi...
ValueError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/pci/whitelist.py/Whitelist._parse_white_list_from_config
4,404
def _get_model_from_node(self, node, attr): """ Helper to look up a model from a <object model=...> or a <field rel=... to=...> node. """ model_identifier = node.getAttribute(attr) if not model_identifier: raise base.DeserializationError( "<%s>...
TypeError
dataset/ETHPy150Open dcramer/django-compositepks/django/core/serializers/xml_serializer.py/Deserializer._get_model_from_node
4,405
def _subjectAltNameString(self): method = _lib.X509V3_EXT_get(self._extension) if method == _ffi.NULL: # TODO: This is untested. _raise_current_error() payload = self._extension.value.data length = self._extension.value.length payloadptr = _ffi.new("unsig...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pyopenssl/OpenSSL/crypto.py/X509Extension._subjectAltNameString
4,406
def get_tests(app_module): try: app_path = app_module.__name__.split('.')[:-1] test_module = __import__('.'.join(app_path + [TEST_MODULE]), {}, {}, TEST_MODULE) except __HOLE__, e: # Couldn't import tests.py. Was it due to a missing file, or # due to an import error in a tests.py...
ImportError
dataset/ETHPy150Open dcramer/django-compositepks/django/test/simple.py/get_tests
4,407
def build_suite(app_module): "Create a complete Django test suite for the provided application module" suite = unittest.TestSuite() # Load unit and doctests in the models.py module. If module has # a suite() method, use it. Otherwise build the test suite ourselves. if hasattr(app_module, 'suite...
ValueError
dataset/ETHPy150Open dcramer/django-compositepks/django/test/simple.py/build_suite
4,408
def build_test(label): """Construct a test case a test with the specified label. Label should be of the form model.TestClass or model.TestClass.test_method. Returns an instantiated test or test suite corresponding to the label provided. """ parts = label.split('.') if len(parts) < 2 or...
TypeError
dataset/ETHPy150Open dcramer/django-compositepks/django/test/simple.py/build_test
4,409
def organize_commands(corrected_commands): """Yields sorted commands without duplicates. :type corrected_commands: Iterable[thefuck.types.CorrectedCommand] :rtype: Iterable[thefuck.types.CorrectedCommand] """ try: first_command = next(corrected_commands) yield first_command exc...
StopIteration
dataset/ETHPy150Open nvbn/thefuck/thefuck/corrector.py/organize_commands
4,410
def __call__(self, environ, start_response): request_path = environ.get('PATH_INFO', '') # check if the request is for static files at all path_parts = request_path.strip('/').split('/', 2) if len(path_parts) == 3 and path_parts[0] in ['play', 'game-meta']: slug = path_part...
OSError
dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/middleware/static_game_files.py/StaticGameFilesMiddleware.__call__
4,411
def reload_qt(): """ Reload the Qt bindings. If the QT_API environment variable has been updated, this will load the new Qt bindings given by this variable. This should be used instead of the build-in ``reload`` function because the latter can in some cases cause issues with the ImportDenier (w...
ImportError
dataset/ETHPy150Open glue-viz/glue/glue/external/qt.py/reload_qt
4,412
def patch_loadui(): # In PySide, loadUi does not exist, so we define it using QUiLoader, and # then make sure we expose that function. This is based on the solution at # # https://gist.github.com/cpbotha/1b42a20c8f3eb9bb7cb8 # # which was released under the MIT license: # # Copyright (c...
KeyError
dataset/ETHPy150Open glue-viz/glue/glue/external/qt.py/patch_loadui
4,413
def code_changed(): global _mtimes, _win filenames = [] for m in list(sys.modules.values()): try: filenames.append(m.__file__) except __HOLE__: pass for filename in filenames + _error_files: if not filename: continue if filename.endswit...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/utils/autoreload.py/code_changed
4,414
def check_errors(fn): def wrapper(*args, **kwargs): try: fn(*args, **kwargs) except (ImportError, IndentationError, __HOLE__, SyntaxError, TypeError, AttributeError): et, ev, tb = sys.exc_info() if getattr(ev, 'filename', None) is None: ...
NameError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/utils/autoreload.py/check_errors
4,415
def python_reloader(main_func, args, kwargs): if os.environ.get("RUN_MAIN") == "true": thread.start_new_thread(main_func, args, kwargs) try: reloader_thread() except KeyboardInterrupt: pass else: try: exit_code = restart_with_reloader() ...
KeyboardInterrupt
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/utils/autoreload.py/python_reloader
4,416
def __init__(self, host='localhost', port=6379, password=None, default_timeout=300, key_prefix=None): BaseCache.__init__(self, default_timeout) if isinstance(host, basestring): try: import redis except __HOLE__: raise RuntimeError(...
ImportError
dataset/ETHPy150Open jojoin/cutout/cutout/cache/rediscache.py/RedisCache.__init__
4,417
def load_object(self, value): """The reversal of :meth:`dump_object`. This might be callde with None. """ if value is None: return None if value.startswith('!'): return pickle.loads(value[1:]) try: return int(value) except __HO...
ValueError
dataset/ETHPy150Open jojoin/cutout/cutout/cache/rediscache.py/RedisCache.load_object
4,418
def _watch_workers(self, check_interval=5): keep_running = True while keep_running: self._start_workers() try: try: sleep(check_interval) self._reap_workers() except self.Stop: logger.deb...
OSError
dataset/ETHPy150Open momyc/gevent-fastcgi/gevent_fastcgi/server.py/FastCGIServer._watch_workers
4,419
def _kill_workers(self, kill_timeout=2): for pid, sig in self._killing_sequence(kill_timeout): try: logger.debug( 'Killing worker {0} with signal {1}'.format(pid, sig)) os.kill(pid, sig) except __HOLE__, x: if x.errno ==...
OSError
dataset/ETHPy150Open momyc/gevent-fastcgi/gevent_fastcgi/server.py/FastCGIServer._kill_workers
4,420
def _remove_socket_file(self): socket_file = self.__dict__.pop('_socket_file', None) if socket_file: try: logger.debug('Removing socket-file {0}'.format(socket_file)) os.unlink(socket_file) except __HOLE__: logger.exception( ...
OSError
dataset/ETHPy150Open momyc/gevent-fastcgi/gevent_fastcgi/server.py/FastCGIServer._remove_socket_file
4,421
def _align_to_newline(self): "Aligns the file object's position to the next newline." fo, bsize = self._file_obj, self._blocksize cur, total_read = '', 0 cur_pos = fo.tell() while '\n' not in cur: cur = fo.read(bsize) total_read += bsize try: ...
ValueError
dataset/ETHPy150Open mahmoud/boltons/boltons/jsonutils.py/JSONLIterator._align_to_newline
4,422
def _main(): import sys if '-h' in sys.argv or '--help' in sys.argv: print('loads one or more JSON Line files for basic validation.') return verbose = False if '-v' in sys.argv or '--verbose' in sys.argv: verbose = True file_count, obj_count = ...
ValueError
dataset/ETHPy150Open mahmoud/boltons/boltons/jsonutils.py/_main
4,423
def most_recent(self): """ Returns the most recent copy of the instance available in the history. """ if not self.instance: raise TypeError("Can't use most_recent() without a %s instance." % self.model._meta.object_name) tmp = [] fo...
IndexError
dataset/ETHPy150Open treyhunner/django-simple-history/simple_history/manager.py/HistoryManager.most_recent
4,424
def as_of(self, date): """Get a snapshot as of a specific date. Returns an instance, or an iterable of the instances, of the original model with all the attributes set according to what was present on the object on the date provided. """ if not self.instance: ...
IndexError
dataset/ETHPy150Open treyhunner/django-simple-history/simple_history/manager.py/HistoryManager.as_of
4,425
def codepoints_to_string(xc, p, contextItem, args): if len(args) != 1: raise XPathContext.FunctionNumArgs() try: return ''.join(chr(c) for c in args[0]) except __HOLE__: XPathContext.FunctionArgType(1,"xs:integer*")
TypeError
dataset/ETHPy150Open Arelle/Arelle/arelle/FunctionFn.py/codepoints_to_string
4,426
def substring_functions(xc, args, contains=None, startEnd=None, beforeAfter=None): if len(args) == 3: raise fnFunctionNotAvailable() if len(args) != 2: raise XPathContext.FunctionNumArgs() string = stringArg(xc, args, 0, "xs:string?") portion = stringArg(xc, args, 1, "xs:string") if contains == True...
ValueError
dataset/ETHPy150Open Arelle/Arelle/arelle/FunctionFn.py/substring_functions
4,427
def avg(xc, p, contextItem, args): if len(args) != 1: raise XPathContext.FunctionNumArgs() addends = xc.atomize( p, args[0] ) try: l = len(addends) if l == 0: return () # xpath allows empty sequence argument hasFloat = False hasDecimal = False for a in a...
TypeError
dataset/ETHPy150Open Arelle/Arelle/arelle/FunctionFn.py/avg
4,428
def fn_max(xc, p, contextItem, args): if len(args) != 1: raise XPathContext.FunctionNumArgs() comparands = xc.atomize( p, args[0] ) try: if len(comparands) == 0: return () # xpath allows empty sequence argument if any(isinstance(c, float) and math.isnan(c) for c in comparands):...
TypeError
dataset/ETHPy150Open Arelle/Arelle/arelle/FunctionFn.py/fn_max
4,429
def fn_min(xc, p, contextItem, args): if len(args) != 1: raise XPathContext.FunctionNumArgs() comparands = xc.atomize( p, args[0] ) try: if len(comparands) == 0: return () # xpath allows empty sequence argument if any(isinstance(c, float) and math.isnan(c) for c in comparands):...
TypeError
dataset/ETHPy150Open Arelle/Arelle/arelle/FunctionFn.py/fn_min
4,430
def fn_sum(xc, p, contextItem, args): if len(args) != 1: raise XPathContext.FunctionNumArgs() addends = xc.atomize( p, args[0] ) try: if len(addends) == 0: return 0 # xpath allows empty sequence argument hasFloat = False hasDecimal = False for a in addends: ...
TypeError
dataset/ETHPy150Open Arelle/Arelle/arelle/FunctionFn.py/fn_sum
4,431
def format_number(xc, p, args): if len(args) != 2: raise XPathContext.FunctionNumArgs() value = numericArg(xc, p, args, 0, missingArgFallback='NaN', emptyFallback='NaN') picture = stringArg(xc, args, 1, "xs:string", missingArgFallback='', emptyFallback='') try: return format_picture(xc.modelXbr...
ValueError
dataset/ETHPy150Open Arelle/Arelle/arelle/FunctionFn.py/format_number
4,432
def _request(self, endpoint, method, data=None, **kwargs): """ Method to hanle both GET and POST requests. :param endpoint: Endpoint of the API. :param method: Method of HTTP request. :param data: POST DATA for the request. :param kwargs: Other keyword arguments. ...
ValueError
dataset/ETHPy150Open v1k45/python-qBittorrent/qbittorrent/client.py/Client._request
4,433
def popd(self): try: path = self._dirstack.pop() except __HOLE__: return None else: os.chdir(path) return path
IndexError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/remote/WindowsServer.py/Win32Agent.popd
4,434
def poll(self, pid): """Poll for async process. Returns exitstatus if done.""" try: proc = self._procs[pid] except __HOLE__: return -errno.ENOENT if proc.poll() is None: return -errno.EAGAIN else: del self._procs[pid] re...
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/remote/WindowsServer.py/Win32Agent.poll
4,435
def kill(self, pid): """Kills a process that was started by run_async.""" try: proc = self._procs.pop(pid) except __HOLE__: return -errno.ENOENT else: proc.kill() sts = proc.wait() return sts
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/remote/WindowsServer.py/Win32Agent.kill
4,436
def _get_home(self): try: # F&*#!&@ windows HOME = os.environ['USERPROFILE'] except __HOLE__: try: HOME = os.path.join(os.environ["HOMEDRIVE"], os.environ["HOMEPATH"]) except KeyError: HOME = "C:\\" return HOME
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/remote/WindowsServer.py/Win32Agent._get_home
4,437
def __str__(self): result = ["GPD Setting"] if self.setting_id in GPDID.types: result.append("%s" % GPDID.types[self.setting_id]) else: result.append(hex(self.setting_id)) if self.content_id > 0 and self.content_id < 6: try: if GPDID.t...
KeyError
dataset/ETHPy150Open arkem/py360/py360/xdbf.py/Setting.__str__
4,438
def run(self): if os.getcwd() != self.cwd: raise DistutilsSetupError("Must be in package root!") self._verify_version() self._verify_tag() self.execute(os.system, ('git2cl > ChangeLog',)) if not self.skip_tests: self.run_command('check') try...
SystemExit
dataset/ETHPy150Open Yubico/python-yubico/release.py/release.run
4,439
def __init__(self, **kwargs): for name in dir(self): value = getattr(self, name) if isinstance(value, Factory): setattr(self, name, value()) for name, value in kwargs.iteritems(): try: attribute = getattr(self, name) except...
AttributeError
dataset/ETHPy150Open disqus/playa/playa/ext/zodb.py/Model.__init__
4,440
def buildClusterSpliceGraph(c, alt5, alt3): """use exon/splice start and end positions to build splice graph for a cluster c. Also finds exons that share same start (but differ at end: alt5), or share the same end (but differ at start: alt3).""" start = {} end = {} none = [] for e in c.exons...
KeyError
dataset/ETHPy150Open cjlee112/pygr/pygr/apps/splicegraph.py/buildClusterSpliceGraph
4,441
def __getattr__(self, attr): 'both parent classes have getattr, so have to call them both...' try: return TupleO.__getattr__(self, attr) except __HOLE__: return SeqPath.__getattr__(self, attr)
AttributeError
dataset/ETHPy150Open cjlee112/pygr/pygr/apps/splicegraph.py/ExonForm.__getattr__
4,442
def loadSpliceGraph(jun03, cluster_t, exon_t, splice_t, genomic_seq_t, mrna_seq_t=None, protein_seq_t=None, loadAll=True): """ Build a splice graph from the specified SQL tables representing gene clusters, exon forms, and splices. Each table must be specified as a DB.TABLENAME string...
IndexError
dataset/ETHPy150Open cjlee112/pygr/pygr/apps/splicegraph.py/loadSpliceGraph
4,443
def emit(self, record): if record.levelno <= logging.ERROR and self.can_record(record): request = None exc_info = None for frame_info in getouterframes(currentframe()): frame = frame_info[0] if not request: request = frame.f...
KeyError
dataset/ETHPy150Open getsentry/raven-python/raven/contrib/zope/__init__.py/ZopeSentryHandler.emit
4,444
def parse(self, extensions=None, keywords=None, compressed=False): """Returns the FITS file header(s) in a readable format. Parameters ---------- extensions : list of int or str, optional Format only specific HDU(s), identified by number or name. The name can be ...
ValueError
dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/scripts/fitsheader.py/HeaderFormatter.parse
4,445
def _get_cards(self, hdukey, keywords, compressed): """Returns a list of `pyfits.card.Card` objects. This function will return the desired header cards, taking into account the user's preference to see the compressed or uncompressed version. Parameters ---------- ...
IndexError
dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/scripts/fitsheader.py/HeaderFormatter._get_cards
4,446
def print_headers_traditional(args): """Prints FITS header(s) using the traditional 80-char format. Parameters ---------- args : argparse.Namespace Arguments passed from the command-line as defined below. """ for idx, filename in enumerate(args.filename): # support wildcards if...
IOError
dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/scripts/fitsheader.py/print_headers_traditional
4,447
def main(args=None): """This is the main function called by the `fitsheader` script.""" parser = argparse.OptionParser( description=('Print the header(s) of a FITS file. ' 'Optional arguments allow the desired extension(s), ' 'keyword(s), and output format to b...
IOError
dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/scripts/fitsheader.py/main
4,448
def encode_str(s): try: s = s.encode('utf-8') except __HOLE__: s = s.decode('iso-8859-1').encode('utf-8') return s
UnicodeDecodeError
dataset/ETHPy150Open gwu-libraries/launchpad/lp/ui/templatetags/launchpad_extras.py/encode_str
4,449
def get_filter_args(argstring, keywords=(), intargs=(), boolargs=(), stripquotes=False): """Convert a string formatted list of arguments into a kwargs dictionary. Automatically converts all keywords in intargs to integers. If keywords is not empty, then enforces that only those keywords are returned. A...
ValueError
dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/satchmo_utils/templatetags/__init__.py/get_filter_args
4,450
def collect_report(self): indexes = [] for app in settings.INSTALLED_APPS: try: mod = importlib.import_module(app) except __HOLE__: warnings.warn('Installed app %s is not an importable Python module and will be ignored' % app) cont...
ImportError
dataset/ETHPy150Open mining/django-report/report/management/commands/update_report.py/Command.collect_report
4,451
def __init__(self, *args, **kwargs): super(YearMonthForm, self).__init__(*args, **kwargs) now = datetime.datetime.now() this_year = now.year this_month = now.month try: first_entry = Entry.no_join.values('end_time')\ .order_by('e...
IndexError
dataset/ETHPy150Open caktus/django-timepiece/timepiece/forms.py/YearMonthForm.__init__
4,452
def _ensure_element(tup, elem): """ Create a tuple containing all elements of tup, plus elem. Returns the new tuple and the index of elem in the new tuple. """ try: return tup, tup.index(elem) except __HOLE__: return tuple(chain(tup, (elem,))), len(tup)
ValueError
dataset/ETHPy150Open quantopian/zipline/zipline/pipeline/expression.py/_ensure_element
4,453
def _start_server(self, callback, workers): """Run a given service. :param callback: callback that will start the required service :param workers: number of service workers :returns: list of spawned workers' pids """ self.workers = workers # Fork a new process ...
SystemExit
dataset/ETHPy150Open openstack/neutron/neutron/tests/functional/test_server.py/TestNeutronServer._start_server
4,454
def load(self): try: self.file = open(self.filename, self.read_mode) self.empty_file = False except __HOLE__: if self.binary: self.file = BytesIO() else: self.file = StringIO() self.empty_file = True
IOError
dataset/ETHPy150Open wq/wq.io/loaders.py/FileLoader.load
4,455
@decorator.decorator def except_500_and_return(fn, *args, **kwargs): def error_as_resp(args, e): """ Always return the error wrapped in a response object """ resp = ErrorResponse(e.response) for arg in args: if isinstance(arg, Document): self.reco...
ValueError
dataset/ETHPy150Open activefrequency/pyavatax/pyavatax/api.py/except_500_and_return
4,456
@except_500_and_return def get_tax(self, lat, lng, doc, sale_amount=None): """Performs a HTTP GET to tax/get/""" if doc is not None: if isinstance(doc, dict): doc = Document.from_data(doc) elif not isinstance(doc, Document) and sale_amount == None: ...
TypeError
dataset/ETHPy150Open activefrequency/pyavatax/pyavatax/api.py/API.get_tax
4,457
@property def _details(self): try: return [{m.RefersTo: m.Summary} for m in self.CancelTaxResult.Messages] except __HOLE__: # doesn't have RefersTo return [{m.Source: m.Summary} for m in self.CancelTaxResult.Messages]
AttributeError
dataset/ETHPy150Open activefrequency/pyavatax/pyavatax/api.py/CancelTaxResponse._details
4,458
@property def is_success(self): """Returns whether or not the response was successful. Avalara bungled this response, it is formatted differently than every other response""" try: return True if self.CancelTaxResult.ResultCode == BaseResponse.SUCCESS else False except __H...
AttributeError
dataset/ETHPy150Open activefrequency/pyavatax/pyavatax/api.py/CancelTaxResponse.is_success
4,459
@property def error(self): """Returns a list of tuples. The first position in the tuple is either the offending field that threw an error, or the class in the Avalara system that threw it. The second position is a human-readable message from Avalara. Avalara bungled this resp...
AttributeError
dataset/ETHPy150Open activefrequency/pyavatax/pyavatax/api.py/CancelTaxResponse.error
4,460
def render(self, context): """ For date values that are tomorrow, today or yesterday compared to present day returns representing string. Otherwise, returns an empty string. """ value = self.value.resolve(context) try: value = date(value.year, value.month, val...
ValueError
dataset/ETHPy150Open zorna/zorna/zorna/templatetags/zorna_tags.py/natural_date.render
4,461
def render(self, context): if self.url: context[self.var_name] = feedparser.parse(self.url) else: try: context[self.var_name] = feedparser.parse( context[self.url_var_name]) except __HOLE__: raise template.TemplateSy...
KeyError
dataset/ETHPy150Open zorna/zorna/zorna/templatetags/zorna_tags.py/RssParserNode.render
4,462
@register.tag(name="get_rss") def get_rss(parser, token): # This version uses a regular expression to parse tag contents. try: # Splitting by None == splitting by spaces. tag_name, arg = token.contents.split(None, 1) except __HOLE__: raise template.TemplateSyntaxError, "%r tag requir...
ValueError
dataset/ETHPy150Open zorna/zorna/zorna/templatetags/zorna_tags.py/get_rss
4,463
def load_backend(path): i = path.rfind('.') module, attr = path[:i], path[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (module, e)) except ValueError, e: raise ImproperlyConfigured...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/auth/__init__.py/load_backend
4,464
def authenticate(**credentials): """ If the given credentials are valid, return a User object. """ for backend in get_backends(): try: user = backend.authenticate(**credentials) except __HOLE__: # This backend doesn't accept these credentials as arguments. Try the...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/auth/__init__.py/authenticate
4,465
def get_user(request): from django.contrib.auth.models import AnonymousUser try: user_id = request.session[SESSION_KEY] backend_path = request.session[BACKEND_SESSION_KEY] backend = load_backend(backend_path) user = backend.get_user(user_id) or AnonymousUser() except __HOLE__...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/auth/__init__.py/get_user
4,466
def setup(self): class Double(Compound): field_schema = [Integer.named(u'x'), Integer.named(u'y')] def compose(self): ex, ey = self.get(u'x'), self.get(u'y') ux, uy = ex.u, ey.u if ex.u and ey.u: string = u"%sx%s" % (...
TypeError
dataset/ETHPy150Open jek/flatland/tests/schema/test_compound.py/TestDoubleField.setup
4,467
def nth(n, seq): try: return seq[n] except __HOLE__: return None except TypeError: return next(islice(seq, n, None), None)
IndexError
dataset/ETHPy150Open Suor/funcy/funcy/seqs.py/nth
4,468
def last(seq): try: return seq[-1] except __HOLE__: return None except TypeError: item = None for item in seq: pass return item
IndexError
dataset/ETHPy150Open Suor/funcy/funcy/seqs.py/last
4,469
def butlast(seq): it = iter(seq) try: prev = next(it) except __HOLE__: pass else: for item in it: yield prev prev = item
StopIteration
dataset/ETHPy150Open Suor/funcy/funcy/seqs.py/butlast
4,470
def byte_FOR_ITER(self, jump): iterobj = self.top() try: v = next(iterobj) self.push(v) except __HOLE__: self.pop() self.jump(jump)
StopIteration
dataset/ETHPy150Open nedbat/byterun/byterun/pyvm2.py/VirtualMachine.byte_FOR_ITER
4,471
def byte_YIELD_FROM(self): u = self.pop() x = self.top() try: if not isinstance(x, Generator) or u is None: # Call next on iterators. retval = next(x) else: retval = x.send(u) self.return_value = retval ...
StopIteration
dataset/ETHPy150Open nedbat/byterun/byterun/pyvm2.py/VirtualMachine.byte_YIELD_FROM
4,472
def _inotify_init(self): try: fd = inotify_syscalls.inotify_init() except __HOLE__, err: self._last_errno = err.errno return -1 return fd
IOError
dataset/ETHPy150Open seb-m/pyinotify/python2/pyinotify.py/_INotifySyscallsWrapper._inotify_init
4,473
def _inotify_add_watch(self, fd, pathname, mask): try: wd = inotify_syscalls.inotify_add_watch(fd, pathname, mask) except __HOLE__, err: self._last_errno = err.errno return -1 return wd
IOError
dataset/ETHPy150Open seb-m/pyinotify/python2/pyinotify.py/_INotifySyscallsWrapper._inotify_add_watch
4,474
def _inotify_rm_watch(self, fd, wd): try: ret = inotify_syscalls.inotify_rm_watch(fd, wd) except __HOLE__, err: self._last_errno = err.errno return -1 return ret
IOError
dataset/ETHPy150Open seb-m/pyinotify/python2/pyinotify.py/_INotifySyscallsWrapper._inotify_rm_watch
4,475
def init(self): assert ctypes try_libc_name = 'c' if sys.platform.startswith('freebsd'): try_libc_name = 'inotify' libc_name = None try: libc_name = ctypes.util.find_library(try_libc_name) except (OSError, IOError): pass # Will attem...
AttributeError
dataset/ETHPy150Open seb-m/pyinotify/python2/pyinotify.py/_CtypesLibcINotifyWrapper.init
4,476
def __init__(self, raw): """ Concretely, this is the raw event plus inferred infos. """ _Event.__init__(self, raw) self.maskname = EventsCodes.maskname(self.mask) if COMPATIBILITY_MODE: self.event_name = self.maskname try: if self.name: ...
AttributeError
dataset/ETHPy150Open seb-m/pyinotify/python2/pyinotify.py/Event.__init__
4,477
def process_IN_CREATE(self, raw_event): """ If the event affects a directory and the auto_add flag of the targetted watch is set to True, a new watch is added on this new directory, with the same attribute values than those of this watch. """ if raw_event.mask & I...
OSError
dataset/ETHPy150Open seb-m/pyinotify/python2/pyinotify.py/_SysProcessEvent.process_IN_CREATE
4,478
def loop(self, callback=None, daemonize=False, **args): """ Events are read only one time every min(read_freq, timeout) seconds at best and only if the size to read is >= threshold. After this method returns it must not be called again for the same instance. @param callb...
KeyboardInterrupt
dataset/ETHPy150Open seb-m/pyinotify/python2/pyinotify.py/Notifier.loop
4,479
def del_watch(self, wd): """ Remove watch entry associated to watch descriptor wd. @param wd: Watch descriptor. @type wd: int """ try: del self._wmd[wd] except __HOLE__, err: log.error('Cannot delete unknown watch descriptor %s' % str(err)...
KeyError
dataset/ETHPy150Open seb-m/pyinotify/python2/pyinotify.py/WatchManager.del_watch
4,480
def exists(self, name): try: self._zip_file.getinfo(name) return True except __HOLE__: return False
KeyError
dataset/ETHPy150Open mwilliamson/python-mammoth/mammoth/zips.py/_Zip.exists
4,481
def verify(self, **kwargs): super(AccessTokenResponse, self).verify(**kwargs) if "id_token" in self: # Try to decode the JWT, checks the signature args = {} for arg in ["key", "keyjar", "algs", "sender"]: try: args[arg] = kwargs[arg...
KeyError
dataset/ETHPy150Open rohe/pyoidc/src/oic/oic/message.py/AccessTokenResponse.verify
4,482
def verify(self, **kwargs): super(AuthorizationResponse, self).verify(**kwargs) if "aud" in self: if "client_id" in kwargs: # check that it's for me if kwargs["client_id"] not in self["aud"]: return False if "id_token" in self: ...
AssertionError
dataset/ETHPy150Open rohe/pyoidc/src/oic/oic/message.py/AuthorizationResponse.verify
4,483
def verify(self, **kwargs): """Authorization Request parameters that are OPTIONAL in the OAuth 2.0 specification MAY be included in the OpenID Request Object without also passing them as OAuth 2.0 Authorization Request parameters, with one exception: The scope parameter MUST always be pr...
KeyError
dataset/ETHPy150Open rohe/pyoidc/src/oic/oic/message.py/AuthorizationRequest.verify
4,484
def verify(self, **kwargs): super(OpenIDSchema, self).verify(**kwargs) if "birthdate" in self: # Either YYYY-MM-DD or just YYYY or 0000-MM-DD try: _ = time.strptime(self["birthdate"], "%Y-%m-%d") except __HOLE__: try: ...
ValueError
dataset/ETHPy150Open rohe/pyoidc/src/oic/oic/message.py/OpenIDSchema.verify
4,485
def verify(self, **kwargs): super(IdToken, self).verify(**kwargs) if "aud" in self: if "client_id" in kwargs: # check that I'm among the recipients if kwargs["client_id"] not in self["aud"]: raise NotForMe("", self) # Then azp...
KeyError
dataset/ETHPy150Open rohe/pyoidc/src/oic/oic/message.py/IdToken.verify
4,486
def verify(self, **kwargs): super(ProviderConfigurationResponse, self).verify(**kwargs) if "scopes_supported" in self: assert "openid" in self["scopes_supported"] for scope in self["scopes_supported"]: check_char_set(scope, SCOPE_CHARSET) parts = urlpars...
AssertionError
dataset/ETHPy150Open rohe/pyoidc/src/oic/oic/message.py/ProviderConfigurationResponse.verify
4,487
def factory(msgtype): for name, obj in inspect.getmembers(sys.modules[__name__]): if inspect.isclass(obj) and issubclass(obj, Message): try: if obj.__name__ == msgtype: return obj except __HOLE__: pass # Fall back to basic OAut...
AttributeError
dataset/ETHPy150Open rohe/pyoidc/src/oic/oic/message.py/factory
4,488
def current_engine(self): try: return settings.DATABASES[self.db]['ENGINE'] except __HOLE__: return settings.DATABASE_ENGINE
AttributeError
dataset/ETHPy150Open celery/django-celery/djcelery/managers.py/ExtendedManager.current_engine
4,489
def __init__(self, *args, **kwargs): self._data = list(Row(arg) for arg in args) self.__headers = None # ('title', index) tuples self._separators = [] # (column, callback) tuples self._formatters = [] try: self.headers = kwargs['headers'] ex...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/core.py/Dataset.__init__
4,490
def __repr__(self): try: return '<%s dataset>' % (self.title.lower()) except __HOLE__: return '<dataset object>'
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/core.py/Dataset.__repr__
4,491
@classmethod def _register_formats(cls): """Adds format properties.""" for fmt in formats.available: try: try: setattr(cls, fmt.title, property(fmt.export_set, fmt.import_set)) except __HOLE__: setattr(cls, fmt.title...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/core.py/Dataset._register_formats
4,492
def _package(self, dicts=True, ordered=True): """Packages Dataset into lists of dictionaries for transmission.""" # TODO: Dicts default to false? _data = list(self._data) if ordered: dict_pack = OrderedDict else: dict_pack = dict # Execute forma...
IndexError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/core.py/Dataset._package
4,493
def _set_headers(self, collection): """Validating headers setter.""" self._validate(collection) if collection: try: self.__headers = list(collection) except __HOLE__: raise TypeError else: self.__headers = None
TypeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/core.py/Dataset._set_headers
4,494
@property def width(self): """The number of columns currently in the :class:`Dataset`. Cannot be directly modified. """ try: return len(self._data[0]) except __HOLE__: try: return len(self.headers) except TypeError: ...
IndexError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/core.py/Dataset.width
4,495
def stack_cols(self, other): """Stack two :class:`Dataset` instances together by joining at the column level, and return a new combined ``Dataset`` instance. If either ``Dataset`` has headers set, than the other must as well.""" if not isinstance(other, Dataset): ret...
TypeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/core.py/Dataset.stack_cols
4,496
def __repr__(self): try: return '<%s databook>' % (self.title.lower()) except __HOLE__: return '<databook object>'
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/core.py/Databook.__repr__
4,497
@classmethod def _register_formats(cls): """Adds format properties.""" for fmt in formats.available: try: try: setattr(cls, fmt.title, property(fmt.export_book, fmt.import_book)) except __HOLE__: setattr(cls, fmt.tit...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/core.py/Databook._register_formats
4,498
def detect(stream): """Return (format, stream) of given stream.""" for fmt in formats.available: try: if fmt.detect(stream): return (fmt, stream) except __HOLE__: pass return (None, stream)
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/core.py/detect
4,499
def import_set(stream): """Return dataset of given stream.""" (format, stream) = detect(stream) try: data = Dataset() format.import_set(data, stream) return data except __HOLE__: return None
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/core.py/import_set