Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
3,600
def mkdirp(path): try: os.makedirs(path) except __HOLE__: pass
OSError
dataset/ETHPy150Open CenterForOpenScience/osf.io/scripts/analytics/utils.py/mkdirp
3,601
def identify_file(self, filename): """Identify the type of @param filename. Call self.handle_matches instead of returning a value. """ self.current_file = filename self.matchtype = "signature" try: t0 = time.clock() f = open(filename, 'rb') ...
IOError
dataset/ETHPy150Open openpreserve/fido/fido/fido.py/Fido.identify_file
3,602
def walk_zip(self, filename, fileobj=None): """Identify the type of each item in the zip @param fileobj. If fileobj is not provided, open @param filename. Call self.handle_matches instead of returning a value. """ # IN 2.7+: with zipfile.ZipFile((fileobj if fi...
IOError
dataset/ETHPy150Open openpreserve/fido/fido/fido.py/Fido.walk_zip
3,603
def main(arglist=None): # The argparse package was introduced in 2.7 t0 = time.clock() from argparselocal import ArgumentParser, RawTextHelpFormatter if arglist == None: arglist = sys.argv[1:] if len(arglist) == False: arglist.append("-h") parser = ArgumentParser(des...
KeyboardInterrupt
dataset/ETHPy150Open openpreserve/fido/fido/fido.py/main
3,604
def prepare_impl(t, cwd, ver, wafdir): Options.tooldir = [t] Options.launch_dir = cwd # some command-line options can be processed immediately if '--version' in sys.argv: opt_obj = Options.Handler() opt_obj.curdir = cwd opt_obj.parse_args() sys.exit(0) # now find the wscript file msg1 = 'Waf: Please run...
AttributeError
dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Scripting.py/prepare_impl
3,605
def prepare(t, cwd, ver, wafdir): if WAFVERSION != ver: msg = 'Version mismatch: waf %s <> wafadmin %s (wafdir %s)' % (ver, WAFVERSION, wafdir) print('\033[91mError: %s\033[0m' % msg) sys.exit(1) #""" try: prepare_impl(t, cwd, ver, wafdir) except Utils.WafError, e: error(str(e)) sys.exit(1) except __H...
KeyboardInterrupt
dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Scripting.py/prepare
3,606
def main(): global commands commands = Options.arg_line[:] while commands: x = commands.pop(0) ini = datetime.datetime.now() if x == 'configure': fun = configure elif x == 'build': fun = build else: fun = getattr(Utils.g_module, x, None) if not fun: raise Utils.WscriptError('No such comman...
TypeError
dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Scripting.py/main
3,607
def configure(conf): src = getattr(Options.options, SRCDIR, None) if not src: src = getattr(Utils.g_module, SRCDIR, None) if not src: src = getattr(Utils.g_module, 'top', None) if not src: src = '.' incomplete_src = 1 src = os.path.abspath(src) bld = getattr(Options.options, BLDDIR, None) if not bld: bld =...
OSError
dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Scripting.py/configure
3,608
def clean(bld): '''removes the build files''' try: proj = Environment.Environment(Options.lockfile) except __HOLE__: raise Utils.WafError('Nothing to clean (project not configured)') bld.load_dirs(proj[SRCDIR], proj[BLDDIR]) bld.load_envs() bld.is_install = 0 # False # read the scripts - and set the path ...
IOError
dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Scripting.py/clean
3,609
def check_configured(bld): if not Configure.autoconfig: return bld conf_cls = getattr(Utils.g_module, 'configure_context', Utils.Context) bld_cls = getattr(Utils.g_module, 'build_context', Utils.Context) def reconf(proj): back = (Options.commands, Options.options.__dict__, Logs.zones, Logs.verbose) Options...
IOError
dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Scripting.py/check_configured
3,610
def build_impl(bld): # compile the project and/or install the files try: proj = Environment.Environment(Options.lockfile) except __HOLE__: raise Utils.WafError("Project not configured (run 'waf configure' first)") bld.load_dirs(proj[SRCDIR], proj[BLDDIR]) bld.load_envs() info("Waf: Entering directory `%s'" ...
IOError
dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Scripting.py/build_impl
3,611
def distclean(ctx=None): '''removes the build directory''' global commands lst = os.listdir('.') for f in lst: if f == Options.lockfile: try: proj = Environment.Environment(f) except: Logs.warn('could not read %r' % f) continue try: shutil.rmtree(proj[BLDDIR]) except IOError: pass...
OSError
dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Scripting.py/distclean
3,612
def dist(appname='', version=''): '''makes a tarball for redistributing the sources''' # return return (distdirname, tarballname) import tarfile if not appname: appname = Utils.g_module.APPNAME if not version: version = Utils.g_module.VERSION tmp_folder = appname + '-' + version if g_gz in ['gz', 'bz2']: arc...
IOError
dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Scripting.py/dist
3,613
def match_preview(self, index, *args): if not self.p.cwdidx: return if not self.p.fileops.recursive and index.parent() != self.p.cwdidx: return target = helpers.splitpath_os(self.p.get_path(index)) if self.p.cwd in target[0] and target in self.p.targets: ...
UnicodeDecodeError
dataset/ETHPy150Open mikar/demimove/demimove/gui.py/DirModel.match_preview
3,614
def create_historytab(self): historyfile = os.path.join(self.fileops.configdir, "history.txt") try: with codecs.open(historyfile, encoding="utf-8") as f: data = f.read() except __HOLE__: historyfile = os.path.join(self.basedir, "data/history.txt") ...
IOError
dataset/ETHPy150Open mikar/demimove/demimove/gui.py/DemiMoveGUI.create_historytab
3,615
def main(): "Main entry point for demimove-ui." startdir = os.getcwd() configfile = None try: args = docopt(__doc__, version="0.2") # args["-v"] = 3 # Force debug logging fileop = fileops.FileOps(verbosity=args["-v"], quiet=args["--quiet"]) ...
NameError
dataset/ETHPy150Open mikar/demimove/demimove/gui.py/main
3,616
def upgrade_connection(self): """ Validate and 'upgrade' the HTTP request to a WebSocket request. If an upgrade succeeded then then handler will have `start_response` with a status of `101`, the environ will also be updated with `wsgi.websocket` and `wsgi.websocket_version` keys...
TypeError
dataset/ETHPy150Open jgelens/gevent-websocket/geventwebsocket/handler.py/WebSocketHandler.upgrade_connection
3,617
def write_to_screen(self, cli, screen, mouse_handlers, write_position): """ Write window to screen. This renders the user control, the margins and copies everything over to the absolute position at the given screen. """ # Calculate margin sizes. left_margin_widths = [self...
KeyError
dataset/ETHPy150Open jonathanslenders/python-prompt-toolkit/prompt_toolkit/layout/containers.py/Window.write_to_screen
3,618
@classmethod def _copy_body(cls, ui_content, new_screen, write_position, move_x, width, vertical_scroll=0, horizontal_scroll=0, has_focus=False, wrap_lines=False, vertical_scroll_2=0, always_hide_cursor=False, cursor_char=None): """ Copy the U...
KeyError
dataset/ETHPy150Open jonathanslenders/python-prompt-toolkit/prompt_toolkit/layout/containers.py/Window._copy_body
3,619
def test_adds_error(self): try: raise ValueError() except __HOLE__: exc = sys.exc_info() plugin = self._make_one() plugin.addError(case.Test(FakeTestCase()), exc) line = plugin.tracker._test_cases['FakeTestCase'][0] self.assertFalse(line.ok)
ValueError
dataset/ETHPy150Open mblayman/tappy/tap/tests/test_nose_plugin.py/TestNosePlugin.test_adds_error
3,620
def test_adds_skip(self): # Since Python versions earlier than 2.7 don't support skipping tests, # this test has to hack around that limitation. try: plugin = self._make_one() plugin.addError(case.Test( FakeTestCase()), (unittest.SkipTest, 'a reason', None...
AttributeError
dataset/ETHPy150Open mblayman/tappy/tap/tests/test_nose_plugin.py/TestNosePlugin.test_adds_skip
3,621
def test_adds_failure(self): try: raise ValueError() except __HOLE__: exc = sys.exc_info() plugin = self._make_one() plugin.addFailure(case.Test(FakeTestCase()), exc) line = plugin.tracker._test_cases['FakeTestCase'][0] self.assertFalse(line.ok)
ValueError
dataset/ETHPy150Open mblayman/tappy/tap/tests/test_nose_plugin.py/TestNosePlugin.test_adds_failure
3,622
def get_env_variable(var_name): """ Get the environment variable or return exception """ try: return os.environ[var_name] except __HOLE__: error_msg = "Set the %s environment variable" % var_name raise ImproperlyConfigured(error_msg)
KeyError
dataset/ETHPy150Open erikr/happinesspackets/happinesspackets/settings/base.py/get_env_variable
3,623
def runTests(self): """Runs all tests. """ _SetupLogging("LOGTOSTDERR" in os.environ) sys.stderr.write("Running %s\n" % self.progName) sys.stderr.flush() # Ensure assertions will be evaluated if not __debug__: raise Exception("Not running in debug mode, assertions would not be" ...
AssertionError
dataset/ETHPy150Open ganeti/ganeti/test/py/testutils/__init__.py/GanetiTestProgram.runTests
3,624
def patch_object(*args, **kwargs): """Unified patch_object for various versions of Python Mock. Different Python Mock versions provide incompatible versions of patching an object. More recent versions use _patch_object, older ones used patch_object. This function unifies the different variations. """ impo...
AttributeError
dataset/ETHPy150Open ganeti/ganeti/test/py/testutils/__init__.py/patch_object
3,625
def pop(self, key, default=None): try: v = self[key] except __HOLE__: if default is None: raise else: return default else: self.expire_cookie(key) return v
KeyError
dataset/ETHPy150Open aht/suas/suas/session.py/CookieSession.pop
3,626
@classmethod def load(klass, request, response): """ Load the session cookies from the request, returning a new instance with the response. """ try: id = request.cookies['SID'][1:-SIG_LEN-1] except KeyError: raise NoSIDError else: c = SignedCookie(SECRET_KEY + id) c.load(request.environ['HTTP...
KeyError
dataset/ETHPy150Open aht/suas/suas/session.py/CookieSession.load
3,627
def initialize(self, request, response): super(RequestHandler, self).initialize(request, response) try: self.session = CookieSession.load(request, response) except NoSIDError: self.session = CookieSession(None, self.response) except BadSignatureError: self.session = CookieSession(None, self.response) ...
ValueError
dataset/ETHPy150Open aht/suas/suas/session.py/RequestHandler.initialize
3,628
def __call__(self, f, prewrapper_func=None): """ This method is called on execution of the decorator to get the wrapper defined inside. The C{prewrapper_func} keyword argument is available for subclasses. If defined, the output of the prewrapper function is returned instead of th...
KeyError
dataset/ETHPy150Open fp7-ofelia/ocf/optin_manager/src/python/openflow/common/permissions/decorators.py/require_obj_permissions.__call__
3,629
def get_message(self, correlation_id): try: while correlation_id not in self.replies: self.consumer.channel.connection.client.drain_events( timeout=self.timeout ) body, message = self.replies.pop(correlation_id) self.provi...
KeyboardInterrupt
dataset/ETHPy150Open onefinestay/nameko/nameko/standalone/rpc.py/PollingQueueConsumer.get_message
3,630
def do_urlencode(value): """Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables. .. versionadded:: 2.7 """ itemiter = None if isinstance(value, dict): itemiter = iteritems(value) elif not isinstance(va...
TypeError
dataset/ETHPy150Open GoogleCloudPlatform/appengine-flask-skeleton/lib/jinja2/filters.py/do_urlencode
3,631
@environmentfilter def do_first(environment, seq): """Return the first item of a sequence.""" try: return next(iter(seq)) except __HOLE__: return environment.undefined('No first item, sequence was empty.')
StopIteration
dataset/ETHPy150Open GoogleCloudPlatform/appengine-flask-skeleton/lib/jinja2/filters.py/do_first
3,632
@environmentfilter def do_last(environment, seq): """Return the last item of a sequence.""" try: return next(iter(reversed(seq))) except __HOLE__: return environment.undefined('No last item, sequence was empty.')
StopIteration
dataset/ETHPy150Open GoogleCloudPlatform/appengine-flask-skeleton/lib/jinja2/filters.py/do_last
3,633
@environmentfilter def do_random(environment, seq): """Return a random item from the sequence.""" try: return choice(seq) except __HOLE__: return environment.undefined('No random item, sequence was empty.')
IndexError
dataset/ETHPy150Open GoogleCloudPlatform/appengine-flask-skeleton/lib/jinja2/filters.py/do_random
3,634
def do_int(value, default=0, base=10): """Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. You can also override the default base (10) in the second parameter, which handles input with prefixes such as ...
TypeError
dataset/ETHPy150Open GoogleCloudPlatform/appengine-flask-skeleton/lib/jinja2/filters.py/do_int
3,635
def do_float(value, default=0.0): """Convert the value into a floating point number. If the conversion doesn't work it will return ``0.0``. You can override this default using the first parameter. """ try: return float(value) except (TypeError, __HOLE__): return default
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/appengine-flask-skeleton/lib/jinja2/filters.py/do_float
3,636
def do_reverse(value): """Reverse the object or return an iterator that iterates over it the other way round. """ if isinstance(value, string_types): return value[::-1] try: return reversed(value) except TypeError: try: rv = list(value) rv.reverse(...
TypeError
dataset/ETHPy150Open GoogleCloudPlatform/appengine-flask-skeleton/lib/jinja2/filters.py/do_reverse
3,637
@environmentfilter def do_attr(environment, obj, name): """Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details. """ try: ...
AttributeError
dataset/ETHPy150Open GoogleCloudPlatform/appengine-flask-skeleton/lib/jinja2/filters.py/do_attr
3,638
def plotmca(self, mca, title=None, set_title=True, as_mca2=False, fullrange=False, init=False, **kws): if as_mca2: self.mca2 = mca kws['new'] = False else: self.mca = mca self.panel.conf.show_grid = False if init: self....
ValueError
dataset/ETHPy150Open xraypy/xraylarch/plugins/wx/xrfdisplay.py/XRFDisplayFrame.plotmca
3,639
def latest_version(*names, **kwargs): ''' Return the latest version of the named package available for upgrade or installation. If more than one package name is specified, a dict of name/version pairs is returned. If the latest version of a given package is already installed, an empty string wi...
IndexError
dataset/ETHPy150Open saltstack/salt/salt/modules/pacman.py/latest_version
3,640
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed as a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs ''' versions_as_list = salt.utils.is_true(versions_as_list) # not yet implemente...
ValueError
dataset/ETHPy150Open saltstack/salt/salt/modules/pacman.py/list_pkgs
3,641
def collect_file_tests(lines, lines_to_execute): makecase = lambda t: IntegrationTestCase(t, correct, line_nr, column, start, line) start = None correct = None test_type = None for line_nr, line in enumerate(lines, 1): if correct is not None: ...
AttributeError
dataset/ETHPy150Open davidhalter/jedi/test/run.py/collect_file_tests
3,642
def collect_dir_tests(base_dir, test_files, check_thirdparty=False): for f_name in os.listdir(base_dir): files_to_execute = [a for a in test_files.items() if f_name.startswith(a[0])] lines_to_execute = reduce(lambda x, y: x + y[1], files_to_execute, []) if f_name.endswith(".py") and (not tes...
ImportError
dataset/ETHPy150Open davidhalter/jedi/test/run.py/collect_dir_tests
3,643
def create_directory(directory_path, ensure_writability = False): """ Creates a directory (with subdirs) if it doesn't exist. @param directory_path: the path of the directory and subdirectories to be created. """ if ensure_writability: if not os.access(os.path.dirname(directory_path), ...
OSError
dataset/ETHPy150Open victor-gil-sepulveda/pyProCT/pyproct/tools/scriptTools.py/create_directory
3,644
def vararg_callback(option, opt_str, value, parser): """ Parses a list of float numbers. To be used with 'optparse'. Got from: http://docs.python.org/2/library/optparse.html @param option: ... @param opt_str: ... @param value: ... @param parser: ... """ assert value is None ...
ValueError
dataset/ETHPy150Open victor-gil-sepulveda/pyProCT/pyproct/tools/scriptTools.py/vararg_callback
3,645
def run(self): '''Thread main loop''' try: self.instance._doc_text = None self.instance._help_text = None self.instance._execute() # used for uper class to generate event after execution self.instance._after_execute() exce...
KeyboardInterrupt
dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/gui/wx/ipshell_nonblocking.py/_CodeExecutor.run
3,646
def do_execute(self, line): """ Tell the thread to process the 'line' command """ self._line_to_execute = line if self._threading: #we launch the ipython line execution in a thread to make it #interruptible with include it in self namespace to be able ...
KeyboardInterrupt
dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/gui/wx/ipshell_nonblocking.py/NonBlockingIPShell.do_execute
3,647
def _execute(self): ''' Executes the current line provided by the shell object. ''' orig_stdout = sys.stdout sys.stdout = Term.cout #self.sys_displayhook_ori = sys.displayhook #sys.displayhook = self.displayhook try: line = self._IP.r...
KeyboardInterrupt
dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/gui/wx/ipshell_nonblocking.py/NonBlockingIPShell._execute
3,648
@bitness.setter def bitness(self, bits): try: self.segment_t.bitness = self.BITS_TO_BITNESS[bits] except __HOLE__: raise exceptions.InvalidBitness("Got {}. Expecting 16, 32 or 64.".format(bits))
KeyError
dataset/ETHPy150Open tmr232/Sark/sark/code/segment.py/Segment.bitness
3,649
def assertTemplateDoesNotExist(self, name): try: self.assertTemplateExists(name) except __HOLE__: return raise AssertionError('Template exists: %s' % name)
AssertionError
dataset/ETHPy150Open disqus/django-mailviews/mailviews/tests/tests.py/EmailMessageViewTestCase.assertTemplateDoesNotExist
3,650
def main(): try: projectfolders.create_folders(args.project[0], cur_dir) #Creates all of the project folders we need projectfiles.create_files(args.project[0], cur_dir) #Creates all of the project files we need except __HOLE__ as e: print(e.strerror)
IOError
dataset/ETHPy150Open Aaronontheweb/scaffold-py/scaffold/__main__.py/main
3,651
def get_cluster_info(host, port): """ return dict with info about nodes in cluster and current version { 'nodes': [ 'IP:port', 'IP:port', ], 'version': '1.4.4' } """ client = Telnet(host, int(port)) client.write(b'version\n') res = client.r...
ValueError
dataset/ETHPy150Open gusdan/django-elasticache/django_elasticache/cluster_utils.py/get_cluster_info
3,652
def check_type(self, interface, typename, type): print "Checking type %s" % typename v = type() for n in dir(v): if n[0] == '_': continue try: value = getattr(v, n) except __HOLE__, errstr: if str(errstr) == "unk...
TypeError
dataset/ETHPy150Open byt3bl33d3r/pth-toolkit/lib/python2.7/site-packages/samba/tests/dcerpc/testrpc.py/RpcTests.check_type
3,653
def _extract_nexe(program_path, processed_images, command): """ Given a `command`, search through the listed tar images (`processed_images`) and extract the nexe matching `command` to the target `program_path` on the host file system. :param program_path: Location (including filename) which...
KeyError
dataset/ETHPy150Open zerovm/zerovm-cli/zvshlib/zvsh.py/_extract_nexe
3,654
def add_image_args(self, zvm_image): if not zvm_image: return img_cache = {} for img in zvm_image: (imgpath, imgmp, imgacc) = (img.split(',') + [None] * 3)[:3] dev_name = img_cache.get(imgpath) if not dev_name: dev_name = self.creat...
KeyError
dataset/ETHPy150Open zerovm/zerovm-cli/zvshlib/zvsh.py/ZvShell.add_image_args
3,655
def parse_return_code(report): rc = report.split('\n', 5)[2] try: rc = int(rc) except __HOLE__: rc = int(rc.replace('user return code = ', '')) return rc
ValueError
dataset/ETHPy150Open zerovm/zerovm-cli/zvshlib/zvsh.py/parse_return_code
3,656
def run(self): try: self.process = Popen(self.command, stdin=PIPE, stdout=PIPE) self.spawn(True, self.stdin_reader) err_reader = self.spawn(True, self.stderr_reader) rep_reader = self.spawn(True, self.report_reader) writer = self.spawn(True, self.stdou...
KeyboardInterrupt
dataset/ETHPy150Open zerovm/zerovm-cli/zvshlib/zvsh.py/ZvRunner.run
3,657
def stdin_reader(self): if sys.stdin.isatty(): try: for l in sys.stdin: self.process.stdin.write(l) except __HOLE__: pass else: try: for l in iter(lambda: sys.stdin.read(65535), b''): ...
IOError
dataset/ETHPy150Open zerovm/zerovm-cli/zvshlib/zvsh.py/ZvRunner.stdin_reader
3,658
def stderr_reader(self): err = open(self.stderr) try: for l in iter(lambda: err.read(65535), b''): sys.stderr.write(l) except __HOLE__: pass err.close()
IOError
dataset/ETHPy150Open zerovm/zerovm-cli/zvshlib/zvsh.py/ZvRunner.stderr_reader
3,659
def spawn(argv, master_read=pty_read, stdin_read=pty_read): """Create a spawned process. Based on pty.spawn code.""" # TODO(larsbutler): This type check won't work with python3 # See http://packages.python.org/six/#six.string_types # for a possible solution. if isinstance(argv, (basestring)): ...
IOError
dataset/ETHPy150Open zerovm/zerovm-cli/zvshlib/zvsh.py/spawn
3,660
def _run_gdb(self): # user wants to debug the program zvsh_args = DebugArgs() zvsh_args.parse(self.cmd_line[1:]) self.args = zvsh_args.args self.zvsh = ZvShell(self.config, self.args.zvm_save_dir) # a month until debug session will time out self.zvsh.config['manif...
KeyboardInterrupt
dataset/ETHPy150Open zerovm/zerovm-cli/zvshlib/zvsh.py/Shell._run_gdb
3,661
def get_version(): """Get the version info from the mpld3 package without importing it""" import ast with open(os.path.join(os.path.abspath('../'), "gemini", "version.py"), "r") as init_file: module = ast.parse(init_file.read()) version = (ast.literal_eval(node.value) for node in ast.walk(modu...
StopIteration
dataset/ETHPy150Open arq5x/gemini/docs/conf.py/get_version
3,662
def form(url, method="post", multipart=False, hidden_fields=None, **attrs): """An open tag for a form that will submit to ``url``. You must close the form yourself by calling ``end_form()`` or outputting </form>. Options: ``method`` The method to use when submitting the form, usually ...
AttributeError
dataset/ETHPy150Open mikeorr/WebHelpers2/webhelpers2/html/tags.py/form
3,663
def _add_nodes(self, states, container): # to be able to process children recursively as well as the state dict of a machine states = states.values() if isinstance(states, dict) else states for state in states: if state.name in self.seen: continue elif has...
KeyError
dataset/ETHPy150Open tyarkoni/transitions/transitions/extensions/diagrams.py/AGraph._add_nodes
3,664
def set_edge_state(self, edge_from, edge_to, state='default'): """ Mark a node as active by changing the attributes """ assert hasattr(self, 'graph') edge = self.graph.get_edge(edge_from, edge_to) # Reset all the edges for e in self.graph.edges_iter(): self.set_edge...
KeyError
dataset/ETHPy150Open tyarkoni/transitions/transitions/extensions/diagrams.py/GraphMachine.set_edge_state
3,665
def set_node_state(self, node_name=None, state='default', reset=False): assert hasattr(self, 'graph') if node_name is None: node_name = self.state if reset: for n in self.graph.nodes_iter(): self.set_node_style(n, 'default') if self.graph.has_nod...
KeyError
dataset/ETHPy150Open tyarkoni/transitions/transitions/extensions/diagrams.py/GraphMachine.set_node_state
3,666
def createPaths(self, prefix = './'): """creates log directory path creates physical directories on disk """ dt = datetime.datetime.now() self.path = "{0}_{1}_{2:04d}{3:02d}{4:02d}_{5:02d}{6:02d}{7:02d}".format( prefix, self.name, dt.year, dt.m...
OSError
dataset/ETHPy150Open ioflo/ioflo/ioflo/base/serving.py/Server.createPaths
3,667
def reopenLog(self): """closes if open then reopens """ self.closeLog() #innocuous to call close() on unopened file try: self.logFile = open(self.logPath, 'a+') except __HOLE__ as ex: console.terse("Error: creating server log file '{0}\n".format(ex)) ...
IOError
dataset/ETHPy150Open ioflo/ioflo/ioflo/base/serving.py/Server.reopenLog
3,668
def log(self, msg): """Called by runner """ stamp = self.store.stamp #self.stamp is last time run so don't use try: self.logFile.write("%0.4f\t%s\n" % (float(stamp), msg)) except __HOLE__ as ex: #if stamp is not a number then type error console.terse("{0}\n".for...
TypeError
dataset/ETHPy150Open ioflo/ioflo/ioflo/base/serving.py/Server.log
3,669
def _align_nums(nums): """ Given an array of numerator coefficient arrays [[a_1, a_2,..., a_n],..., [b_1, b_2,..., b_m]], this function pads shorter numerator arrays with zero's so that all numerators have the same length. Such alignment is necessary for functions like 'tf2ss', which needs the a...
ValueError
dataset/ETHPy150Open scipy/scipy/scipy/signal/filter_design.py/_align_nums
3,670
def lp2lp(b, a, wo=1.0): """ Transform a lowpass filter prototype to a different frequency. Return an analog low-pass filter with cutoff frequency `wo` from an analog low-pass filter prototype with unity cutoff frequency, in transfer function ('ba') representation. """ a, b = map(atleast_1...
TypeError
dataset/ETHPy150Open scipy/scipy/scipy/signal/filter_design.py/lp2lp
3,671
def lp2hp(b, a, wo=1.0): """ Transform a lowpass filter prototype to a highpass filter. Return an analog high-pass filter with cutoff frequency `wo` from an analog low-pass filter prototype with unity cutoff frequency, in transfer function ('ba') representation. """ a, b = map(atleast_1d, ...
TypeError
dataset/ETHPy150Open scipy/scipy/scipy/signal/filter_design.py/lp2hp
3,672
def iirdesign(wp, ws, gpass, gstop, analog=False, ftype='ellip', output='ba'): """Complete IIR digital and analog filter design. Given passband and stopband frequencies and gains, construct an analog or digital IIR filter of minimum order for a given basic type. Return the output in numerator, denomin...
IndexError
dataset/ETHPy150Open scipy/scipy/scipy/signal/filter_design.py/iirdesign
3,673
def iirfilter(N, Wn, rp=None, rs=None, btype='band', analog=False, ftype='butter', output='ba'): """ IIR digital and analog filter design given order and critical points. Design an Nth-order digital or analog filter and return the filter coefficients. Parameters ---------- N ...
IndexError
dataset/ETHPy150Open scipy/scipy/scipy/signal/filter_design.py/iirfilter
3,674
def mkdir_p(path): try: os.makedirs(path) except __HOLE__ as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
OSError
dataset/ETHPy150Open Akagi201/learning-python/flask/flask-boost/test/application/utils/helpers.py/mkdir_p
3,675
@staticmethod def sync_repository_last_pull_time(row): """ Last pull synchronization date/time for this repository """ try: repository_id = row["sync_repository.id"] except __HOLE__: return "-" table = current.s3db.sync_task query = (table.repository...
AttributeError
dataset/ETHPy150Open sahana/eden/modules/s3db/sync.py/SyncDataModel.sync_repository_last_pull_time
3,676
@staticmethod def sync_repository_last_push_time(row): """ Last push synchronization date/time for this repository """ try: repository_id = row["sync_repository.id"] except __HOLE__: return "-" table = current.s3db.sync_task query = (table.repository...
AttributeError
dataset/ETHPy150Open sahana/eden/modules/s3db/sync.py/SyncDataModel.sync_repository_last_push_time
3,677
def get_specific_reference_set_list(self, mendeley_discipline, provider, interaction): lookup_dict = dict(provider=provider, interaction=interaction, year=self.year, genre=self.genre, host=self.host, mendele...
KeyError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/reference_set.py/ProductLevelReferenceSet.get_specific_reference_set_list
3,678
def process_profile(self, profile): logger.info(u"build_refsets: on {url_slug}".format(url_slug=profile.url_slug)) for product in profile.products_not_removed: if product.biblio.display_title == "no title": # logger.info("no good biblio for tiid {tiid}".format( ...
ValueError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/reference_set.py/RefsetBuilder.process_profile
3,679
def launchServer(pipeline, options): # first follow up on the previously reported total number of # stages in the pipeline with how many have already finished: pipeline.printNumberProcessedStages() # expensive, so only create for pipelines that will actually run pipeline.shutdown_ev = Event() ...
KeyboardInterrupt
dataset/ETHPy150Open Mouse-Imaging-Centre/pydpiper/pydpiper/pipeline.py/launchServer
3,680
def parse(feedparser, args): """parse a feed using feedparser""" entries = [] args = irc3.utils.Config(args) max_date = datetime.datetime.now() - datetime.timedelta(days=2) for filename in args['filenames']: try: with open(filename + '.updated') as fd: updated = ...
AttributeError
dataset/ETHPy150Open gawel/irc3/irc3/plugins/feeds.py/parse
3,681
def imports(self): """show some warnings if needed""" try: import feedparser self.feedparser = feedparser except ImportError: # pragma: no cover self.bot.log.critical('feedparser is not installed') self.feedparser = None try: i...
ImportError
dataset/ETHPy150Open gawel/irc3/irc3/plugins/feeds.py/Feeds.imports
3,682
def _cmake_version(cmake_path): command = os.path.join(cmake_path, "cmake") try: simple_exe.output = "" simple_exe('%s --version' % command) version_match = re.search('cmake version ([0-9.]+)', simple_exe.output) del simple_exe.output if version_match: return ...
OSError
dataset/ETHPy150Open biicode/client/setups/cmake.py/_cmake_version
3,683
def check_output(command, timeout=None, ignore=None, **kwargs): """This is a version of subprocess.check_output that adds a timeout parameter to kill the subprocess if it does not return within the specified time.""" # pylint: disable=too-many-branches if ignore is None: ignore = [] elif isi...
OSError
dataset/ETHPy150Open ARM-software/workload-automation/wlauto/utils/misc.py/check_output
3,684
def diff_tokens(before_token, after_token): """ Creates a diff of two tokens. If the two tokens are the same it just returns returns the token (whitespace tokens are considered the same irrespective of type/number of whitespace characters in the token). If the tokens are numeric, the differenc...
ValueError
dataset/ETHPy150Open ARM-software/workload-automation/wlauto/utils/misc.py/diff_tokens
3,685
def reverse_lookup(lat, lon): if(lat is None or lon is None): return None key = get_key() try: params = {'format': 'json', 'key': key, 'lat': lat, 'lon': lon} headers = {"Accept-Language": constants.accepted_language} r = requests.get( 'http://open.mapquestapi.c...
ValueError
dataset/ETHPy150Open jmathai/elodie/elodie/geolocation.py/reverse_lookup
3,686
def lookup(name): if(name is None or len(name) == 0): return None key = get_key() try: params = {'format': 'json', 'key': key, 'location': name} if(constants.debug is True): print 'http://open.mapquestapi.com/geocoding/v1/address?%s' % urllib.urlencode(params) # noqa ...
ValueError
dataset/ETHPy150Open jmathai/elodie/elodie/geolocation.py/lookup
3,687
def from_pyfile(self, filename, silent=False): """Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the :meth:`from_object` function. :param filename: the filename of the config. This can either be an ...
IOError
dataset/ETHPy150Open pallets/flask/flask/config.py/Config.from_pyfile
3,688
def from_json(self, filename, silent=False): """Updates the values in the config from a JSON file. This function behaves as if the JSON object was a dictionary and passed to the :meth:`from_mapping` function. :param filename: the filename of the JSON file. This can either be an ...
IOError
dataset/ETHPy150Open pallets/flask/flask/config.py/Config.from_json
3,689
def handle(self): digest = self.request.get("d") # expects client-side hashing if not digest or len(digest) != 64: return {"success" : False, "reason" : "format"} try: digest.decode("hex") except __HOLE__: return {"success" : False, "reason" : "format"} ret = self.stor...
TypeError
dataset/ETHPy150Open maraoz/proofofexistence/api.py/ExternalRegisterHandler.handle
3,690
def test_method(self): """ :py:obj:`Context` can be instantiated with one of :py:obj:`SSLv2_METHOD`, :py:obj:`SSLv3_METHOD`, :py:obj:`SSLv23_METHOD`, :py:obj:`TLSv1_METHOD`, :py:obj:`TLSv1_1_METHOD`, or :py:obj:`TLSv1_2_METHOD`. """ methods = [ SSLv3_METHOD, S...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pyopenssl/OpenSSL/test/test_ssl.py/ContextTests.test_method
3,691
def defaults(): """ Parse `/etc/blueprintignore` and `~/.blueprintignore` to build the default `Rules` object. """ r = None # Check for a fresh cache of the complete blueprintignore(5) rules. if _mtime('/etc/blueprintignore') < _mtime(CACHE) \ and _mtime(os.path.expanduser('~/.blueprint...
ValueError
dataset/ETHPy150Open devstructure/blueprint/blueprint/rules.py/defaults
3,692
def _apt(): """ Return the set of packages that should never appear in a blueprint because they're already guaranteed (to some degree) to be there. """ CACHE = '/tmp/blueprint-apt-exclusions' # Read from a cached copy. try: return set([line.rstrip() for line in open(CACHE)]) ex...
OSError
dataset/ETHPy150Open devstructure/blueprint/blueprint/rules.py/_apt
3,693
def _yum(): """ Return the set of packages that should never appear in a blueprint because they're already guaranteed (to some degree) to be there. """ CACHE = '/tmp/blueprint-yum-exclusions' # Read from a cached copy. try: return set([line.rstrip() for line in open(CACHE)]) ex...
OSError
dataset/ETHPy150Open devstructure/blueprint/blueprint/rules.py/_yum
3,694
def _mtime(pathname): try: return os.stat(pathname).st_mtime except __HOLE__: return 0
OSError
dataset/ETHPy150Open devstructure/blueprint/blueprint/rules.py/_mtime
3,695
def parse(self, f, negate=False): """ Parse rules from the given file-like object. This is used both for `blueprintignore`(5) and for `blueprint-rules`(1). """ for pattern in f: pattern = pattern.rstrip() # Comments and blank lines. if '' == ...
ValueError
dataset/ETHPy150Open devstructure/blueprint/blueprint/rules.py/Rules.parse
3,696
def get(self, key, default=None): try: return self.__getitem__(key) except __HOLE__: return default
KeyError
dataset/ETHPy150Open cooper-software/siteglass/siteglass/config.py/Config.get
3,697
def get_version(self): if self._incremented_version: return self._version if not self.has_version(): return None path = self.get('global.cache_bust.versioning.filename', './version') if os.path.exists(path): version = ope...
ValueError
dataset/ETHPy150Open cooper-software/siteglass/siteglass/config.py/Config.get_version
3,698
def unicode_from_html(content): """Attempts to decode an HTML string into unicode. If unsuccessful, the original content is returned. """ encodings = get_encodings_from_content(content) for encoding in encodings: try: return unicode(content, encoding) except (UnicodeEr...
TypeError
dataset/ETHPy150Open bububa/pyTOP/pyTOP/packages/requests/utils.py/unicode_from_html
3,699
def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. every encodings from ``<meta ... charset=XXX>`` 3. fall back and replace all unicode characters """ tri...
TypeError
dataset/ETHPy150Open bububa/pyTOP/pyTOP/packages/requests/utils.py/get_unicode_from_response