Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
7,000
def get_case_transactions(case_id, updated_xforms=None): """ This fetches all the transactions required to rebuild the case along with all the forms for those transactions. For any forms that have been updated it replaces the old form with the new one. :param case_id: ID of case to rebuild :param updated_xforms: list of forms that have been changed. :return: list of ``CaseTransaction`` objects with their associated forms attached. """ transactions = CaseAccessorSQL.get_transactions_for_case_rebuild(case_id) form_ids = {tx.form_id for tx in transactions} updated_xforms_map = { xform.form_id: xform for xform in updated_xforms if not xform.is_deprecated } if updated_xforms else {} form_ids_to_fetch = list(form_ids - set(updated_xforms_map.keys())) xform_map = {form.form_id: form for form in FormAccessorSQL.get_forms_with_attachments_meta(form_ids_to_fetch)} def get_form(form_id): if form_id in updated_xforms_map: return updated_xforms_map[form_id] try: return xform_map[form_id] except __HOLE__: raise XFormNotFound for transaction in transactions: if transaction.form_id: try: transaction.cached_form = get_form(transaction.form_id) except XFormNotFound: logging.error('Form not found during rebuild: %s', transaction.form_id) return transactions
KeyError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/form_processor/backends/sql/processor.py/get_case_transactions
7,001
def match(self, v2): """Assert two values are equivalent. NOTE: If you don't care (or don't know) a given value, you can specify the string DONTCARE as the value. This will cause that item to be skipped. """ try: error = abs(float(self.v1) - float(v2)) within_tolerance = error <= self.tolerance except (__HOLE__, TypeError): # If both values aren't convertible to float, just ignore # ValueError if arg is a str, TypeError if it's something else # (like None) within_tolerance = False if hasattr(self.v1, 'keys') and hasattr(v2, 'keys'): matcher = DictMatches(self.v1, self.approx_equal, self.tolerance, self.orderless_lists) did_match = matcher.match(v2) if did_match is not None: return did_match elif isinstance(self.v1, list) and isinstance(v2, list): matcher = ListMatches(self.v1, self.approx_equal, self.tolerance, self.orderless_lists) did_match = matcher.match(v2) if did_match is not None: return did_match elif 'DONTCARE' in (self.v1, v2): return elif self.approx_equal and within_tolerance: return elif self.v1 != v2: return ValueMismatch(self.v1, v2)
ValueError
dataset/ETHPy150Open openstack/ec2-api/ec2api/tests/unit/matchers.py/ValueMatches.match
7,002
def parse(self, lines): missing = [] packages = {} for line in lines: try: req = pkg_resources.parse_requirements(line.strip()).next() except ValueError: missing.append(line) continue except __HOLE__: continue specs = [s for s in req.specs if s[0] == '=='] if specs: packages[req.project_name] = specs[0][1] else: missing.append(req.project_name) return packages, missing
StopIteration
dataset/ETHPy150Open rocketDuck/folivora/folivora/utils/parsers.py/PipRequirementsParser.parse
7,003
def print_success_message(message): """Print a message indicating success in green color to STDOUT. :param message: the message to print :type message: :class:`str` """ try: import colorama print(colorama.Fore.GREEN + message + colorama.Fore.RESET) except __HOLE__: print(message)
ImportError
dataset/ETHPy150Open calvinschmdt/EasyTensorflow/setup.py/print_success_message
7,004
def print_failure_message(message): """Print a message indicating failure in red color to STDERR. :param message: the message to print :type message: :class:`str` """ try: import colorama print(colorama.Fore.RED + message + colorama.Fore.RESET, file=sys.stderr) except __HOLE__: print(message, file=sys.stderr)
ImportError
dataset/ETHPy150Open calvinschmdt/EasyTensorflow/setup.py/print_failure_message
7,005
def _load_tracker_uri_from_file(self): f = None try: f = open(self.tracker_file_name, 'r') uri = f.readline().strip() self._set_tracker_uri(uri) except __HOLE__, e: # Ignore non-existent file (happens first time an upload # is attempted on a file), but warn user for other errors. if e.errno != errno.ENOENT: # Will restart because self.tracker_uri == None. print('Couldn\'t read URI tracker file (%s): %s. Restarting ' 'upload from scratch.' % (self.tracker_file_name, e.strerror)) except InvalidUriError, e: # Warn user, but proceed (will restart because # self.tracker_uri == None). print('Invalid tracker URI (%s) found in URI tracker file ' '(%s). Restarting upload from scratch.' % (uri, self.tracker_file_name)) finally: if f: f.close()
IOError
dataset/ETHPy150Open radlab/sparrow/deploy/third_party/boto-2.1.1/boto/gs/resumable_upload_handler.py/ResumableUploadHandler._load_tracker_uri_from_file
7,006
def _save_tracker_uri_to_file(self): """ Saves URI to tracker file if one was passed to constructor. """ if not self.tracker_file_name: return f = None try: f = open(self.tracker_file_name, 'w') f.write(self.tracker_uri) except __HOLE__, e: raise ResumableUploadException( 'Couldn\'t write URI tracker file (%s): %s.\nThis can happen' 'if you\'re using an incorrectly configured upload tool\n' '(e.g., gsutil configured to save tracker files to an ' 'unwritable directory)' % (self.tracker_file_name, e.strerror), ResumableTransferDisposition.ABORT) finally: if f: f.close()
IOError
dataset/ETHPy150Open radlab/sparrow/deploy/third_party/boto-2.1.1/boto/gs/resumable_upload_handler.py/ResumableUploadHandler._save_tracker_uri_to_file
7,007
def build_resource_for_web_client(hs): webclient_path = hs.get_config().web_client_location if not webclient_path: try: import syweb except __HOLE__: quit_with_error( "Could not find a webclient.\n\n" "Please either install the matrix-angular-sdk or configure\n" "the location of the source to serve via the configuration\n" "option `web_client_location`\n\n" "To install the `matrix-angular-sdk` via pip, run:\n\n" " pip install '%(dep)s'\n" "\n" "You can also disable hosting of the webclient via the\n" "configuration option `web_client`\n" % {"dep": DEPENDENCY_LINKS["matrix-angular-sdk"]} ) syweb_path = os.path.dirname(syweb.__file__) webclient_path = os.path.join(syweb_path, "webclient") # GZip is disabled here due to # https://twistedmatrix.com/trac/ticket/7678 # (It can stay enabled for the API resources: they call # write() with the whole body and then finish() straight # after and so do not trigger the bug. # GzipFile was removed in commit 184ba09 # return GzipFile(webclient_path) # TODO configurable? return File(webclient_path) # TODO configurable?
ImportError
dataset/ETHPy150Open matrix-org/synapse/synapse/app/homeserver.py/build_resource_for_web_client
7,008
def change_resource_limit(soft_file_no): try: soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) if not soft_file_no: soft_file_no = hard resource.setrlimit(resource.RLIMIT_NOFILE, (soft_file_no, hard)) logger.info("Set file limit to: %d", soft_file_no) resource.setrlimit( resource.RLIMIT_CORE, (resource.RLIM_INFINITY, resource.RLIM_INFINITY) ) except (__HOLE__, resource.error) as e: logger.warn("Failed to set file or core limit: %s", e)
ValueError
dataset/ETHPy150Open matrix-org/synapse/synapse/app/homeserver.py/change_resource_limit
7,009
def main(main_func, args=None, kwargs=None): if os.environ.get("RUN_MAIN") == "true": if args is None: args = () if kwargs is None: kwargs = {} thread.start_new_thread(main_func, args, kwargs) try: reloader_thread() except __HOLE__: pass else: try: sys.exit(restart_with_reloader()) except KeyboardInterrupt: pass
KeyboardInterrupt
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/utils/autoreload.py/main
7,010
def _ensure_console_pid_dir_exists(): """Ensure that the console PID directory exists Checks that the directory for the console PID file exists and if not, creates it. :raises: ConsoleError if the directory doesn't exist and cannot be created """ dir = _get_console_pid_dir() if not os.path.exists(dir): try: os.makedirs(dir) except __HOLE__ as exc: msg = (_("Cannot create directory '%(path)s' for console PID file." " Reason: %(reason)s.") % {'path': dir, 'reason': exc}) LOG.error(msg) raise exception.ConsoleError(message=msg)
OSError
dataset/ETHPy150Open openstack/ironic/ironic/drivers/modules/console_utils.py/_ensure_console_pid_dir_exists
7,011
def _get_console_pid(node_uuid): """Get the terminal process id from pid file.""" pid_path = _get_console_pid_file(node_uuid) try: with open(pid_path, 'r') as f: pid_str = f.readline() return int(pid_str) except (IOError, __HOLE__): raise exception.NoConsolePid(pid_path=pid_path)
ValueError
dataset/ETHPy150Open openstack/ironic/ironic/drivers/modules/console_utils.py/_get_console_pid
7,012
def _stop_console(node_uuid): """Close the serial console for a node Kills the console process and deletes the PID file. :param node_uuid: the UUID of the node :raises: NoConsolePid if no console PID was found :raises: ConsoleError if unable to stop the console process """ try: console_pid = _get_console_pid(node_uuid) os.kill(console_pid, signal.SIGTERM) except __HOLE__ as exc: if exc.errno != errno.ESRCH: msg = (_("Could not stop the console for node '%(node)s'. " "Reason: %(err)s.") % {'node': node_uuid, 'err': exc}) raise exception.ConsoleError(message=msg) else: LOG.warning(_LW("Console process for node %s is not running " "but pid file exists while trying to stop " "shellinabox console."), node_uuid) finally: ironic_utils.unlink_without_raise(_get_console_pid_file(node_uuid))
OSError
dataset/ETHPy150Open openstack/ironic/ironic/drivers/modules/console_utils.py/_stop_console
7,013
def start_shellinabox_console(node_uuid, port, console_cmd): """Open the serial console for a node. :param node_uuid: the uuid for the node. :param port: the terminal port for the node. :param console_cmd: the shell command that gets the console. :raises: ConsoleError if the directory for the PID file cannot be created. :raises: ConsoleSubprocessFailed when invoking the subprocess failed. """ # make sure that the old console for this node is stopped # and the files are cleared try: _stop_console(node_uuid) except exception.NoConsolePid: pass except processutils.ProcessExecutionError as exc: LOG.warning(_LW("Failed to kill the old console process " "before starting a new shellinabox console " "for node %(node)s. Reason: %(err)s"), {'node': node_uuid, 'err': exc}) _ensure_console_pid_dir_exists() pid_file = _get_console_pid_file(node_uuid) # put together the command and arguments for invoking the console args = [] args.append(CONF.console.terminal) if CONF.console.terminal_cert_dir: args.append("-c") args.append(CONF.console.terminal_cert_dir) else: args.append("-t") args.append("-p") args.append(str(port)) args.append("--background=%s" % pid_file) args.append("-s") args.append(console_cmd) # run the command as a subprocess try: LOG.debug('Running subprocess: %s', ' '.join(args)) # use pipe here to catch the error in case shellinaboxd # failed to start. obj = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except (OSError, __HOLE__) as e: error = _("%(exec_error)s\n" "Command: %(command)s") % {'exec_error': str(e), 'command': ' '.join(args)} LOG.warning(error) raise exception.ConsoleSubprocessFailed(error=error) def _wait(node_uuid, popen_obj): locals['returncode'] = popen_obj.poll() # check if the console pid is created and the process is running. # if it is, then the shellinaboxd is invoked successfully as a daemon. # otherwise check the error. if locals['returncode'] is not None: if (locals['returncode'] == 0 and os.path.exists(pid_file) and psutil.pid_exists(_get_console_pid(node_uuid))): raise loopingcall.LoopingCallDone() else: (stdout, stderr) = popen_obj.communicate() locals['errstr'] = _( "Command: %(command)s.\n" "Exit code: %(return_code)s.\n" "Stdout: %(stdout)r\n" "Stderr: %(stderr)r") % { 'command': ' '.join(args), 'return_code': locals['returncode'], 'stdout': stdout, 'stderr': stderr} LOG.warning(locals['errstr']) raise loopingcall.LoopingCallDone() if (time.time() > expiration): locals['errstr'] = _("Timeout while waiting for console subprocess" "to start for node %s.") % node_uuid LOG.warning(locals['errstr']) raise loopingcall.LoopingCallDone() locals = {'returncode': None, 'errstr': ''} expiration = time.time() + CONF.console.subprocess_timeout timer = loopingcall.FixedIntervalLoopingCall(_wait, node_uuid, obj) timer.start(interval=CONF.console.subprocess_checking_interval).wait() if locals['errstr']: raise exception.ConsoleSubprocessFailed(error=locals['errstr'])
ValueError
dataset/ETHPy150Open openstack/ironic/ironic/drivers/modules/console_utils.py/start_shellinabox_console
7,014
def clean(self, value): from in_states import STATES_NORMALIZED super(INStateField, self).clean(value) if value in EMPTY_VALUES: return u'' try: value = value.strip().lower() except __HOLE__: pass else: try: return smart_unicode(STATES_NORMALIZED[value.strip().lower()]) except KeyError: pass raise ValidationError(self.error_messages['invalid'])
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/localflavor/in_/forms.py/INStateField.clean
7,015
def _iterate_items(self): with self.mutex: for k in self: try: yield (k, self.data[k]) except __HOLE__: # pragma: no cover pass
KeyError
dataset/ETHPy150Open celery/kombu/kombu/utils/functional.py/LRUCache._iterate_items
7,016
def _iterate_values(self): with self.mutex: for k in self: try: yield self.data[k] except __HOLE__: # pragma: no cover pass
KeyError
dataset/ETHPy150Open celery/kombu/kombu/utils/functional.py/LRUCache._iterate_values
7,017
def memoize(maxsize=None, keyfun=None, Cache=LRUCache): def _memoize(fun): mutex = threading.Lock() cache = Cache(limit=maxsize) @wraps(fun) def _M(*args, **kwargs): if keyfun: key = keyfun(args, kwargs) else: key = args + (KEYWORD_MARK,) + tuple(sorted(kwargs.items())) try: with mutex: value = cache[key] except __HOLE__: value = fun(*args, **kwargs) _M.misses += 1 with mutex: cache[key] = value else: _M.hits += 1 return value def clear(): """Clear the cache and reset cache statistics.""" cache.clear() _M.hits = _M.misses = 0 _M.hits = _M.misses = 0 _M.clear = clear _M.original_func = fun return _M return _memoize
KeyError
dataset/ETHPy150Open celery/kombu/kombu/utils/functional.py/memoize
7,018
@lazy_import def pickle(): try: import cPickle as pickle except __HOLE__: import pickle return pickle
ImportError
dataset/ETHPy150Open cloudmatrix/esky/esky/__init__.py/pickle
7,019
@lazy_import def threading(): try: import threading except __HOLE__: threading = None return threading
ImportError
dataset/ETHPy150Open cloudmatrix/esky/esky/__init__.py/threading
7,020
@allow_from_sudo() def lock(self, num_retries=0): """Lock the application directory for exclusive write access. If the appdir is already locked by another process/thread then EskyLockedError is raised. There is no way to perform a blocking lock on an appdir. Locking is achieved by creating a "locked" directory and writing the current process/thread ID into it. os.mkdir is atomic on all platforms that we care about. This also has the side-effect of failing early if the user does not have permission to modify the application directory. """ if self.sudo_proxy is not None: return self.sudo_proxy.lock() if num_retries > 5: raise EskyLockedError if threading: curthread = threading.currentThread() try: threadid = curthread.ident except __HOLE__: threadid = curthread.getName() else: threadid = "0" myid = "%s-%s-%s" % (socket.gethostname(), os.getpid(), threadid) lockdir = os.path.join(self.appdir, "locked") # Do I already own the lock? if os.path.exists(os.path.join(lockdir, myid)): # Update file mtime to keep it safe from breakers os.utime(os.path.join(lockdir, myid), None) self._lock_count += 1 return True # Try to make the "locked" directory. try: os.mkdir(lockdir) except OSError, e: if e.errno != errno.EEXIST: raise # Is it stale? If so, break it and try again. try: newest_mtime = os.path.getmtime(lockdir) for nm in os.listdir(lockdir): mtime = os.path.getmtime(os.path.join(lockdir, nm)) if mtime > newest_mtime: newest_mtime = mtime if newest_mtime + self.lock_timeout < time.time(): really_rmtree(lockdir) return self.lock(num_retries+1) else: raise EskyLockedError except OSError, e: if e.errno not in (errno.ENOENT, errno.ENOTDIR,): raise return self.lock(num_retries+1) else: # Success! Record my ownership open(os.path.join(lockdir, myid), "wb").close() self._lock_count = 1 return True
AttributeError
dataset/ETHPy150Open cloudmatrix/esky/esky/__init__.py/Esky.lock
7,021
@allow_from_sudo() def unlock(self): """Unlock the application directory for exclusive write access.""" if self.sudo_proxy is not None: return self.sudo_proxy.unlock() self._lock_count -= 1 if self._lock_count == 0: if threading: curthread = threading.currentThread() try: threadid = curthread.ident except __HOLE__: threadid = curthread.getName() else: threadid = "0" myid = "%s-%s-%s" % (socket.gethostname(), os.getpid(), threadid) lockdir = os.path.join(self.appdir, "locked") os.unlink(os.path.join(lockdir, myid)) os.rmdir(lockdir)
AttributeError
dataset/ETHPy150Open cloudmatrix/esky/esky/__init__.py/Esky.unlock
7,022
@allow_from_sudo() def cleanup(self): """Perform cleanup tasks in the app directory. This includes removing older versions of the app and completing any failed update attempts. Such maintenance is not done automatically since it can take a non-negligible amount of time. If the cleanup proceeds sucessfully this method will return True; it there is work that cannot currently be completed, it returns False. """ if self.sudo_proxy is not None: return self.sudo_proxy.cleanup() if not self.needs_cleanup(): return True self.lock() try: # This is a little coroutine trampoline that executes each # action yielded from self._cleanup_actions(). Any exceptions # that the action raises are thrown back into the generator. # The result of each is and-ed into the success code. # # If you're looking for the actual logic of the cleanup process, # it's all in the _cleanup_actions() method. success = True actions = self._cleanup_actions() try: act = lambda: True while True: try: if callable(act): res = act() elif len(act) == 1: res = act[0]() elif len(act) == 2: res = act[0](*act[1]) else: res = act[0](*act[1], **act[2]) if res is not None: success &= res except Exception: act = actions.throw(*sys.exc_info()) else: act = actions.next() except __HOLE__: return success finally: self.unlock()
StopIteration
dataset/ETHPy150Open cloudmatrix/esky/esky/__init__.py/Esky.cleanup
7,023
def _version_manifest(self, vdir): """Get the bootstrap manifest for the given version directory. This is the set of files/directories that the given version expects to be in the main app directory. """ vsdir = self._get_versions_dir() mpath = os.path.join(vsdir, vdir, ESKY_CONTROL_DIR) mpath = os.path.join(mpath, "bootstrap-manifest.txt") # TODO: remove compatability hooks for ESKY_APPDATA_DIR="". if not os.path.exists(mpath): if vsdir == self.appdir: mpath = os.path.join(self.appdir, ESKY_APPDATA_DIR, vdir, ESKY_CONTROL_DIR) else: mpath = os.path.join(self.appdir, vdir, ESKY_CONTROL_DIR) mpath = os.path.join(mpath, "bootstrap-manifest.txt") manifest = set() try: with open(mpath, "rt") as mf: for ln in mf: # Guard against malicious input, since we might try # to manipulate these files with root privs. nm = os.path.normpath(ln.strip()) assert not os.path.isabs(nm) assert not nm.startswith("..") manifest.add(nm) except __HOLE__: pass return manifest
IOError
dataset/ETHPy150Open cloudmatrix/esky/esky/__init__.py/Esky._version_manifest
7,024
def testAssertDictEqual(self): self.assertDictEqual({}, {}) c = {'x': 1} d = {} self.assertRaises(basetest.TestCase.failureException, self.assertDictEqual, c, d) d.update(c) self.assertDictEqual(c, d) d['x'] = 0 self.assertRaises(basetest.TestCase.failureException, self.assertDictEqual, c, d, 'These are unequal') self.assertRaises(AssertionError, self.assertDictEqual, None, d) self.assertRaises(AssertionError, self.assertDictEqual, [], d) self.assertRaises(AssertionError, self.assertDictEqual, 1, 1) try: # Ensure we use equality as the sole measure of elements, not type, since # that is consistent with dict equality. self.assertDictEqual({1: 1.0, 2: 2}, {1: 1, 2: 3}) except AssertionError, e: self.assertMultiLineEqual('{1: 1.0, 2: 2} != {1: 1, 2: 3}\n' 'repr() of differing entries:\n2: 2 != 3\n', str(e)) try: self.assertDictEqual({}, {'x': 1}) except AssertionError, e: self.assertMultiLineEqual("{} != {'x': 1}\n" "Unexpected, but present entries:\n'x': 1\n", str(e)) else: self.fail('Expecting AssertionError') try: self.assertDictEqual({}, {'x': 1}, 'a message') except AssertionError, e: self.assertIn('a message', str(e)) else: self.fail('Expecting AssertionError') expected = {'a': 1, 'b': 2, 'c': 3} seen = {'a': 2, 'c': 3, 'd': 4} try: self.assertDictEqual(expected, seen) except AssertionError, e: self.assertMultiLineEqual("""\ {'a': 1, 'b': 2, 'c': 3} != {'a': 2, 'c': 3, 'd': 4} Unexpected, but present entries: 'd': 4 repr() of differing entries: 'a': 1 != 2 Missing entries: 'b': 2 """, str(e)) else: self.fail('Expecting AssertionError') self.assertRaises(AssertionError, self.assertDictEqual, (1, 2), {}) self.assertRaises(AssertionError, self.assertDictEqual, {}, (1, 2)) # Ensure deterministic output of keys in dictionaries whose sort order # doesn't match the lexical ordering of repr -- this is most Python objects, # which are keyed by memory address. class Obj(object): def __init__(self, name): self.name = name def __repr__(self): return self.name try: self.assertDictEqual( {'a': Obj('A'), Obj('b'): Obj('B'), Obj('c'): Obj('C')}, {'a': Obj('A'), Obj('d'): Obj('D'), Obj('e'): Obj('E')}) except AssertionError, e: # Do as best we can not to be misleading when objects have the same repr # but aren't equal. err_str = str(e) self.assertStartsWith(err_str, "{'a': A, b: B, c: C} != {'a': A, d: D, e: E}\n") self.assertRegexpMatches(err_str, r'(?ms).*^Unexpected, but present entries:\s+' r'^(d: D$\s+^e: E|e: E$\s+^d: D)$') self.assertRegexpMatches(err_str, r'(?ms).*^repr\(\) of differing entries:\s+' r'^.a.: A != A$', err_str) self.assertRegexpMatches(err_str, r'(?ms).*^Missing entries:\s+' r'^(b: B$\s+^c: C|c: C$\s+^b: B)$') else: self.fail('Expecting AssertionError') # Confirm that safe_repr, not repr, is being used. class RaisesOnRepr(object): def __repr__(self): return 1/0 # Intentionally broken __repr__ implementation. try: self.assertDictEqual( {RaisesOnRepr(): RaisesOnRepr()}, {RaisesOnRepr(): RaisesOnRepr()} ) self.fail('Expected dicts not to match') except __HOLE__ as e: # Depending on the testing environment, the object may get a __main__ # prefix or a basetest_test prefix, so strip that for comparison. error_msg = re.sub( r'( at 0x[^>]+)|__main__\.|basetest_test\.', '', str(e)) self.assertRegexpMatches(error_msg, """(?m)\ {<.*RaisesOnRepr object.*>: <.*RaisesOnRepr object.*>} != \ {<.*RaisesOnRepr object.*>: <.*RaisesOnRepr object.*>} Unexpected, but present entries: <.*RaisesOnRepr object.*>: <.*RaisesOnRepr object.*> Missing entries: <.*RaisesOnRepr object.*>: <.*RaisesOnRepr object.*> """) # Confirm that safe_repr, not repr, is being used. class RaisesOnLt(object): def __lt__(self): raise TypeError('Object is unordered.') def __repr__(self): return '<RaisesOnLt object>' try: self.assertDictEqual( {RaisesOnLt(): RaisesOnLt()}, {RaisesOnLt(): RaisesOnLt()}) except AssertionError as e: self.assertIn('Unexpected, but present entries:\n<RaisesOnLt', str(e)) self.assertIn('Missing entries:\n<RaisesOnLt', str(e))
AssertionError
dataset/ETHPy150Open google/google-apputils/tests/basetest_test.py/GoogleTestBaseUnitTest.testAssertDictEqual
7,025
def testAssertTotallyOrdered(self): # Valid. self.assertTotallyOrdered() self.assertTotallyOrdered([1]) self.assertTotallyOrdered([1], [2]) self.assertTotallyOrdered([1, 1, 1]) self.assertTotallyOrdered([(1, 1)], [(1, 2)], [(2, 1)]) if PY_VERSION_2: # In Python 3 comparing different types of elements is not supported. self.assertTotallyOrdered([None], [1], [2]) self.assertTotallyOrdered([1, 1, 1], ['a string']) # From the docstring. class A(object): def __init__(self, x, y): self.x = x self.y = y def __hash__(self): return hash(self.x) def __repr__(self): return 'A(%r, %r)' % (self.x, self.y) def __eq__(self, other): try: return self.x == other.x except AttributeError: return NotImplemented def __ne__(self, other): try: return self.x != other.x except AttributeError: return NotImplemented def __lt__(self, other): try: return self.x < other.x except AttributeError: return NotImplemented def __le__(self, other): try: return self.x <= other.x except AttributeError: return NotImplemented def __gt__(self, other): try: return self.x > other.x except AttributeError: return NotImplemented def __ge__(self, other): try: return self.x >= other.x except __HOLE__: return NotImplemented if PY_VERSION_2: self.assertTotallyOrdered( [None], # None should come before everything else. [1], # Integers sort earlier. [A(1, 'a')], [A(2, 'b')], # 2 is after 1. [A(3, 'c'), A(3, 'd')], # The second argument is irrelevant. [A(4, 'z')], ['foo']) # Strings sort last. else: # Python 3 does not define ordering across different types. self.assertTotallyOrdered( [A(1, 'a')], [A(2, 'b')], # 2 is after 1. [A(3, 'c'), A(3, 'd')], # The second argument is irrelevant. [A(4, 'z')]) # Invalid. self.assertRaises(AssertionError, self.assertTotallyOrdered, [2], [1]) self.assertRaises(AssertionError, self.assertTotallyOrdered, [2], [1], [3]) self.assertRaises(AssertionError, self.assertTotallyOrdered, [1, 2])
AttributeError
dataset/ETHPy150Open google/google-apputils/tests/basetest_test.py/GoogleTestBaseUnitTest.testAssertTotallyOrdered
7,026
def get_from_location_by_extension(resource, location, extension, version=None): try: found_files = [os.path.join(location, f) for f in os.listdir(location)] except __HOLE__: return None try: return get_from_list_by_extension(resource, found_files, extension, version) except ResourceError: raise ResourceError('More than one .{} found in {} for {}.'.format(extension, location, resource.owner.name))
OSError
dataset/ETHPy150Open ARM-software/workload-automation/wlauto/resource_getters/standard.py/get_from_location_by_extension
7,027
def get_plugin_object(self): """For the selected plugin, returns a tuple of the module name to import and the class name to construct in order to get a Camera object.""" # Find the selected plugin plugin_id = self.cameras[self.camera_selection][0] # This should not fail, because only plugins which have all the requred # dependencies installed should be able to be selected try: return self.plugins[plugin_id].load() except __HOLE__: assert 0, ("A plugin was selected that didn't have all its " + "dependencies installed. This should not happen.")
ImportError
dataset/ETHPy150Open ptomato/Beams/beams/CameraDialog.py/CameraDialog.get_plugin_object
7,028
def __init__(self, **traits): super(CameraDialog, self).__init__(**traits) # Load the plugins self.plugins = pkg_resources.get_entry_map('beams', 'camera_plugins') if 'dummy' not in self.plugins.keys(): raise IOError("Plugin directory isn't configured properly") # Try to select the webcam try: self._select_plugin_by_name('webcam') except __HOLE__: self.select_fallback()
ValueError
dataset/ETHPy150Open ptomato/Beams/beams/CameraDialog.py/CameraDialog.__init__
7,029
def _cameras_default(self): # Construct list store of plugins retval = [] for plugin in self.plugins.keys(): try: info = self.plugins[plugin].load().plugin_info except __HOLE__: # A required module was not found for that plugin, ignore it continue retval += [(plugin, info['name'], info['description'])] return retval
ImportError
dataset/ETHPy150Open ptomato/Beams/beams/CameraDialog.py/CameraDialog._cameras_default
7,030
def select_fallback(self): """Select the dummy plugin as a fallback""" try: self._select_plugin_by_name('dummy') except __HOLE__: assert 0, 'Dummy plugin was not in list. Should not happen.'
ValueError
dataset/ETHPy150Open ptomato/Beams/beams/CameraDialog.py/CameraDialog.select_fallback
7,031
def readline(self, *args, **kwargs): try: row = list(self.data.next()) except __HOLE__: if self.verbose: print('') return '' else: self.processor(self.table, row) try: return '%s\n' % ('\t'.join(row)) except UnicodeDecodeError: return '%s\n' % ('\t'.join(r.decode('utf8') for r in row)) finally: if self.verbose: if (self.idx % 20000) == 0: now = time.time() elapsed = now - self.start_time val = '%.2f rows/sec [%s] ' % ((self.idx - self.prev_idx) / elapsed, self.idx) print_row_progress('%s%s' % (("\b" * self.prev_val_len), val)), self.prev_val_len = len(val) + 3 self.start_time = now self.prev_idx = self.idx + 0 self.idx += 1
StopIteration
dataset/ETHPy150Open philipsoutham/py-mysql2pgsql/mysql2pgsql/lib/postgres_db_writer.py/PostgresDbWriter.FileObjFaker.readline
7,032
def import_string(import_name, silent=False): """Imports an object based on a string. If *silent* is True the return value will be None if the import fails. Simplified version of the function with same name from `Werkzeug`_. :param import_name: The dotted name for the object to import. :param silent: If True, import errors are ignored and None is returned instead. :returns: The imported object. """ import_name = str(import_name) try: if '.' in import_name: module, obj = import_name.rsplit('.', 1) return getattr(__import__(module, None, None, [obj]), obj) else: return __import__(import_name) except (__HOLE__, AttributeError): if not silent: raise
ImportError
dataset/ETHPy150Open disqus/nydus/nydus/utils.py/import_string
7,033
def _git_version(): curdir = os.getcwd() filedir, _ = op.split(__file__) os.chdir(filedir) try: fnull = open(os.devnull, 'w') version = ('-git-' + subprocess.check_output( ['git', 'describe', '--abbrev=8', '--dirty', '--always', '--tags'], stderr=fnull).strip().decode('ascii')) return version except (__HOLE__, subprocess.CalledProcessError): # pragma: no cover return "" finally: os.chdir(curdir)
OSError
dataset/ETHPy150Open kwikteam/phy/phy/utils/_misc.py/_git_version
7,034
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_unicode, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ if strings_only and isinstance(s, (types.NoneType, int, long, datetime.datetime, datetime.date, datetime.time, float)): return s try: if not isinstance(s, basestring,): if hasattr(s, '__unicode__'): s = unicode(s) else: s = unicode(str(s), encoding, errors) elif not isinstance(s, unicode): # Note: We use .decode() here, instead of unicode(s, encoding, # errors), so that if s is a SafeString, it ends up being a # SafeUnicode at the end. s = s.decode(encoding, errors) except __HOLE__, e: raise DjangoUnicodeDecodeError(s, *e.args) return s
UnicodeDecodeError
dataset/ETHPy150Open ericw/onelinr/onelinr.py/force_unicode
7,035
def __get__(self, obj, objtype=None): if obj is None: return self if not obj.data: return obj.default try: return getattr(obj, self.internal_name) except __HOLE__: setattr(obj, self.internal_name, self.func(obj)) return getattr(obj, self.internal_name)
AttributeError
dataset/ETHPy150Open mahmoud/boltons/boltons/statsutils.py/_StatsProperty.__get__
7,036
def __call__(self, *args): try: return self.cache[args] except KeyError: value = self.func(*args) self.cache[args] = value return value except __HOLE__: # uncachable -- for instance, passing a list as an argument. # Better to not cache than to blow up entirely. return self.func(*args)
TypeError
dataset/ETHPy150Open tanghaibao/jcvi/utils/cbook.py/memoized.__call__
7,037
def __getitem__(self, item): try: return dict.__getitem__(self, item) except __HOLE__: value = self[item] = type(self)() return value
KeyError
dataset/ETHPy150Open tanghaibao/jcvi/utils/cbook.py/AutoVivification.__getitem__
7,038
@post_only def vote(request): # The type of object we're voting on, can be 'submission' or 'comment' vote_object_type = request.POST.get('what', None) # The ID of that object as it's stored in the database, positive int vote_object_id = request.POST.get('what_id', None) # The value of the vote we're writing to that object, -1 or 1 # Passing the same value twice will cancel the vote i.e. set it to 0 new_vote_value = request.POST.get('vote_value', None) # By how much we'll change the score, used to modify score on the fly # client side by the javascript instead of waiting for a refresh. vote_diff = 0 if not request.user.is_authenticated(): return HttpResponseForbidden() else: user = RedditUser.objects.get(user=request.user) try: # If the vote value isn't an integer that's equal to -1 or 1 # the request is bad and we can not continue. new_vote_value = int(new_vote_value) if new_vote_value not in [-1, 1]: raise ValueError("Wrong value for the vote!") except (ValueError, __HOLE__): return HttpResponseBadRequest() # if one of the objects is None, 0 or some other bool(value) == False value # or if the object type isn't 'comment' or 'submission' it's a bad request if not all([vote_object_type, vote_object_id, new_vote_value]) or \ vote_object_type not in ['comment', 'submission']: return HttpResponseBadRequest() # Try and get the actual object we're voting on. try: if vote_object_type == "comment": vote_object = Comment.objects.get(id=vote_object_id) elif vote_object_type == "submission": vote_object = Submission.objects.get(id=vote_object_id) else: return HttpResponseBadRequest() # should never happen except (Comment.DoesNotExist, Submission.DoesNotExist): return HttpResponseBadRequest() # Try and get the existing vote for this object, if it exists. try: vote = Vote.objects.get(vote_object_type=vote_object.get_content_type(), vote_object_id=vote_object.id, user=user) except Vote.DoesNotExist: # Create a new vote and that's it. vote = Vote.create(user=user, vote_object=vote_object, vote_value=new_vote_value) vote.save() vote_diff = new_vote_value return JsonResponse({'error' : None, 'voteDiff': vote_diff}) # User already voted on this item, this means the vote is either # being canceled (same value) or changed (different new_vote_value) if vote.value == new_vote_value: # canceling vote vote_diff = vote.cancel_vote() if not vote_diff: return HttpResponseBadRequest( 'Something went wrong while canceling the vote') else: # changing vote vote_diff = vote.change_vote(new_vote_value) if not vote_diff: return HttpResponseBadRequest( 'Wrong values for old/new vote combination') return JsonResponse({'error' : None, 'voteDiff': vote_diff})
TypeError
dataset/ETHPy150Open Nikola-K/django_reddit/reddit/views.py/vote
7,039
def add_related_update(self, model, field, value): """ Adds (name, value) to an update query for an ancestor model. Updates are coalesced so that we only run one update query per ancestor. """ try: self.related_updates[model].append((field, None, value)) except __HOLE__: self.related_updates[model] = [(field, None, value)]
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/db/models/sql/subqueries.py/UpdateQuery.add_related_update
7,040
def launch_tor(config, reactor, tor_binary=None, progress_updates=None, connection_creator=None, timeout=None, kill_on_stderr=True, stdout=None, stderr=None): """launches a new Tor process with the given config. There may seem to be a ton of options, but don't panic: this method should be easy to use and most options can be ignored except for advanced use-cases. Calling with a completely empty TorConfig should Just Work:: config = TorConfig() d = launch_tor(config, reactor) d.addCallback(...) Note that the incoming TorConfig instance is examined and several config options are acted upon appropriately: ``DataDirectory``: if supplied, a tempdir is not created, and the one supplied is not deleted. ``ControlPort``: if 0 (zero), a control connection is NOT established (and ``connection_creator`` is ignored). In this case we can't wait for Tor to bootstrap, and **you must kill the tor** yourself. ``User``: if this exists, we attempt to set ownership of the tempdir to this user (but only if our effective UID is 0). This method may set the following options on the supplied TorConfig object: ``DataDirectory, ControlPort, CookieAuthentication, __OwningControllerProcess`` and WILL call :meth:`txtorcon.TorConfig.save` :param config: an instance of :class:`txtorcon.TorConfig` with any configuration values you want. If ``ControlPort`` isn't set, 9052 is used; if ``DataDirectory`` isn't set, tempdir is used to create one (in this case, it will be deleted upon exit). :param reactor: a Twisted IReactorCore implementation (usually twisted.internet.reactor) :param tor_binary: path to the Tor binary to run. Tries to find the tor binary if unset. :param progress_updates: a callback which gets progress updates; gets as args: percent, tag, summary (FIXME make an interface for this). :param kill_on_stderr: When True (the default), if Tor prints anything on stderr we kill off the process, close the TorControlProtocol and raise an exception. :param stdout: a file-like object to which we write anything that Tor prints on stdout (just needs to support write()). :param stderr: a file-like object to which we write anything that Tor prints on stderr (just needs .write()). Note that we kill Tor off by default if anything appears on stderr; pass "no_kill=True" if you don't like the behavior. :param connection_creator: is mostly available to ease testing, so you probably don't want to supply this. If supplied, it is a callable that should return a Deferred that delivers an :api:`twisted.internet.interfaces.IProtocol <IProtocol>` or ConnectError. See :api:`twisted.internet.interfaces.IStreamClientEndpoint`.connect Note that this parameter is ignored if config.ControlPort == 0 :return: a Deferred which callbacks with a TorProcessProtocol connected to the fully-bootstrapped Tor; this has a :class:`txtorcon.TorControlProtocol` instance as `.tor_protocol`. In Tor, ``__OwningControllerProcess`` will be set and TAKEOWNERSHIP will have been called, so if you close the TorControlProtocol the Tor should exit also (see `control-spec <https://gitweb.torproject.org/torspec.git/blob/HEAD:/control-spec.txt>`_ 3.23). Note that if ControlPort was 0, we don't connect at all and therefore don't wait for Tor to be bootstrapped. In this case, it's up to you to kill off the Tor you created. HACKS: 1. It's hard to know when Tor has both (completely!) written its authentication cookie file AND is listening on the control port. It seems that waiting for the first 'bootstrap' message on stdout is sufficient. Seems fragile...and doesn't work 100% of the time, so FIXME look at Tor source. """ # We have a slight problem with the approach: we need to pass a # few minimum values to a torrc file so that Tor will start up # enough that we may connect to it. Ideally, we'd be able to # start a Tor up which doesn't really do anything except provide # "AUTHENTICATE" and "GETINFO config/names" so we can do our # config validation. # the other option here is to simply write a torrc version of our # config and get Tor to load that...which might be the best # option anyway. # actually, can't we pass them all as command-line arguments? # could be pushing some limits for giant configs... if tor_binary is None: tor_binary = find_tor_binary() if tor_binary is None: # We fail right here instead of waiting for the reactor to start raise TorNotFound('Tor binary could not be found') # make sure we got things that have write() for stderr, stdout # kwargs for arg in [stderr, stdout]: if arg and not getattr(arg, "write", None): raise RuntimeError( 'File-like object needed for stdout or stderr args.') try: data_directory = config.DataDirectory user_set_data_directory = True except KeyError: user_set_data_directory = False data_directory = tempfile.mkdtemp(prefix='tortmp') config.DataDirectory = data_directory # Set ownership on the temp-dir to the user tor will drop privileges to # when executing as root. try: user = config.User except KeyError: pass else: if sys.platform in ('linux2', 'darwin') and os.geteuid() == 0: os.chown(data_directory, pwd.getpwnam(user).pw_uid, -1) try: control_port = config.ControlPort except KeyError: control_port = 9052 # FIXME choose a random, unoccupied one? config.ControlPort = control_port # so, we support passing in ControlPort=0 -- not really sure if # this is a good idea (since then the caller has to kill the tor # off, etc), but at least one person has requested it :/ if control_port != 0: config.CookieAuthentication = 1 config.__OwningControllerProcess = os.getpid() if connection_creator is None: connection_creator = functools.partial( TCP4ClientEndpoint(reactor, 'localhost', control_port).connect, TorProtocolFactory() ) else: connection_creator = None # NOTE well, that if we don't pass "-f" then Tor will merrily load # it's default torrc, and apply our options over top... :/ config_args = ['-f', '/non-existant', '--ignore-missing-torrc'] # ...now add all our config options on the command-line. This # avoids writing a temporary torrc. for (k, v) in config.config_args(): config_args.append(k) config_args.append(v) # txtorlog.msg('Running with config:\n', ' '.join(config_args)) process_protocol = TorProcessProtocol( connection_creator, progress_updates, config, reactor, timeout, kill_on_stderr, stdout, stderr ) # we set both to_delete and the shutdown events because this # process might be shut down way before the reactor, but if the # reactor bombs out without the subprocess getting closed cleanly, # we'll want the system shutdown events triggered so the temporary # files get cleaned up either way # we don't want to delete the user's directories, just temporary # ones this method created. if not user_set_data_directory: process_protocol.to_delete = [data_directory] reactor.addSystemEventTrigger( 'before', 'shutdown', functools.partial(delete_file_or_tree, data_directory) ) try: log.msg('Spawning tor process with DataDirectory', data_directory) args = [tor_binary] + config_args transport = reactor.spawnProcess( process_protocol, tor_binary, args=args, env={'HOME': data_directory}, path=data_directory ) # FIXME? don't need rest of the args: uid, gid, usePTY, childFDs) transport.closeStdin() except __HOLE__ as e: return defer.fail(e) if process_protocol.connected_cb: return process_protocol.connected_cb return defer.succeed(process_protocol)
RuntimeError
dataset/ETHPy150Open meejah/txtorcon/txtorcon/torconfig.py/launch_tor
7,041
def __getattr__(self, name): ''' FIXME can't we just move this to @property decorated methods instead? ''' # For stealth authentication, the .onion is per-client. So in # that case, we really have no choice here -- we can't have # "a" hostname. So we just barf; it's an error to access to # hostname this way. Instead, use .clients.{hostname, cookie} if name == 'private_key': with open(os.path.join(self.dir, name)) as f: data = f.read().strip() self.__dict__[name] = data elif name == 'clients': clients = [] try: with open(os.path.join(self.dir, 'hostname')) as f: for line in f.readlines(): args = line.split() # XXX should be a dict? if len(args) > 1: # tag, onion-uri? clients.append((args[0], args[1])) else: clients.append(('default', args[0])) except __HOLE__: pass self.__dict__[name] = clients elif name == 'hostname': with open(os.path.join(self.dir, name)) as f: data = f.read().strip() host = None for line in data.split('\n'): h = line.split(' ')[0] if host is None: host = h elif h != host: raise RuntimeError( ".hostname accessed on stealth-auth'd hidden-service " "with multiple onion addresses." ) self.__dict__[name] = h elif name == 'client_keys': fname = os.path.join(self.dir, name) keys = [] if os.path.exists(fname): with open(fname) as f: keys = parse_client_keys(f) self.__dict__[name] = keys return self.__dict__[name]
IOError
dataset/ETHPy150Open meejah/txtorcon/txtorcon/torconfig.py/HiddenService.__getattr__
7,042
def bootstrap(self, arg=None): ''' This only takes args so it can be used as a callback. Don't pass an arg, it is ignored. ''' try: self.protocol.add_event_listener( 'CONF_CHANGED', self._conf_changed) except __HOLE__: # for Tor versions which don't understand CONF_CHANGED # there's nothing we can really do. log.msg( "Can't listen for CONF_CHANGED event; won't stay up-to-date " "with other clients.") d = self.protocol.get_info_raw("config/names") d.addCallback(self._do_setup) d.addCallback(self.do_post_bootstrap) d.addErrback(self.do_post_errback)
RuntimeError
dataset/ETHPy150Open meejah/txtorcon/txtorcon/torconfig.py/TorConfig.bootstrap
7,043
@jit.elidable def _lookup(self, sym, version): try: return self.bindings[sym] except __HOLE__: raise SchemeException("toplevel variable %s not found" % sym.variable_name())
KeyError
dataset/ETHPy150Open samth/pycket/pycket/env.py/ToplevelEnv._lookup
7,044
def add_client(self, client_name, redirect_uri): """Adds a client application to the database, with its client name and redirect URI. It returns the generated client_id and client_secret """ try: self.db.clients except __HOLE__: self.create_tables() client_id = self.generate_hash_sha1() client_secret = self.generate_hash_sha1() self.db.clients.insert(**{'client_id': client_id, 'client_secret': client_secret, 'redirect_uri': redirect_uri, 'client_name': client_name}) return client_id, client_secret
AttributeError
dataset/ETHPy150Open joaoqalves/web2py-oauth2/modules/oauth/storage/__init__.py/web2pyStorage.add_client
7,045
def get_client_credentials(self, client_id): """Gets the client credentials by the client application ID given.""" try: return self.db.clients(client_id) except __HOLE__: self.create_tables() return None
AttributeError
dataset/ETHPy150Open joaoqalves/web2py-oauth2/modules/oauth/storage/__init__.py/web2pyStorage.get_client_credentials
7,046
def valid_code(self, client_id, code): """Validates if a code is (still) a valid one. It takes two arguments: * The client application ID * The temporary code given by the application It returns True if the code is valid. Otherwise, False """ try: data = self.db.codes(self.db.codes.code_id == code).select(self.db.expires_access).first() except __HOLE__: self.create_tables() return False if data: return datetime.datetime.now() < data.expires_access return False
AttributeError
dataset/ETHPy150Open joaoqalves/web2py-oauth2/modules/oauth/storage/__init__.py/web2pyStorage.valid_code
7,047
def exists_code(self, code): """Checks if a given code exists on the database or not""" try: self.db.codes(self.db.codes.code_id == code).select().first() != None except __HOLE__: self.create_tables() return False
AttributeError
dataset/ETHPy150Open joaoqalves/web2py-oauth2/modules/oauth/storage/__init__.py/web2pyStorage.exists_code
7,048
def get_user_id(self, client_id, code): """Gets the user ID, given a client application ID and a temporary authentication code """ try: return self.db.codes(self.db.codes.code_id == code).select(self.db.codes.user_id).first() except __HOLE__: self.create_tables() return None
AttributeError
dataset/ETHPy150Open joaoqalves/web2py-oauth2/modules/oauth/storage/__init__.py/web2pyStorage.get_user_id
7,049
def get_access_token(self, access_token): """Returns the token data, if the access token exists""" try: return self.db(self.db.tokens.access_token == access_token).select().first() except __HOLE__: self.create_tables() return None
AttributeError
dataset/ETHPy150Open joaoqalves/web2py-oauth2/modules/oauth/storage/__init__.py/web2pyStorage.get_access_token
7,050
def get_refresh_token(self, refresh_token): """Returns the token data, if the refresh token exists""" try: return self.db.tokens(self.db.tokens.refresh_token == refresh_token).select().first() # 'code' == 'refresh_token', right? [pid that is] except __HOLE__: self.create_tables() return None
AttributeError
dataset/ETHPy150Open joaoqalves/web2py-oauth2/modules/oauth/storage/__init__.py/web2pyStorage.get_refresh_token
7,051
def invoke(self, args): if args.static: print(settings.bokehjsdir()) else: try: import IPython ipy_version = IPython.__version__ except __HOLE__: ipy_version = "Not installed" print("Python version : %s" % sys.version.split('\n')[0]) print("IPython version : %s" % ipy_version) print("Bokeh version : %s" % __version__) print("BokehJS static path : %s" % settings.bokehjsdir())
ImportError
dataset/ETHPy150Open bokeh/bokeh/bokeh/command/subcommands/info.py/Info.invoke
7,052
def render_paginate(request, template, objects, per_page, extra_context={}): """ Paginated list of objects. """ paginator = Paginator(objects, per_page) page = request.GET.get('page', 1) get_params = '&'.join(['%s=%s' % (k, request.GET[k]) for k in request.GET if k != 'page']) try: page_number = int(page) except __HOLE__: if page == 'last': page_number = paginator.num_pages else: raise Http404 try: page_obj = paginator.page(page_number) except InvalidPage: raise Http404 context = { 'object_list': page_obj.object_list, 'paginator': paginator, 'page_obj': page_obj, 'is_paginated': page_obj.has_other_pages(), 'get_params': get_params } context.update(extra_context) return render(request, template, context)
ValueError
dataset/ETHPy150Open aisayko/Django-tinymce-filebrowser/mce_filebrowser/utils.py/render_paginate
7,053
def get_connection(backend=None, fail_silently=False, **kwds): """Load an email backend and return an instance of it. If backend is None (default) settings.EMAIL_BACKEND is used. Both fail_silently and other keyword arguments are used in the constructor of the backend. """ path = backend or settings.EMAIL_BACKEND try: mod_name, klass_name = path.rsplit('.', 1) mod = import_module(mod_name) except __HOLE__, e: raise ImproperlyConfigured(('Error importing email backend module %s: "%s"' % (mod_name, e))) try: klass = getattr(mod, klass_name) except AttributeError: raise ImproperlyConfigured(('Module "%s" does not define a ' '"%s" class' % (mod_name, klass_name))) return klass(fail_silently=fail_silently, **kwds)
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/mail/__init__.py/get_connection
7,054
def _check_extra_specs(self, specs): if type(specs) is not dict: msg = _('Bad extra_specs provided') raise exc.HTTPBadRequest(explanation=msg) try: flavors.validate_extra_spec_keys(specs.keys()) except __HOLE__: msg = _("Fail to validate provided extra specs keys. " "Expected string") raise exc.HTTPBadRequest(explanation=msg) except exception.InvalidInput as error: raise exc.HTTPBadRequest(explanation=error.format_message()) for key, value in six.iteritems(specs): try: utils.check_string_length(key, 'extra_specs key', min_length=1, max_length=255) # NOTE(dims): The following check was added for backwards # compatibility. if (isinstance(value, float) or type(value) in six.integer_types): value = six.text_type(value) utils.check_string_length(value, 'extra_specs value', max_length=255) except exception.InvalidInput as error: raise exc.HTTPBadRequest(explanation=error.format_message())
TypeError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/flavorextraspecs.py/FlavorExtraSpecsController._check_extra_specs
7,055
def show(self, req, flavor_id, id): """Return a single extra spec item.""" context = req.environ['nova.context'] authorize(context, action='show') flavor = common.get_flavor(context, flavor_id) try: return {id: flavor.extra_specs[id]} except __HOLE__: msg = _("Flavor %(flavor_id)s has no extra specs with " "key %(key)s.") % dict(flavor_id=flavor_id, key=id) raise exc.HTTPNotFound(explanation=msg)
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/flavorextraspecs.py/FlavorExtraSpecsController.show
7,056
def delete(self, req, flavor_id, id): """Deletes an existing extra spec.""" context = req.environ['nova.context'] authorize(context, action='delete') flavor = common.get_flavor(context, flavor_id) try: del flavor.extra_specs[id] flavor.save() except (exception.FlavorNotFound, exception.FlavorExtraSpecsNotFound) as e: raise exc.HTTPNotFound(explanation=e.format_message()) except __HOLE__: msg = _("Flavor %(flavor_id)s has no extra specs with " "key %(key)s.") % dict(flavor_id=flavor_id, key=id) raise exc.HTTPNotFound(explanation=msg)
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/flavorextraspecs.py/FlavorExtraSpecsController.delete
7,057
def __call__(self, *args): try: return self.cache[args] except __HOLE__: result = self.func(*args) self.cache[args] = result return result
KeyError
dataset/ETHPy150Open adblockplus/gyp/pylib/gyp/common.py/memoize.__call__
7,058
def WriteOnDiff(filename): """Write to a file only if the new contents differ. Arguments: filename: name of the file to potentially write to. Returns: A file like object which will write to temporary file and only overwrite the target if it differs (on close). """ class Writer(object): """Wrapper around file which only covers the target if it differs.""" def __init__(self): # Pick temporary file. tmp_fd, self.tmp_path = tempfile.mkstemp( suffix='.tmp', prefix=os.path.split(filename)[1] + '.gyp.', dir=os.path.split(filename)[0]) try: self.tmp_file = os.fdopen(tmp_fd, 'wb') except Exception: # Don't leave turds behind. os.unlink(self.tmp_path) raise def __getattr__(self, attrname): # Delegate everything else to self.tmp_file return getattr(self.tmp_file, attrname) def close(self): try: # Close tmp file. self.tmp_file.close() # Determine if different. same = False try: same = filecmp.cmp(self.tmp_path, filename, False) except __HOLE__, e: if e.errno != errno.ENOENT: raise if same: # The new file is identical to the old one, just get rid of the new # one. os.unlink(self.tmp_path) else: # The new file is different from the old one, or there is no old one. # Rename the new file to the permanent name. # # tempfile.mkstemp uses an overly restrictive mode, resulting in a # file that can only be read by the owner, regardless of the umask. # There's no reason to not respect the umask here, which means that # an extra hoop is required to fetch it and reset the new file's mode. # # No way to get the umask without setting a new one? Set a safe one # and then set it back to the old value. umask = os.umask(077) os.umask(umask) os.chmod(self.tmp_path, 0666 & ~umask) if sys.platform == 'win32' and os.path.exists(filename): # NOTE: on windows (but not cygwin) rename will not replace an # existing file, so it must be preceded with a remove. Sadly there # is no way to make the switch atomic. os.remove(filename) os.rename(self.tmp_path, filename) except Exception: # Don't leave turds behind. os.unlink(self.tmp_path) raise return Writer()
OSError
dataset/ETHPy150Open adblockplus/gyp/pylib/gyp/common.py/WriteOnDiff
7,059
def EnsureDirExists(path): """Make sure the directory for |path| exists.""" try: os.makedirs(os.path.dirname(path)) except __HOLE__: pass
OSError
dataset/ETHPy150Open adblockplus/gyp/pylib/gyp/common.py/EnsureDirExists
7,060
def run(self): import os, sys try: import pyflakes.scripts.pyflakes as flakes except __HOLE__: print "Audit requires PyFlakes installed in your system.""" sys.exit(-1) warns = 0 # Define top-level directories dirs = ('flask', 'examples', 'scripts') for dir in dirs: for root, _, files in os.walk(dir): for file in files: if file != '__init__.py' and file.endswith('.py') : warns += flakes.checkPath(os.path.join(root, file)) if warns > 0: print "Audit finished with total %d warnings." % warns else: print "No problems found in sourcecode."
ImportError
dataset/ETHPy150Open tokuda109/flask-docs-ja/setup.py/run_audit.run
7,061
def topological_sort(G): """Return a generator of nodes in topologically sorted order. A topological sort is a nonunique permutation of the nodes such that an edge from u to v implies that u appears before v in the topological sort order. Parameters ---------- G : NetworkX digraph A directed graph Returns ------- topologically_sorted_nodes : iterable An iterable of node names in topological sorted order. Raises ------ NetworkXError Topological sort is defined for directed graphs only. If the graph G is undirected, a :exc:`NetworkXError` is raised. NetworkXUnfeasible If G is not a directed acyclic graph (DAG) no topological sort exists and a NetworkXUnfeasible exception is raised. This can also be raised if G is changed while the returned iterator is being processed. RuntimeError If G is changed while the returned iterator is being processed. Examples -------- To get the reverse order of the topological sort:: >>> DG = nx.DiGraph([(1, 2), (2, 3)]) >>> list(reversed(list(nx.topological_sort(DG)))) [3, 2, 1] Notes ----- This algorithm is based on a description and proof in Introduction to algorithms - a creative approach [1]_ . See also -------- is_directed_acyclic_graph, lexicographical_topological_sort References ---------- .. [1] Manber, U. (1989). Introduction to algorithms - a creative approach. Addison-Wesley. http://www.amazon.com/Introduction-Algorithms-A-Creative-Approach/dp/0201120372 """ if not G.is_directed(): raise nx.NetworkXError( "Topological sort not defined on undirected graphs.") indegree_map = {v: d for v, d in G.in_degree() if d > 0} # These nodes have zero indegree and ready to be returned. zero_indegree = [v for v, d in G.in_degree() if d == 0] while zero_indegree: node = zero_indegree.pop() if node not in G: raise RuntimeError("Graph changed during iteration") for _, child in G.edges(node): try: indegree_map[child] -= 1 except __HOLE__: raise RuntimeError("Graph changed during iteration") if indegree_map[child] == 0: zero_indegree.append(child) del indegree_map[child] yield node if indegree_map: raise nx.NetworkXUnfeasible("Graph contains a cycle or graph changed " "during iteration")
KeyError
dataset/ETHPy150Open networkx/networkx/networkx/algorithms/dag.py/topological_sort
7,062
def lexicographical_topological_sort(G, key=None): """Return a generator of nodes in lexicographically topologically sorted order. A topological sort is a nonunique permutation of the nodes such that an edge from u to v implies that u appears before v in the topological sort order. Parameters ---------- G : NetworkX digraph A directed graph key : function, optional This function maps nodes to keys with which to resolve ambiguities in the sort order. Defaults to the identity function. Returns ------- lexicographically_topologically_sorted_nodes : iterable An iterable of node names in lexicographical topological sort order. Raises ------ NetworkXError Topological sort is defined for directed graphs only. If the graph G is undirected, a :exc:`NetworkXError` is raised. NetworkXUnfeasible If G is not a directed acyclic graph (DAG) no topological sort exists and a NetworkXUnfeasible exception is raised. This can also be raised if G is changed while the returned iterator is being processed. RuntimeError If G is changed while the returned iterator is being processed. Notes ----- This algorithm is based on a description and proof in Introduction to algorithms - a creative approach [1]_ . See also -------- topological_sort References ---------- .. [1] Manber, U. (1989). Introduction to algorithms - a creative approach. Addison-Wesley. http://www.amazon.com/Introduction-Algorithms-A-Creative-Approach/dp/0201120372 """ if not G.is_directed(): raise nx.NetworkXError( "Topological sort not defined on undirected graphs.") if key is None: key = lambda x: x def create_tuple(node): return key(node), node indegree_map = {v: d for v, d in G.in_degree() if d > 0} # These nodes have zero indegree and ready to be returned. zero_indegree = [create_tuple(v) for v, d in G.in_degree() if d == 0] heapq.heapify(zero_indegree) while zero_indegree: _, node = heapq.heappop(zero_indegree) if node not in G: raise RuntimeError("Graph changed during iteration") for _, child in G.edges(node): try: indegree_map[child] -= 1 except __HOLE__: raise RuntimeError("Graph changed during iteration") if indegree_map[child] == 0: heapq.heappush(zero_indegree, create_tuple(child)) del indegree_map[child] yield node if indegree_map: raise nx.NetworkXUnfeasible("Graph contains a cycle or graph changed " "during iteration")
KeyError
dataset/ETHPy150Open networkx/networkx/networkx/algorithms/dag.py/lexicographical_topological_sort
7,063
def get_notification_language(user): """ Returns site-specific notification language for this user. Raises LanguageStoreNotAvailable if this site does not use translated notifications. """ if getattr(settings, "NOTIFICATION_LANGUAGE_MODULE", False): try: app_label, model_name = settings.NOTIFICATION_LANGUAGE_MODULE.split(".") model = apps.get_app_config(app_label).get_model(model_name) language_model = model._default_manager.get(user__id__exact=user.id) if hasattr(language_model, "language"): return language_model.language except (__HOLE__, ImproperlyConfigured, model.DoesNotExist): raise LanguageStoreNotAvailable raise LanguageStoreNotAvailable
ImportError
dataset/ETHPy150Open amarandon/smeuhsocial/apps/notification/models.py/get_notification_language
7,064
def __call__(self, cutpoint_function): if isgeneratorfunction(cutpoint_function): if PY3: from aspectlib.py3support import decorate_advising_generator_py3 return decorate_advising_generator_py3(self.advising_function, cutpoint_function, self.bind) else: def advising_generator_wrapper(*args, **kwargs): if self.bind: advisor = self.advising_function(cutpoint_function, *args, **kwargs) else: advisor = self.advising_function(*args, **kwargs) if not isgenerator(advisor): raise ExpectedGenerator("advising_function %s did not return a generator." % self.advising_function) try: advice = next(advisor) while True: logdebug('Got advice %r from %s', advice, self.advising_function) if advice is Proceed or advice is None or isinstance(advice, Proceed): if isinstance(advice, Proceed): args = advice.args kwargs = advice.kwargs gen = cutpoint_function(*args, **kwargs) try: try: generated = next(gen) except StopIteration as exc: logexception("The cutpoint has been exhausted (early).") result = exc.args if result: if len(result) == 1: result = exc.args[0] else: result = None else: while True: try: sent = yield generated except GeneratorExit as exc: logexception("Got GeneratorExit while consuming the cutpoint") gen.close() raise exc except BaseException as exc: logexception("Got exception %r. Throwing it the cutpoint", exc) try: generated = gen.throw(*sys.exc_info()) except StopIteration as exc: logexception("The cutpoint has been exhausted.") result = exc.args if result: if len(result) == 1: result = exc.args[0] else: result = None break else: try: if sent is None: generated = next(gen) else: generated = gen.send(sent) except __HOLE__ as exc: logexception("The cutpoint has been exhausted.") result = exc.args if result: if len(result) == 1: result = exc.args[0] else: result = None break except BaseException as exc: advice = advisor.throw(*sys.exc_info()) else: try: advice = advisor.send(result) except StopIteration: raise StopIteration(result) finally: gen.close() elif advice is Return: return elif isinstance(advice, Return): raise StopIteration(advice.value) else: raise UnacceptableAdvice("Unknown advice %s" % advice) finally: advisor.close() return mimic(advising_generator_wrapper, cutpoint_function) else: def advising_function_wrapper(*args, **kwargs): if self.bind: advisor = self.advising_function(cutpoint_function, *args, **kwargs) else: advisor = self.advising_function(*args, **kwargs) if not isgenerator(advisor): raise ExpectedGenerator("advising_function %s did not return a generator." % self.advising_function) try: advice = next(advisor) while True: logdebug('Got advice %r from %s', advice, self.advising_function) if advice is Proceed or advice is None or isinstance(advice, Proceed): if isinstance(advice, Proceed): args = advice.args kwargs = advice.kwargs try: result = cutpoint_function(*args, **kwargs) except Exception: advice = advisor.throw(*sys.exc_info()) else: try: advice = advisor.send(result) except StopIteration: return result elif advice is Return: return elif isinstance(advice, Return): return advice.value else: raise UnacceptableAdvice("Unknown advice %s" % advice) finally: advisor.close() return mimic(advising_function_wrapper, cutpoint_function)
StopIteration
dataset/ETHPy150Open ionelmc/python-aspectlib/src/aspectlib/__init__.py/Aspect.__call__
7,065
def weave(target, aspects, **options): """ Send a message to a recipient Args: target (string, class, instance, function or builtin): The object to weave. aspects (:py:obj:`aspectlib.Aspect`, function decorator or list of): The aspects to apply to the object. subclasses (bool): If ``True``, subclasses of target are weaved. *Only available for classes* aliases (bool): If ``True``, aliases of target are replaced. lazy (bool): If ``True`` only target's ``__init__`` method is patched, the rest of the methods are patched after ``__init__`` is called. *Only available for classes*. methods (list or regex or string): Methods from target to patch. *Only available for classes* Returns: aspectlib.Rollback: An object that can rollback the patches. Raises: TypeError: If target is a unacceptable object, or the specified options are not available for that type of object. .. versionchanged:: 0.4.0 Replaced `only_methods`, `skip_methods`, `skip_magicmethods` options with `methods`. Renamed `on_init` option to `lazy`. Added `aliases` option. Replaced `skip_subclasses` option with `subclasses`. """ if not callable(aspects): if not hasattr(aspects, '__iter__'): raise ExpectedAdvice('%s must be an `Aspect` instance, a callable or an iterable of.' % aspects) for obj in aspects: if not callable(obj): raise ExpectedAdvice('%s must be an `Aspect` instance or a callable.' % obj) assert target, "Can't weave falsy value %r." % target logdebug("weave (target=%s, aspects=%s, **options=%s)", target, aspects, options) bag = options.setdefault('bag', ObjectBag()) if isinstance(target, (list, tuple)): return Rollback([ weave(item, aspects, **options) for item in target ]) elif isinstance(target, basestring): parts = target.split('.') for part in parts: _check_name(part) if len(parts) == 1: __import__(part) return weave_module(sys.modules[part], aspects, **options) for pos in reversed(range(1, len(parts))): owner, name = '.'.join(parts[:pos]), '.'.join(parts[pos:]) try: __import__(owner) owner = sys.modules[owner] except __HOLE__: continue else: break else: raise ImportError("Could not import %r. Last try was for %s" % (target, owner)) if '.' in name: path, name = name.rsplit('.', 1) path = deque(path.split('.')) while path: owner = getattr(owner, path.popleft()) logdebug("@ patching %s from %s ...", name, owner) obj = getattr(owner, name) if isinstance(obj, (type, ClassType)): logdebug(" .. as a class %r.", obj) return weave_class( obj, aspects, owner=owner, name=name, **options ) elif callable(obj): # or isinstance(obj, FunctionType) ?? logdebug(" .. as a callable %r.", obj) if bag.has(obj): return Nothing return patch_module_function(owner, obj, aspects, force_name=name, **options) else: return weave(obj, aspects, **options) name = getattr(target, '__name__', None) if name and getattr(__builtin__, name, None) is target: if bag.has(target): return Nothing return patch_module_function(__builtin__, target, aspects, **options) elif PY3 and ismethod(target): if bag.has(target): return Nothing inst = target.__self__ name = target.__name__ logdebug("@ patching %r (%s) as instance method.", target, name) func = target.__func__ setattr(inst, name, _checked_apply(aspects, func).__get__(inst, type(inst))) return Rollback(lambda: delattr(inst, name)) elif PY3 and isfunction(target): if bag.has(target): return Nothing owner = __import__(target.__module__) path = deque(target.__qualname__.split('.')[:-1]) while path: owner = getattr(owner, path.popleft()) name = target.__name__ logdebug("@ patching %r (%s) as a property.", target, name) func = owner.__dict__[name] return patch_module(owner, name, _checked_apply(aspects, func), func, **options) elif PY2 and isfunction(target): if bag.has(target): return Nothing return patch_module_function(__import__(target.__module__), target, aspects, **options) elif PY2 and ismethod(target): if target.im_self: if bag.has(target): return Nothing inst = target.im_self name = target.__name__ logdebug("@ patching %r (%s) as instance method.", target, name) func = target.im_func setattr(inst, name, _checked_apply(aspects, func).__get__(inst, type(inst))) return Rollback(lambda: delattr(inst, name)) else: klass = target.im_class name = target.__name__ return weave(klass, aspects, methods='%s$' % name, **options) elif isclass(target): return weave_class(target, aspects, **options) elif ismodule(target): return weave_module(target, aspects, **options) elif type(target).__module__ not in ('builtins', '__builtin__') or InstanceType and isinstance(target, InstanceType): return weave_instance(target, aspects, **options) else: raise UnsupportedType("Can't weave object %s of type %s" % (target, type(target)))
ImportError
dataset/ETHPy150Open ionelmc/python-aspectlib/src/aspectlib/__init__.py/weave
7,066
def patch_module(module, name, replacement, original=UNSPECIFIED, aliases=True, location=None, **_bogus_options): """ Low-level attribute patcher. :param module module: Object to patch. :param str name: Attribute to patch :param replacement: The replacement value. :param original: The original value (in case the object beeing patched uses descriptors or is plain weird). :param bool aliases: If ``True`` patch all the attributes that have the same original value. :returns: An :obj:`aspectlib.Rollback` object. """ rollback = Rollback() seen = False original = getattr(module, name) if original is UNSPECIFIED else original location = module.__name__ if hasattr(module, '__name__') else type(module).__module__ target = module.__name__ if hasattr(module, '__name__') else type(module).__name__ try: replacement.__module__ = location except (TypeError, __HOLE__): pass for alias in dir(module): logdebug("alias:%s (%s)", alias, name) if hasattr(module, alias): obj = getattr(module, alias) logdebug("- %s:%s (%s)", obj, original, obj is original) if obj is original: if aliases or alias == name: logdebug("= saving %s on %s.%s ...", replacement, target, alias) setattr(module, alias, replacement) rollback.merge(lambda alias=alias: setattr(module, alias, original)) if alias == name: seen = True elif alias == name: if ismethod(obj): logdebug("= saving %s on %s.%s ...", replacement, target, alias) setattr(module, alias, replacement) rollback.merge(lambda alias=alias: setattr(module, alias, original)) seen = True else: raise AssertionError("%s.%s = %s is not %s." % (module, alias, obj, original)) if not seen: warnings.warn('Setting %s.%s to %s. There was no previous definition, probably patching the wrong module.' % ( target, name, replacement )) logdebug("= saving %s on %s.%s ...", replacement, target, name) setattr(module, name, replacement) rollback.merge(lambda: setattr(module, name, original)) return rollback
AttributeError
dataset/ETHPy150Open ionelmc/python-aspectlib/src/aspectlib/__init__.py/patch_module
7,067
def deployment_table(deployments): """Returns a PrettyTable representation of the provided marathon deployments. :param deployments: deployments to render :type deployments: [dict] :rtype: PrettyTable """ def get_action(deployment): multiple_apps = len({action['app'] for action in deployment['currentActions']}) > 1 ret = [] for action in deployment['currentActions']: try: action_display = DEPLOYMENT_DISPLAY[action['action']] except __HOLE__: logger.exception('Missing action entry') raise ValueError( 'Unknown Marathon action: {}'.format(action['action'])) if multiple_apps: ret.append('{0} {1}'.format(action_display, action['app'])) else: ret.append(action_display) return '\n'.join(ret) fields = OrderedDict([ ('APP', lambda d: '\n'.join(d['affectedApps'])), ('ACTION', get_action), ('PROGRESS', lambda d: '{0}/{1}'.format(d['currentStep']-1, d['totalSteps'])), ('ID', lambda d: d['id']) ]) tb = table(fields, deployments, sortby="APP") tb.align['APP'] = 'l' tb.align['ACTION'] = 'l' tb.align['ID'] = 'l' return tb
KeyError
dataset/ETHPy150Open dcos/dcos-cli/cli/dcoscli/tables.py/deployment_table
7,068
def __del__(self): try: self._driver.destroy() except (AttributeError, __HOLE__): pass
TypeError
dataset/ETHPy150Open parente/pyttsx/pyttsx/driver.py/DriverProxy.__del__
7,069
def stop(self): ''' Called by the engine to stop the current utterance and clear the queue of commands. ''' # clear queue up to first end loop command while(True): try: mtd, args, name = self._queue[0] except __HOLE__: break if(mtd == self._engine.endLoop): break self._queue.pop(0) self._driver.stop()
IndexError
dataset/ETHPy150Open parente/pyttsx/pyttsx/driver.py/DriverProxy.stop
7,070
def iterate(self): ''' Called by the engine to iterate driver commands and notifications from within an external event loop. ''' try: self._iterator.next() except __HOLE__: pass
StopIteration
dataset/ETHPy150Open parente/pyttsx/pyttsx/driver.py/DriverProxy.iterate
7,071
def __getitem__(self, key): key = '_reserved_' + key if key in self._special_fields else key try: return getattr(self, key) except __HOLE__: raise KeyError(key)
AttributeError
dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/datastructures.py/StrictDict.__getitem__
7,072
def get(self, key, default=None): try: return self[key] except __HOLE__: return default
KeyError
dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/datastructures.py/StrictDict.get
7,073
def pop(self, key, default=None): v = self.get(key, default) try: delattr(self, key) except __HOLE__: pass return v
AttributeError
dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/datastructures.py/StrictDict.pop
7,074
def __getattr__(self, attr): try: super(SemiStrictDict, self).__getattr__(attr) except __HOLE__: try: return self.__getattribute__('_extras')[attr] except KeyError as e: raise AttributeError(e)
AttributeError
dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/datastructures.py/SemiStrictDict.__getattr__
7,075
def __setattr__(self, attr, value): try: super(SemiStrictDict, self).__setattr__(attr, value) except __HOLE__: try: self._extras[attr] = value except AttributeError: self._extras = {attr: value}
AttributeError
dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/datastructures.py/SemiStrictDict.__setattr__
7,076
def __delattr__(self, attr): try: super(SemiStrictDict, self).__delattr__(attr) except AttributeError: try: del self._extras[attr] except __HOLE__ as e: raise AttributeError(e)
KeyError
dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/datastructures.py/SemiStrictDict.__delattr__
7,077
def __iter__(self): try: extras_iter = iter(self.__getattribute__('_extras')) except __HOLE__: extras_iter = () return itertools.chain(super(SemiStrictDict, self).__iter__(), extras_iter)
AttributeError
dataset/ETHPy150Open MongoEngine/mongoengine/mongoengine/base/datastructures.py/SemiStrictDict.__iter__
7,078
def _build_preprocessed_function(func, processors, args_defaults, varargs, varkw): """ Build a preprocessed function with the same signature as `func`. Uses `exec` internally to build a function that actually has the same signature as `func. """ format_kwargs = {'func_name': func.__name__} def mangle(name): return 'a' + uuid4().hex + name format_kwargs['mangled_func'] = mangled_funcname = mangle(func.__name__) def make_processor_assignment(arg, processor_name): template = "{arg} = {processor}({func}, '{arg}', {arg})" return template.format( arg=arg, processor=processor_name, func=mangled_funcname, ) exec_globals = {mangled_funcname: func, 'wraps': wraps} defaults_seen = 0 default_name_template = 'a' + uuid4().hex + '_%d' signature = [] call_args = [] assignments = [] star_map = { varargs: '*', varkw: '**', } def name_as_arg(arg): return star_map.get(arg, '') + arg for arg, default in args_defaults: if default is NO_DEFAULT: signature.append(name_as_arg(arg)) else: default_name = default_name_template % defaults_seen exec_globals[default_name] = default signature.append('='.join([name_as_arg(arg), default_name])) defaults_seen += 1 if arg in processors: procname = mangle('_processor_' + arg) exec_globals[procname] = processors[arg] assignments.append(make_processor_assignment(arg, procname)) call_args.append(name_as_arg(arg)) exec_str = dedent( """\ @wraps({wrapped_funcname}) def {func_name}({signature}): {assignments} return {wrapped_funcname}({call_args}) """ ).format( func_name=func.__name__, signature=', '.join(signature), assignments='\n '.join(assignments), wrapped_funcname=mangled_funcname, call_args=', '.join(call_args), ) compiled = compile( exec_str, func.__code__.co_filename, mode='exec', ) exec_locals = {} exec_(compiled, exec_globals, exec_locals) new_func = exec_locals[func.__name__] code = new_func.__code__ args = { attr: getattr(code, attr) for attr in dir(code) if attr.startswith('co_') } # Copy the firstlineno out of the underlying function so that exceptions # get raised with the correct traceback. # This also makes dynamic source inspection (like IPython `??` operator) # work as intended. try: # Try to get the pycode object from the underlying function. original_code = func.__code__ except __HOLE__: try: # The underlying callable was not a function, try to grab the # `__func__.__code__` which exists on method objects. original_code = func.__func__.__code__ except AttributeError: # The underlying callable does not have a `__code__`. There is # nothing for us to correct. return new_func args['co_firstlineno'] = original_code.co_firstlineno new_func.__code__ = CodeType(*map(getitem(args), _code_argorder)) return new_func
AttributeError
dataset/ETHPy150Open quantopian/zipline/zipline/utils/preprocess.py/_build_preprocessed_function
7,079
def send_private_file(path): path = os.path.join(frappe.local.conf.get('private_path', 'private'), path.strip("/")) filename = os.path.basename(path) if frappe.local.request.headers.get('X-Use-X-Accel-Redirect'): path = '/protected/' + path response = Response() response.headers[b'X-Accel-Redirect'] = frappe.utils.encode(path) else: filepath = frappe.utils.get_site_path(path) try: f = open(filepath, 'rb') except __HOLE__: raise NotFound response = Response(wrap_file(frappe.local.request.environ, f), direct_passthrough=True) # no need for content disposition and force download. let browser handle its opening. # response.headers.add(b'Content-Disposition', b'attachment', filename=filename.encode("utf-8")) response.mimetype = mimetypes.guess_type(filename)[0] or b'application/octet-stream' return response
IOError
dataset/ETHPy150Open frappe/frappe/frappe/utils/response.py/send_private_file
7,080
def search_results_sorted(self, key, document_list, reverse=False): """ Sorting method of DMS search. Sorts documents making query of required data by itself from CouchDB. Appends documents that have no key to the end of the list in uncontrolled order. e.g. order they appear in iteration. @param key: Can be either "mdt_indexes" key name, e.g. "Employee" or one of "metadata_created_date", "metadata_description", "metadata_doc_type_rule_id" @param document_list: List of document names to sort. e.g.: ['ADL-0001', 'CCC-0001', ... ] @param reverse: Direction of sorting (True/False) @return: Sorted list of document names using given @param key e.g.: ['CCC-0001', 'ADL-0001', ... ] """ if document_list: values_list = [] empty_values_list = [] documents = self.get_sorting_docs_indexes(document_list) # Selecting proper sorting couch query params if key in ["metadata_created_date", "metadata_description", "metadata_doc_type_rule_id"]: doc_field = key else: doc_field = 'mdt_indexes' # Creating special, sorting capable list of tuples (Docname, Sorting field value) for doc in documents: if doc_field == 'mdt_indexes': if key in doc[doc_field]: value = doc[doc_field][key] else: value = '' else: value = doc[key] if value: values_list.append((doc.get_id, value)) else: empty_values_list.append(doc.get_id) try: document_list = sorted(values_list, key=itemgetter(1), reverse=reverse) document_list = map(lambda doc: doc[0], document_list) document_list = document_list + empty_values_list except __HOLE__, e: log.error('sorting TypeError error in indexes: %s, in documents_list: %s' % (e, document_list)) pass return document_list
TypeError
dataset/ETHPy150Open adlibre/Adlibre-DMS/adlibre_dms/apps/core/search.py/DMSSearchManager.search_results_sorted
7,081
def parse_melody(fullMeasureNotes, fullMeasureChords): # Remove extraneous elements.x measure = copy.deepcopy(fullMeasureNotes) chords = copy.deepcopy(fullMeasureChords) measure.removeByNotOfClass([note.Note, note.Rest]) chords.removeByNotOfClass([chord.Chord]) # Information for the start of the measure. # 1) measureStartTime: the offset for measure's start, e.g. 476.0. # 2) measureStartOffset: how long from the measure start to the first element. measureStartTime = measure[0].offset - (measure[0].offset % 4) measureStartOffset = measure[0].offset - measureStartTime # Iterate over the notes and rests in measure, finding the grammar for each # note in the measure and adding an abstract grammatical string for it. fullGrammar = "" prevNote = None # Store previous note. Need for interval. numNonRests = 0 # Number of non-rest elements. Need for updating prevNote. for ix, nr in enumerate(measure): # Get the last chord. If no last chord, then (assuming chords is of length # >0) shift first chord in chords to the beginning of the measure. try: lastChord = [n for n in chords if n.offset <= nr.offset][-1] except __HOLE__: chords[0].offset = measureStartTime lastChord = [n for n in chords if n.offset <= nr.offset][-1] # FIRST, get type of note, e.g. R for Rest, C for Chord, etc. # Dealing with solo notes here. If unexpected chord: still call 'C'. elementType = ' ' # R: First, check if it's a rest. Clearly a rest --> only one possibility. if isinstance(nr, note.Rest): elementType = 'R' # C: Next, check to see if note pitch is in the last chord. elif nr.name in lastChord.pitchNames or isinstance(nr, chord.Chord): elementType = 'C' # L: (Complement tone) Skip this for now. # S: Check if it's a scale tone. elif __is_scale_tone(lastChord, nr): elementType = 'S' # A: Check if it's an approach tone, i.e. +-1 halfstep chord tone. elif __is_approach_tone(lastChord, nr): elementType = 'A' # X: Otherwise, it's an arbitrary tone. Generate random note. else: elementType = 'X' # SECOND, get the length for each element. e.g. 8th note = R8, but # to simplify things you'll use the direct num, e.g. R,0.125 if (ix == (len(measure)-1)): # formula for a in "a - b": start of measure (e.g. 476) + 4 diff = measureStartTime + 4.0 - nr.offset else: diff = measure[ix + 1].offset - nr.offset # Combine into the note info. noteInfo = "%s,%.3f" % (elementType, nr.quarterLength) # back to diff # THIRD, get the deltas (max range up, max range down) based on where # the previous note was, +- minor 3. Skip rests (don't affect deltas). intervalInfo = "" if isinstance(nr, note.Note): numNonRests += 1 if numNonRests == 1: prevNote = nr else: noteDist = interval.Interval(noteStart=prevNote, noteEnd=nr) noteDistUpper = interval.add([noteDist, "m3"]) noteDistLower = interval.subtract([noteDist, "m3"]) intervalInfo = ",<%s,%s>" % (noteDistUpper.directedName, noteDistLower.directedName) # print "Upper, lower: %s, %s" % (noteDistUpper, # noteDistLower) # print "Upper, lower dnames: %s, %s" % ( # noteDistUpper.directedName, # noteDistLower.directedName) # print "The interval: %s" % (intervalInfo) prevNote = nr # Return. Do lazy evaluation for real-time performance. grammarTerm = noteInfo + intervalInfo fullGrammar += (grammarTerm + " ") return fullGrammar.rstrip()
IndexError
dataset/ETHPy150Open jisungk/deepjazz/grammar.py/parse_melody
7,082
def unparse_grammar(m1_grammar, m1_chords): m1_elements = stream.Voice() currOffset = 0.0 # for recalculate last chord. prevElement = None for ix, grammarElement in enumerate(m1_grammar.split(' ')): terms = grammarElement.split(',') currOffset += float(terms[1]) # works just fine # Case 1: it's a rest. Just append if terms[0] == 'R': rNote = note.Rest(quarterLength = float(terms[1])) m1_elements.insert(currOffset, rNote) continue # Get the last chord first so you can find chord note, scale note, etc. try: lastChord = [n for n in m1_chords if n.offset <= currOffset][-1] except __HOLE__: m1_chords[0].offset = 0.0 lastChord = [n for n in m1_chords if n.offset <= currOffset][-1] # Case: no < > (should just be the first note) so generate from range # of lowest chord note to highest chord note (if not a chord note, else # just generate one of the actual chord notes). # Case #1: if no < > to indicate next note range. Usually this lack of < > # is for the first note (no precedent), or for rests. if (len(terms) == 2): # Case 1: if no < >. insertNote = note.Note() # default is C # Case C: chord note. if terms[0] == 'C': insertNote = __generate_chord_tone(lastChord) # Case S: scale note. elif terms[0] == 'S': insertNote = __generate_scale_tone(lastChord) # Case A: approach note. # Handle both A and X notes here for now. else: insertNote = __generate_approach_tone(lastChord) # Update the stream of generated notes insertNote.quarterLength = float(terms[1]) if insertNote.octave < 4: insertNote.octave = 4 m1_elements.insert(currOffset, insertNote) prevElement = insertNote # Case #2: if < > for the increment. Usually for notes after the first one. else: # Get lower, upper intervals and notes. interval1 = interval.Interval(terms[2].replace("<",'')) interval2 = interval.Interval(terms[3].replace(">",'')) if interval1.cents > interval2.cents: upperInterval, lowerInterval = interval1, interval2 else: upperInterval, lowerInterval = interval2, interval1 lowPitch = interval.transposePitch(prevElement.pitch, lowerInterval) highPitch = interval.transposePitch(prevElement.pitch, upperInterval) numNotes = int(highPitch.ps - lowPitch.ps + 1) # for range(s, e) # Case C: chord note, must be within increment (terms[2]). # First, transpose note with lowerInterval to get note that is # the lower bound. Then iterate over, and find valid notes. Then # choose randomly from those. if terms[0] == 'C': relevantChordTones = [] for i in xrange(0, numNotes): currNote = note.Note(lowPitch.transpose(i).simplifyEnharmonic()) if __is_chord_tone(lastChord, currNote): relevantChordTones.append(currNote) if len(relevantChordTones) > 1: insertNote = random.choice([i for i in relevantChordTones if i.nameWithOctave != prevElement.nameWithOctave]) elif len(relevantChordTones) == 1: insertNote = relevantChordTones[0] else: # if no choices, set to prev element +-1 whole step insertNote = prevElement.transpose(random.choice([-2,2])) if insertNote.octave < 3: insertNote.octave = 3 insertNote.quarterLength = float(terms[1]) m1_elements.insert(currOffset, insertNote) # Case S: scale note, must be within increment. elif terms[0] == 'S': relevantScaleTones = [] for i in xrange(0, numNotes): currNote = note.Note(lowPitch.transpose(i).simplifyEnharmonic()) if __is_scale_tone(lastChord, currNote): relevantScaleTones.append(currNote) if len(relevantScaleTones) > 1: insertNote = random.choice([i for i in relevantScaleTones if i.nameWithOctave != prevElement.nameWithOctave]) elif len(relevantScaleTones) == 1: insertNote = relevantScaleTones[0] else: # if no choices, set to prev element +-1 whole step insertNote = prevElement.transpose(random.choice([-2,2])) if insertNote.octave < 3: insertNote.octave = 3 insertNote.quarterLength = float(terms[1]) m1_elements.insert(currOffset, insertNote) # Case A: approach tone, must be within increment. # For now: handle both A and X cases. else: relevantApproachTones = [] for i in xrange(0, numNotes): currNote = note.Note(lowPitch.transpose(i).simplifyEnharmonic()) if __is_approach_tone(lastChord, currNote): relevantApproachTones.append(currNote) if len(relevantApproachTones) > 1: insertNote = random.choice([i for i in relevantApproachTones if i.nameWithOctave != prevElement.nameWithOctave]) elif len(relevantApproachTones) == 1: insertNote = relevantApproachTones[0] else: # if no choices, set to prev element +-1 whole step insertNote = prevElement.transpose(random.choice([-2,2])) if insertNote.octave < 3: insertNote.octave = 3 insertNote.quarterLength = float(terms[1]) m1_elements.insert(currOffset, insertNote) # update the previous element. prevElement = insertNote return m1_elements
IndexError
dataset/ETHPy150Open jisungk/deepjazz/grammar.py/unparse_grammar
7,083
def handle(self, *args, **options): from django.conf import settings from django.utils import translation # Activate the current language, because it won't get activated later. try: translation.activate(settings.LANGUAGE_CODE) except __HOLE__: pass runcpserver(args)
AttributeError
dataset/ETHPy150Open lincolnloop/django-cpserver/django_cpserver/management/commands/runcpserver.py/Command.handle
7,084
def get_uid_gid(uid, gid=None): """Try to change UID and GID to the provided values. UID and GID are given as names like 'nobody' not integer. Src: http://mail.mems-exchange.org/durusmail/quixote-users/4940/1/ """ import pwd, grp uid, default_grp = pwd.getpwnam(uid)[2:4] if gid is None: gid = default_grp else: try: gid = grp.getgrnam(gid)[2] except __HOLE__: gid = default_grp return (uid, gid)
KeyError
dataset/ETHPy150Open lincolnloop/django-cpserver/django_cpserver/management/commands/runcpserver.py/get_uid_gid
7,085
def poll_process(pid): """ Poll for process with given pid up to 10 times waiting .25 seconds in between each poll. Returns False if the process no longer exists otherwise, True. """ for n in range(10): time.sleep(0.25) try: # poll the process state os.kill(pid, 0) except __HOLE__, e: if e[0] == errno.ESRCH: # process has died return False else: raise Exception return True
OSError
dataset/ETHPy150Open lincolnloop/django-cpserver/django_cpserver/management/commands/runcpserver.py/poll_process
7,086
def stop_server(pidfile): """ Stop process whose pid was written to supplied pidfile. First try SIGTERM and if it fails, SIGKILL. If process is still running, an exception is raised. """ if os.path.exists(pidfile): pid = int(open(pidfile).read()) try: os.kill(pid, signal.SIGTERM) except __HOLE__: #process does not exist os.remove(pidfile) return if poll_process(pid): #process didn't exit cleanly, make one last effort to kill it os.kill(pid, signal.SIGKILL) if poll_process(pid): raise OSError, "Process %s did not stop." os.remove(pidfile)
OSError
dataset/ETHPy150Open lincolnloop/django-cpserver/django_cpserver/management/commands/runcpserver.py/stop_server
7,087
def start_server(options): """ Start CherryPy server """ if options['daemonize'] and options['server_user'] and options['server_group']: #ensure the that the daemon runs as specified user change_uid_gid(options['server_user'], options['server_group']) from cherrypy.wsgiserver import CherryPyWSGIServer as Server from django.core.handlers.wsgi import WSGIHandler server = Server( (options['host'], int(options['port'])), WSGIHandler(), int(options['threads']), options['server_name'] ) if options['ssl_certificate'] and options['ssl_private_key']: server.ssl_certificate = options['ssl_certificate'] server.ssl_private_key = options['ssl_private_key'] try: server.start() except __HOLE__: server.stop()
KeyboardInterrupt
dataset/ETHPy150Open lincolnloop/django-cpserver/django_cpserver/management/commands/runcpserver.py/start_server
7,088
def execute(): for user in frappe.get_all("User"): username = user["name"] bookmarks = frappe.db.get_default("_bookmarks", username) if not bookmarks: continue if isinstance(bookmarks, basestring): bookmarks = json.loads(bookmarks) for opts in bookmarks: route = (opts.get("route") or "").strip("#/ ") if route and route.startswith("Form"): try: view, doctype, docname = opts["route"].split("/") except __HOLE__: continue if frappe.db.exists(doctype, docname): if (doctype=="DocType" or int(frappe.db.get_value("DocType", doctype, "issingle") or 0) or not frappe.db.table_exists(doctype)): continue _toggle_like(doctype, docname, add="Yes", user=username)
ValueError
dataset/ETHPy150Open frappe/frappe/frappe/patches/v5_0/bookmarks_to_stars.py/execute
7,089
def find(self, obj, name=None, module=None, globs=None, extraglobs=None): """ Return a list of the DocTests that are defined by the given object's docstring, or by any of its contained objects' docstrings. The optional parameter `module` is the module that contains the given object. If the module is not specified or is None, then the test finder will attempt to automatically determine the correct module. The object's module is used: - As a default namespace, if `globs` is not specified. - To prevent the DocTestFinder from extracting DocTests from objects that are imported from other modules. - To find the name of the file containing the object. - To help find the line number of the object within its file. Contained objects whose module does not match `module` are ignored. If `module` is False, no attempt to find the module will be made. This is obscure, of use mostly in tests: if `module` is False, or is None but cannot be found automatically, then all objects are considered to belong to the (non-existent) module, so all contained objects will (recursively) be searched for doctests. The globals for each DocTest is formed by combining `globs` and `extraglobs` (bindings in `extraglobs` override bindings in `globs`). A new copy of the globals dictionary is created for each DocTest. If `globs` is not specified, then it defaults to the module's `__dict__`, if specified, or {} otherwise. If `extraglobs` is not specified, then it defaults to {}. """ # If name was not specified, then extract it from the object. if name is None: name = getattr(obj, '__name__', None) if name is None: raise ValueError("DocTestFinder.find: name must be given " "when obj.__name__ doesn't exist: %r" % (type(obj),)) # Find the module that contains the given object (if obj is # a module, then module=obj.). Note: this may fail, in which # case module will be None. if module is False: module = None elif module is None: module = inspect.getmodule(obj) # Read the module's source code. This is used by # DocTestFinder._find_lineno to find the line number for a # given object's docstring. try: file = inspect.getsourcefile(obj) or inspect.getfile(obj) source_lines = linecache.getlines(file) if not source_lines: source_lines = None except __HOLE__: source_lines = None # Initialize globals, and merge in extraglobs. if globs is None: if module is None: globs = {} else: globs = module.__dict__.copy() else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) # Recursively explore `obj`, extracting DocTests. tests = [] self._find(tests, obj, name, module, source_lines, globs, {}) return tests
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/test/_doctest.py/DocTestFinder.find
7,090
def _get_test(self, obj, name, module, globs, source_lines): """ Return a DocTest for the given object, if it defines a docstring; otherwise, return None. """ # Extract the object's docstring. If it doesn't have one, # then return None (no test for this object). if isinstance(obj, basestring): docstring = obj else: try: if obj.__doc__ is None: docstring = '' else: docstring = obj.__doc__ if not isinstance(docstring, basestring): docstring = str(docstring) except (TypeError, __HOLE__): docstring = '' # Find the docstring's location in the file. lineno = self._find_lineno(obj, source_lines) # Don't bother if the docstring is empty. if self._exclude_empty and not docstring: return None # Return a DocTest for this object. if module is None: filename = None else: filename = getattr(module, '__file__', module.__name__) if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] return self._parser.get_doctest(docstring, globs, name, filename, lineno)
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/test/_doctest.py/DocTestFinder._get_test
7,091
def __run(self, test, compileflags, out): """ Run the examples in `test`. Write the outcome of each example with one of the `DocTestRunner.report_*` methods, using the writer function `out`. `compileflags` is the set of compiler flags that should be used to execute examples. Return a tuple `(f, t)`, where `t` is the number of examples tried, and `f` is the number of examples that failed. The examples are run in the namespace `test.globs`. """ # Keep track of the number of failures and tries. failures = tries = 0 # Save the option flags (since option directives can be used # to modify them). original_optionflags = self.optionflags SUCCESS, FAILURE, BOOM = range(3) # `outcome` state check = self._checker.check_output # Process each example. for examplenum, example in enumerate(test.examples): # If REPORT_ONLY_FIRST_FAILURE is set, then suppress # reporting after the first failure. quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and failures > 0) # Merge in the example's options. self.optionflags = original_optionflags if example.options: for (optionflag, val) in example.options.items(): if val: self.optionflags |= optionflag else: self.optionflags &= ~optionflag # Record that we started this example. tries += 1 if not quiet: self.report_start(out, test, example) # Use a special filename for compile(), so we can retrieve # the source code during interactive debugging (see # __patched_linecache_getlines). filename = '<doctest %s[%d]>' % (test.name, examplenum) # Run the example in the given context (globs), and record # any exception that gets raised. (But don't intercept # keyboard interrupts.) try: # Don't blink! This is where the user's code gets run. exec compile(example.source, filename, "single", compileflags, 1) in test.globs self.debugger.set_continue() # ==== Example Finished ==== exception = None except __HOLE__: raise except: exception = sys.exc_info() self.debugger.set_continue() # ==== Example Finished ==== got = self._fakeout.getvalue() # the actual output self._fakeout.truncate(0) outcome = FAILURE # guilty until proved innocent or insane # If the example executed without raising any exceptions, # verify its output. if exception is None: if check(example.want, got, self.optionflags): outcome = SUCCESS # The example raised an exception: check if it was expected. else: exc_info = sys.exc_info() exc_msg = traceback.format_exception_only(*exc_info[:2])[-1] if not quiet: got += _exception_traceback(exc_info) # If `example.exc_msg` is None, then we weren't expecting # an exception. if example.exc_msg is None: outcome = BOOM # We expected an exception: see whether it matches. elif check(example.exc_msg, exc_msg, self.optionflags): outcome = SUCCESS # Another chance if they didn't care about the detail. elif self.optionflags & IGNORE_EXCEPTION_DETAIL: m1 = re.match(r'[^:]*:', example.exc_msg) m2 = re.match(r'[^:]*:', exc_msg) if m1 and m2 and check(m1.group(0), m2.group(0), self.optionflags): outcome = SUCCESS # Report the outcome. if outcome is SUCCESS: if not quiet: self.report_success(out, test, example, got) elif outcome is FAILURE: if not quiet: self.report_failure(out, test, example, got) failures += 1 elif outcome is BOOM: if not quiet: self.report_unexpected_exception(out, test, example, exc_info) failures += 1 else: assert False, ("unknown outcome", outcome) # Restore the option flags (in case they were modified) self.optionflags = original_optionflags # Record and return the number of failures and tries. self.__record_outcome(test, failures, tries) return failures, tries
KeyboardInterrupt
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/test/_doctest.py/DocTestRunner.__run
7,092
def start_program(name): program = Program(name) # Remove base logging handlers, this is read from the log files that are # set up after the start method logger = logging.getLogger('chalmers') logger.handlers = [] logger.handlers.append(logging.NullHandler()) try: program.start(daemon=False) except __HOLE__: log.error('Program %s is shutting down' % program.name)
KeyboardInterrupt
dataset/ETHPy150Open Anaconda-Platform/chalmers/chalmers/utils/mutiplex_io_pool.py/start_program
7,093
def printer_loop(self): colors = ColorPicker() sleep_time = SLEEP_START try: while not self.finished: seen_data = False for name, fd in list(self.watched): data = fd.readline() while data: seen_data = True with colors[name]: print('[%s]' % name, end='') print(" ", end='') print(data, end='') data = fd.readline() if not seen_data: time.sleep(sleep_time) sleep_time = SLEEP_MAX if sleep_time >= SLEEP_MAX else sleep_time + SLEEP_INC else: sleep_time = SLEEP_START self.manage_logs() finally: for _, fd in self.watched: try: fd.close() except __HOLE__: pass
IOError
dataset/ETHPy150Open Anaconda-Platform/chalmers/chalmers/utils/mutiplex_io_pool.py/MultiPlexIOPool.printer_loop
7,094
def handle(self, *args, **kwargs): self.docs_dir = os.path.join( settings.REPO_DIR, 'docs' ) self.target_path = os.path.join(self.docs_dir, 'filingforms.rst') group_dict = {} for form in all_filing_forms: try: group_dict[form.group].append(form) except __HOLE__: group_dict[form.group] = [form] group_list = sorted(group_dict.items(), key=lambda x:x[0]) context = { 'group_list': group_list, } rendered = render_to_string('toolbox/filingforms.rst', context) with open(self.target_path, 'w') as target_file: target_file.write(rendered)
KeyError
dataset/ETHPy150Open california-civic-data-coalition/django-calaccess-raw-data/example/toolbox/management/commands/createcalaccessrawformdocs.py/Command.handle
7,095
def _Interactive(self, opt, args): all = filter(lambda x: x.IsDirty(), self.GetProjects(args)) if not all: print >>sys.stderr,'no projects have uncommitted modifications' return out = _ProjectList(self.manifest.manifestProject.config) while True: out.header(' %s', 'project') out.nl() for i in xrange(0, len(all)): p = all[i] out.write('%3d: %s', i + 1, p.relpath + '/') out.nl() out.nl() out.write('%3d: (', 0) out.prompt('q') out.write('uit)') out.nl() out.prompt('project> ') try: a = sys.stdin.readline() except __HOLE__: out.nl() break if a == '': out.nl() break a = a.strip() if a.lower() in ('q', 'quit', 'exit'): break if not a: continue try: a_index = int(a) except ValueError: a_index = None if a_index is not None: if a_index == 0: break if 0 < a_index and a_index <= len(all): _AddI(all[a_index - 1]) continue p = filter(lambda x: x.name == a or x.relpath == a, all) if len(p) == 1: _AddI(p[0]) continue print 'Bye.'
KeyboardInterrupt
dataset/ETHPy150Open android/tools_repo/subcmds/stage.py/Stage._Interactive
7,096
def get_file_size(file_obj): """ Analyze file-like object and attempt to determine its size. :param file_obj: file-like object. :retval The file's size or None if it cannot be determined. """ if hasattr(file_obj, 'seek') and hasattr(file_obj, 'tell'): try: curr = file_obj.tell() file_obj.seek(0, os.SEEK_END) size = file_obj.tell() file_obj.seek(curr) return size except __HOLE__: return
IOError
dataset/ETHPy150Open MirantisWorkloadMobility/CloudFerry/cloudferry/lib/utils/file_proxy.py/get_file_size
7,097
def copy_cover(self, file_id, new_file_id): try: data, metadata = self.load(file_id, 'cover') with open(self._get_filename(new_file_id, 'cover'), "w") as f: f.write(data) except __HOLE__: # Cover not existing pass
IOError
dataset/ETHPy150Open Net-ng/kansha/kansha/services/simpleassetsmanager/simpleassetsmanager.py/SimpleAssetsManager.copy_cover
7,098
def save(self, data, file_id=None, metadata={}, THUMB_SIZE=()): if file_id is None: file_id = unicode(uuid.uuid4()) with open(self._get_filename(file_id), "w") as f: f.write(data) # Store metadata with open(self._get_metadata_filename(file_id), "w") as f: f.write(json.dumps(metadata)) img = None try: img = Image.open(self._get_filename(file_id)) except __HOLE__: log.info('Not an image file, skipping medium & thumbnail generation') else: # Store thumbnail & medium kw = {} if 'transparency' in img.info: kw['transparency'] = img.info["transparency"] orig_width, orig_height = img.size medium_size = self.MEDIUM_WIDTH, int(float(self.MEDIUM_WIDTH) * orig_height / orig_width) medium = img.copy() medium.thumbnail(medium_size, Image.ANTIALIAS) medium.save(self._get_filename(file_id, 'medium'), img.format, quality=75, **kw) # 'JPEG') thumb = ImageOps.fit(img, THUMB_SIZE if THUMB_SIZE else self.THUMB_SIZE, Image.ANTIALIAS) thumb.save(self._get_filename(file_id, 'thumb'), img.format, quality=75, **kw) # 'JPEG') return file_id
IOError
dataset/ETHPy150Open Net-ng/kansha/kansha/services/simpleassetsmanager/simpleassetsmanager.py/SimpleAssetsManager.save
7,099
def delete(self, file_id): files = [self._get_filename(file_id), self._get_filename(file_id, 'thumb'), self._get_filename(file_id, 'medium'), self._get_filename(file_id, 'cover'), self._get_filename(file_id, 'large'), self._get_metadata_filename(file_id)] for f in files: try: os.remove(f) except __HOLE__: # File does not exist pass
OSError
dataset/ETHPy150Open Net-ng/kansha/kansha/services/simpleassetsmanager/simpleassetsmanager.py/SimpleAssetsManager.delete