Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
3,900 | def _bcompile(file, cfile=None, dfile=None, doraise=False):
encoding = py_compile.read_encoding(file, "utf-8")
f = open(file, 'U', encoding=encoding)
try:
timestamp = int(os.fstat(f.fileno()).st_mtime)
except __HOLE__:
timestamp = int(os.stat(file).st_mtime)
... | AttributeError | dataset/ETHPy150Open cournape/Bento/bento/private/_bytecode_3.py/_bcompile |
3,901 | def _bcompile(file, cfile=None, dfile=None, doraise=False, optimize=-1):
with tokenize.open(file) as f:
try:
timestamp = int(os.fstat(f.fileno()).st_mtime)
except AttributeError:
timestamp = int(os.stat(file).st_mtime)
codestring = f.read()
... | OSError | dataset/ETHPy150Open cournape/Bento/bento/private/_bytecode_3.py/_bcompile |
3,902 | def node_dictionary():
"""Return a dictionary containing node name as key and node class as
value. This will be depreciated soon in favour of
:func:`node_catalogue()`"""
classes = node_subclasses(Node)
dictionary = {}
for c in classes:
try:
name = c.identifier()
... | AttributeError | dataset/ETHPy150Open Stiivi/brewery/brewery/nodes/base.py/node_dictionary |
3,903 | def node_catalogue():
"""Returns a dictionary of information about all available nodes. Keys are
node identifiers, values are dictionaries. The information dictionary contains
all the keys from the node's `node_info` dictionary plus keys: `factory`
with node class, `type` (if not provided) is set to one... | AttributeError | dataset/ETHPy150Open Stiivi/brewery/brewery/nodes/base.py/node_catalogue |
3,904 | def node_subclasses(root, abstract = False):
"""Get all subclasses of node.
:Parameters:
* `abstract`: If set to ``True`` all abstract classes are included as well. Default is
``False``
"""
classes = []
for c in utils.subclass_iterator(root):
try:
info = get_no... | AttributeError | dataset/ETHPy150Open Stiivi/brewery/brewery/nodes/base.py/node_subclasses |
3,905 | def syncfile(src, dst):
"""Same as cp() but only do copying when source file is newer than target file"""
if not os.path.isfile(src):
raise Exception("No such file: %s" % src)
try:
dst_mtime = os.path.getmtime(dst)
src_mtime = os.path.getmtime(src)
# Only a... | OSError | dataset/ETHPy150Open zynga/jasy/jasy/core/File.py/syncfile |
3,906 | def get_pvalue(self, pvalue):
"""Gets the PValue's computed value from the runner's cache."""
try:
return self._cache.get_pvalue(pvalue)
except __HOLE__:
raise error.PValueError('PValue is not computed.') | KeyError | dataset/ETHPy150Open GoogleCloudPlatform/DataflowPythonSDK/google/cloud/dataflow/runners/direct_runner.py/DirectPipelineRunner.get_pvalue |
3,907 | def _cmp(self, other, op):
try:
diff = self - other
except __HOLE__:
return NotImplemented
else:
return op(diff.p, 0) | TypeError | dataset/ETHPy150Open sympy/sympy/sympy/polys/domains/pythonrational.py/PythonRational._cmp |
3,908 | def __pow__(self, value):
try:
float(value)
except __HOLE__:
raise ValueError("Non-numeric value supplied for boost")
q = LuceneQuery()
q.subqueries = [self]
q._and = False
q._pow = value
return q | ValueError | dataset/ETHPy150Open lugensa/scorched/scorched/search.py/LuceneQuery.__pow__ |
3,909 | def add(self, args, kwargs):
self.normalized = False
_args = []
for arg in args:
if isinstance(arg, LuceneQuery):
self.subqueries.append(arg)
else:
_args.append(arg)
args = _args
try:
terms_or_phrases = kwargs.po... | KeyError | dataset/ETHPy150Open lugensa/scorched/scorched/search.py/LuceneQuery.add |
3,910 | def add_range(self, field_name, rel, value):
if rel not in self.range_query_templates:
raise scorched.exc.SolrError("No such relation '%s' defined" % rel)
insts = (value,)
if rel in ('range', 'rangeexc'):
try:
assert len(value) == 2
except (__H... | AssertionError | dataset/ETHPy150Open lugensa/scorched/scorched/search.py/LuceneQuery.add_range |
3,911 | def boost_relevancy(self, boost_score, **kwargs):
if not self.query_obj:
raise TypeError("Can't boost the relevancy of an empty query")
try:
float(boost_score)
except __HOLE__:
raise ValueError("Non-numeric boost value supplied")
newself = self.clone(... | ValueError | dataset/ETHPy150Open lugensa/scorched/scorched/search.py/BaseSearch.boost_relevancy |
3,912 | def update(self, **kwargs):
checked_kwargs = self.check_opts(kwargs)
for f in ('qf', 'pf'):
field = kwargs.get(f, {})
for k, v in list(field.items()):
if v is not None:
try:
v = float(v)
except __HOLE... | ValueError | dataset/ETHPy150Open lugensa/scorched/scorched/search.py/DismaxOptions.update |
3,913 | def update(self, fields, query_fields=None, **kwargs):
if fields is None:
return
if not is_iter(fields):
fields = [fields]
self.fields.update(fields)
if query_fields is not None:
for k, v in list(query_fields.items()):
if k not in self... | ValueError | dataset/ETHPy150Open lugensa/scorched/scorched/search.py/MoreLikeThisOptions.update |
3,914 | def main():
parser = argparse.ArgumentParser(
description='An easier way to use cProfile.',
usage='%(prog)s [--version] [-a ADDRESS] [-p PORT] scriptfile [arg] ...',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--version', action='version', version=VERSION)
par... | TypeError | dataset/ETHPy150Open ymichael/cprofilev/cprofilev.py/main |
3,915 | def __init__(self, watchers, endpoint, pubsub_endpoint, check_delay=1.0,
prereload_fn=None, context=None, loop=None, statsd=False,
stats_endpoint=None, statsd_close_outputs=False,
multicast_endpoint=None, plugins=None,
sockets=None, warmup_delay=0, htt... | KeyError | dataset/ETHPy150Open circus-tent/circus/circus/arbiter.py/Arbiter.__init__ |
3,916 | @classmethod
def load_from_config(cls, config_file, loop=None):
cfg = get_config(config_file)
watchers = []
for watcher in cfg.get('watchers', []):
watchers.append(Watcher.load_from_config(watcher))
sockets = []
for socket_ in cfg.get('sockets', []):
... | ImportError | dataset/ETHPy150Open circus-tent/circus/circus/arbiter.py/Arbiter.load_from_config |
3,917 | def reap_processes(self):
# map watcher to pids
watchers_pids = {}
for watcher in self.iter_watchers():
if not watcher.is_stopped():
for process in watcher.processes.values():
watchers_pids[process.pid] = watcher
# detect dead children
... | OSError | dataset/ETHPy150Open circus-tent/circus/circus/arbiter.py/Arbiter.reap_processes |
3,918 | def StructuredPropertyToProto(prop, index):
"""Converts a structured property to the corresponding message field.
Args:
prop: The NDB property to be converted.
index: The index of the property within the message.
Returns:
A message field with attributes corresponding to those in prop, index
... | TypeError | dataset/ETHPy150Open GoogleCloudPlatform/endpoints-proto-datastore/endpoints_proto_datastore/ndb/utils.py/StructuredPropertyToProto |
3,919 | def callback(self, root, raw):
tag, attrs = root
if self._device_handler.perform_qualify_check():
if tag != qualify("rpc-reply"):
return
for key in attrs: # in the <rpc-reply> attributes
if key == "message-id": # if we found msgid attr
id =... | KeyError | dataset/ETHPy150Open ncclient/ncclient/ncclient/operations/rpc.py/RPCReplyListener.callback |
3,920 | def __init__(self, session, device_handler, async=False, timeout=30, raise_mode=RaiseMode.NONE):
"""
*session* is the :class:`~ncclient.transport.Session` instance
*device_handler" is the :class:`~ncclient.devices.*.*DeviceHandler` instance
*async* specifies whether the request is to b... | AttributeError | dataset/ETHPy150Open ncclient/ncclient/ncclient/operations/rpc.py/RPC.__init__ |
3,921 | def testFileRebuild(self):
from twisted.python.util import sibpath
import shutil, time
shutil.copyfile(sibpath(__file__, "myrebuilder1.py"),
os.path.join(self.fakelibPath, "myrebuilder.py"))
from twisted_rebuild_fakelib import myrebuilder
a = myrebuilder.A... | NameError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/test/test_rebuild.py/RebuildTestCase.testFileRebuild |
3,922 | def check_if_installed(self):
self.log.debug('Check Siege: %s' % self.tool_path)
try:
shell_exec([self.tool_path, '-h'])
except __HOLE__:
return False
return True | OSError | dataset/ETHPy150Open Blazemeter/taurus/bzt/modules/siege.py/Siege.check_if_installed |
3,923 | def _check_stat_op(self, name, alternate, check_objects=False,
check_allna=False):
import pandas.core.nanops as nanops
def testit():
f = getattr(Series, name)
# add some NaNs
self.series[5:15] = np.NaN
# idxmax, idxmin, min, and m... | ImportError | dataset/ETHPy150Open pydata/pandas/pandas/tests/series/test_analytics.py/TestSeriesAnalytics._check_stat_op |
3,924 | def envFileAsDictionary(fname):
retval = {}
fp = open(fname, 'r')
for line in fp:
line = line.rstrip('\r\n')
try:
(k, v) = line.split('=', 1)
except __HOLE__:
continue
retval[k] = v
return retval | ValueError | dataset/ETHPy150Open Netflix/gcviz/root/apps/apache/htdocs/AdminGCViz/vmsgcvizutils.py/envFileAsDictionary |
3,925 | def setting(name, default=None):
try:
return getattr(settings, setting_name(name))
except __HOLE__:
return getattr(settings, name, default) | AttributeError | dataset/ETHPy150Open omab/python-social-auth/social/apps/django_app/utils.py/setting |
3,926 | def list_directory(project_tree, directory):
"""List Paths directly below the given path, relative to the ProjectTree.
Raises an exception if the path is not a directory.
:returns: A DirectoryListing.
"""
try:
path = normpath(directory.path)
entries = [join(path, e) for e in project_tree.listdir(pat... | IOError | dataset/ETHPy150Open pantsbuild/pants/src/python/pants/engine/exp/fs.py/list_directory |
3,927 | def file_content(project_tree, path):
try:
return FileContent(path.path, project_tree.content(path.path))
except (IOError, __HOLE__) as e:
if e.errno == errno.ENOENT:
return FileContent(path.path, None)
else:
raise e | OSError | dataset/ETHPy150Open pantsbuild/pants/src/python/pants/engine/exp/fs.py/file_content |
3,928 | def quad(func, a, b, args=(), full_output=0, epsabs=1.49e-8, epsrel=1.49e-8,
limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50,
limlst=50):
"""
Compute a definite integral.
Integrate func from `a` to `b` (possibly infinite interval) using a
technique from the Fortran... | KeyError | dataset/ETHPy150Open scipy/scipy/scipy/integrate/quadpack.py/quad |
3,929 | def Exec(self, feedback_fn):
jobs = []
if self.op.group_name:
groups = [self.op.group_name]
depends_fn = lambda: None
else:
groups = self.cfg.GetNodeGroupList()
# Verify global configuration
jobs.append([
opcodes.OpClusterVerifyConfig(ignore_errors=self.op.ignore_erro... | AttributeError | dataset/ETHPy150Open ganeti/ganeti/lib/cmdlib/cluster/verify.py/LUClusterVerify.Exec |
3,930 | def _VerifyNodeTime(self, ninfo, nresult,
nvinfo_starttime, nvinfo_endtime):
"""Check the node time.
@type ninfo: L{objects.Node}
@param ninfo: the node to check
@param nresult: the remote results for the node
@param nvinfo_starttime: the start time of the RPC call
@param ... | ValueError | dataset/ETHPy150Open ganeti/ganeti/lib/cmdlib/cluster/verify.py/LUClusterVerifyGroup._VerifyNodeTime |
3,931 | def _VerifyAcceptedFileStoragePaths(self, ninfo, nresult, is_master):
"""Verifies paths in L{pathutils.FILE_STORAGE_PATHS_FILE}.
@type ninfo: L{objects.Node}
@param ninfo: the node to check
@param nresult: the remote results for the node
@type is_master: bool
@param is_master: Whether node is t... | KeyError | dataset/ETHPy150Open ganeti/ganeti/lib/cmdlib/cluster/verify.py/LUClusterVerifyGroup._VerifyAcceptedFileStoragePaths |
3,932 | def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
"""Verifies and computes a node information map
@type ninfo: L{objects.Node}
@param ninfo: the node to check
@param nresult: the remote results for the node
@param nimg: the node image object
@param vg_name: the configured VG name
"... | ValueError | dataset/ETHPy150Open ganeti/ganeti/lib/cmdlib/cluster/verify.py/LUClusterVerifyGroup._UpdateNodeInfo |
3,933 | def _convert_dpid(self, dpid_str):
try:
return int(dpid_str, 16)
except __HOLE__ as err:
self.logger.error('Invarid dpid parameter. %s', err)
self._test_end() | ValueError | dataset/ETHPy150Open osrg/ryu/ryu/tests/switch/tester.py/OfTester._convert_dpid |
3,934 | def _get_tests(self, path):
with open(path, 'r') as fhandle:
buf = fhandle.read()
try:
json_list = json.loads(buf)
for test_json in json_list:
if isinstance(test_json, six.text_type):
self.description = test_json... | ValueError | dataset/ETHPy150Open osrg/ryu/ryu/tests/switch/tester.py/TestFile._get_tests |
3,935 | @pytest.mark.slow
@pytest.mark.parametrize("module_name", _example_modules())
def test_example(example, module_name):
try:
main = getattr(import_module(module_name), 'main')
except __HOLE__ as e:
skip_exceptions = ["requires a GPU", "pylearn2", "dnn not available"]
if any([text in str(e)... | ImportError | dataset/ETHPy150Open Lasagne/Lasagne/lasagne/tests/test_examples.py/test_example |
3,936 | def _get_by_id(self, resource_id, exclude_fields=None):
try:
resource_db = self.access.get(id=resource_id, exclude_fields=exclude_fields)
except __HOLE__:
resource_db = None
return resource_db | ValidationError | dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/resource.py/ResourceController._get_by_id |
3,937 | def testTasklets_Raising(self):
self.ExpectWarnings()
@tasklets.tasklet
def t1():
f = t2(True)
try:
yield f
except __HOLE__, err:
self.assertEqual(f.get_exception(), err)
raise tasklets.Return(str(err))
@tasklets.tasklet
def t2(error):
if error:
... | RuntimeError | dataset/ETHPy150Open GoogleCloudPlatform/datastore-ndb-python/ndb/tasklets_test.py/TaskletTests.testTasklets_Raising |
3,938 | def testTasklet_YieldTupleTypeError(self):
self.ExpectWarnings()
@tasklets.tasklet
def good():
yield tasklets.sleep(0)
@tasklets.tasklet
def bad():
raise ZeroDivisionError
yield tasklets.sleep(0)
@tasklets.tasklet
def foo():
try:
yield good(), bad(), 42
... | TypeError | dataset/ETHPy150Open GoogleCloudPlatform/datastore-ndb-python/ndb/tasklets_test.py/TaskletTests.testTasklet_YieldTupleTypeError |
3,939 | def testBasicError(self):
self.ExpectWarnings()
frames = [sys._getframe()]
@tasklets.tasklet
def level3():
frames.append(sys._getframe())
raise RuntimeError('hello')
yield
@tasklets.tasklet
def level2():
frames.append(sys._getframe())
yield level3()
@tasklets... | RuntimeError | dataset/ETHPy150Open GoogleCloudPlatform/datastore-ndb-python/ndb/tasklets_test.py/TracebackTests.testBasicError |
3,940 | def testYieldError(self):
try:
self.provoke_yield_error()
except __HOLE__, err:
self.assertTrue(re.match(
"A tasklet should not yield a plain value: "
".*bad_user_code.*yielded 'abc'$",
str(err))) | RuntimeError | dataset/ETHPy150Open GoogleCloudPlatform/datastore-ndb-python/ndb/tasklets_test.py/TracebackTests.testYieldError |
3,941 | def execute(self, arguments, updateCompletion, updateMessage, updateStats, updateLicense):
self.log.debug("Callable runner arguments: %s" % arguments)
execType = arguments['execType']
#
# Add locations to site path if needed
#
# TODO instead, we should start rez with a ... | ImportError | dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/puliclient/runner.py/CallableRunner.execute |
3,942 | @classmethod
def executeWithOutput(cls, command, outputCallback=None):
"""
| Starts a subprocess with given command string. The subprocess is started without shell
| for safety reason. stderr is send to stdout and stdout is either send to a callback if given or
| printed on stdout ag... | OSError | dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/puliclient/runner.py/RunnerToolkit.executeWithOutput |
3,943 | @classmethod
def runGraphInXterm(cls, graph, keepWindowOpen=True):
"""
Specifically runs a graph locally in a separate xterm windows and subprocess.
Several possibilities to render locally:
- use graph.execute() in current thread --> PB: blocks the GUI
- use graph.execute... | OSError | dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/puliclient/runner.py/RunnerToolkit.runGraphInXterm |
3,944 | def test_max_recursion_error(self):
"""
Overriding a method on a super class and then calling that method on
the super class should not trigger infinite recursion. See #17011.
"""
try:
super(ClassDecoratedTestCase, self).test_max_recursion_error()
except __HO... | RuntimeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/settings_tests/tests.py/ClassDecoratedTestCase.test_max_recursion_error |
3,945 | @run_in_both(Person, "['setreadonly', 'setemitter', '_setprop1', '_setprop2']")
def test_try_illegal_stuff(Person):
# we cannot test delete, because deleting *is* possible
# on JS
res = []
name = Person()
try:
name.full_name = 'john doe'
except AttributeError:
res.append('setread... | TypeError | dataset/ETHPy150Open zoofIO/flexx/flexx/event/tests/test_both.py/test_try_illegal_stuff |
3,946 | @run_in_both(Person, "['ok-label', 'ok-type']")
def test_emit_fail(Person):
res = []
name = Person()
try:
name.emit('first_name:xx', dict(old_value='x1', new_value='y1'))
except ValueError:
res.append('ok-label')
try:
name.emit('first_name', 4)
except __HOLE__:
re... | TypeError | dataset/ETHPy150Open zoofIO/flexx/flexx/event/tests/test_both.py/test_emit_fail |
3,947 | @run_in_both(ConnectFail, "['ok']")
def test_handler_connection_fail1(ConnectFail):
try:
m = ConnectFail()
except __HOLE__:
return ['ok']
return ['fail'] | RuntimeError | dataset/ETHPy150Open zoofIO/flexx/flexx/event/tests/test_both.py/test_handler_connection_fail1 |
3,948 | @run_in_both(Person, "['ok']")
def test_handler_connection_fail2(Person):
name = Person()
def handler(*events):
pass
try:
name.connect(handler, 'foo.bar')
except __HOLE__:
return ['ok']
return ['fail'] | RuntimeError | dataset/ETHPy150Open zoofIO/flexx/flexx/event/tests/test_both.py/test_handler_connection_fail2 |
3,949 | @run_in_both(HandlerFail, "', 1, 1]")
def test_handler_exception1(HandlerFail):
res = []
m = HandlerFail()
def handler(*events):
raise IndexError('bla')
handler = m.connect(handler, 'foo')
# Does not fail when triggered
m.foo = 3
m.foo = 42
m.failing_handler.handle_now(... | IndexError | dataset/ETHPy150Open zoofIO/flexx/flexx/event/tests/test_both.py/test_handler_exception1 |
3,950 | def handle(self, **options):
if len(settings.SOCKJS_CLASSES) > 1:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured(
"Multiple connections not yet supported"
)
module_name, cls_name = settings.SOCKJS_CLASSES[0].rsplit(... | KeyboardInterrupt | dataset/ETHPy150Open peterbe/django-sockjs-tornado/django_sockjs_tornado/management/commands/socketserver.py/Command.handle |
3,951 | def retry(retries=4, delay_multiplier=3, backoff=2):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param int retries: number of tim... | SystemExit | dataset/ETHPy150Open cloudify-cosmo/packman/packman/utils.py/retry |
3,952 | def mkdir(self, dir):
"""creates (recursively) a directory
:param string dir: directory to create
"""
if not os.path.isdir(dir):
lgr.debug('Creating directory {0}'.format(dir))
try:
os.makedirs(dir)
except __HOLE__ as ex:
... | OSError | dataset/ETHPy150Open cloudify-cosmo/packman/packman/utils.py/Handler.mkdir |
3,953 | def cp(self, src, dst):
"""copies (recuresively or not) files or directories
:param string src: source to copy
:param string dst: destination to copy to
:param bool recurse: should the copying process be recursive?
"""
lgr.debug('Copying {0} to {1}'.format(src, dst))
... | OSError | dataset/ETHPy150Open cloudify-cosmo/packman/packman/utils.py/Handler.cp |
3,954 | def HasSniSupport():
try:
import OpenSSL
return (distutils.version.StrictVersion(OpenSSL.__version__) >=
distutils.version.StrictVersion('0.13'))
except __HOLE__:
return False | ImportError | dataset/ETHPy150Open chromium/web-page-replay/platformsettings.py/HasSniSupport |
3,955 | def has_ipfw(self):
try:
self.ipfw('list')
return True
except __HOLE__ as e:
logging.warning('Failed to start ipfw command. '
'Error: %s' % e.message)
return False | AssertionError | dataset/ETHPy150Open chromium/web-page-replay/platformsettings.py/_BasePlatformSettings.has_ipfw |
3,956 | def _get_primary_nameserver(self):
try:
resolv_file = open(self.RESOLV_CONF)
except __HOLE__:
raise DnsReadError()
for line in resolv_file:
if line.startswith('nameserver '):
return line.split()[1]
raise DnsReadError() | IOError | dataset/ETHPy150Open chromium/web-page-replay/platformsettings.py/_FreeBSDPlatformSettings._get_primary_nameserver |
3,957 | def _get_primary_nameserver(self):
try:
resolv_file = open(self.RESOLV_CONF)
except __HOLE__:
raise DnsReadError()
for line in resolv_file:
if line.startswith('nameserver '):
return line.split()[1]
raise DnsReadError() | IOError | dataset/ETHPy150Open chromium/web-page-replay/platformsettings.py/_LinuxPlatformSettings._get_primary_nameserver |
3,958 | def _set_primary_nameserver(self, dns):
"""Replace the first nameserver entry with the one given."""
try:
self._write_resolve_conf(dns)
except __HOLE__, e:
if 'Permission denied' in e:
raise self._get_dns_update_error()
raise | OSError | dataset/ETHPy150Open chromium/web-page-replay/platformsettings.py/_LinuxPlatformSettings._set_primary_nameserver |
3,959 | def _perform_unique_checks(self, unique_checks):
errors = {}
for model_class, unique_check in unique_checks:
lookup_kwargs = {}
for field_name in unique_check:
f = self._meta.get_field(field_name)
lookup_value = getattr(self, f.attname)
... | ValueError | dataset/ETHPy150Open potatolondon/djangae/djangae/db/constraints.py/UniquenessMixin._perform_unique_checks |
3,960 | def to_agraph(N):
"""Return a pygraphviz graph from a NetworkX graph N.
Parameters
----------
N : NetworkX graph
A graph created with NetworkX
Examples
--------
>>> K5=nx.complete_graph(5)
>>> A=nx.to_agraph(K5)
Notes
-----
If N has an dict N.graph_attr an attempt wi... | ImportError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/drawing/nx_agraph.py/to_agraph |
3,961 | def write_dot(G,path):
"""Write NetworkX graph G to Graphviz dot format on path.
Parameters
----------
G : graph
A networkx graph
path : filename
Filename or file handle to write
"""
try:
import pygraphviz
except __HOLE__:
raise ImportError('requires pygrap... | ImportError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/drawing/nx_agraph.py/write_dot |
3,962 | def read_dot(path):
"""Return a NetworkX graph from a dot file on path.
Parameters
----------
path : file or string
File name or file handle to read.
"""
try:
import pygraphviz
except __HOLE__:
raise ImportError('read_dot() requires pygraphviz ',
... | ImportError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/drawing/nx_agraph.py/read_dot |
3,963 | def pygraphviz_layout(G,prog='neato',root=None, args=''):
"""Create node positions for G using Graphviz.
Parameters
----------
G : NetworkX graph
A graph created with NetworkX
prog : string
Name of Graphviz layout program
root : string, optional
Root node for twopi layout
... | ImportError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/drawing/nx_agraph.py/pygraphviz_layout |
3,964 | def _libvirt_creds():
'''
Returns the user and group that the disk images should be owned by
'''
g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf'
u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf'
try:
stdout = subprocess.Popen(g_cmd,
shell=True,
stdo... | IndexError | dataset/ETHPy150Open saltstack/salt/salt/modules/virt.py/_libvirt_creds |
3,965 | def _qemu_image_info(path):
'''
Detect information for the image at path
'''
ret = {}
out = __salt__['cmd.run']('qemu-img info {0}'.format(path))
match_map = {'size': r'virtual size: \w+ \((\d+) byte[s]?\)',
'format': r'file format: (\w+)'}
for info, search in six.iteritem... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/modules/virt.py/_qemu_image_info |
3,966 | def init(name,
cpu,
mem,
image=None,
nic='default',
hypervisor=VIRT_DEFAULT_HYPER,
start=True, # pylint: disable=redefined-outer-name
disk='default',
saltenv='base',
seed=True,
install=True,
pub_key=None,
priv_k... | OSError | dataset/ETHPy150Open saltstack/salt/salt/modules/virt.py/init |
3,967 | def get_disks(vm_):
'''
Return the disks of a named vm
CLI Example:
.. code-block:: bash
salt '*' virt.get_disks <domain>
'''
disks = {}
doc = minidom.parse(_StringIO(get_xml(vm_)))
for elem in doc.getElementsByTagName('disk'):
sources = elem.getElementsByTagName('sour... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/modules/virt.py/get_disks |
3,968 | def is_kvm_hyper():
'''
Returns a bool whether or not this node is a KVM hypervisor
CLI Example:
.. code-block:: bash
salt '*' virt.is_kvm_hyper
'''
try:
if 'kvm_' not in salt.utils.fopen('/proc/modules').read():
return False
except __HOLE__:
# No /proc... | IOError | dataset/ETHPy150Open saltstack/salt/salt/modules/virt.py/is_kvm_hyper |
3,969 | def is_xen_hyper():
'''
Returns a bool whether or not this node is a XEN hypervisor
CLI Example:
.. code-block:: bash
salt '*' virt.is_xen_hyper
'''
try:
if __grains__['virtual_subtype'] != 'Xen Dom0':
return False
except KeyError:
# virtual_subtype isn... | IOError | dataset/ETHPy150Open saltstack/salt/salt/modules/virt.py/is_xen_hyper |
3,970 | def Next(self, this, celt, rgVar, pCeltFetched):
if not rgVar: return E_POINTER
if not pCeltFetched: pCeltFetched = [None]
pCeltFetched[0] = 0
try:
for index in range(celt):
item = self.seq.next()
p = item.QueryInterface(IDispatch)
... | StopIteration | dataset/ETHPy150Open enthought/comtypes/comtypes/server/automation.py/VARIANTEnumerator.Next |
3,971 | def Skip(self, this, celt):
# skip some elements.
try:
for _ in range(celt):
self.seq.next()
except __HOLE__:
return S_FALSE
return S_OK | StopIteration | dataset/ETHPy150Open enthought/comtypes/comtypes/server/automation.py/VARIANTEnumerator.Skip |
3,972 | def OnViewCreated(self, view):
print "OnViewCreated", view
# And if our demo view has been registered, it may well
# be that view!
try:
pyview = unwrap(view)
print "and look - its a Python implemented view!", pyview
except __HOLE__:
pass | ValueError | dataset/ETHPy150Open Jackeriss/Email_My_PC/shell/demos/explorer_browser.py/EventHandler.OnViewCreated |
3,973 | def make_dirs(*lpath):
"""Ensure the directories exist.
lpath: path fragments
"""
path = os.path.join(*lpath)
try:
os.makedirs(os.path.dirname(path))
except __HOLE__ as e:
if e.errno != errno.EEXIST:
raise
return os.path.abspath(path) | OSError | dataset/ETHPy150Open jpscaletti/Voodoo/voodoo/helpers.py/make_dirs |
3,974 | @classmethod
def socket_connect(cls, host, port, queryport, password=None, timeout=None):
"""Connect to socket.
Stores arguments on class variables to remember for reconnect.
Closes socket if open.
Returns:
Bool, Error
"""
if cls._socket:
cl... | OSError | dataset/ETHPy150Open f4ble/pyarc/ark/steam/steam_socket_core.py/SteamSocketCore.socket_connect |
3,975 | @classmethod
def loop_communication(cls):
while True:
# Don't send stuff when we're not connected.
while not cls.is_connected:
time.sleep(1)
send_packet = None
try:
send_packet = cls.outgoing_queue.popleft()
# No i... | IndexError | dataset/ETHPy150Open f4ble/pyarc/ark/steam/steam_socket_core.py/SteamSocketCore.loop_communication |
3,976 | @classmethod
def socket_send(cls, packet):
"""
Send SteamPacket
Args:
packet: SteamPacket
Returns:
bytes_sent: False or 0 means failure.
err: String
"""
assert isinstance(packet, SteamPacket), 'packet argument not of object... | OSError | dataset/ETHPy150Open f4ble/pyarc/ark/steam/steam_socket_core.py/SteamSocketCore.socket_send |
3,977 | @classmethod
def _socket_read(cls, wait=False):
"""
Read from socket. Does not fail on low timeout - only returns None.
Args:
wait: Bool. Blocking mode - wait until timeout.
Returns:
True, error_message: None
None, error_message: ... | OSError | dataset/ETHPy150Open f4ble/pyarc/ark/steam/steam_socket_core.py/SteamSocketCore._socket_read |
3,978 | def _get_project_file(win_id):
session_data = None
# Construct the base settings paths
auto_save_session_path = os.path.join(
sublime.packages_path(),
'..',
'Settings',
'Auto Save Session.sublime_session'
)
regular_session_path = os.path.join(
sublime.package... | IOError | dataset/ETHPy150Open Varriount/NimLime/nimlime_core/utils/project.py/_get_project_file |
3,979 | def get_nim_project(window, view):
"""
Given a window and view, return the Nim project associated with it.
:type window: sublime.Window
:type view: sublime.View
:rtype: str
"""
st_project = _get_project_file(window.id())
result = view.file_name()
if st_project is not None:
w... | IOError | dataset/ETHPy150Open Varriount/NimLime/nimlime_core/utils/project.py/get_nim_project |
3,980 | def __new__(cls, file):
unicodeFile = False
if PY3:
try:
file.write(b"")
except __HOLE__:
unicodeFile = True
if unicodeFile:
# On Python 3 native json module outputs unicode:
_dumps = pyjson.dumps
_lineb... | TypeError | dataset/ETHPy150Open ClusterHQ/eliot/eliot/_output.py/FileDestination.__new__ |
3,981 | def get_userdata(self, code):
"""Returns the relevant userdata from github.
This function must be called from githun oauth callback
and the auth code must be passed as argument.
"""
try:
session = self.get_auth_session(data={'code': code})
d = session.get... | KeyError | dataset/ETHPy150Open anandology/broadgauge/broadgauge/oauth.py/GitHub.get_userdata |
3,982 | def get_userdata(self, code):
"""Returns the relevant userdata from github.
This function must be called from githun oauth callback
and the auth code must be passed as argument.
"""
try:
session = self.get_auth_session(data={'code': code},
... | KeyError | dataset/ETHPy150Open anandology/broadgauge/broadgauge/oauth.py/Google.get_userdata |
3,983 | def get_userdata(self, code):
"""Returns the relevant userdata from github.
This function must be called from githun oauth callback
and the auth code must be passed as argument.
"""
try:
session = self.get_auth_session(
data={'code': code, 'redire... | KeyError | dataset/ETHPy150Open anandology/broadgauge/broadgauge/oauth.py/Facebook.get_userdata |
3,984 | def create_model(self, origin_resource, args=None, wait_time=3, retries=10):
"""Creates a model from an origin_resource.
Uses a remote resource to create a new model using the
arguments in `args`.
The allowed remote resources can be:
- dataset
- list of datasets
... | KeyError | dataset/ETHPy150Open bigmlcom/python/bigml/modelhandler.py/ModelHandler.create_model |
3,985 | def detach(self):
if self._parent:
try:
i = self._parent.index(self)
del self._parent[i]
except __HOLE__:
pass
self._parent = None
return self | ValueError | dataset/ETHPy150Open kdart/pycopia/net/pycopia/router.py/Impairment.detach |
3,986 | @staticmethod
def _associate_pd_user(email_address, pager):
try:
user = next(pager.users.list(query=email_address, limit=1))
return user
except __HOLE__:
return None | StopIteration | dataset/ETHPy150Open skoczen/will/will/plugins/devops/pagerduty.py/PagerDutyPlugin._associate_pd_user |
3,987 | def _get_user_email_from_mention_name(self, mention_name):
try:
u = self.get_user_by_nick(mention_name[1:])
email_address = self.get_hipchat_user(u['hipchat_id'])['email']
return email_address
except __HOLE__:
return None | TypeError | dataset/ETHPy150Open skoczen/will/will/plugins/devops/pagerduty.py/PagerDutyPlugin._get_user_email_from_mention_name |
3,988 | def pytest_configure():
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'}},
SITE_ID=1,
SECRET_KEY='not very secret in tests',
... | ImportError | dataset/ETHPy150Open tomchristie/django-rest-framework/tests/conftest.py/pytest_configure |
3,989 | def test_create_node_invalid_disk_size(self):
image = NodeImage(
id=1, name='Ubuntu 8.10 (intrepid)', driver=self.driver)
size = NodeSize(
1, '256 slice', None, None, None, None, driver=self.driver)
location = NodeLocation(id=1, name='Europe', country='England',
... | ValueError | dataset/ETHPy150Open apache/libcloud/libcloud/test/compute/test_voxel.py/VoxelTest.test_create_node_invalid_disk_size |
3,990 | def run(self, *args):
self.options += self.default_options()
cmd_ns = self.parser.parse_args(args)
logger.debug('Parsed command namespace: %s' % cmd_ns.__dict__)
kwargs = {}
for k, v in cmd_ns.__dict__.items():
if k in self.args:
kwargs[k] = v
... | TypeError | dataset/ETHPy150Open jmohr/compago/compago/command.py/Command.run |
3,991 | def get_values(in_file, out_file, keyword1):
"""
Created on 21 Oct 2014
Created for use with Wonderware Archestra, using the exported csv file from an object.
Lets say you exported a composite object to a csv file and you want all the short descriptions or all the tagnames, this function will get it for... | IOError | dataset/ETHPy150Open RoanFourie/ArchestrA-Tools/aaTools/aaCSV.py/get_values |
3,992 | def DestroyDatastore(self):
try:
data_store.DB.cache.Flush()
except __HOLE__:
pass
try:
if self.root_path:
shutil.rmtree(self.root_path)
except (OSError, IOError):
pass | AttributeError | dataset/ETHPy150Open google/grr/grr/lib/data_stores/sqlite_data_store_test.py/SqliteTestMixin.DestroyDatastore |
3,993 | def _render_cell(self, row, column, cell_format):
"""
Renders table cell with padding.
:param row: The row to render
:type: row: list
:param column: The column to render
:param cell_format: The cell format
:type cell_format: str
"""
try:
... | IndexError | dataset/ETHPy150Open sdispater/cleo/cleo/helpers/table.py/Table._render_cell |
3,994 | def _get_cell_width(self, row, column):
"""
Gets cell width.
:type row: list
:type column: int
:rtype: int
"""
try:
cell = row[column]
cell_width = Helper.len_without_decoration(self._output.get_formatter(), cell)
if isinsta... | IndexError | dataset/ETHPy150Open sdispater/cleo/cleo/helpers/table.py/Table._get_cell_width |
3,995 | def __delitem__(self, header):
try:
del self.headers[header]
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/http/__init__.py/HttpResponse.__delitem__ |
3,996 | def check_py_syntax(src_path, dst_path):
"""Check the Python syntax."""
if not os.path.exists(src_path):
os.makedirs(dst_path)
good = []
bad = []
for file_name in glob.glob(os.path.join(src_path, '*.mochi')):
mod_name = os.path.splitext(os.path.basename(file_name))[0]
py_file... | TypeError | dataset/ETHPy150Open i2y/mochi/tests/check_py_source.py/check_py_syntax |
3,997 | def __init__(self, client_cert=None, ca_cert=None, verify=None,
ssl_version=None, assert_hostname=None,
assert_fingerprint=None):
# Argument compatibility/mapping with
# https://docs.docker.com/engine/articles/https/
# This diverges from the Docker CLI in that u... | ValueError | dataset/ETHPy150Open docker/docker-py/docker/tls.py/TLSConfig.__init__ |
3,998 | @error_handler
def execute(request, design_id=None):
response = {'status': -1, 'message': ''}
if request.method != 'POST':
response['message'] = _('A POST request is required.')
app_name = get_app_name(request)
query_server = get_query_server_config(app_name)
query_type = beeswax.models.SavedQuery.TYPES... | RuntimeError | dataset/ETHPy150Open cloudera/hue/apps/beeswax/src/beeswax/api.py/execute |
3,999 | @error_handler
def save_query_design(request, design_id=None):
response = {'status': -1, 'message': ''}
if request.method != 'POST':
response['message'] = _('A POST request is required.')
app_name = get_app_name(request)
query_type = beeswax.models.SavedQuery.TYPES_MAPPING[app_name]
design = safe_get_de... | RuntimeError | dataset/ETHPy150Open cloudera/hue/apps/beeswax/src/beeswax/api.py/save_query_design |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.