partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test | get_py_filename | Return a valid python filename in the current directory.
If the given name is not a file, it adds '.py' and searches again.
Raises IOError with an informative message if the file isn't found.
On Windows, apply Windows semantics to the filename. In particular, remove
any quoting that has been applied to it. This option can be forced for
testing purposes. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def get_py_filename(name, force_win32=None):
"""Return a valid python filename in the current directory.
If the given name is not a file, it adds '.py' and searches again.
Raises IOError with an informative message if the file isn't found.
On Windows, apply Windows semantics to the filename. In particular, remove
any quoting that has been applied to it. This option can be forced for
testing purposes.
"""
name = os.path.expanduser(name)
if force_win32 is None:
win32 = (sys.platform == 'win32')
else:
win32 = force_win32
name = unquote_filename(name, win32=win32)
if not os.path.isfile(name) and not name.endswith('.py'):
name += '.py'
if os.path.isfile(name):
return name
else:
raise IOError,'File `%r` not found.' % name | def get_py_filename(name, force_win32=None):
"""Return a valid python filename in the current directory.
If the given name is not a file, it adds '.py' and searches again.
Raises IOError with an informative message if the file isn't found.
On Windows, apply Windows semantics to the filename. In particular, remove
any quoting that has been applied to it. This option can be forced for
testing purposes.
"""
name = os.path.expanduser(name)
if force_win32 is None:
win32 = (sys.platform == 'win32')
else:
win32 = force_win32
name = unquote_filename(name, win32=win32)
if not os.path.isfile(name) and not name.endswith('.py'):
name += '.py'
if os.path.isfile(name):
return name
else:
raise IOError,'File `%r` not found.' % name | [
"Return",
"a",
"valid",
"python",
"filename",
"in",
"the",
"current",
"directory",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L88-L110 | [
"def",
"get_py_filename",
"(",
"name",
",",
"force_win32",
"=",
"None",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"name",
")",
"if",
"force_win32",
"is",
"None",
":",
"win32",
"=",
"(",
"sys",
".",
"platform",
"==",
"'win32'",
")",
"else",
":",
"win32",
"=",
"force_win32",
"name",
"=",
"unquote_filename",
"(",
"name",
",",
"win32",
"=",
"win32",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"name",
")",
"and",
"not",
"name",
".",
"endswith",
"(",
"'.py'",
")",
":",
"name",
"+=",
"'.py'",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"name",
")",
":",
"return",
"name",
"else",
":",
"raise",
"IOError",
",",
"'File `%r` not found.'",
"%",
"name"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | filefind | Find a file by looking through a sequence of paths.
This iterates through a sequence of paths looking for a file and returns
the full, absolute path of the first occurence of the file. If no set of
path dirs is given, the filename is tested as is, after running through
:func:`expandvars` and :func:`expanduser`. Thus a simple call::
filefind('myfile.txt')
will find the file in the current working dir, but::
filefind('~/myfile.txt')
Will find the file in the users home directory. This function does not
automatically try any paths, such as the cwd or the user's home directory.
Parameters
----------
filename : str
The filename to look for.
path_dirs : str, None or sequence of str
The sequence of paths to look for the file in. If None, the filename
need to be absolute or be in the cwd. If a string, the string is
put into a sequence and the searched. If a sequence, walk through
each element and join with ``filename``, calling :func:`expandvars`
and :func:`expanduser` before testing for existence.
Returns
-------
Raises :exc:`IOError` or returns absolute path to file. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def filefind(filename, path_dirs=None):
"""Find a file by looking through a sequence of paths.
This iterates through a sequence of paths looking for a file and returns
the full, absolute path of the first occurence of the file. If no set of
path dirs is given, the filename is tested as is, after running through
:func:`expandvars` and :func:`expanduser`. Thus a simple call::
filefind('myfile.txt')
will find the file in the current working dir, but::
filefind('~/myfile.txt')
Will find the file in the users home directory. This function does not
automatically try any paths, such as the cwd or the user's home directory.
Parameters
----------
filename : str
The filename to look for.
path_dirs : str, None or sequence of str
The sequence of paths to look for the file in. If None, the filename
need to be absolute or be in the cwd. If a string, the string is
put into a sequence and the searched. If a sequence, walk through
each element and join with ``filename``, calling :func:`expandvars`
and :func:`expanduser` before testing for existence.
Returns
-------
Raises :exc:`IOError` or returns absolute path to file.
"""
# If paths are quoted, abspath gets confused, strip them...
filename = filename.strip('"').strip("'")
# If the input is an absolute path, just check it exists
if os.path.isabs(filename) and os.path.isfile(filename):
return filename
if path_dirs is None:
path_dirs = ("",)
elif isinstance(path_dirs, basestring):
path_dirs = (path_dirs,)
for path in path_dirs:
if path == '.': path = os.getcwdu()
testname = expand_path(os.path.join(path, filename))
if os.path.isfile(testname):
return os.path.abspath(testname)
raise IOError("File %r does not exist in any of the search paths: %r" %
(filename, path_dirs) ) | def filefind(filename, path_dirs=None):
"""Find a file by looking through a sequence of paths.
This iterates through a sequence of paths looking for a file and returns
the full, absolute path of the first occurence of the file. If no set of
path dirs is given, the filename is tested as is, after running through
:func:`expandvars` and :func:`expanduser`. Thus a simple call::
filefind('myfile.txt')
will find the file in the current working dir, but::
filefind('~/myfile.txt')
Will find the file in the users home directory. This function does not
automatically try any paths, such as the cwd or the user's home directory.
Parameters
----------
filename : str
The filename to look for.
path_dirs : str, None or sequence of str
The sequence of paths to look for the file in. If None, the filename
need to be absolute or be in the cwd. If a string, the string is
put into a sequence and the searched. If a sequence, walk through
each element and join with ``filename``, calling :func:`expandvars`
and :func:`expanduser` before testing for existence.
Returns
-------
Raises :exc:`IOError` or returns absolute path to file.
"""
# If paths are quoted, abspath gets confused, strip them...
filename = filename.strip('"').strip("'")
# If the input is an absolute path, just check it exists
if os.path.isabs(filename) and os.path.isfile(filename):
return filename
if path_dirs is None:
path_dirs = ("",)
elif isinstance(path_dirs, basestring):
path_dirs = (path_dirs,)
for path in path_dirs:
if path == '.': path = os.getcwdu()
testname = expand_path(os.path.join(path, filename))
if os.path.isfile(testname):
return os.path.abspath(testname)
raise IOError("File %r does not exist in any of the search paths: %r" %
(filename, path_dirs) ) | [
"Find",
"a",
"file",
"by",
"looking",
"through",
"a",
"sequence",
"of",
"paths",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L113-L164 | [
"def",
"filefind",
"(",
"filename",
",",
"path_dirs",
"=",
"None",
")",
":",
"# If paths are quoted, abspath gets confused, strip them...",
"filename",
"=",
"filename",
".",
"strip",
"(",
"'\"'",
")",
".",
"strip",
"(",
"\"'\"",
")",
"# If the input is an absolute path, just check it exists",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"filename",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"return",
"filename",
"if",
"path_dirs",
"is",
"None",
":",
"path_dirs",
"=",
"(",
"\"\"",
",",
")",
"elif",
"isinstance",
"(",
"path_dirs",
",",
"basestring",
")",
":",
"path_dirs",
"=",
"(",
"path_dirs",
",",
")",
"for",
"path",
"in",
"path_dirs",
":",
"if",
"path",
"==",
"'.'",
":",
"path",
"=",
"os",
".",
"getcwdu",
"(",
")",
"testname",
"=",
"expand_path",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"testname",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"testname",
")",
"raise",
"IOError",
"(",
"\"File %r does not exist in any of the search paths: %r\"",
"%",
"(",
"filename",
",",
"path_dirs",
")",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_home_dir | Return the 'home' directory, as a unicode string.
* First, check for frozen env in case of py2exe
* Otherwise, defer to os.path.expanduser('~')
See stdlib docs for how this is determined.
$HOME is first priority on *ALL* platforms.
Parameters
----------
require_writable : bool [default: False]
if True:
guarantees the return value is a writable directory, otherwise
raises HomeDirError
if False:
The path is resolved, but it is not guaranteed to exist or be writable. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def get_home_dir(require_writable=False):
"""Return the 'home' directory, as a unicode string.
* First, check for frozen env in case of py2exe
* Otherwise, defer to os.path.expanduser('~')
See stdlib docs for how this is determined.
$HOME is first priority on *ALL* platforms.
Parameters
----------
require_writable : bool [default: False]
if True:
guarantees the return value is a writable directory, otherwise
raises HomeDirError
if False:
The path is resolved, but it is not guaranteed to exist or be writable.
"""
# first, check py2exe distribution root directory for _ipython.
# This overrides all. Normally does not exist.
if hasattr(sys, "frozen"): #Is frozen by py2exe
if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
root, rest = IPython.__file__.lower().split('library.zip')
else:
root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
root=os.path.abspath(root).rstrip('\\')
if _writable_dir(os.path.join(root, '_ipython')):
os.environ["IPYKITROOT"] = root
return py3compat.cast_unicode(root, fs_encoding)
homedir = os.path.expanduser('~')
# Next line will make things work even when /home/ is a symlink to
# /usr/home as it is on FreeBSD, for example
homedir = os.path.realpath(homedir)
if not _writable_dir(homedir) and os.name == 'nt':
# expanduser failed, use the registry to get the 'My Documents' folder.
try:
import _winreg as wreg
key = wreg.OpenKey(
wreg.HKEY_CURRENT_USER,
"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
)
homedir = wreg.QueryValueEx(key,'Personal')[0]
key.Close()
except:
pass
if (not require_writable) or _writable_dir(homedir):
return py3compat.cast_unicode(homedir, fs_encoding)
else:
raise HomeDirError('%s is not a writable dir, '
'set $HOME environment variable to override' % homedir) | def get_home_dir(require_writable=False):
"""Return the 'home' directory, as a unicode string.
* First, check for frozen env in case of py2exe
* Otherwise, defer to os.path.expanduser('~')
See stdlib docs for how this is determined.
$HOME is first priority on *ALL* platforms.
Parameters
----------
require_writable : bool [default: False]
if True:
guarantees the return value is a writable directory, otherwise
raises HomeDirError
if False:
The path is resolved, but it is not guaranteed to exist or be writable.
"""
# first, check py2exe distribution root directory for _ipython.
# This overrides all. Normally does not exist.
if hasattr(sys, "frozen"): #Is frozen by py2exe
if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
root, rest = IPython.__file__.lower().split('library.zip')
else:
root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
root=os.path.abspath(root).rstrip('\\')
if _writable_dir(os.path.join(root, '_ipython')):
os.environ["IPYKITROOT"] = root
return py3compat.cast_unicode(root, fs_encoding)
homedir = os.path.expanduser('~')
# Next line will make things work even when /home/ is a symlink to
# /usr/home as it is on FreeBSD, for example
homedir = os.path.realpath(homedir)
if not _writable_dir(homedir) and os.name == 'nt':
# expanduser failed, use the registry to get the 'My Documents' folder.
try:
import _winreg as wreg
key = wreg.OpenKey(
wreg.HKEY_CURRENT_USER,
"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
)
homedir = wreg.QueryValueEx(key,'Personal')[0]
key.Close()
except:
pass
if (not require_writable) or _writable_dir(homedir):
return py3compat.cast_unicode(homedir, fs_encoding)
else:
raise HomeDirError('%s is not a writable dir, '
'set $HOME environment variable to override' % homedir) | [
"Return",
"the",
"home",
"directory",
"as",
"a",
"unicode",
"string",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L171-L226 | [
"def",
"get_home_dir",
"(",
"require_writable",
"=",
"False",
")",
":",
"# first, check py2exe distribution root directory for _ipython.",
"# This overrides all. Normally does not exist.",
"if",
"hasattr",
"(",
"sys",
",",
"\"frozen\"",
")",
":",
"#Is frozen by py2exe",
"if",
"'\\\\library.zip\\\\'",
"in",
"IPython",
".",
"__file__",
".",
"lower",
"(",
")",
":",
"#libraries compressed to zip-file",
"root",
",",
"rest",
"=",
"IPython",
".",
"__file__",
".",
"lower",
"(",
")",
".",
"split",
"(",
"'library.zip'",
")",
"else",
":",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"split",
"(",
"IPython",
".",
"__file__",
")",
"[",
"0",
"]",
",",
"\"../../\"",
")",
"root",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"root",
")",
".",
"rstrip",
"(",
"'\\\\'",
")",
"if",
"_writable_dir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"'_ipython'",
")",
")",
":",
"os",
".",
"environ",
"[",
"\"IPYKITROOT\"",
"]",
"=",
"root",
"return",
"py3compat",
".",
"cast_unicode",
"(",
"root",
",",
"fs_encoding",
")",
"homedir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"# Next line will make things work even when /home/ is a symlink to",
"# /usr/home as it is on FreeBSD, for example",
"homedir",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"homedir",
")",
"if",
"not",
"_writable_dir",
"(",
"homedir",
")",
"and",
"os",
".",
"name",
"==",
"'nt'",
":",
"# expanduser failed, use the registry to get the 'My Documents' folder.",
"try",
":",
"import",
"_winreg",
"as",
"wreg",
"key",
"=",
"wreg",
".",
"OpenKey",
"(",
"wreg",
".",
"HKEY_CURRENT_USER",
",",
"\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\"",
")",
"homedir",
"=",
"wreg",
".",
"QueryValueEx",
"(",
"key",
",",
"'Personal'",
")",
"[",
"0",
"]",
"key",
".",
"Close",
"(",
")",
"except",
":",
"pass",
"if",
"(",
"not",
"require_writable",
")",
"or",
"_writable_dir",
"(",
"homedir",
")",
":",
"return",
"py3compat",
".",
"cast_unicode",
"(",
"homedir",
",",
"fs_encoding",
")",
"else",
":",
"raise",
"HomeDirError",
"(",
"'%s is not a writable dir, '",
"'set $HOME environment variable to override'",
"%",
"homedir",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_xdg_dir | Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
This is only for non-OS X posix (Linux,Unix,etc.) systems. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def get_xdg_dir():
"""Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
This is only for non-OS X posix (Linux,Unix,etc.) systems.
"""
env = os.environ
if os.name == 'posix' and sys.platform != 'darwin':
# Linux, Unix, AIX, etc.
# use ~/.config if empty OR not set
xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
if xdg and _writable_dir(xdg):
return py3compat.cast_unicode(xdg, fs_encoding)
return None | def get_xdg_dir():
"""Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
This is only for non-OS X posix (Linux,Unix,etc.) systems.
"""
env = os.environ
if os.name == 'posix' and sys.platform != 'darwin':
# Linux, Unix, AIX, etc.
# use ~/.config if empty OR not set
xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
if xdg and _writable_dir(xdg):
return py3compat.cast_unicode(xdg, fs_encoding)
return None | [
"Return",
"the",
"XDG_CONFIG_HOME",
"if",
"it",
"is",
"defined",
"and",
"exists",
"else",
"None",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L228-L243 | [
"def",
"get_xdg_dir",
"(",
")",
":",
"env",
"=",
"os",
".",
"environ",
"if",
"os",
".",
"name",
"==",
"'posix'",
"and",
"sys",
".",
"platform",
"!=",
"'darwin'",
":",
"# Linux, Unix, AIX, etc.",
"# use ~/.config if empty OR not set",
"xdg",
"=",
"env",
".",
"get",
"(",
"\"XDG_CONFIG_HOME\"",
",",
"None",
")",
"or",
"os",
".",
"path",
".",
"join",
"(",
"get_home_dir",
"(",
")",
",",
"'.config'",
")",
"if",
"xdg",
"and",
"_writable_dir",
"(",
"xdg",
")",
":",
"return",
"py3compat",
".",
"cast_unicode",
"(",
"xdg",
",",
"fs_encoding",
")",
"return",
"None"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_ipython_dir | Get the IPython directory for this platform and user.
This uses the logic in `get_home_dir` to find the home directory
and then adds .ipython to the end of the path. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def get_ipython_dir():
"""Get the IPython directory for this platform and user.
This uses the logic in `get_home_dir` to find the home directory
and then adds .ipython to the end of the path.
"""
env = os.environ
pjoin = os.path.join
ipdir_def = '.ipython'
xdg_def = 'ipython'
home_dir = get_home_dir()
xdg_dir = get_xdg_dir()
# import pdb; pdb.set_trace() # dbg
if 'IPYTHON_DIR' in env:
warnings.warn('The environment variable IPYTHON_DIR is deprecated. '
'Please use IPYTHONDIR instead.')
ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None))
if ipdir is None:
# not set explicitly, use XDG_CONFIG_HOME or HOME
home_ipdir = pjoin(home_dir, ipdir_def)
if xdg_dir:
# use XDG, as long as the user isn't already
# using $HOME/.ipython and *not* XDG/ipython
xdg_ipdir = pjoin(xdg_dir, xdg_def)
if _writable_dir(xdg_ipdir) or not _writable_dir(home_ipdir):
ipdir = xdg_ipdir
if ipdir is None:
# not using XDG
ipdir = home_ipdir
ipdir = os.path.normpath(os.path.expanduser(ipdir))
if os.path.exists(ipdir) and not _writable_dir(ipdir):
# ipdir exists, but is not writable
warnings.warn("IPython dir '%s' is not a writable location,"
" using a temp directory."%ipdir)
ipdir = tempfile.mkdtemp()
elif not os.path.exists(ipdir):
parent = ipdir.rsplit(os.path.sep, 1)[0]
if not _writable_dir(parent):
# ipdir does not exist and parent isn't writable
warnings.warn("IPython parent '%s' is not a writable location,"
" using a temp directory."%parent)
ipdir = tempfile.mkdtemp()
return py3compat.cast_unicode(ipdir, fs_encoding) | def get_ipython_dir():
"""Get the IPython directory for this platform and user.
This uses the logic in `get_home_dir` to find the home directory
and then adds .ipython to the end of the path.
"""
env = os.environ
pjoin = os.path.join
ipdir_def = '.ipython'
xdg_def = 'ipython'
home_dir = get_home_dir()
xdg_dir = get_xdg_dir()
# import pdb; pdb.set_trace() # dbg
if 'IPYTHON_DIR' in env:
warnings.warn('The environment variable IPYTHON_DIR is deprecated. '
'Please use IPYTHONDIR instead.')
ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None))
if ipdir is None:
# not set explicitly, use XDG_CONFIG_HOME or HOME
home_ipdir = pjoin(home_dir, ipdir_def)
if xdg_dir:
# use XDG, as long as the user isn't already
# using $HOME/.ipython and *not* XDG/ipython
xdg_ipdir = pjoin(xdg_dir, xdg_def)
if _writable_dir(xdg_ipdir) or not _writable_dir(home_ipdir):
ipdir = xdg_ipdir
if ipdir is None:
# not using XDG
ipdir = home_ipdir
ipdir = os.path.normpath(os.path.expanduser(ipdir))
if os.path.exists(ipdir) and not _writable_dir(ipdir):
# ipdir exists, but is not writable
warnings.warn("IPython dir '%s' is not a writable location,"
" using a temp directory."%ipdir)
ipdir = tempfile.mkdtemp()
elif not os.path.exists(ipdir):
parent = ipdir.rsplit(os.path.sep, 1)[0]
if not _writable_dir(parent):
# ipdir does not exist and parent isn't writable
warnings.warn("IPython parent '%s' is not a writable location,"
" using a temp directory."%parent)
ipdir = tempfile.mkdtemp()
return py3compat.cast_unicode(ipdir, fs_encoding) | [
"Get",
"the",
"IPython",
"directory",
"for",
"this",
"platform",
"and",
"user",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L246-L299 | [
"def",
"get_ipython_dir",
"(",
")",
":",
"env",
"=",
"os",
".",
"environ",
"pjoin",
"=",
"os",
".",
"path",
".",
"join",
"ipdir_def",
"=",
"'.ipython'",
"xdg_def",
"=",
"'ipython'",
"home_dir",
"=",
"get_home_dir",
"(",
")",
"xdg_dir",
"=",
"get_xdg_dir",
"(",
")",
"# import pdb; pdb.set_trace() # dbg",
"if",
"'IPYTHON_DIR'",
"in",
"env",
":",
"warnings",
".",
"warn",
"(",
"'The environment variable IPYTHON_DIR is deprecated. '",
"'Please use IPYTHONDIR instead.'",
")",
"ipdir",
"=",
"env",
".",
"get",
"(",
"'IPYTHONDIR'",
",",
"env",
".",
"get",
"(",
"'IPYTHON_DIR'",
",",
"None",
")",
")",
"if",
"ipdir",
"is",
"None",
":",
"# not set explicitly, use XDG_CONFIG_HOME or HOME",
"home_ipdir",
"=",
"pjoin",
"(",
"home_dir",
",",
"ipdir_def",
")",
"if",
"xdg_dir",
":",
"# use XDG, as long as the user isn't already",
"# using $HOME/.ipython and *not* XDG/ipython",
"xdg_ipdir",
"=",
"pjoin",
"(",
"xdg_dir",
",",
"xdg_def",
")",
"if",
"_writable_dir",
"(",
"xdg_ipdir",
")",
"or",
"not",
"_writable_dir",
"(",
"home_ipdir",
")",
":",
"ipdir",
"=",
"xdg_ipdir",
"if",
"ipdir",
"is",
"None",
":",
"# not using XDG",
"ipdir",
"=",
"home_ipdir",
"ipdir",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"ipdir",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"ipdir",
")",
"and",
"not",
"_writable_dir",
"(",
"ipdir",
")",
":",
"# ipdir exists, but is not writable",
"warnings",
".",
"warn",
"(",
"\"IPython dir '%s' is not a writable location,\"",
"\" using a temp directory.\"",
"%",
"ipdir",
")",
"ipdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"elif",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"ipdir",
")",
":",
"parent",
"=",
"ipdir",
".",
"rsplit",
"(",
"os",
".",
"path",
".",
"sep",
",",
"1",
")",
"[",
"0",
"]",
"if",
"not",
"_writable_dir",
"(",
"parent",
")",
":",
"# ipdir does not exist and parent isn't writable",
"warnings",
".",
"warn",
"(",
"\"IPython parent '%s' is not a writable location,\"",
"\" using a temp directory.\"",
"%",
"parent",
")",
"ipdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"return",
"py3compat",
".",
"cast_unicode",
"(",
"ipdir",
",",
"fs_encoding",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_ipython_package_dir | Get the base directory where IPython itself is installed. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def get_ipython_package_dir():
"""Get the base directory where IPython itself is installed."""
ipdir = os.path.dirname(IPython.__file__)
return py3compat.cast_unicode(ipdir, fs_encoding) | def get_ipython_package_dir():
"""Get the base directory where IPython itself is installed."""
ipdir = os.path.dirname(IPython.__file__)
return py3compat.cast_unicode(ipdir, fs_encoding) | [
"Get",
"the",
"base",
"directory",
"where",
"IPython",
"itself",
"is",
"installed",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L302-L305 | [
"def",
"get_ipython_package_dir",
"(",
")",
":",
"ipdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"IPython",
".",
"__file__",
")",
"return",
"py3compat",
".",
"cast_unicode",
"(",
"ipdir",
",",
"fs_encoding",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_ipython_module_path | Find the path to an IPython module in this version of IPython.
This will always find the version of the module that is in this importable
IPython package. This will always return the path to the ``.py``
version of the module. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def get_ipython_module_path(module_str):
"""Find the path to an IPython module in this version of IPython.
This will always find the version of the module that is in this importable
IPython package. This will always return the path to the ``.py``
version of the module.
"""
if module_str == 'IPython':
return os.path.join(get_ipython_package_dir(), '__init__.py')
mod = import_item(module_str)
the_path = mod.__file__.replace('.pyc', '.py')
the_path = the_path.replace('.pyo', '.py')
return py3compat.cast_unicode(the_path, fs_encoding) | def get_ipython_module_path(module_str):
"""Find the path to an IPython module in this version of IPython.
This will always find the version of the module that is in this importable
IPython package. This will always return the path to the ``.py``
version of the module.
"""
if module_str == 'IPython':
return os.path.join(get_ipython_package_dir(), '__init__.py')
mod = import_item(module_str)
the_path = mod.__file__.replace('.pyc', '.py')
the_path = the_path.replace('.pyo', '.py')
return py3compat.cast_unicode(the_path, fs_encoding) | [
"Find",
"the",
"path",
"to",
"an",
"IPython",
"module",
"in",
"this",
"version",
"of",
"IPython",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L308-L320 | [
"def",
"get_ipython_module_path",
"(",
"module_str",
")",
":",
"if",
"module_str",
"==",
"'IPython'",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"get_ipython_package_dir",
"(",
")",
",",
"'__init__.py'",
")",
"mod",
"=",
"import_item",
"(",
"module_str",
")",
"the_path",
"=",
"mod",
".",
"__file__",
".",
"replace",
"(",
"'.pyc'",
",",
"'.py'",
")",
"the_path",
"=",
"the_path",
".",
"replace",
"(",
"'.pyo'",
",",
"'.py'",
")",
"return",
"py3compat",
".",
"cast_unicode",
"(",
"the_path",
",",
"fs_encoding",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | locate_profile | Find the path to the folder associated with a given profile.
I.e. find $IPYTHONDIR/profile_whatever. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def locate_profile(profile='default'):
"""Find the path to the folder associated with a given profile.
I.e. find $IPYTHONDIR/profile_whatever.
"""
from IPython.core.profiledir import ProfileDir, ProfileDirError
try:
pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
except ProfileDirError:
# IOError makes more sense when people are expecting a path
raise IOError("Couldn't find profile %r" % profile)
return pd.location | def locate_profile(profile='default'):
"""Find the path to the folder associated with a given profile.
I.e. find $IPYTHONDIR/profile_whatever.
"""
from IPython.core.profiledir import ProfileDir, ProfileDirError
try:
pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
except ProfileDirError:
# IOError makes more sense when people are expecting a path
raise IOError("Couldn't find profile %r" % profile)
return pd.location | [
"Find",
"the",
"path",
"to",
"the",
"folder",
"associated",
"with",
"a",
"given",
"profile",
".",
"I",
".",
"e",
".",
"find",
"$IPYTHONDIR",
"/",
"profile_whatever",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L322-L333 | [
"def",
"locate_profile",
"(",
"profile",
"=",
"'default'",
")",
":",
"from",
"IPython",
".",
"core",
".",
"profiledir",
"import",
"ProfileDir",
",",
"ProfileDirError",
"try",
":",
"pd",
"=",
"ProfileDir",
".",
"find_profile_dir_by_name",
"(",
"get_ipython_dir",
"(",
")",
",",
"profile",
")",
"except",
"ProfileDirError",
":",
"# IOError makes more sense when people are expecting a path",
"raise",
"IOError",
"(",
"\"Couldn't find profile %r\"",
"%",
"profile",
")",
"return",
"pd",
".",
"location"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | expand_path | Expand $VARS and ~names in a string, like a shell
:Examples:
In [2]: os.environ['FOO']='test'
In [3]: expand_path('variable FOO is $FOO')
Out[3]: 'variable FOO is test' | environment/lib/python2.7/site-packages/IPython/utils/path.py | def expand_path(s):
"""Expand $VARS and ~names in a string, like a shell
:Examples:
In [2]: os.environ['FOO']='test'
In [3]: expand_path('variable FOO is $FOO')
Out[3]: 'variable FOO is test'
"""
# This is a pretty subtle hack. When expand user is given a UNC path
# on Windows (\\server\share$\%username%), os.path.expandvars, removes
# the $ to get (\\server\share\%username%). I think it considered $
# alone an empty var. But, we need the $ to remains there (it indicates
# a hidden share).
if os.name=='nt':
s = s.replace('$\\', 'IPYTHON_TEMP')
s = os.path.expandvars(os.path.expanduser(s))
if os.name=='nt':
s = s.replace('IPYTHON_TEMP', '$\\')
return s | def expand_path(s):
"""Expand $VARS and ~names in a string, like a shell
:Examples:
In [2]: os.environ['FOO']='test'
In [3]: expand_path('variable FOO is $FOO')
Out[3]: 'variable FOO is test'
"""
# This is a pretty subtle hack. When expand user is given a UNC path
# on Windows (\\server\share$\%username%), os.path.expandvars, removes
# the $ to get (\\server\share\%username%). I think it considered $
# alone an empty var. But, we need the $ to remains there (it indicates
# a hidden share).
if os.name=='nt':
s = s.replace('$\\', 'IPYTHON_TEMP')
s = os.path.expandvars(os.path.expanduser(s))
if os.name=='nt':
s = s.replace('IPYTHON_TEMP', '$\\')
return s | [
"Expand",
"$VARS",
"and",
"~names",
"in",
"a",
"string",
"like",
"a",
"shell"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L335-L355 | [
"def",
"expand_path",
"(",
"s",
")",
":",
"# This is a pretty subtle hack. When expand user is given a UNC path",
"# on Windows (\\\\server\\share$\\%username%), os.path.expandvars, removes",
"# the $ to get (\\\\server\\share\\%username%). I think it considered $",
"# alone an empty var. But, we need the $ to remains there (it indicates",
"# a hidden share).",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"'$\\\\'",
",",
"'IPYTHON_TEMP'",
")",
"s",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"s",
")",
")",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"'IPYTHON_TEMP'",
",",
"'$\\\\'",
")",
"return",
"s"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | target_outdated | Determine whether a target is out of date.
target_outdated(target,deps) -> 1/0
deps: list of filenames which MUST exist.
target: single filename which may or may not exist.
If target doesn't exist or is older than any file listed in deps, return
true, otherwise return false. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def target_outdated(target,deps):
"""Determine whether a target is out of date.
target_outdated(target,deps) -> 1/0
deps: list of filenames which MUST exist.
target: single filename which may or may not exist.
If target doesn't exist or is older than any file listed in deps, return
true, otherwise return false.
"""
try:
target_time = os.path.getmtime(target)
except os.error:
return 1
for dep in deps:
dep_time = os.path.getmtime(dep)
if dep_time > target_time:
#print "For target",target,"Dep failed:",dep # dbg
#print "times (dep,tar):",dep_time,target_time # dbg
return 1
return 0 | def target_outdated(target,deps):
"""Determine whether a target is out of date.
target_outdated(target,deps) -> 1/0
deps: list of filenames which MUST exist.
target: single filename which may or may not exist.
If target doesn't exist or is older than any file listed in deps, return
true, otherwise return false.
"""
try:
target_time = os.path.getmtime(target)
except os.error:
return 1
for dep in deps:
dep_time = os.path.getmtime(dep)
if dep_time > target_time:
#print "For target",target,"Dep failed:",dep # dbg
#print "times (dep,tar):",dep_time,target_time # dbg
return 1
return 0 | [
"Determine",
"whether",
"a",
"target",
"is",
"out",
"of",
"date",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L358-L379 | [
"def",
"target_outdated",
"(",
"target",
",",
"deps",
")",
":",
"try",
":",
"target_time",
"=",
"os",
".",
"path",
".",
"getmtime",
"(",
"target",
")",
"except",
"os",
".",
"error",
":",
"return",
"1",
"for",
"dep",
"in",
"deps",
":",
"dep_time",
"=",
"os",
".",
"path",
".",
"getmtime",
"(",
"dep",
")",
"if",
"dep_time",
">",
"target_time",
":",
"#print \"For target\",target,\"Dep failed:\",dep # dbg",
"#print \"times (dep,tar):\",dep_time,target_time # dbg",
"return",
"1",
"return",
"0"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | filehash | Make an MD5 hash of a file, ignoring any differences in line
ending characters. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def filehash(path):
"""Make an MD5 hash of a file, ignoring any differences in line
ending characters."""
with open(path, "rU") as f:
return md5(py3compat.str_to_bytes(f.read())).hexdigest() | def filehash(path):
"""Make an MD5 hash of a file, ignoring any differences in line
ending characters."""
with open(path, "rU") as f:
return md5(py3compat.str_to_bytes(f.read())).hexdigest() | [
"Make",
"an",
"MD5",
"hash",
"of",
"a",
"file",
"ignoring",
"any",
"differences",
"in",
"line",
"ending",
"characters",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L393-L397 | [
"def",
"filehash",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"rU\"",
")",
"as",
"f",
":",
"return",
"md5",
"(",
"py3compat",
".",
"str_to_bytes",
"(",
"f",
".",
"read",
"(",
")",
")",
")",
".",
"hexdigest",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | check_for_old_config | Check for old config files, and present a warning if they exist.
A link to the docs of the new config is included in the message.
This should mitigate confusion with the transition to the new
config system in 0.11. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def check_for_old_config(ipython_dir=None):
"""Check for old config files, and present a warning if they exist.
A link to the docs of the new config is included in the message.
This should mitigate confusion with the transition to the new
config system in 0.11.
"""
if ipython_dir is None:
ipython_dir = get_ipython_dir()
old_configs = ['ipy_user_conf.py', 'ipythonrc', 'ipython_config.py']
warned = False
for cfg in old_configs:
f = os.path.join(ipython_dir, cfg)
if os.path.exists(f):
if filehash(f) == old_config_md5.get(cfg, ''):
os.unlink(f)
else:
warnings.warn("Found old IPython config file %r (modified by user)"%f)
warned = True
if warned:
warnings.warn("""
The IPython configuration system has changed as of 0.11, and these files will
be ignored. See http://ipython.github.com/ipython-doc/dev/config for details
of the new config system.
To start configuring IPython, do `ipython profile create`, and edit
`ipython_config.py` in <ipython_dir>/profile_default.
If you need to leave the old config files in place for an older version of
IPython and want to suppress this warning message, set
`c.InteractiveShellApp.ignore_old_config=True` in the new config.""") | def check_for_old_config(ipython_dir=None):
"""Check for old config files, and present a warning if they exist.
A link to the docs of the new config is included in the message.
This should mitigate confusion with the transition to the new
config system in 0.11.
"""
if ipython_dir is None:
ipython_dir = get_ipython_dir()
old_configs = ['ipy_user_conf.py', 'ipythonrc', 'ipython_config.py']
warned = False
for cfg in old_configs:
f = os.path.join(ipython_dir, cfg)
if os.path.exists(f):
if filehash(f) == old_config_md5.get(cfg, ''):
os.unlink(f)
else:
warnings.warn("Found old IPython config file %r (modified by user)"%f)
warned = True
if warned:
warnings.warn("""
The IPython configuration system has changed as of 0.11, and these files will
be ignored. See http://ipython.github.com/ipython-doc/dev/config for details
of the new config system.
To start configuring IPython, do `ipython profile create`, and edit
`ipython_config.py` in <ipython_dir>/profile_default.
If you need to leave the old config files in place for an older version of
IPython and want to suppress this warning message, set
`c.InteractiveShellApp.ignore_old_config=True` in the new config.""") | [
"Check",
"for",
"old",
"config",
"files",
"and",
"present",
"a",
"warning",
"if",
"they",
"exist",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L405-L436 | [
"def",
"check_for_old_config",
"(",
"ipython_dir",
"=",
"None",
")",
":",
"if",
"ipython_dir",
"is",
"None",
":",
"ipython_dir",
"=",
"get_ipython_dir",
"(",
")",
"old_configs",
"=",
"[",
"'ipy_user_conf.py'",
",",
"'ipythonrc'",
",",
"'ipython_config.py'",
"]",
"warned",
"=",
"False",
"for",
"cfg",
"in",
"old_configs",
":",
"f",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ipython_dir",
",",
"cfg",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"f",
")",
":",
"if",
"filehash",
"(",
"f",
")",
"==",
"old_config_md5",
".",
"get",
"(",
"cfg",
",",
"''",
")",
":",
"os",
".",
"unlink",
"(",
"f",
")",
"else",
":",
"warnings",
".",
"warn",
"(",
"\"Found old IPython config file %r (modified by user)\"",
"%",
"f",
")",
"warned",
"=",
"True",
"if",
"warned",
":",
"warnings",
".",
"warn",
"(",
"\"\"\"\n The IPython configuration system has changed as of 0.11, and these files will\n be ignored. See http://ipython.github.com/ipython-doc/dev/config for details\n of the new config system.\n To start configuring IPython, do `ipython profile create`, and edit\n `ipython_config.py` in <ipython_dir>/profile_default.\n If you need to leave the old config files in place for an older version of\n IPython and want to suppress this warning message, set\n `c.InteractiveShellApp.ignore_old_config=True` in the new config.\"\"\"",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_security_file | Return the absolute path of a security file given by filename and profile
This allows users and developers to find security files without
knowledge of the IPython directory structure. The search path
will be ['.', profile.security_dir]
Parameters
----------
filename : str
The file to be found. If it is passed as an absolute path, it will
simply be returned.
profile : str [default: 'default']
The name of the profile to search. Leaving this unspecified
The file to be found. If it is passed as an absolute path, fname will
simply be returned.
Returns
-------
Raises :exc:`IOError` if file not found or returns absolute path to file. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def get_security_file(filename, profile='default'):
"""Return the absolute path of a security file given by filename and profile
This allows users and developers to find security files without
knowledge of the IPython directory structure. The search path
will be ['.', profile.security_dir]
Parameters
----------
filename : str
The file to be found. If it is passed as an absolute path, it will
simply be returned.
profile : str [default: 'default']
The name of the profile to search. Leaving this unspecified
The file to be found. If it is passed as an absolute path, fname will
simply be returned.
Returns
-------
Raises :exc:`IOError` if file not found or returns absolute path to file.
"""
# import here, because profiledir also imports from utils.path
from IPython.core.profiledir import ProfileDir
try:
pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
except Exception:
# will raise ProfileDirError if no such profile
raise IOError("Profile %r not found")
return filefind(filename, ['.', pd.security_dir]) | def get_security_file(filename, profile='default'):
"""Return the absolute path of a security file given by filename and profile
This allows users and developers to find security files without
knowledge of the IPython directory structure. The search path
will be ['.', profile.security_dir]
Parameters
----------
filename : str
The file to be found. If it is passed as an absolute path, it will
simply be returned.
profile : str [default: 'default']
The name of the profile to search. Leaving this unspecified
The file to be found. If it is passed as an absolute path, fname will
simply be returned.
Returns
-------
Raises :exc:`IOError` if file not found or returns absolute path to file.
"""
# import here, because profiledir also imports from utils.path
from IPython.core.profiledir import ProfileDir
try:
pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
except Exception:
# will raise ProfileDirError if no such profile
raise IOError("Profile %r not found")
return filefind(filename, ['.', pd.security_dir]) | [
"Return",
"the",
"absolute",
"path",
"of",
"a",
"security",
"file",
"given",
"by",
"filename",
"and",
"profile",
"This",
"allows",
"users",
"and",
"developers",
"to",
"find",
"security",
"files",
"without",
"knowledge",
"of",
"the",
"IPython",
"directory",
"structure",
".",
"The",
"search",
"path",
"will",
"be",
"[",
".",
"profile",
".",
"security_dir",
"]",
"Parameters",
"----------",
"filename",
":",
"str",
"The",
"file",
"to",
"be",
"found",
".",
"If",
"it",
"is",
"passed",
"as",
"an",
"absolute",
"path",
"it",
"will",
"simply",
"be",
"returned",
".",
"profile",
":",
"str",
"[",
"default",
":",
"default",
"]",
"The",
"name",
"of",
"the",
"profile",
"to",
"search",
".",
"Leaving",
"this",
"unspecified",
"The",
"file",
"to",
"be",
"found",
".",
"If",
"it",
"is",
"passed",
"as",
"an",
"absolute",
"path",
"fname",
"will",
"simply",
"be",
"returned",
".",
"Returns",
"-------",
"Raises",
":",
"exc",
":",
"IOError",
"if",
"file",
"not",
"found",
"or",
"returns",
"absolute",
"path",
"to",
"file",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L438-L467 | [
"def",
"get_security_file",
"(",
"filename",
",",
"profile",
"=",
"'default'",
")",
":",
"# import here, because profiledir also imports from utils.path",
"from",
"IPython",
".",
"core",
".",
"profiledir",
"import",
"ProfileDir",
"try",
":",
"pd",
"=",
"ProfileDir",
".",
"find_profile_dir_by_name",
"(",
"get_ipython_dir",
"(",
")",
",",
"profile",
")",
"except",
"Exception",
":",
"# will raise ProfileDirError if no such profile",
"raise",
"IOError",
"(",
"\"Profile %r not found\"",
")",
"return",
"filefind",
"(",
"filename",
",",
"[",
"'.'",
",",
"pd",
".",
"security_dir",
"]",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | update_suggestions_dictionary | Updates the suggestions' dictionary for an object upon visiting its page | suggestions/views.py | def update_suggestions_dictionary(request, object):
"""
Updates the suggestions' dictionary for an object upon visiting its page
"""
if request.user.is_authenticated():
user = request.user
content_type = ContentType.objects.get_for_model(type(object))
try:
# Check if the user has visited this page before
ObjectView.objects.get(
user=user, object_id=object.id, content_type=content_type)
except:
ObjectView.objects.create(user=user, content_object=object)
# Get a list of all the objects a user has visited
viewed = ObjectView.objects.filter(user=user)
else:
update_dict_for_guests(request, object, content_type)
return
if viewed:
for obj in viewed:
if content_type == obj.content_type:
if not exists_in_dictionary(request, object,
content_type,
obj, True):
# Create an entry if it's non existent
if object.id != obj.object_id:
ObjectViewDictionary.objects.create(
current_object=object,
visited_before_object=obj.content_object)
if not exists_in_dictionary(request, obj,
obj.content_type,
object, False):
ObjectViewDictionary.objects.create(
current_object=obj.content_object,
visited_before_object=object)
return | def update_suggestions_dictionary(request, object):
"""
Updates the suggestions' dictionary for an object upon visiting its page
"""
if request.user.is_authenticated():
user = request.user
content_type = ContentType.objects.get_for_model(type(object))
try:
# Check if the user has visited this page before
ObjectView.objects.get(
user=user, object_id=object.id, content_type=content_type)
except:
ObjectView.objects.create(user=user, content_object=object)
# Get a list of all the objects a user has visited
viewed = ObjectView.objects.filter(user=user)
else:
update_dict_for_guests(request, object, content_type)
return
if viewed:
for obj in viewed:
if content_type == obj.content_type:
if not exists_in_dictionary(request, object,
content_type,
obj, True):
# Create an entry if it's non existent
if object.id != obj.object_id:
ObjectViewDictionary.objects.create(
current_object=object,
visited_before_object=obj.content_object)
if not exists_in_dictionary(request, obj,
obj.content_type,
object, False):
ObjectViewDictionary.objects.create(
current_object=obj.content_object,
visited_before_object=object)
return | [
"Updates",
"the",
"suggestions",
"dictionary",
"for",
"an",
"object",
"upon",
"visiting",
"its",
"page"
] | dreidev/Suggestions | python | https://github.com/dreidev/Suggestions/blob/f04c181dc815d32c35b44c6e1c91521e88a9dd6c/suggestions/views.py#L5-L42 | [
"def",
"update_suggestions_dictionary",
"(",
"request",
",",
"object",
")",
":",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"user",
"=",
"request",
".",
"user",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"type",
"(",
"object",
")",
")",
"try",
":",
"# Check if the user has visited this page before",
"ObjectView",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"user",
",",
"object_id",
"=",
"object",
".",
"id",
",",
"content_type",
"=",
"content_type",
")",
"except",
":",
"ObjectView",
".",
"objects",
".",
"create",
"(",
"user",
"=",
"user",
",",
"content_object",
"=",
"object",
")",
"# Get a list of all the objects a user has visited",
"viewed",
"=",
"ObjectView",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"user",
")",
"else",
":",
"update_dict_for_guests",
"(",
"request",
",",
"object",
",",
"content_type",
")",
"return",
"if",
"viewed",
":",
"for",
"obj",
"in",
"viewed",
":",
"if",
"content_type",
"==",
"obj",
".",
"content_type",
":",
"if",
"not",
"exists_in_dictionary",
"(",
"request",
",",
"object",
",",
"content_type",
",",
"obj",
",",
"True",
")",
":",
"# Create an entry if it's non existent",
"if",
"object",
".",
"id",
"!=",
"obj",
".",
"object_id",
":",
"ObjectViewDictionary",
".",
"objects",
".",
"create",
"(",
"current_object",
"=",
"object",
",",
"visited_before_object",
"=",
"obj",
".",
"content_object",
")",
"if",
"not",
"exists_in_dictionary",
"(",
"request",
",",
"obj",
",",
"obj",
".",
"content_type",
",",
"object",
",",
"False",
")",
":",
"ObjectViewDictionary",
".",
"objects",
".",
"create",
"(",
"current_object",
"=",
"obj",
".",
"content_object",
",",
"visited_before_object",
"=",
"object",
")",
"return"
] | f04c181dc815d32c35b44c6e1c91521e88a9dd6c |
test | get_suggestions_with_size | Gets a list with a certain size of suggestions for an object | suggestions/views.py | def get_suggestions_with_size(object, size):
""" Gets a list with a certain size of suggestions for an object """
content_type = ContentType.objects.get_for_model(type(object))
try:
return ObjectViewDictionary.objects.filter(
current_object_id=object.id,
current_content_type=content_type).extra(
order_by=['-visits'])[:size]
except:
return ObjectViewDictionary.objects.filter(
current_object_id=object.id,
current_content_type=content_type).extra(order_by=['-visits']) | def get_suggestions_with_size(object, size):
""" Gets a list with a certain size of suggestions for an object """
content_type = ContentType.objects.get_for_model(type(object))
try:
return ObjectViewDictionary.objects.filter(
current_object_id=object.id,
current_content_type=content_type).extra(
order_by=['-visits'])[:size]
except:
return ObjectViewDictionary.objects.filter(
current_object_id=object.id,
current_content_type=content_type).extra(order_by=['-visits']) | [
"Gets",
"a",
"list",
"with",
"a",
"certain",
"size",
"of",
"suggestions",
"for",
"an",
"object"
] | dreidev/Suggestions | python | https://github.com/dreidev/Suggestions/blob/f04c181dc815d32c35b44c6e1c91521e88a9dd6c/suggestions/views.py#L100-L111 | [
"def",
"get_suggestions_with_size",
"(",
"object",
",",
"size",
")",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"type",
"(",
"object",
")",
")",
"try",
":",
"return",
"ObjectViewDictionary",
".",
"objects",
".",
"filter",
"(",
"current_object_id",
"=",
"object",
".",
"id",
",",
"current_content_type",
"=",
"content_type",
")",
".",
"extra",
"(",
"order_by",
"=",
"[",
"'-visits'",
"]",
")",
"[",
":",
"size",
"]",
"except",
":",
"return",
"ObjectViewDictionary",
".",
"objects",
".",
"filter",
"(",
"current_object_id",
"=",
"object",
".",
"id",
",",
"current_content_type",
"=",
"content_type",
")",
".",
"extra",
"(",
"order_by",
"=",
"[",
"'-visits'",
"]",
")"
] | f04c181dc815d32c35b44c6e1c91521e88a9dd6c |
test | get_suggestions | Gets a list of all suggestions for an object | suggestions/views.py | def get_suggestions(object):
""" Gets a list of all suggestions for an object """
content_type = ContentType.objects.get_for_model(type(object))
return ObjectViewDictionary.objects.filter(
current_object_id=object.id,
current_content_type=content_type).extra(order_by=['-visits']) | def get_suggestions(object):
""" Gets a list of all suggestions for an object """
content_type = ContentType.objects.get_for_model(type(object))
return ObjectViewDictionary.objects.filter(
current_object_id=object.id,
current_content_type=content_type).extra(order_by=['-visits']) | [
"Gets",
"a",
"list",
"of",
"all",
"suggestions",
"for",
"an",
"object"
] | dreidev/Suggestions | python | https://github.com/dreidev/Suggestions/blob/f04c181dc815d32c35b44c6e1c91521e88a9dd6c/suggestions/views.py#L114-L119 | [
"def",
"get_suggestions",
"(",
"object",
")",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"type",
"(",
"object",
")",
")",
"return",
"ObjectViewDictionary",
".",
"objects",
".",
"filter",
"(",
"current_object_id",
"=",
"object",
".",
"id",
",",
"current_content_type",
"=",
"content_type",
")",
".",
"extra",
"(",
"order_by",
"=",
"[",
"'-visits'",
"]",
")"
] | f04c181dc815d32c35b44c6e1c91521e88a9dd6c |
test | path.relpath | Return this path as a relative path,
based from the current working directory. | environment/lib/python2.7/site-packages/IPython/external/path/_path.py | def relpath(self):
""" Return this path as a relative path,
based from the current working directory.
"""
cwd = self.__class__(os.getcwdu())
return cwd.relpathto(self) | def relpath(self):
""" Return this path as a relative path,
based from the current working directory.
"""
cwd = self.__class__(os.getcwdu())
return cwd.relpathto(self) | [
"Return",
"this",
"path",
"as",
"a",
"relative",
"path",
"based",
"from",
"the",
"current",
"working",
"directory",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/path/_path.py#L244-L249 | [
"def",
"relpath",
"(",
"self",
")",
":",
"cwd",
"=",
"self",
".",
"__class__",
"(",
"os",
".",
"getcwdu",
"(",
")",
")",
"return",
"cwd",
".",
"relpathto",
"(",
"self",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | path.glob | Return a list of path objects that match the pattern.
pattern - a path relative to this directory, with wildcards.
For example, path('/users').glob('*/bin/*') returns a list
of all the files users have in their bin directories. | environment/lib/python2.7/site-packages/IPython/external/path/_path.py | def glob(self, pattern):
""" Return a list of path objects that match the pattern.
pattern - a path relative to this directory, with wildcards.
For example, path('/users').glob('*/bin/*') returns a list
of all the files users have in their bin directories.
"""
cls = self.__class__
return [cls(s) for s in glob.glob(unicode(self / pattern))] | def glob(self, pattern):
""" Return a list of path objects that match the pattern.
pattern - a path relative to this directory, with wildcards.
For example, path('/users').glob('*/bin/*') returns a list
of all the files users have in their bin directories.
"""
cls = self.__class__
return [cls(s) for s in glob.glob(unicode(self / pattern))] | [
"Return",
"a",
"list",
"of",
"path",
"objects",
"that",
"match",
"the",
"pattern",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/path/_path.py#L478-L487 | [
"def",
"glob",
"(",
"self",
",",
"pattern",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"return",
"[",
"cls",
"(",
"s",
")",
"for",
"s",
"in",
"glob",
".",
"glob",
"(",
"unicode",
"(",
"self",
"/",
"pattern",
")",
")",
"]"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | path.lines | r""" Open this file, read all lines, return them in a list.
Optional arguments:
encoding - The Unicode encoding (or character set) of
the file. The default is None, meaning the content
of the file is read as 8-bit characters and returned
as a list of (non-Unicode) str objects.
errors - How to handle Unicode errors; see help(str.decode)
for the options. Default is 'strict'
retain - If true, retain newline characters; but all newline
character combinations ('\r', '\n', '\r\n') are
translated to '\n'. If false, newline characters are
stripped off. Default is True.
This uses 'U' mode in Python 2.3 and later. | environment/lib/python2.7/site-packages/IPython/external/path/_path.py | def lines(self, encoding=None, errors='strict', retain=True):
r""" Open this file, read all lines, return them in a list.
Optional arguments:
encoding - The Unicode encoding (or character set) of
the file. The default is None, meaning the content
of the file is read as 8-bit characters and returned
as a list of (non-Unicode) str objects.
errors - How to handle Unicode errors; see help(str.decode)
for the options. Default is 'strict'
retain - If true, retain newline characters; but all newline
character combinations ('\r', '\n', '\r\n') are
translated to '\n'. If false, newline characters are
stripped off. Default is True.
This uses 'U' mode in Python 2.3 and later.
"""
if encoding is None and retain:
f = self.open('U')
try:
return f.readlines()
finally:
f.close()
else:
return self.text(encoding, errors).splitlines(retain) | def lines(self, encoding=None, errors='strict', retain=True):
r""" Open this file, read all lines, return them in a list.
Optional arguments:
encoding - The Unicode encoding (or character set) of
the file. The default is None, meaning the content
of the file is read as 8-bit characters and returned
as a list of (non-Unicode) str objects.
errors - How to handle Unicode errors; see help(str.decode)
for the options. Default is 'strict'
retain - If true, retain newline characters; but all newline
character combinations ('\r', '\n', '\r\n') are
translated to '\n'. If false, newline characters are
stripped off. Default is True.
This uses 'U' mode in Python 2.3 and later.
"""
if encoding is None and retain:
f = self.open('U')
try:
return f.readlines()
finally:
f.close()
else:
return self.text(encoding, errors).splitlines(retain) | [
"r",
"Open",
"this",
"file",
"read",
"all",
"lines",
"return",
"them",
"in",
"a",
"list",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/path/_path.py#L646-L670 | [
"def",
"lines",
"(",
"self",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"retain",
"=",
"True",
")",
":",
"if",
"encoding",
"is",
"None",
"and",
"retain",
":",
"f",
"=",
"self",
".",
"open",
"(",
"'U'",
")",
"try",
":",
"return",
"f",
".",
"readlines",
"(",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"else",
":",
"return",
"self",
".",
"text",
"(",
"encoding",
",",
"errors",
")",
".",
"splitlines",
"(",
"retain",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | path.read_md5 | Calculate the md5 hash for this file.
This reads through the entire file. | environment/lib/python2.7/site-packages/IPython/external/path/_path.py | def read_md5(self):
""" Calculate the md5 hash for this file.
This reads through the entire file.
"""
f = self.open('rb')
try:
m = md5()
while True:
d = f.read(8192)
if not d:
break
m.update(d)
finally:
f.close()
return m.digest() | def read_md5(self):
""" Calculate the md5 hash for this file.
This reads through the entire file.
"""
f = self.open('rb')
try:
m = md5()
while True:
d = f.read(8192)
if not d:
break
m.update(d)
finally:
f.close()
return m.digest() | [
"Calculate",
"the",
"md5",
"hash",
"for",
"this",
"file",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/path/_path.py#L737-L752 | [
"def",
"read_md5",
"(",
"self",
")",
":",
"f",
"=",
"self",
".",
"open",
"(",
"'rb'",
")",
"try",
":",
"m",
"=",
"md5",
"(",
")",
"while",
"True",
":",
"d",
"=",
"f",
".",
"read",
"(",
"8192",
")",
"if",
"not",
"d",
":",
"break",
"m",
".",
"update",
"(",
"d",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"return",
"m",
".",
"digest",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Profile.options | Register commandline options. | environment/lib/python2.7/site-packages/nose/plugins/prof.py | def options(self, parser, env):
"""Register commandline options.
"""
if not self.available():
return
Plugin.options(self, parser, env)
parser.add_option('--profile-sort', action='store', dest='profile_sort',
default=env.get('NOSE_PROFILE_SORT', 'cumulative'),
metavar="SORT",
help="Set sort order for profiler output")
parser.add_option('--profile-stats-file', action='store',
dest='profile_stats_file',
metavar="FILE",
default=env.get('NOSE_PROFILE_STATS_FILE'),
help='Profiler stats file; default is a new '
'temp file on each run')
parser.add_option('--profile-restrict', action='append',
dest='profile_restrict',
metavar="RESTRICT",
default=env.get('NOSE_PROFILE_RESTRICT'),
help="Restrict profiler output. See help for "
"pstats.Stats for details") | def options(self, parser, env):
"""Register commandline options.
"""
if not self.available():
return
Plugin.options(self, parser, env)
parser.add_option('--profile-sort', action='store', dest='profile_sort',
default=env.get('NOSE_PROFILE_SORT', 'cumulative'),
metavar="SORT",
help="Set sort order for profiler output")
parser.add_option('--profile-stats-file', action='store',
dest='profile_stats_file',
metavar="FILE",
default=env.get('NOSE_PROFILE_STATS_FILE'),
help='Profiler stats file; default is a new '
'temp file on each run')
parser.add_option('--profile-restrict', action='append',
dest='profile_restrict',
metavar="RESTRICT",
default=env.get('NOSE_PROFILE_RESTRICT'),
help="Restrict profiler output. See help for "
"pstats.Stats for details") | [
"Register",
"commandline",
"options",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/prof.py#L33-L54 | [
"def",
"options",
"(",
"self",
",",
"parser",
",",
"env",
")",
":",
"if",
"not",
"self",
".",
"available",
"(",
")",
":",
"return",
"Plugin",
".",
"options",
"(",
"self",
",",
"parser",
",",
"env",
")",
"parser",
".",
"add_option",
"(",
"'--profile-sort'",
",",
"action",
"=",
"'store'",
",",
"dest",
"=",
"'profile_sort'",
",",
"default",
"=",
"env",
".",
"get",
"(",
"'NOSE_PROFILE_SORT'",
",",
"'cumulative'",
")",
",",
"metavar",
"=",
"\"SORT\"",
",",
"help",
"=",
"\"Set sort order for profiler output\"",
")",
"parser",
".",
"add_option",
"(",
"'--profile-stats-file'",
",",
"action",
"=",
"'store'",
",",
"dest",
"=",
"'profile_stats_file'",
",",
"metavar",
"=",
"\"FILE\"",
",",
"default",
"=",
"env",
".",
"get",
"(",
"'NOSE_PROFILE_STATS_FILE'",
")",
",",
"help",
"=",
"'Profiler stats file; default is a new '",
"'temp file on each run'",
")",
"parser",
".",
"add_option",
"(",
"'--profile-restrict'",
",",
"action",
"=",
"'append'",
",",
"dest",
"=",
"'profile_restrict'",
",",
"metavar",
"=",
"\"RESTRICT\"",
",",
"default",
"=",
"env",
".",
"get",
"(",
"'NOSE_PROFILE_RESTRICT'",
")",
",",
"help",
"=",
"\"Restrict profiler output. See help for \"",
"\"pstats.Stats for details\"",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Profile.begin | Create profile stats file and load profiler. | environment/lib/python2.7/site-packages/nose/plugins/prof.py | def begin(self):
"""Create profile stats file and load profiler.
"""
if not self.available():
return
self._create_pfile()
self.prof = hotshot.Profile(self.pfile) | def begin(self):
"""Create profile stats file and load profiler.
"""
if not self.available():
return
self._create_pfile()
self.prof = hotshot.Profile(self.pfile) | [
"Create",
"profile",
"stats",
"file",
"and",
"load",
"profiler",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/prof.py#L60-L66 | [
"def",
"begin",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"available",
"(",
")",
":",
"return",
"self",
".",
"_create_pfile",
"(",
")",
"self",
".",
"prof",
"=",
"hotshot",
".",
"Profile",
"(",
"self",
".",
"pfile",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Profile.configure | Configure plugin. | environment/lib/python2.7/site-packages/nose/plugins/prof.py | def configure(self, options, conf):
"""Configure plugin.
"""
if not self.available():
self.enabled = False
return
Plugin.configure(self, options, conf)
self.conf = conf
if options.profile_stats_file:
self.pfile = options.profile_stats_file
self.clean_stats_file = False
else:
self.pfile = None
self.clean_stats_file = True
self.fileno = None
self.sort = options.profile_sort
self.restrict = tolist(options.profile_restrict) | def configure(self, options, conf):
"""Configure plugin.
"""
if not self.available():
self.enabled = False
return
Plugin.configure(self, options, conf)
self.conf = conf
if options.profile_stats_file:
self.pfile = options.profile_stats_file
self.clean_stats_file = False
else:
self.pfile = None
self.clean_stats_file = True
self.fileno = None
self.sort = options.profile_sort
self.restrict = tolist(options.profile_restrict) | [
"Configure",
"plugin",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/prof.py#L68-L84 | [
"def",
"configure",
"(",
"self",
",",
"options",
",",
"conf",
")",
":",
"if",
"not",
"self",
".",
"available",
"(",
")",
":",
"self",
".",
"enabled",
"=",
"False",
"return",
"Plugin",
".",
"configure",
"(",
"self",
",",
"options",
",",
"conf",
")",
"self",
".",
"conf",
"=",
"conf",
"if",
"options",
".",
"profile_stats_file",
":",
"self",
".",
"pfile",
"=",
"options",
".",
"profile_stats_file",
"self",
".",
"clean_stats_file",
"=",
"False",
"else",
":",
"self",
".",
"pfile",
"=",
"None",
"self",
".",
"clean_stats_file",
"=",
"True",
"self",
".",
"fileno",
"=",
"None",
"self",
".",
"sort",
"=",
"options",
".",
"profile_sort",
"self",
".",
"restrict",
"=",
"tolist",
"(",
"options",
".",
"profile_restrict",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Profile.report | Output profiler report. | environment/lib/python2.7/site-packages/nose/plugins/prof.py | def report(self, stream):
"""Output profiler report.
"""
log.debug('printing profiler report')
self.prof.close()
prof_stats = stats.load(self.pfile)
prof_stats.sort_stats(self.sort)
# 2.5 has completely different stream handling from 2.4 and earlier.
# Before 2.5, stats objects have no stream attribute; in 2.5 and later
# a reference sys.stdout is stored before we can tweak it.
compat_25 = hasattr(prof_stats, 'stream')
if compat_25:
tmp = prof_stats.stream
prof_stats.stream = stream
else:
tmp = sys.stdout
sys.stdout = stream
try:
if self.restrict:
log.debug('setting profiler restriction to %s', self.restrict)
prof_stats.print_stats(*self.restrict)
else:
prof_stats.print_stats()
finally:
if compat_25:
prof_stats.stream = tmp
else:
sys.stdout = tmp | def report(self, stream):
"""Output profiler report.
"""
log.debug('printing profiler report')
self.prof.close()
prof_stats = stats.load(self.pfile)
prof_stats.sort_stats(self.sort)
# 2.5 has completely different stream handling from 2.4 and earlier.
# Before 2.5, stats objects have no stream attribute; in 2.5 and later
# a reference sys.stdout is stored before we can tweak it.
compat_25 = hasattr(prof_stats, 'stream')
if compat_25:
tmp = prof_stats.stream
prof_stats.stream = stream
else:
tmp = sys.stdout
sys.stdout = stream
try:
if self.restrict:
log.debug('setting profiler restriction to %s', self.restrict)
prof_stats.print_stats(*self.restrict)
else:
prof_stats.print_stats()
finally:
if compat_25:
prof_stats.stream = tmp
else:
sys.stdout = tmp | [
"Output",
"profiler",
"report",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/prof.py#L97-L125 | [
"def",
"report",
"(",
"self",
",",
"stream",
")",
":",
"log",
".",
"debug",
"(",
"'printing profiler report'",
")",
"self",
".",
"prof",
".",
"close",
"(",
")",
"prof_stats",
"=",
"stats",
".",
"load",
"(",
"self",
".",
"pfile",
")",
"prof_stats",
".",
"sort_stats",
"(",
"self",
".",
"sort",
")",
"# 2.5 has completely different stream handling from 2.4 and earlier.",
"# Before 2.5, stats objects have no stream attribute; in 2.5 and later",
"# a reference sys.stdout is stored before we can tweak it.",
"compat_25",
"=",
"hasattr",
"(",
"prof_stats",
",",
"'stream'",
")",
"if",
"compat_25",
":",
"tmp",
"=",
"prof_stats",
".",
"stream",
"prof_stats",
".",
"stream",
"=",
"stream",
"else",
":",
"tmp",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdout",
"=",
"stream",
"try",
":",
"if",
"self",
".",
"restrict",
":",
"log",
".",
"debug",
"(",
"'setting profiler restriction to %s'",
",",
"self",
".",
"restrict",
")",
"prof_stats",
".",
"print_stats",
"(",
"*",
"self",
".",
"restrict",
")",
"else",
":",
"prof_stats",
".",
"print_stats",
"(",
")",
"finally",
":",
"if",
"compat_25",
":",
"prof_stats",
".",
"stream",
"=",
"tmp",
"else",
":",
"sys",
".",
"stdout",
"=",
"tmp"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Profile.finalize | Clean up stats file, if configured to do so. | environment/lib/python2.7/site-packages/nose/plugins/prof.py | def finalize(self, result):
"""Clean up stats file, if configured to do so.
"""
if not self.available():
return
try:
self.prof.close()
except AttributeError:
# TODO: is this trying to catch just the case where not
# hasattr(self.prof, "close")? If so, the function call should be
# moved out of the try: suite.
pass
if self.clean_stats_file:
if self.fileno:
try:
os.close(self.fileno)
except OSError:
pass
try:
os.unlink(self.pfile)
except OSError:
pass
return None | def finalize(self, result):
"""Clean up stats file, if configured to do so.
"""
if not self.available():
return
try:
self.prof.close()
except AttributeError:
# TODO: is this trying to catch just the case where not
# hasattr(self.prof, "close")? If so, the function call should be
# moved out of the try: suite.
pass
if self.clean_stats_file:
if self.fileno:
try:
os.close(self.fileno)
except OSError:
pass
try:
os.unlink(self.pfile)
except OSError:
pass
return None | [
"Clean",
"up",
"stats",
"file",
"if",
"configured",
"to",
"do",
"so",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/prof.py#L127-L149 | [
"def",
"finalize",
"(",
"self",
",",
"result",
")",
":",
"if",
"not",
"self",
".",
"available",
"(",
")",
":",
"return",
"try",
":",
"self",
".",
"prof",
".",
"close",
"(",
")",
"except",
"AttributeError",
":",
"# TODO: is this trying to catch just the case where not",
"# hasattr(self.prof, \"close\")? If so, the function call should be",
"# moved out of the try: suite.",
"pass",
"if",
"self",
".",
"clean_stats_file",
":",
"if",
"self",
".",
"fileno",
":",
"try",
":",
"os",
".",
"close",
"(",
"self",
".",
"fileno",
")",
"except",
"OSError",
":",
"pass",
"try",
":",
"os",
".",
"unlink",
"(",
"self",
".",
"pfile",
")",
"except",
"OSError",
":",
"pass",
"return",
"None"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Command.handle | Handle CLI command | src/sisy/management/commands/sisy_heartbeat.py | def handle(self, *args, **options):
"""Handle CLI command"""
try:
while True:
Channel(HEARTBEAT_CHANNEL).send({'time':time.time()})
time.sleep(HEARTBEAT_FREQUENCY)
except KeyboardInterrupt:
print("Received keyboard interrupt, exiting...") | def handle(self, *args, **options):
"""Handle CLI command"""
try:
while True:
Channel(HEARTBEAT_CHANNEL).send({'time':time.time()})
time.sleep(HEARTBEAT_FREQUENCY)
except KeyboardInterrupt:
print("Received keyboard interrupt, exiting...") | [
"Handle",
"CLI",
"command"
] | phoikoi/sisy | python | https://github.com/phoikoi/sisy/blob/840c5463ab65488d34e99531f230e61f755d2d69/src/sisy/management/commands/sisy_heartbeat.py#L15-L22 | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"try",
":",
"while",
"True",
":",
"Channel",
"(",
"HEARTBEAT_CHANNEL",
")",
".",
"send",
"(",
"{",
"'time'",
":",
"time",
".",
"time",
"(",
")",
"}",
")",
"time",
".",
"sleep",
"(",
"HEARTBEAT_FREQUENCY",
")",
"except",
"KeyboardInterrupt",
":",
"print",
"(",
"\"Received keyboard interrupt, exiting...\"",
")"
] | 840c5463ab65488d34e99531f230e61f755d2d69 |
test | InputHookManager.enable_wx | Enable event loop integration with wxPython.
Parameters
----------
app : WX Application, optional.
Running application to use. If not given, we probe WX for an
existing application object, and create a new one if none is found.
Notes
-----
This methods sets the ``PyOS_InputHook`` for wxPython, which allows
the wxPython to integrate with terminal based applications like
IPython.
If ``app`` is not given we probe for an existing one, and return it if
found. If no existing app is found, we create an :class:`wx.App` as
follows::
import wx
app = wx.App(redirect=False, clearSigInt=False) | environment/lib/python2.7/site-packages/IPython/lib/inputhook.py | def enable_wx(self, app=None):
"""Enable event loop integration with wxPython.
Parameters
----------
app : WX Application, optional.
Running application to use. If not given, we probe WX for an
existing application object, and create a new one if none is found.
Notes
-----
This methods sets the ``PyOS_InputHook`` for wxPython, which allows
the wxPython to integrate with terminal based applications like
IPython.
If ``app`` is not given we probe for an existing one, and return it if
found. If no existing app is found, we create an :class:`wx.App` as
follows::
import wx
app = wx.App(redirect=False, clearSigInt=False)
"""
import wx
wx_version = V(wx.__version__).version
if wx_version < [2, 8]:
raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
from IPython.lib.inputhookwx import inputhook_wx
self.set_inputhook(inputhook_wx)
self._current_gui = GUI_WX
import wx
if app is None:
app = wx.GetApp()
if app is None:
app = wx.App(redirect=False, clearSigInt=False)
app._in_event_loop = True
self._apps[GUI_WX] = app
return app | def enable_wx(self, app=None):
"""Enable event loop integration with wxPython.
Parameters
----------
app : WX Application, optional.
Running application to use. If not given, we probe WX for an
existing application object, and create a new one if none is found.
Notes
-----
This methods sets the ``PyOS_InputHook`` for wxPython, which allows
the wxPython to integrate with terminal based applications like
IPython.
If ``app`` is not given we probe for an existing one, and return it if
found. If no existing app is found, we create an :class:`wx.App` as
follows::
import wx
app = wx.App(redirect=False, clearSigInt=False)
"""
import wx
wx_version = V(wx.__version__).version
if wx_version < [2, 8]:
raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
from IPython.lib.inputhookwx import inputhook_wx
self.set_inputhook(inputhook_wx)
self._current_gui = GUI_WX
import wx
if app is None:
app = wx.GetApp()
if app is None:
app = wx.App(redirect=False, clearSigInt=False)
app._in_event_loop = True
self._apps[GUI_WX] = app
return app | [
"Enable",
"event",
"loop",
"integration",
"with",
"wxPython",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/inputhook.py#L182-L221 | [
"def",
"enable_wx",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"import",
"wx",
"wx_version",
"=",
"V",
"(",
"wx",
".",
"__version__",
")",
".",
"version",
"if",
"wx_version",
"<",
"[",
"2",
",",
"8",
"]",
":",
"raise",
"ValueError",
"(",
"\"requires wxPython >= 2.8, but you have %s\"",
"%",
"wx",
".",
"__version__",
")",
"from",
"IPython",
".",
"lib",
".",
"inputhookwx",
"import",
"inputhook_wx",
"self",
".",
"set_inputhook",
"(",
"inputhook_wx",
")",
"self",
".",
"_current_gui",
"=",
"GUI_WX",
"import",
"wx",
"if",
"app",
"is",
"None",
":",
"app",
"=",
"wx",
".",
"GetApp",
"(",
")",
"if",
"app",
"is",
"None",
":",
"app",
"=",
"wx",
".",
"App",
"(",
"redirect",
"=",
"False",
",",
"clearSigInt",
"=",
"False",
")",
"app",
".",
"_in_event_loop",
"=",
"True",
"self",
".",
"_apps",
"[",
"GUI_WX",
"]",
"=",
"app",
"return",
"app"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InputHookManager.disable_wx | Disable event loop integration with wxPython.
This merely sets PyOS_InputHook to NULL. | environment/lib/python2.7/site-packages/IPython/lib/inputhook.py | def disable_wx(self):
"""Disable event loop integration with wxPython.
This merely sets PyOS_InputHook to NULL.
"""
if self._apps.has_key(GUI_WX):
self._apps[GUI_WX]._in_event_loop = False
self.clear_inputhook() | def disable_wx(self):
"""Disable event loop integration with wxPython.
This merely sets PyOS_InputHook to NULL.
"""
if self._apps.has_key(GUI_WX):
self._apps[GUI_WX]._in_event_loop = False
self.clear_inputhook() | [
"Disable",
"event",
"loop",
"integration",
"with",
"wxPython",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/inputhook.py#L223-L230 | [
"def",
"disable_wx",
"(",
"self",
")",
":",
"if",
"self",
".",
"_apps",
".",
"has_key",
"(",
"GUI_WX",
")",
":",
"self",
".",
"_apps",
"[",
"GUI_WX",
"]",
".",
"_in_event_loop",
"=",
"False",
"self",
".",
"clear_inputhook",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InputHookManager.enable_qt4 | Enable event loop integration with PyQt4.
Parameters
----------
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Notes
-----
This methods sets the PyOS_InputHook for PyQt4, which allows
the PyQt4 to integrate with terminal based applications like
IPython.
If ``app`` is not given we probe for an existing one, and return it if
found. If no existing app is found, we create an :class:`QApplication`
as follows::
from PyQt4 import QtCore
app = QtGui.QApplication(sys.argv) | environment/lib/python2.7/site-packages/IPython/lib/inputhook.py | def enable_qt4(self, app=None):
"""Enable event loop integration with PyQt4.
Parameters
----------
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Notes
-----
This methods sets the PyOS_InputHook for PyQt4, which allows
the PyQt4 to integrate with terminal based applications like
IPython.
If ``app`` is not given we probe for an existing one, and return it if
found. If no existing app is found, we create an :class:`QApplication`
as follows::
from PyQt4 import QtCore
app = QtGui.QApplication(sys.argv)
"""
from IPython.lib.inputhookqt4 import create_inputhook_qt4
app, inputhook_qt4 = create_inputhook_qt4(self, app)
self.set_inputhook(inputhook_qt4)
self._current_gui = GUI_QT4
app._in_event_loop = True
self._apps[GUI_QT4] = app
return app | def enable_qt4(self, app=None):
"""Enable event loop integration with PyQt4.
Parameters
----------
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Notes
-----
This methods sets the PyOS_InputHook for PyQt4, which allows
the PyQt4 to integrate with terminal based applications like
IPython.
If ``app`` is not given we probe for an existing one, and return it if
found. If no existing app is found, we create an :class:`QApplication`
as follows::
from PyQt4 import QtCore
app = QtGui.QApplication(sys.argv)
"""
from IPython.lib.inputhookqt4 import create_inputhook_qt4
app, inputhook_qt4 = create_inputhook_qt4(self, app)
self.set_inputhook(inputhook_qt4)
self._current_gui = GUI_QT4
app._in_event_loop = True
self._apps[GUI_QT4] = app
return app | [
"Enable",
"event",
"loop",
"integration",
"with",
"PyQt4",
".",
"Parameters",
"----------",
"app",
":",
"Qt",
"Application",
"optional",
".",
"Running",
"application",
"to",
"use",
".",
"If",
"not",
"given",
"we",
"probe",
"Qt",
"for",
"an",
"existing",
"application",
"object",
"and",
"create",
"a",
"new",
"one",
"if",
"none",
"is",
"found",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/inputhook.py#L232-L261 | [
"def",
"enable_qt4",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"from",
"IPython",
".",
"lib",
".",
"inputhookqt4",
"import",
"create_inputhook_qt4",
"app",
",",
"inputhook_qt4",
"=",
"create_inputhook_qt4",
"(",
"self",
",",
"app",
")",
"self",
".",
"set_inputhook",
"(",
"inputhook_qt4",
")",
"self",
".",
"_current_gui",
"=",
"GUI_QT4",
"app",
".",
"_in_event_loop",
"=",
"True",
"self",
".",
"_apps",
"[",
"GUI_QT4",
"]",
"=",
"app",
"return",
"app"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InputHookManager.disable_qt4 | Disable event loop integration with PyQt4.
This merely sets PyOS_InputHook to NULL. | environment/lib/python2.7/site-packages/IPython/lib/inputhook.py | def disable_qt4(self):
"""Disable event loop integration with PyQt4.
This merely sets PyOS_InputHook to NULL.
"""
if self._apps.has_key(GUI_QT4):
self._apps[GUI_QT4]._in_event_loop = False
self.clear_inputhook() | def disable_qt4(self):
"""Disable event loop integration with PyQt4.
This merely sets PyOS_InputHook to NULL.
"""
if self._apps.has_key(GUI_QT4):
self._apps[GUI_QT4]._in_event_loop = False
self.clear_inputhook() | [
"Disable",
"event",
"loop",
"integration",
"with",
"PyQt4",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/inputhook.py#L263-L270 | [
"def",
"disable_qt4",
"(",
"self",
")",
":",
"if",
"self",
".",
"_apps",
".",
"has_key",
"(",
"GUI_QT4",
")",
":",
"self",
".",
"_apps",
"[",
"GUI_QT4",
"]",
".",
"_in_event_loop",
"=",
"False",
"self",
".",
"clear_inputhook",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InputHookManager.enable_gtk | Enable event loop integration with PyGTK.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for PyGTK, which allows
the PyGTK to integrate with terminal based applications like
IPython. | environment/lib/python2.7/site-packages/IPython/lib/inputhook.py | def enable_gtk(self, app=None):
"""Enable event loop integration with PyGTK.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for PyGTK, which allows
the PyGTK to integrate with terminal based applications like
IPython.
"""
import gtk
try:
gtk.set_interactive(True)
self._current_gui = GUI_GTK
except AttributeError:
# For older versions of gtk, use our own ctypes version
from IPython.lib.inputhookgtk import inputhook_gtk
self.set_inputhook(inputhook_gtk)
self._current_gui = GUI_GTK | def enable_gtk(self, app=None):
"""Enable event loop integration with PyGTK.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for PyGTK, which allows
the PyGTK to integrate with terminal based applications like
IPython.
"""
import gtk
try:
gtk.set_interactive(True)
self._current_gui = GUI_GTK
except AttributeError:
# For older versions of gtk, use our own ctypes version
from IPython.lib.inputhookgtk import inputhook_gtk
self.set_inputhook(inputhook_gtk)
self._current_gui = GUI_GTK | [
"Enable",
"event",
"loop",
"integration",
"with",
"PyGTK",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/inputhook.py#L272-L296 | [
"def",
"enable_gtk",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"import",
"gtk",
"try",
":",
"gtk",
".",
"set_interactive",
"(",
"True",
")",
"self",
".",
"_current_gui",
"=",
"GUI_GTK",
"except",
"AttributeError",
":",
"# For older versions of gtk, use our own ctypes version",
"from",
"IPython",
".",
"lib",
".",
"inputhookgtk",
"import",
"inputhook_gtk",
"self",
".",
"set_inputhook",
"(",
"inputhook_gtk",
")",
"self",
".",
"_current_gui",
"=",
"GUI_GTK"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InputHookManager.enable_tk | Enable event loop integration with Tk.
Parameters
----------
app : toplevel :class:`Tkinter.Tk` widget, optional.
Running toplevel widget to use. If not given, we probe Tk for an
existing one, and create a new one if none is found.
Notes
-----
If you have already created a :class:`Tkinter.Tk` object, the only
thing done by this method is to register with the
:class:`InputHookManager`, since creating that object automatically
sets ``PyOS_InputHook``. | environment/lib/python2.7/site-packages/IPython/lib/inputhook.py | def enable_tk(self, app=None):
"""Enable event loop integration with Tk.
Parameters
----------
app : toplevel :class:`Tkinter.Tk` widget, optional.
Running toplevel widget to use. If not given, we probe Tk for an
existing one, and create a new one if none is found.
Notes
-----
If you have already created a :class:`Tkinter.Tk` object, the only
thing done by this method is to register with the
:class:`InputHookManager`, since creating that object automatically
sets ``PyOS_InputHook``.
"""
self._current_gui = GUI_TK
if app is None:
import Tkinter
app = Tkinter.Tk()
app.withdraw()
self._apps[GUI_TK] = app
return app | def enable_tk(self, app=None):
"""Enable event loop integration with Tk.
Parameters
----------
app : toplevel :class:`Tkinter.Tk` widget, optional.
Running toplevel widget to use. If not given, we probe Tk for an
existing one, and create a new one if none is found.
Notes
-----
If you have already created a :class:`Tkinter.Tk` object, the only
thing done by this method is to register with the
:class:`InputHookManager`, since creating that object automatically
sets ``PyOS_InputHook``.
"""
self._current_gui = GUI_TK
if app is None:
import Tkinter
app = Tkinter.Tk()
app.withdraw()
self._apps[GUI_TK] = app
return app | [
"Enable",
"event",
"loop",
"integration",
"with",
"Tk",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/inputhook.py#L305-L327 | [
"def",
"enable_tk",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"self",
".",
"_current_gui",
"=",
"GUI_TK",
"if",
"app",
"is",
"None",
":",
"import",
"Tkinter",
"app",
"=",
"Tkinter",
".",
"Tk",
"(",
")",
"app",
".",
"withdraw",
"(",
")",
"self",
".",
"_apps",
"[",
"GUI_TK",
"]",
"=",
"app",
"return",
"app"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InputHookManager.enable_pyglet | Enable event loop integration with pyglet.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the ``PyOS_InputHook`` for pyglet, which allows
pyglet to integrate with terminal based applications like
IPython. | environment/lib/python2.7/site-packages/IPython/lib/inputhook.py | def enable_pyglet(self, app=None):
"""Enable event loop integration with pyglet.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the ``PyOS_InputHook`` for pyglet, which allows
pyglet to integrate with terminal based applications like
IPython.
"""
import pyglet
from IPython.lib.inputhookpyglet import inputhook_pyglet
self.set_inputhook(inputhook_pyglet)
self._current_gui = GUI_PYGLET
return app | def enable_pyglet(self, app=None):
"""Enable event loop integration with pyglet.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the ``PyOS_InputHook`` for pyglet, which allows
pyglet to integrate with terminal based applications like
IPython.
"""
import pyglet
from IPython.lib.inputhookpyglet import inputhook_pyglet
self.set_inputhook(inputhook_pyglet)
self._current_gui = GUI_PYGLET
return app | [
"Enable",
"event",
"loop",
"integration",
"with",
"pyglet",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/inputhook.py#L403-L424 | [
"def",
"enable_pyglet",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"import",
"pyglet",
"from",
"IPython",
".",
"lib",
".",
"inputhookpyglet",
"import",
"inputhook_pyglet",
"self",
".",
"set_inputhook",
"(",
"inputhook_pyglet",
")",
"self",
".",
"_current_gui",
"=",
"GUI_PYGLET",
"return",
"app"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InputHookManager.enable_gtk3 | Enable event loop integration with Gtk3 (gir bindings).
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for Gtk3, which allows
the Gtk3 to integrate with terminal based applications like
IPython. | environment/lib/python2.7/site-packages/IPython/lib/inputhook.py | def enable_gtk3(self, app=None):
"""Enable event loop integration with Gtk3 (gir bindings).
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for Gtk3, which allows
the Gtk3 to integrate with terminal based applications like
IPython.
"""
from IPython.lib.inputhookgtk3 import inputhook_gtk3
self.set_inputhook(inputhook_gtk3)
self._current_gui = GUI_GTK | def enable_gtk3(self, app=None):
"""Enable event loop integration with Gtk3 (gir bindings).
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for Gtk3, which allows
the Gtk3 to integrate with terminal based applications like
IPython.
"""
from IPython.lib.inputhookgtk3 import inputhook_gtk3
self.set_inputhook(inputhook_gtk3)
self._current_gui = GUI_GTK | [
"Enable",
"event",
"loop",
"integration",
"with",
"Gtk3",
"(",
"gir",
"bindings",
")",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/inputhook.py#L433-L451 | [
"def",
"enable_gtk3",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"from",
"IPython",
".",
"lib",
".",
"inputhookgtk3",
"import",
"inputhook_gtk3",
"self",
".",
"set_inputhook",
"(",
"inputhook_gtk3",
")",
"self",
".",
"_current_gui",
"=",
"GUI_GTK"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | setup_partitioner | create a partitioner in the engine namespace | environment/share/doc/ipython/examples/parallel/wave2D/parallelwave-mpi.py | def setup_partitioner(index, num_procs, gnum_cells, parts):
"""create a partitioner in the engine namespace"""
global partitioner
p = MPIRectPartitioner2D(my_id=index, num_procs=num_procs)
p.redim(global_num_cells=gnum_cells, num_parts=parts)
p.prepare_communication()
# put the partitioner into the global namespace:
partitioner=p | def setup_partitioner(index, num_procs, gnum_cells, parts):
"""create a partitioner in the engine namespace"""
global partitioner
p = MPIRectPartitioner2D(my_id=index, num_procs=num_procs)
p.redim(global_num_cells=gnum_cells, num_parts=parts)
p.prepare_communication()
# put the partitioner into the global namespace:
partitioner=p | [
"create",
"a",
"partitioner",
"in",
"the",
"engine",
"namespace"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/wave2D/parallelwave-mpi.py#L33-L40 | [
"def",
"setup_partitioner",
"(",
"index",
",",
"num_procs",
",",
"gnum_cells",
",",
"parts",
")",
":",
"global",
"partitioner",
"p",
"=",
"MPIRectPartitioner2D",
"(",
"my_id",
"=",
"index",
",",
"num_procs",
"=",
"num_procs",
")",
"p",
".",
"redim",
"(",
"global_num_cells",
"=",
"gnum_cells",
",",
"num_parts",
"=",
"parts",
")",
"p",
".",
"prepare_communication",
"(",
")",
"# put the partitioner into the global namespace:",
"partitioner",
"=",
"p"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | wave_saver | save the wave log | environment/share/doc/ipython/examples/parallel/wave2D/parallelwave-mpi.py | def wave_saver(u, x, y, t):
"""save the wave log"""
global u_hist
global t_hist
t_hist.append(t)
u_hist.append(1.0*u) | def wave_saver(u, x, y, t):
"""save the wave log"""
global u_hist
global t_hist
t_hist.append(t)
u_hist.append(1.0*u) | [
"save",
"the",
"wave",
"log"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/wave2D/parallelwave-mpi.py#L47-L52 | [
"def",
"wave_saver",
"(",
"u",
",",
"x",
",",
"y",
",",
"t",
")",
":",
"global",
"u_hist",
"global",
"t_hist",
"t_hist",
".",
"append",
"(",
"t",
")",
"u_hist",
".",
"append",
"(",
"1.0",
"*",
"u",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | extract_hist_ranges | Turn a string of history ranges into 3-tuples of (session, start, stop).
Examples
--------
list(extract_input_ranges("~8/5-~7/4 2"))
[(-8, 5, None), (-7, 1, 4), (0, 2, 3)] | environment/lib/python2.7/site-packages/IPython/core/history.py | def extract_hist_ranges(ranges_str):
"""Turn a string of history ranges into 3-tuples of (session, start, stop).
Examples
--------
list(extract_input_ranges("~8/5-~7/4 2"))
[(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
"""
for range_str in ranges_str.split():
rmatch = range_re.match(range_str)
if not rmatch:
continue
start = int(rmatch.group("start"))
end = rmatch.group("end")
end = int(end) if end else start+1 # If no end specified, get (a, a+1)
if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
end += 1
startsess = rmatch.group("startsess") or "0"
endsess = rmatch.group("endsess") or startsess
startsess = int(startsess.replace("~","-"))
endsess = int(endsess.replace("~","-"))
assert endsess >= startsess
if endsess == startsess:
yield (startsess, start, end)
continue
# Multiple sessions in one range:
yield (startsess, start, None)
for sess in range(startsess+1, endsess):
yield (sess, 1, None)
yield (endsess, 1, end) | def extract_hist_ranges(ranges_str):
"""Turn a string of history ranges into 3-tuples of (session, start, stop).
Examples
--------
list(extract_input_ranges("~8/5-~7/4 2"))
[(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
"""
for range_str in ranges_str.split():
rmatch = range_re.match(range_str)
if not rmatch:
continue
start = int(rmatch.group("start"))
end = rmatch.group("end")
end = int(end) if end else start+1 # If no end specified, get (a, a+1)
if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
end += 1
startsess = rmatch.group("startsess") or "0"
endsess = rmatch.group("endsess") or startsess
startsess = int(startsess.replace("~","-"))
endsess = int(endsess.replace("~","-"))
assert endsess >= startsess
if endsess == startsess:
yield (startsess, start, end)
continue
# Multiple sessions in one range:
yield (startsess, start, None)
for sess in range(startsess+1, endsess):
yield (sess, 1, None)
yield (endsess, 1, end) | [
"Turn",
"a",
"string",
"of",
"history",
"ranges",
"into",
"3",
"-",
"tuples",
"of",
"(",
"session",
"start",
"stop",
")",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L682-L712 | [
"def",
"extract_hist_ranges",
"(",
"ranges_str",
")",
":",
"for",
"range_str",
"in",
"ranges_str",
".",
"split",
"(",
")",
":",
"rmatch",
"=",
"range_re",
".",
"match",
"(",
"range_str",
")",
"if",
"not",
"rmatch",
":",
"continue",
"start",
"=",
"int",
"(",
"rmatch",
".",
"group",
"(",
"\"start\"",
")",
")",
"end",
"=",
"rmatch",
".",
"group",
"(",
"\"end\"",
")",
"end",
"=",
"int",
"(",
"end",
")",
"if",
"end",
"else",
"start",
"+",
"1",
"# If no end specified, get (a, a+1)",
"if",
"rmatch",
".",
"group",
"(",
"\"sep\"",
")",
"==",
"\"-\"",
":",
"# 1-3 == 1:4 --> [1, 2, 3]",
"end",
"+=",
"1",
"startsess",
"=",
"rmatch",
".",
"group",
"(",
"\"startsess\"",
")",
"or",
"\"0\"",
"endsess",
"=",
"rmatch",
".",
"group",
"(",
"\"endsess\"",
")",
"or",
"startsess",
"startsess",
"=",
"int",
"(",
"startsess",
".",
"replace",
"(",
"\"~\"",
",",
"\"-\"",
")",
")",
"endsess",
"=",
"int",
"(",
"endsess",
".",
"replace",
"(",
"\"~\"",
",",
"\"-\"",
")",
")",
"assert",
"endsess",
">=",
"startsess",
"if",
"endsess",
"==",
"startsess",
":",
"yield",
"(",
"startsess",
",",
"start",
",",
"end",
")",
"continue",
"# Multiple sessions in one range:",
"yield",
"(",
"startsess",
",",
"start",
",",
"None",
")",
"for",
"sess",
"in",
"range",
"(",
"startsess",
"+",
"1",
",",
"endsess",
")",
":",
"yield",
"(",
"sess",
",",
"1",
",",
"None",
")",
"yield",
"(",
"endsess",
",",
"1",
",",
"end",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryAccessor.init_db | Connect to the database, and create tables if necessary. | environment/lib/python2.7/site-packages/IPython/core/history.py | def init_db(self):
"""Connect to the database, and create tables if necessary."""
# use detect_types so that timestamps return datetime objects
self.db = sqlite3.connect(self.hist_file,
detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
primary key autoincrement, start timestamp,
end timestamp, num_cmds integer, remark text)""")
self.db.execute("""CREATE TABLE IF NOT EXISTS history
(session integer, line integer, source text, source_raw text,
PRIMARY KEY (session, line))""")
# Output history is optional, but ensure the table's there so it can be
# enabled later.
self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
(session integer, line integer, output text,
PRIMARY KEY (session, line))""")
self.db.commit() | def init_db(self):
"""Connect to the database, and create tables if necessary."""
# use detect_types so that timestamps return datetime objects
self.db = sqlite3.connect(self.hist_file,
detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
primary key autoincrement, start timestamp,
end timestamp, num_cmds integer, remark text)""")
self.db.execute("""CREATE TABLE IF NOT EXISTS history
(session integer, line integer, source text, source_raw text,
PRIMARY KEY (session, line))""")
# Output history is optional, but ensure the table's there so it can be
# enabled later.
self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
(session integer, line integer, output text,
PRIMARY KEY (session, line))""")
self.db.commit() | [
"Connect",
"to",
"the",
"database",
"and",
"create",
"tables",
"if",
"necessary",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L149-L165 | [
"def",
"init_db",
"(",
"self",
")",
":",
"# use detect_types so that timestamps return datetime objects",
"self",
".",
"db",
"=",
"sqlite3",
".",
"connect",
"(",
"self",
".",
"hist_file",
",",
"detect_types",
"=",
"sqlite3",
".",
"PARSE_DECLTYPES",
"|",
"sqlite3",
".",
"PARSE_COLNAMES",
")",
"self",
".",
"db",
".",
"execute",
"(",
"\"\"\"CREATE TABLE IF NOT EXISTS sessions (session integer\n primary key autoincrement, start timestamp,\n end timestamp, num_cmds integer, remark text)\"\"\"",
")",
"self",
".",
"db",
".",
"execute",
"(",
"\"\"\"CREATE TABLE IF NOT EXISTS history\n (session integer, line integer, source text, source_raw text,\n PRIMARY KEY (session, line))\"\"\"",
")",
"# Output history is optional, but ensure the table's there so it can be",
"# enabled later.",
"self",
".",
"db",
".",
"execute",
"(",
"\"\"\"CREATE TABLE IF NOT EXISTS output_history\n (session integer, line integer, output text,\n PRIMARY KEY (session, line))\"\"\"",
")",
"self",
".",
"db",
".",
"commit",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryAccessor._run_sql | Prepares and runs an SQL query for the history database.
Parameters
----------
sql : str
Any filtering expressions to go after SELECT ... FROM ...
params : tuple
Parameters passed to the SQL query (to replace "?")
raw, output : bool
See :meth:`get_range`
Returns
-------
Tuples as :meth:`get_range` | environment/lib/python2.7/site-packages/IPython/core/history.py | def _run_sql(self, sql, params, raw=True, output=False):
"""Prepares and runs an SQL query for the history database.
Parameters
----------
sql : str
Any filtering expressions to go after SELECT ... FROM ...
params : tuple
Parameters passed to the SQL query (to replace "?")
raw, output : bool
See :meth:`get_range`
Returns
-------
Tuples as :meth:`get_range`
"""
toget = 'source_raw' if raw else 'source'
sqlfrom = "history"
if output:
sqlfrom = "history LEFT JOIN output_history USING (session, line)"
toget = "history.%s, output_history.output" % toget
cur = self.db.execute("SELECT session, line, %s FROM %s " %\
(toget, sqlfrom) + sql, params)
if output: # Regroup into 3-tuples, and parse JSON
return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
return cur | def _run_sql(self, sql, params, raw=True, output=False):
"""Prepares and runs an SQL query for the history database.
Parameters
----------
sql : str
Any filtering expressions to go after SELECT ... FROM ...
params : tuple
Parameters passed to the SQL query (to replace "?")
raw, output : bool
See :meth:`get_range`
Returns
-------
Tuples as :meth:`get_range`
"""
toget = 'source_raw' if raw else 'source'
sqlfrom = "history"
if output:
sqlfrom = "history LEFT JOIN output_history USING (session, line)"
toget = "history.%s, output_history.output" % toget
cur = self.db.execute("SELECT session, line, %s FROM %s " %\
(toget, sqlfrom) + sql, params)
if output: # Regroup into 3-tuples, and parse JSON
return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
return cur | [
"Prepares",
"and",
"runs",
"an",
"SQL",
"query",
"for",
"the",
"history",
"database",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L175-L200 | [
"def",
"_run_sql",
"(",
"self",
",",
"sql",
",",
"params",
",",
"raw",
"=",
"True",
",",
"output",
"=",
"False",
")",
":",
"toget",
"=",
"'source_raw'",
"if",
"raw",
"else",
"'source'",
"sqlfrom",
"=",
"\"history\"",
"if",
"output",
":",
"sqlfrom",
"=",
"\"history LEFT JOIN output_history USING (session, line)\"",
"toget",
"=",
"\"history.%s, output_history.output\"",
"%",
"toget",
"cur",
"=",
"self",
".",
"db",
".",
"execute",
"(",
"\"SELECT session, line, %s FROM %s \"",
"%",
"(",
"toget",
",",
"sqlfrom",
")",
"+",
"sql",
",",
"params",
")",
"if",
"output",
":",
"# Regroup into 3-tuples, and parse JSON",
"return",
"(",
"(",
"ses",
",",
"lin",
",",
"(",
"inp",
",",
"out",
")",
")",
"for",
"ses",
",",
"lin",
",",
"inp",
",",
"out",
"in",
"cur",
")",
"return",
"cur"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryAccessor.get_session_info | get info about a session
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
Returns
-------
(session_id [int], start [datetime], end [datetime], num_cmds [int],
remark [unicode])
Sessions that are running or did not exit cleanly will have `end=None`
and `num_cmds=None`. | environment/lib/python2.7/site-packages/IPython/core/history.py | def get_session_info(self, session=0):
"""get info about a session
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
Returns
-------
(session_id [int], start [datetime], end [datetime], num_cmds [int],
remark [unicode])
Sessions that are running or did not exit cleanly will have `end=None`
and `num_cmds=None`.
"""
if session <= 0:
session += self.session_number
query = "SELECT * from sessions where session == ?"
return self.db.execute(query, (session,)).fetchone() | def get_session_info(self, session=0):
"""get info about a session
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
Returns
-------
(session_id [int], start [datetime], end [datetime], num_cmds [int],
remark [unicode])
Sessions that are running or did not exit cleanly will have `end=None`
and `num_cmds=None`.
"""
if session <= 0:
session += self.session_number
query = "SELECT * from sessions where session == ?"
return self.db.execute(query, (session,)).fetchone() | [
"get",
"info",
"about",
"a",
"session"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L203-L228 | [
"def",
"get_session_info",
"(",
"self",
",",
"session",
"=",
"0",
")",
":",
"if",
"session",
"<=",
"0",
":",
"session",
"+=",
"self",
".",
"session_number",
"query",
"=",
"\"SELECT * from sessions where session == ?\"",
"return",
"self",
".",
"db",
".",
"execute",
"(",
"query",
",",
"(",
"session",
",",
")",
")",
".",
"fetchone",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryAccessor.get_tail | Get the last n lines from the history database.
Parameters
----------
n : int
The number of lines to get
raw, output : bool
See :meth:`get_range`
include_latest : bool
If False (default), n+1 lines are fetched, and the latest one
is discarded. This is intended to be used where the function
is called by a user command, which it should not return.
Returns
-------
Tuples as :meth:`get_range` | environment/lib/python2.7/site-packages/IPython/core/history.py | def get_tail(self, n=10, raw=True, output=False, include_latest=False):
"""Get the last n lines from the history database.
Parameters
----------
n : int
The number of lines to get
raw, output : bool
See :meth:`get_range`
include_latest : bool
If False (default), n+1 lines are fetched, and the latest one
is discarded. This is intended to be used where the function
is called by a user command, which it should not return.
Returns
-------
Tuples as :meth:`get_range`
"""
self.writeout_cache()
if not include_latest:
n += 1
cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
(n,), raw=raw, output=output)
if not include_latest:
return reversed(list(cur)[1:])
return reversed(list(cur)) | def get_tail(self, n=10, raw=True, output=False, include_latest=False):
"""Get the last n lines from the history database.
Parameters
----------
n : int
The number of lines to get
raw, output : bool
See :meth:`get_range`
include_latest : bool
If False (default), n+1 lines are fetched, and the latest one
is discarded. This is intended to be used where the function
is called by a user command, which it should not return.
Returns
-------
Tuples as :meth:`get_range`
"""
self.writeout_cache()
if not include_latest:
n += 1
cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
(n,), raw=raw, output=output)
if not include_latest:
return reversed(list(cur)[1:])
return reversed(list(cur)) | [
"Get",
"the",
"last",
"n",
"lines",
"from",
"the",
"history",
"database",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L230-L255 | [
"def",
"get_tail",
"(",
"self",
",",
"n",
"=",
"10",
",",
"raw",
"=",
"True",
",",
"output",
"=",
"False",
",",
"include_latest",
"=",
"False",
")",
":",
"self",
".",
"writeout_cache",
"(",
")",
"if",
"not",
"include_latest",
":",
"n",
"+=",
"1",
"cur",
"=",
"self",
".",
"_run_sql",
"(",
"\"ORDER BY session DESC, line DESC LIMIT ?\"",
",",
"(",
"n",
",",
")",
",",
"raw",
"=",
"raw",
",",
"output",
"=",
"output",
")",
"if",
"not",
"include_latest",
":",
"return",
"reversed",
"(",
"list",
"(",
"cur",
")",
"[",
"1",
":",
"]",
")",
"return",
"reversed",
"(",
"list",
"(",
"cur",
")",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryAccessor.search | Search the database using unix glob-style matching (wildcards
* and ?).
Parameters
----------
pattern : str
The wildcarded pattern to match when searching
search_raw : bool
If True, search the raw input, otherwise, the parsed input
raw, output : bool
See :meth:`get_range`
Returns
-------
Tuples as :meth:`get_range` | environment/lib/python2.7/site-packages/IPython/core/history.py | def search(self, pattern="*", raw=True, search_raw=True,
output=False):
"""Search the database using unix glob-style matching (wildcards
* and ?).
Parameters
----------
pattern : str
The wildcarded pattern to match when searching
search_raw : bool
If True, search the raw input, otherwise, the parsed input
raw, output : bool
See :meth:`get_range`
Returns
-------
Tuples as :meth:`get_range`
"""
tosearch = "source_raw" if search_raw else "source"
if output:
tosearch = "history." + tosearch
self.writeout_cache()
return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,),
raw=raw, output=output) | def search(self, pattern="*", raw=True, search_raw=True,
output=False):
"""Search the database using unix glob-style matching (wildcards
* and ?).
Parameters
----------
pattern : str
The wildcarded pattern to match when searching
search_raw : bool
If True, search the raw input, otherwise, the parsed input
raw, output : bool
See :meth:`get_range`
Returns
-------
Tuples as :meth:`get_range`
"""
tosearch = "source_raw" if search_raw else "source"
if output:
tosearch = "history." + tosearch
self.writeout_cache()
return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,),
raw=raw, output=output) | [
"Search",
"the",
"database",
"using",
"unix",
"glob",
"-",
"style",
"matching",
"(",
"wildcards",
"*",
"and",
"?",
")",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L257-L280 | [
"def",
"search",
"(",
"self",
",",
"pattern",
"=",
"\"*\"",
",",
"raw",
"=",
"True",
",",
"search_raw",
"=",
"True",
",",
"output",
"=",
"False",
")",
":",
"tosearch",
"=",
"\"source_raw\"",
"if",
"search_raw",
"else",
"\"source\"",
"if",
"output",
":",
"tosearch",
"=",
"\"history.\"",
"+",
"tosearch",
"self",
".",
"writeout_cache",
"(",
")",
"return",
"self",
".",
"_run_sql",
"(",
"\"WHERE %s GLOB ?\"",
"%",
"tosearch",
",",
"(",
"pattern",
",",
")",
",",
"raw",
"=",
"raw",
",",
"output",
"=",
"output",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryAccessor.get_range | Retrieve input by session.
Parameters
----------
session : int
Session number to retrieve.
start : int
First line to retrieve.
stop : int
End of line range (excluded from output itself). If None, retrieve
to the end of the session.
raw : bool
If True, return untranslated input
output : bool
If True, attempt to include output. This will be 'real' Python
objects for the current session, or text reprs from previous
sessions if db_log_output was enabled at the time. Where no output
is found, None is used.
Returns
-------
An iterator over the desired lines. Each line is a 3-tuple, either
(session, line, input) if output is False, or
(session, line, (input, output)) if output is True. | environment/lib/python2.7/site-packages/IPython/core/history.py | def get_range(self, session, start=1, stop=None, raw=True,output=False):
"""Retrieve input by session.
Parameters
----------
session : int
Session number to retrieve.
start : int
First line to retrieve.
stop : int
End of line range (excluded from output itself). If None, retrieve
to the end of the session.
raw : bool
If True, return untranslated input
output : bool
If True, attempt to include output. This will be 'real' Python
objects for the current session, or text reprs from previous
sessions if db_log_output was enabled at the time. Where no output
is found, None is used.
Returns
-------
An iterator over the desired lines. Each line is a 3-tuple, either
(session, line, input) if output is False, or
(session, line, (input, output)) if output is True.
"""
if stop:
lineclause = "line >= ? AND line < ?"
params = (session, start, stop)
else:
lineclause = "line>=?"
params = (session, start)
return self._run_sql("WHERE session==? AND %s""" % lineclause,
params, raw=raw, output=output) | def get_range(self, session, start=1, stop=None, raw=True,output=False):
"""Retrieve input by session.
Parameters
----------
session : int
Session number to retrieve.
start : int
First line to retrieve.
stop : int
End of line range (excluded from output itself). If None, retrieve
to the end of the session.
raw : bool
If True, return untranslated input
output : bool
If True, attempt to include output. This will be 'real' Python
objects for the current session, or text reprs from previous
sessions if db_log_output was enabled at the time. Where no output
is found, None is used.
Returns
-------
An iterator over the desired lines. Each line is a 3-tuple, either
(session, line, input) if output is False, or
(session, line, (input, output)) if output is True.
"""
if stop:
lineclause = "line >= ? AND line < ?"
params = (session, start, stop)
else:
lineclause = "line>=?"
params = (session, start)
return self._run_sql("WHERE session==? AND %s""" % lineclause,
params, raw=raw, output=output) | [
"Retrieve",
"input",
"by",
"session",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L282-L316 | [
"def",
"get_range",
"(",
"self",
",",
"session",
",",
"start",
"=",
"1",
",",
"stop",
"=",
"None",
",",
"raw",
"=",
"True",
",",
"output",
"=",
"False",
")",
":",
"if",
"stop",
":",
"lineclause",
"=",
"\"line >= ? AND line < ?\"",
"params",
"=",
"(",
"session",
",",
"start",
",",
"stop",
")",
"else",
":",
"lineclause",
"=",
"\"line>=?\"",
"params",
"=",
"(",
"session",
",",
"start",
")",
"return",
"self",
".",
"_run_sql",
"(",
"\"WHERE session==? AND %s\"",
"\"\"",
"%",
"lineclause",
",",
"params",
",",
"raw",
"=",
"raw",
",",
"output",
"=",
"output",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryAccessor.get_range_by_str | Get lines of history from a string of ranges, as used by magic
commands %hist, %save, %macro, etc.
Parameters
----------
rangestr : str
A string specifying ranges, e.g. "5 ~2/1-4". See
:func:`magic_history` for full details.
raw, output : bool
As :meth:`get_range`
Returns
-------
Tuples as :meth:`get_range` | environment/lib/python2.7/site-packages/IPython/core/history.py | def get_range_by_str(self, rangestr, raw=True, output=False):
"""Get lines of history from a string of ranges, as used by magic
commands %hist, %save, %macro, etc.
Parameters
----------
rangestr : str
A string specifying ranges, e.g. "5 ~2/1-4". See
:func:`magic_history` for full details.
raw, output : bool
As :meth:`get_range`
Returns
-------
Tuples as :meth:`get_range`
"""
for sess, s, e in extract_hist_ranges(rangestr):
for line in self.get_range(sess, s, e, raw=raw, output=output):
yield line | def get_range_by_str(self, rangestr, raw=True, output=False):
"""Get lines of history from a string of ranges, as used by magic
commands %hist, %save, %macro, etc.
Parameters
----------
rangestr : str
A string specifying ranges, e.g. "5 ~2/1-4". See
:func:`magic_history` for full details.
raw, output : bool
As :meth:`get_range`
Returns
-------
Tuples as :meth:`get_range`
"""
for sess, s, e in extract_hist_ranges(rangestr):
for line in self.get_range(sess, s, e, raw=raw, output=output):
yield line | [
"Get",
"lines",
"of",
"history",
"from",
"a",
"string",
"of",
"ranges",
"as",
"used",
"by",
"magic",
"commands",
"%hist",
"%save",
"%macro",
"etc",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L318-L336 | [
"def",
"get_range_by_str",
"(",
"self",
",",
"rangestr",
",",
"raw",
"=",
"True",
",",
"output",
"=",
"False",
")",
":",
"for",
"sess",
",",
"s",
",",
"e",
"in",
"extract_hist_ranges",
"(",
"rangestr",
")",
":",
"for",
"line",
"in",
"self",
".",
"get_range",
"(",
"sess",
",",
"s",
",",
"e",
",",
"raw",
"=",
"raw",
",",
"output",
"=",
"output",
")",
":",
"yield",
"line"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryManager._get_hist_file_name | Get default history file name based on the Shell's profile.
The profile parameter is ignored, but must exist for compatibility with
the parent class. | environment/lib/python2.7/site-packages/IPython/core/history.py | def _get_hist_file_name(self, profile=None):
"""Get default history file name based on the Shell's profile.
The profile parameter is ignored, but must exist for compatibility with
the parent class."""
profile_dir = self.shell.profile_dir.location
return os.path.join(profile_dir, 'history.sqlite') | def _get_hist_file_name(self, profile=None):
"""Get default history file name based on the Shell's profile.
The profile parameter is ignored, but must exist for compatibility with
the parent class."""
profile_dir = self.shell.profile_dir.location
return os.path.join(profile_dir, 'history.sqlite') | [
"Get",
"default",
"history",
"file",
"name",
"based",
"on",
"the",
"Shell",
"s",
"profile",
".",
"The",
"profile",
"parameter",
"is",
"ignored",
"but",
"must",
"exist",
"for",
"compatibility",
"with",
"the",
"parent",
"class",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L411-L417 | [
"def",
"_get_hist_file_name",
"(",
"self",
",",
"profile",
"=",
"None",
")",
":",
"profile_dir",
"=",
"self",
".",
"shell",
".",
"profile_dir",
".",
"location",
"return",
"os",
".",
"path",
".",
"join",
"(",
"profile_dir",
",",
"'history.sqlite'",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryManager.new_session | Get a new session number. | environment/lib/python2.7/site-packages/IPython/core/history.py | def new_session(self, conn=None):
"""Get a new session number."""
if conn is None:
conn = self.db
with conn:
cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
NULL, "") """, (datetime.datetime.now(),))
self.session_number = cur.lastrowid | def new_session(self, conn=None):
"""Get a new session number."""
if conn is None:
conn = self.db
with conn:
cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
NULL, "") """, (datetime.datetime.now(),))
self.session_number = cur.lastrowid | [
"Get",
"a",
"new",
"session",
"number",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L420-L428 | [
"def",
"new_session",
"(",
"self",
",",
"conn",
"=",
"None",
")",
":",
"if",
"conn",
"is",
"None",
":",
"conn",
"=",
"self",
".",
"db",
"with",
"conn",
":",
"cur",
"=",
"conn",
".",
"execute",
"(",
"\"\"\"INSERT INTO sessions VALUES (NULL, ?, NULL,\n NULL, \"\") \"\"\"",
",",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
",",
")",
")",
"self",
".",
"session_number",
"=",
"cur",
".",
"lastrowid"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryManager.end_session | Close the database session, filling in the end time and line count. | environment/lib/python2.7/site-packages/IPython/core/history.py | def end_session(self):
"""Close the database session, filling in the end time and line count."""
self.writeout_cache()
with self.db:
self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
session==?""", (datetime.datetime.now(),
len(self.input_hist_parsed)-1, self.session_number))
self.session_number = 0 | def end_session(self):
"""Close the database session, filling in the end time and line count."""
self.writeout_cache()
with self.db:
self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
session==?""", (datetime.datetime.now(),
len(self.input_hist_parsed)-1, self.session_number))
self.session_number = 0 | [
"Close",
"the",
"database",
"session",
"filling",
"in",
"the",
"end",
"time",
"and",
"line",
"count",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L430-L437 | [
"def",
"end_session",
"(",
"self",
")",
":",
"self",
".",
"writeout_cache",
"(",
")",
"with",
"self",
".",
"db",
":",
"self",
".",
"db",
".",
"execute",
"(",
"\"\"\"UPDATE sessions SET end=?, num_cmds=? WHERE\n session==?\"\"\"",
",",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
",",
"len",
"(",
"self",
".",
"input_hist_parsed",
")",
"-",
"1",
",",
"self",
".",
"session_number",
")",
")",
"self",
".",
"session_number",
"=",
"0"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryManager.name_session | Give the current session a name in the history database. | environment/lib/python2.7/site-packages/IPython/core/history.py | def name_session(self, name):
"""Give the current session a name in the history database."""
with self.db:
self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
(name, self.session_number)) | def name_session(self, name):
"""Give the current session a name in the history database."""
with self.db:
self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
(name, self.session_number)) | [
"Give",
"the",
"current",
"session",
"a",
"name",
"in",
"the",
"history",
"database",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L439-L443 | [
"def",
"name_session",
"(",
"self",
",",
"name",
")",
":",
"with",
"self",
".",
"db",
":",
"self",
".",
"db",
".",
"execute",
"(",
"\"UPDATE sessions SET remark=? WHERE session==?\"",
",",
"(",
"name",
",",
"self",
".",
"session_number",
")",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryManager.reset | Clear the session history, releasing all object references, and
optionally open a new session. | environment/lib/python2.7/site-packages/IPython/core/history.py | def reset(self, new_session=True):
"""Clear the session history, releasing all object references, and
optionally open a new session."""
self.output_hist.clear()
# The directory history can't be completely empty
self.dir_hist[:] = [os.getcwdu()]
if new_session:
if self.session_number:
self.end_session()
self.input_hist_parsed[:] = [""]
self.input_hist_raw[:] = [""]
self.new_session() | def reset(self, new_session=True):
"""Clear the session history, releasing all object references, and
optionally open a new session."""
self.output_hist.clear()
# The directory history can't be completely empty
self.dir_hist[:] = [os.getcwdu()]
if new_session:
if self.session_number:
self.end_session()
self.input_hist_parsed[:] = [""]
self.input_hist_raw[:] = [""]
self.new_session() | [
"Clear",
"the",
"session",
"history",
"releasing",
"all",
"object",
"references",
"and",
"optionally",
"open",
"a",
"new",
"session",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L445-L457 | [
"def",
"reset",
"(",
"self",
",",
"new_session",
"=",
"True",
")",
":",
"self",
".",
"output_hist",
".",
"clear",
"(",
")",
"# The directory history can't be completely empty",
"self",
".",
"dir_hist",
"[",
":",
"]",
"=",
"[",
"os",
".",
"getcwdu",
"(",
")",
"]",
"if",
"new_session",
":",
"if",
"self",
".",
"session_number",
":",
"self",
".",
"end_session",
"(",
")",
"self",
".",
"input_hist_parsed",
"[",
":",
"]",
"=",
"[",
"\"\"",
"]",
"self",
".",
"input_hist_raw",
"[",
":",
"]",
"=",
"[",
"\"\"",
"]",
"self",
".",
"new_session",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryManager._get_range_session | Get input and output history from the current session. Called by
get_range, and takes similar parameters. | environment/lib/python2.7/site-packages/IPython/core/history.py | def _get_range_session(self, start=1, stop=None, raw=True, output=False):
"""Get input and output history from the current session. Called by
get_range, and takes similar parameters."""
input_hist = self.input_hist_raw if raw else self.input_hist_parsed
n = len(input_hist)
if start < 0:
start += n
if not stop or (stop > n):
stop = n
elif stop < 0:
stop += n
for i in range(start, stop):
if output:
line = (input_hist[i], self.output_hist_reprs.get(i))
else:
line = input_hist[i]
yield (0, i, line) | def _get_range_session(self, start=1, stop=None, raw=True, output=False):
"""Get input and output history from the current session. Called by
get_range, and takes similar parameters."""
input_hist = self.input_hist_raw if raw else self.input_hist_parsed
n = len(input_hist)
if start < 0:
start += n
if not stop or (stop > n):
stop = n
elif stop < 0:
stop += n
for i in range(start, stop):
if output:
line = (input_hist[i], self.output_hist_reprs.get(i))
else:
line = input_hist[i]
yield (0, i, line) | [
"Get",
"input",
"and",
"output",
"history",
"from",
"the",
"current",
"session",
".",
"Called",
"by",
"get_range",
"and",
"takes",
"similar",
"parameters",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L462-L480 | [
"def",
"_get_range_session",
"(",
"self",
",",
"start",
"=",
"1",
",",
"stop",
"=",
"None",
",",
"raw",
"=",
"True",
",",
"output",
"=",
"False",
")",
":",
"input_hist",
"=",
"self",
".",
"input_hist_raw",
"if",
"raw",
"else",
"self",
".",
"input_hist_parsed",
"n",
"=",
"len",
"(",
"input_hist",
")",
"if",
"start",
"<",
"0",
":",
"start",
"+=",
"n",
"if",
"not",
"stop",
"or",
"(",
"stop",
">",
"n",
")",
":",
"stop",
"=",
"n",
"elif",
"stop",
"<",
"0",
":",
"stop",
"+=",
"n",
"for",
"i",
"in",
"range",
"(",
"start",
",",
"stop",
")",
":",
"if",
"output",
":",
"line",
"=",
"(",
"input_hist",
"[",
"i",
"]",
",",
"self",
".",
"output_hist_reprs",
".",
"get",
"(",
"i",
")",
")",
"else",
":",
"line",
"=",
"input_hist",
"[",
"i",
"]",
"yield",
"(",
"0",
",",
"i",
",",
"line",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryManager.get_range | Retrieve input by session.
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
start : int
First line to retrieve.
stop : int
End of line range (excluded from output itself). If None, retrieve
to the end of the session.
raw : bool
If True, return untranslated input
output : bool
If True, attempt to include output. This will be 'real' Python
objects for the current session, or text reprs from previous
sessions if db_log_output was enabled at the time. Where no output
is found, None is used.
Returns
-------
An iterator over the desired lines. Each line is a 3-tuple, either
(session, line, input) if output is False, or
(session, line, (input, output)) if output is True. | environment/lib/python2.7/site-packages/IPython/core/history.py | def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
"""Retrieve input by session.
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
start : int
First line to retrieve.
stop : int
End of line range (excluded from output itself). If None, retrieve
to the end of the session.
raw : bool
If True, return untranslated input
output : bool
If True, attempt to include output. This will be 'real' Python
objects for the current session, or text reprs from previous
sessions if db_log_output was enabled at the time. Where no output
is found, None is used.
Returns
-------
An iterator over the desired lines. Each line is a 3-tuple, either
(session, line, input) if output is False, or
(session, line, (input, output)) if output is True.
"""
if session <= 0:
session += self.session_number
if session==self.session_number: # Current session
return self._get_range_session(start, stop, raw, output)
return super(HistoryManager, self).get_range(session, start, stop, raw,
output) | def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
"""Retrieve input by session.
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
start : int
First line to retrieve.
stop : int
End of line range (excluded from output itself). If None, retrieve
to the end of the session.
raw : bool
If True, return untranslated input
output : bool
If True, attempt to include output. This will be 'real' Python
objects for the current session, or text reprs from previous
sessions if db_log_output was enabled at the time. Where no output
is found, None is used.
Returns
-------
An iterator over the desired lines. Each line is a 3-tuple, either
(session, line, input) if output is False, or
(session, line, (input, output)) if output is True.
"""
if session <= 0:
session += self.session_number
if session==self.session_number: # Current session
return self._get_range_session(start, stop, raw, output)
return super(HistoryManager, self).get_range(session, start, stop, raw,
output) | [
"Retrieve",
"input",
"by",
"session",
".",
"Parameters",
"----------",
"session",
":",
"int",
"Session",
"number",
"to",
"retrieve",
".",
"The",
"current",
"session",
"is",
"0",
"and",
"negative",
"numbers",
"count",
"back",
"from",
"current",
"session",
"so",
"-",
"1",
"is",
"previous",
"session",
".",
"start",
":",
"int",
"First",
"line",
"to",
"retrieve",
".",
"stop",
":",
"int",
"End",
"of",
"line",
"range",
"(",
"excluded",
"from",
"output",
"itself",
")",
".",
"If",
"None",
"retrieve",
"to",
"the",
"end",
"of",
"the",
"session",
".",
"raw",
":",
"bool",
"If",
"True",
"return",
"untranslated",
"input",
"output",
":",
"bool",
"If",
"True",
"attempt",
"to",
"include",
"output",
".",
"This",
"will",
"be",
"real",
"Python",
"objects",
"for",
"the",
"current",
"session",
"or",
"text",
"reprs",
"from",
"previous",
"sessions",
"if",
"db_log_output",
"was",
"enabled",
"at",
"the",
"time",
".",
"Where",
"no",
"output",
"is",
"found",
"None",
"is",
"used",
".",
"Returns",
"-------",
"An",
"iterator",
"over",
"the",
"desired",
"lines",
".",
"Each",
"line",
"is",
"a",
"3",
"-",
"tuple",
"either",
"(",
"session",
"line",
"input",
")",
"if",
"output",
"is",
"False",
"or",
"(",
"session",
"line",
"(",
"input",
"output",
"))",
"if",
"output",
"is",
"True",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L482-L514 | [
"def",
"get_range",
"(",
"self",
",",
"session",
"=",
"0",
",",
"start",
"=",
"1",
",",
"stop",
"=",
"None",
",",
"raw",
"=",
"True",
",",
"output",
"=",
"False",
")",
":",
"if",
"session",
"<=",
"0",
":",
"session",
"+=",
"self",
".",
"session_number",
"if",
"session",
"==",
"self",
".",
"session_number",
":",
"# Current session",
"return",
"self",
".",
"_get_range_session",
"(",
"start",
",",
"stop",
",",
"raw",
",",
"output",
")",
"return",
"super",
"(",
"HistoryManager",
",",
"self",
")",
".",
"get_range",
"(",
"session",
",",
"start",
",",
"stop",
",",
"raw",
",",
"output",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryManager.store_inputs | Store source and raw input in history and create input cache
variables _i*.
Parameters
----------
line_num : int
The prompt number of this input.
source : str
Python input.
source_raw : str, optional
If given, this is the raw input without any IPython transformations
applied to it. If not given, ``source`` is used. | environment/lib/python2.7/site-packages/IPython/core/history.py | def store_inputs(self, line_num, source, source_raw=None):
"""Store source and raw input in history and create input cache
variables _i*.
Parameters
----------
line_num : int
The prompt number of this input.
source : str
Python input.
source_raw : str, optional
If given, this is the raw input without any IPython transformations
applied to it. If not given, ``source`` is used.
"""
if source_raw is None:
source_raw = source
source = source.rstrip('\n')
source_raw = source_raw.rstrip('\n')
# do not store exit/quit commands
if self._exit_re.match(source_raw.strip()):
return
self.input_hist_parsed.append(source)
self.input_hist_raw.append(source_raw)
with self.db_input_cache_lock:
self.db_input_cache.append((line_num, source, source_raw))
# Trigger to flush cache and write to DB.
if len(self.db_input_cache) >= self.db_cache_size:
self.save_flag.set()
# update the auto _i variables
self._iii = self._ii
self._ii = self._i
self._i = self._i00
self._i00 = source_raw
# hackish access to user namespace to create _i1,_i2... dynamically
new_i = '_i%s' % line_num
to_main = {'_i': self._i,
'_ii': self._ii,
'_iii': self._iii,
new_i : self._i00 }
self.shell.push(to_main, interactive=False) | def store_inputs(self, line_num, source, source_raw=None):
"""Store source and raw input in history and create input cache
variables _i*.
Parameters
----------
line_num : int
The prompt number of this input.
source : str
Python input.
source_raw : str, optional
If given, this is the raw input without any IPython transformations
applied to it. If not given, ``source`` is used.
"""
if source_raw is None:
source_raw = source
source = source.rstrip('\n')
source_raw = source_raw.rstrip('\n')
# do not store exit/quit commands
if self._exit_re.match(source_raw.strip()):
return
self.input_hist_parsed.append(source)
self.input_hist_raw.append(source_raw)
with self.db_input_cache_lock:
self.db_input_cache.append((line_num, source, source_raw))
# Trigger to flush cache and write to DB.
if len(self.db_input_cache) >= self.db_cache_size:
self.save_flag.set()
# update the auto _i variables
self._iii = self._ii
self._ii = self._i
self._i = self._i00
self._i00 = source_raw
# hackish access to user namespace to create _i1,_i2... dynamically
new_i = '_i%s' % line_num
to_main = {'_i': self._i,
'_ii': self._ii,
'_iii': self._iii,
new_i : self._i00 }
self.shell.push(to_main, interactive=False) | [
"Store",
"source",
"and",
"raw",
"input",
"in",
"history",
"and",
"create",
"input",
"cache",
"variables",
"_i",
"*",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L519-L566 | [
"def",
"store_inputs",
"(",
"self",
",",
"line_num",
",",
"source",
",",
"source_raw",
"=",
"None",
")",
":",
"if",
"source_raw",
"is",
"None",
":",
"source_raw",
"=",
"source",
"source",
"=",
"source",
".",
"rstrip",
"(",
"'\\n'",
")",
"source_raw",
"=",
"source_raw",
".",
"rstrip",
"(",
"'\\n'",
")",
"# do not store exit/quit commands",
"if",
"self",
".",
"_exit_re",
".",
"match",
"(",
"source_raw",
".",
"strip",
"(",
")",
")",
":",
"return",
"self",
".",
"input_hist_parsed",
".",
"append",
"(",
"source",
")",
"self",
".",
"input_hist_raw",
".",
"append",
"(",
"source_raw",
")",
"with",
"self",
".",
"db_input_cache_lock",
":",
"self",
".",
"db_input_cache",
".",
"append",
"(",
"(",
"line_num",
",",
"source",
",",
"source_raw",
")",
")",
"# Trigger to flush cache and write to DB.",
"if",
"len",
"(",
"self",
".",
"db_input_cache",
")",
">=",
"self",
".",
"db_cache_size",
":",
"self",
".",
"save_flag",
".",
"set",
"(",
")",
"# update the auto _i variables",
"self",
".",
"_iii",
"=",
"self",
".",
"_ii",
"self",
".",
"_ii",
"=",
"self",
".",
"_i",
"self",
".",
"_i",
"=",
"self",
".",
"_i00",
"self",
".",
"_i00",
"=",
"source_raw",
"# hackish access to user namespace to create _i1,_i2... dynamically",
"new_i",
"=",
"'_i%s'",
"%",
"line_num",
"to_main",
"=",
"{",
"'_i'",
":",
"self",
".",
"_i",
",",
"'_ii'",
":",
"self",
".",
"_ii",
",",
"'_iii'",
":",
"self",
".",
"_iii",
",",
"new_i",
":",
"self",
".",
"_i00",
"}",
"self",
".",
"shell",
".",
"push",
"(",
"to_main",
",",
"interactive",
"=",
"False",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryManager.store_output | If database output logging is enabled, this saves all the
outputs from the indicated prompt number to the database. It's
called by run_cell after code has been executed.
Parameters
----------
line_num : int
The line number from which to save outputs | environment/lib/python2.7/site-packages/IPython/core/history.py | def store_output(self, line_num):
"""If database output logging is enabled, this saves all the
outputs from the indicated prompt number to the database. It's
called by run_cell after code has been executed.
Parameters
----------
line_num : int
The line number from which to save outputs
"""
if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
return
output = self.output_hist_reprs[line_num]
with self.db_output_cache_lock:
self.db_output_cache.append((line_num, output))
if self.db_cache_size <= 1:
self.save_flag.set() | def store_output(self, line_num):
"""If database output logging is enabled, this saves all the
outputs from the indicated prompt number to the database. It's
called by run_cell after code has been executed.
Parameters
----------
line_num : int
The line number from which to save outputs
"""
if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
return
output = self.output_hist_reprs[line_num]
with self.db_output_cache_lock:
self.db_output_cache.append((line_num, output))
if self.db_cache_size <= 1:
self.save_flag.set() | [
"If",
"database",
"output",
"logging",
"is",
"enabled",
"this",
"saves",
"all",
"the",
"outputs",
"from",
"the",
"indicated",
"prompt",
"number",
"to",
"the",
"database",
".",
"It",
"s",
"called",
"by",
"run_cell",
"after",
"code",
"has",
"been",
"executed",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L568-L585 | [
"def",
"store_output",
"(",
"self",
",",
"line_num",
")",
":",
"if",
"(",
"not",
"self",
".",
"db_log_output",
")",
"or",
"(",
"line_num",
"not",
"in",
"self",
".",
"output_hist_reprs",
")",
":",
"return",
"output",
"=",
"self",
".",
"output_hist_reprs",
"[",
"line_num",
"]",
"with",
"self",
".",
"db_output_cache_lock",
":",
"self",
".",
"db_output_cache",
".",
"append",
"(",
"(",
"line_num",
",",
"output",
")",
")",
"if",
"self",
".",
"db_cache_size",
"<=",
"1",
":",
"self",
".",
"save_flag",
".",
"set",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistoryManager.writeout_cache | Write any entries in the cache to the database. | environment/lib/python2.7/site-packages/IPython/core/history.py | def writeout_cache(self, conn=None):
"""Write any entries in the cache to the database."""
if conn is None:
conn = self.db
with self.db_input_cache_lock:
try:
self._writeout_input_cache(conn)
except sqlite3.IntegrityError:
self.new_session(conn)
print("ERROR! Session/line number was not unique in",
"database. History logging moved to new session",
self.session_number)
try:
# Try writing to the new session. If this fails, don't
# recurse
self._writeout_input_cache(conn)
except sqlite3.IntegrityError:
pass
finally:
self.db_input_cache = []
with self.db_output_cache_lock:
try:
self._writeout_output_cache(conn)
except sqlite3.IntegrityError:
print("!! Session/line number for output was not unique",
"in database. Output will not be stored.")
finally:
self.db_output_cache = [] | def writeout_cache(self, conn=None):
"""Write any entries in the cache to the database."""
if conn is None:
conn = self.db
with self.db_input_cache_lock:
try:
self._writeout_input_cache(conn)
except sqlite3.IntegrityError:
self.new_session(conn)
print("ERROR! Session/line number was not unique in",
"database. History logging moved to new session",
self.session_number)
try:
# Try writing to the new session. If this fails, don't
# recurse
self._writeout_input_cache(conn)
except sqlite3.IntegrityError:
pass
finally:
self.db_input_cache = []
with self.db_output_cache_lock:
try:
self._writeout_output_cache(conn)
except sqlite3.IntegrityError:
print("!! Session/line number for output was not unique",
"in database. Output will not be stored.")
finally:
self.db_output_cache = [] | [
"Write",
"any",
"entries",
"in",
"the",
"cache",
"to",
"the",
"database",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L600-L629 | [
"def",
"writeout_cache",
"(",
"self",
",",
"conn",
"=",
"None",
")",
":",
"if",
"conn",
"is",
"None",
":",
"conn",
"=",
"self",
".",
"db",
"with",
"self",
".",
"db_input_cache_lock",
":",
"try",
":",
"self",
".",
"_writeout_input_cache",
"(",
"conn",
")",
"except",
"sqlite3",
".",
"IntegrityError",
":",
"self",
".",
"new_session",
"(",
"conn",
")",
"print",
"(",
"\"ERROR! Session/line number was not unique in\"",
",",
"\"database. History logging moved to new session\"",
",",
"self",
".",
"session_number",
")",
"try",
":",
"# Try writing to the new session. If this fails, don't",
"# recurse",
"self",
".",
"_writeout_input_cache",
"(",
"conn",
")",
"except",
"sqlite3",
".",
"IntegrityError",
":",
"pass",
"finally",
":",
"self",
".",
"db_input_cache",
"=",
"[",
"]",
"with",
"self",
".",
"db_output_cache_lock",
":",
"try",
":",
"self",
".",
"_writeout_output_cache",
"(",
"conn",
")",
"except",
"sqlite3",
".",
"IntegrityError",
":",
"print",
"(",
"\"!! Session/line number for output was not unique\"",
",",
"\"in database. Output will not be stored.\"",
")",
"finally",
":",
"self",
".",
"db_output_cache",
"=",
"[",
"]"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HistorySavingThread.stop | This can be called from the main thread to safely stop this thread.
Note that it does not attempt to write out remaining history before
exiting. That should be done by calling the HistoryManager's
end_session method. | environment/lib/python2.7/site-packages/IPython/core/history.py | def stop(self):
"""This can be called from the main thread to safely stop this thread.
Note that it does not attempt to write out remaining history before
exiting. That should be done by calling the HistoryManager's
end_session method."""
self.stop_now = True
self.history_manager.save_flag.set()
self.join() | def stop(self):
"""This can be called from the main thread to safely stop this thread.
Note that it does not attempt to write out remaining history before
exiting. That should be done by calling the HistoryManager's
end_session method."""
self.stop_now = True
self.history_manager.save_flag.set()
self.join() | [
"This",
"can",
"be",
"called",
"from",
"the",
"main",
"thread",
"to",
"safely",
"stop",
"this",
"thread",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/history.py#L661-L669 | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"stop_now",
"=",
"True",
"self",
".",
"history_manager",
".",
"save_flag",
".",
"set",
"(",
")",
"self",
".",
"join",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | _get_boot_time | Return system boot time (epoch in seconds) | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def _get_boot_time():
"""Return system boot time (epoch in seconds)"""
f = open('/proc/stat', 'r')
try:
for line in f:
if line.startswith('btime'):
return float(line.strip().split()[1])
raise RuntimeError("line not found")
finally:
f.close() | def _get_boot_time():
"""Return system boot time (epoch in seconds)"""
f = open('/proc/stat', 'r')
try:
for line in f:
if line.startswith('btime'):
return float(line.strip().split()[1])
raise RuntimeError("line not found")
finally:
f.close() | [
"Return",
"system",
"boot",
"time",
"(",
"epoch",
"in",
"seconds",
")"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L34-L43 | [
"def",
"_get_boot_time",
"(",
")",
":",
"f",
"=",
"open",
"(",
"'/proc/stat'",
",",
"'r'",
")",
"try",
":",
"for",
"line",
"in",
"f",
":",
"if",
"line",
".",
"startswith",
"(",
"'btime'",
")",
":",
"return",
"float",
"(",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
"raise",
"RuntimeError",
"(",
"\"line not found\"",
")",
"finally",
":",
"f",
".",
"close",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | _get_num_cpus | Return the number of CPUs on the system | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def _get_num_cpus():
"""Return the number of CPUs on the system"""
# we try to determine num CPUs by using different approaches.
# SC_NPROCESSORS_ONLN seems to be the safer and it is also
# used by multiprocessing module
try:
return os.sysconf("SC_NPROCESSORS_ONLN")
except ValueError:
# as a second fallback we try to parse /proc/cpuinfo
num = 0
f = open('/proc/cpuinfo', 'r')
try:
lines = f.readlines()
finally:
f.close()
for line in lines:
if line.lower().startswith('processor'):
num += 1
# unknown format (e.g. amrel/sparc architectures), see:
# http://code.google.com/p/psutil/issues/detail?id=200
# try to parse /proc/stat as a last resort
if num == 0:
f = open('/proc/stat', 'r')
try:
lines = f.readlines()
finally:
f.close()
search = re.compile('cpu\d')
for line in lines:
line = line.split(' ')[0]
if search.match(line):
num += 1
if num == 0:
raise RuntimeError("can't determine number of CPUs")
return num | def _get_num_cpus():
"""Return the number of CPUs on the system"""
# we try to determine num CPUs by using different approaches.
# SC_NPROCESSORS_ONLN seems to be the safer and it is also
# used by multiprocessing module
try:
return os.sysconf("SC_NPROCESSORS_ONLN")
except ValueError:
# as a second fallback we try to parse /proc/cpuinfo
num = 0
f = open('/proc/cpuinfo', 'r')
try:
lines = f.readlines()
finally:
f.close()
for line in lines:
if line.lower().startswith('processor'):
num += 1
# unknown format (e.g. amrel/sparc architectures), see:
# http://code.google.com/p/psutil/issues/detail?id=200
# try to parse /proc/stat as a last resort
if num == 0:
f = open('/proc/stat', 'r')
try:
lines = f.readlines()
finally:
f.close()
search = re.compile('cpu\d')
for line in lines:
line = line.split(' ')[0]
if search.match(line):
num += 1
if num == 0:
raise RuntimeError("can't determine number of CPUs")
return num | [
"Return",
"the",
"number",
"of",
"CPUs",
"on",
"the",
"system"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L45-L81 | [
"def",
"_get_num_cpus",
"(",
")",
":",
"# we try to determine num CPUs by using different approaches.",
"# SC_NPROCESSORS_ONLN seems to be the safer and it is also",
"# used by multiprocessing module",
"try",
":",
"return",
"os",
".",
"sysconf",
"(",
"\"SC_NPROCESSORS_ONLN\"",
")",
"except",
"ValueError",
":",
"# as a second fallback we try to parse /proc/cpuinfo",
"num",
"=",
"0",
"f",
"=",
"open",
"(",
"'/proc/cpuinfo'",
",",
"'r'",
")",
"try",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'processor'",
")",
":",
"num",
"+=",
"1",
"# unknown format (e.g. amrel/sparc architectures), see:",
"# http://code.google.com/p/psutil/issues/detail?id=200",
"# try to parse /proc/stat as a last resort",
"if",
"num",
"==",
"0",
":",
"f",
"=",
"open",
"(",
"'/proc/stat'",
",",
"'r'",
")",
"try",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"search",
"=",
"re",
".",
"compile",
"(",
"'cpu\\d'",
")",
"for",
"line",
"in",
"lines",
":",
"line",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"[",
"0",
"]",
"if",
"search",
".",
"match",
"(",
"line",
")",
":",
"num",
"+=",
"1",
"if",
"num",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"can't determine number of CPUs\"",
")",
"return",
"num"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_system_cpu_times | Return a named tuple representing the following CPU times:
user, nice, system, idle, iowait, irq, softirq. | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def get_system_cpu_times():
"""Return a named tuple representing the following CPU times:
user, nice, system, idle, iowait, irq, softirq.
"""
f = open('/proc/stat', 'r')
try:
values = f.readline().split()
finally:
f.close()
values = values[1:8]
values = tuple([float(x) / _CLOCK_TICKS for x in values])
return nt_sys_cputimes(*values[:7]) | def get_system_cpu_times():
"""Return a named tuple representing the following CPU times:
user, nice, system, idle, iowait, irq, softirq.
"""
f = open('/proc/stat', 'r')
try:
values = f.readline().split()
finally:
f.close()
values = values[1:8]
values = tuple([float(x) / _CLOCK_TICKS for x in values])
return nt_sys_cputimes(*values[:7]) | [
"Return",
"a",
"named",
"tuple",
"representing",
"the",
"following",
"CPU",
"times",
":",
"user",
"nice",
"system",
"idle",
"iowait",
"irq",
"softirq",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L183-L195 | [
"def",
"get_system_cpu_times",
"(",
")",
":",
"f",
"=",
"open",
"(",
"'/proc/stat'",
",",
"'r'",
")",
"try",
":",
"values",
"=",
"f",
".",
"readline",
"(",
")",
".",
"split",
"(",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"values",
"=",
"values",
"[",
"1",
":",
"8",
"]",
"values",
"=",
"tuple",
"(",
"[",
"float",
"(",
"x",
")",
"/",
"_CLOCK_TICKS",
"for",
"x",
"in",
"values",
"]",
")",
"return",
"nt_sys_cputimes",
"(",
"*",
"values",
"[",
":",
"7",
"]",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_system_per_cpu_times | Return a list of namedtuple representing the CPU times
for every CPU available on the system. | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def get_system_per_cpu_times():
"""Return a list of namedtuple representing the CPU times
for every CPU available on the system.
"""
cpus = []
f = open('/proc/stat', 'r')
# get rid of the first line who refers to system wide CPU stats
try:
f.readline()
for line in f.readlines():
if line.startswith('cpu'):
values = line.split()[1:8]
values = tuple([float(x) / _CLOCK_TICKS for x in values])
entry = nt_sys_cputimes(*values[:7])
cpus.append(entry)
return cpus
finally:
f.close() | def get_system_per_cpu_times():
"""Return a list of namedtuple representing the CPU times
for every CPU available on the system.
"""
cpus = []
f = open('/proc/stat', 'r')
# get rid of the first line who refers to system wide CPU stats
try:
f.readline()
for line in f.readlines():
if line.startswith('cpu'):
values = line.split()[1:8]
values = tuple([float(x) / _CLOCK_TICKS for x in values])
entry = nt_sys_cputimes(*values[:7])
cpus.append(entry)
return cpus
finally:
f.close() | [
"Return",
"a",
"list",
"of",
"namedtuple",
"representing",
"the",
"CPU",
"times",
"for",
"every",
"CPU",
"available",
"on",
"the",
"system",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L197-L214 | [
"def",
"get_system_per_cpu_times",
"(",
")",
":",
"cpus",
"=",
"[",
"]",
"f",
"=",
"open",
"(",
"'/proc/stat'",
",",
"'r'",
")",
"# get rid of the first line who refers to system wide CPU stats",
"try",
":",
"f",
".",
"readline",
"(",
")",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'cpu'",
")",
":",
"values",
"=",
"line",
".",
"split",
"(",
")",
"[",
"1",
":",
"8",
"]",
"values",
"=",
"tuple",
"(",
"[",
"float",
"(",
"x",
")",
"/",
"_CLOCK_TICKS",
"for",
"x",
"in",
"values",
"]",
")",
"entry",
"=",
"nt_sys_cputimes",
"(",
"*",
"values",
"[",
":",
"7",
"]",
")",
"cpus",
".",
"append",
"(",
"entry",
")",
"return",
"cpus",
"finally",
":",
"f",
".",
"close",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | disk_partitions | Return mounted disk partitions as a list of nameduples | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def disk_partitions(all=False):
"""Return mounted disk partitions as a list of nameduples"""
phydevs = []
f = open("/proc/filesystems", "r")
try:
for line in f:
if not line.startswith("nodev"):
phydevs.append(line.strip())
finally:
f.close()
retlist = []
partitions = _psutil_linux.get_disk_partitions()
for partition in partitions:
device, mountpoint, fstype, opts = partition
if device == 'none':
device = ''
if not all:
if device == '' or fstype not in phydevs:
continue
ntuple = nt_partition(device, mountpoint, fstype, opts)
retlist.append(ntuple)
return retlist | def disk_partitions(all=False):
"""Return mounted disk partitions as a list of nameduples"""
phydevs = []
f = open("/proc/filesystems", "r")
try:
for line in f:
if not line.startswith("nodev"):
phydevs.append(line.strip())
finally:
f.close()
retlist = []
partitions = _psutil_linux.get_disk_partitions()
for partition in partitions:
device, mountpoint, fstype, opts = partition
if device == 'none':
device = ''
if not all:
if device == '' or fstype not in phydevs:
continue
ntuple = nt_partition(device, mountpoint, fstype, opts)
retlist.append(ntuple)
return retlist | [
"Return",
"mounted",
"disk",
"partitions",
"as",
"a",
"list",
"of",
"nameduples"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L219-L241 | [
"def",
"disk_partitions",
"(",
"all",
"=",
"False",
")",
":",
"phydevs",
"=",
"[",
"]",
"f",
"=",
"open",
"(",
"\"/proc/filesystems\"",
",",
"\"r\"",
")",
"try",
":",
"for",
"line",
"in",
"f",
":",
"if",
"not",
"line",
".",
"startswith",
"(",
"\"nodev\"",
")",
":",
"phydevs",
".",
"append",
"(",
"line",
".",
"strip",
"(",
")",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"retlist",
"=",
"[",
"]",
"partitions",
"=",
"_psutil_linux",
".",
"get_disk_partitions",
"(",
")",
"for",
"partition",
"in",
"partitions",
":",
"device",
",",
"mountpoint",
",",
"fstype",
",",
"opts",
"=",
"partition",
"if",
"device",
"==",
"'none'",
":",
"device",
"=",
"''",
"if",
"not",
"all",
":",
"if",
"device",
"==",
"''",
"or",
"fstype",
"not",
"in",
"phydevs",
":",
"continue",
"ntuple",
"=",
"nt_partition",
"(",
"device",
",",
"mountpoint",
",",
"fstype",
",",
"opts",
")",
"retlist",
".",
"append",
"(",
"ntuple",
")",
"return",
"retlist"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_system_users | Return currently connected users as a list of namedtuples. | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def get_system_users():
"""Return currently connected users as a list of namedtuples."""
retlist = []
rawlist = _psutil_linux.get_system_users()
for item in rawlist:
user, tty, hostname, tstamp, user_process = item
# XXX the underlying C function includes entries about
# system boot, run level and others. We might want
# to use them in the future.
if not user_process:
continue
if hostname == ':0.0':
hostname = 'localhost'
nt = nt_user(user, tty or None, hostname, tstamp)
retlist.append(nt)
return retlist | def get_system_users():
"""Return currently connected users as a list of namedtuples."""
retlist = []
rawlist = _psutil_linux.get_system_users()
for item in rawlist:
user, tty, hostname, tstamp, user_process = item
# XXX the underlying C function includes entries about
# system boot, run level and others. We might want
# to use them in the future.
if not user_process:
continue
if hostname == ':0.0':
hostname = 'localhost'
nt = nt_user(user, tty or None, hostname, tstamp)
retlist.append(nt)
return retlist | [
"Return",
"currently",
"connected",
"users",
"as",
"a",
"list",
"of",
"namedtuples",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L248-L263 | [
"def",
"get_system_users",
"(",
")",
":",
"retlist",
"=",
"[",
"]",
"rawlist",
"=",
"_psutil_linux",
".",
"get_system_users",
"(",
")",
"for",
"item",
"in",
"rawlist",
":",
"user",
",",
"tty",
",",
"hostname",
",",
"tstamp",
",",
"user_process",
"=",
"item",
"# XXX the underlying C function includes entries about",
"# system boot, run level and others. We might want",
"# to use them in the future.",
"if",
"not",
"user_process",
":",
"continue",
"if",
"hostname",
"==",
"':0.0'",
":",
"hostname",
"=",
"'localhost'",
"nt",
"=",
"nt_user",
"(",
"user",
",",
"tty",
"or",
"None",
",",
"hostname",
",",
"tstamp",
")",
"retlist",
".",
"append",
"(",
"nt",
")",
"return",
"retlist"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_pid_list | Returns a list of PIDs currently running on the system. | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def get_pid_list():
"""Returns a list of PIDs currently running on the system."""
pids = [int(x) for x in os.listdir('/proc') if x.isdigit()]
return pids | def get_pid_list():
"""Returns a list of PIDs currently running on the system."""
pids = [int(x) for x in os.listdir('/proc') if x.isdigit()]
return pids | [
"Returns",
"a",
"list",
"of",
"PIDs",
"currently",
"running",
"on",
"the",
"system",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L267-L270 | [
"def",
"get_pid_list",
"(",
")",
":",
"pids",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"'/proc'",
")",
"if",
"x",
".",
"isdigit",
"(",
")",
"]",
"return",
"pids"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | network_io_counters | Return network I/O statistics for every network interface
installed on the system as a dict of raw tuples. | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def network_io_counters():
"""Return network I/O statistics for every network interface
installed on the system as a dict of raw tuples.
"""
f = open("/proc/net/dev", "r")
try:
lines = f.readlines()
finally:
f.close()
retdict = {}
for line in lines[2:]:
colon = line.find(':')
assert colon > 0, line
name = line[:colon].strip()
fields = line[colon+1:].strip().split()
bytes_recv = int(fields[0])
packets_recv = int(fields[1])
errin = int(fields[2])
dropin = int(fields[2])
bytes_sent = int(fields[8])
packets_sent = int(fields[9])
errout = int(fields[10])
dropout = int(fields[11])
retdict[name] = (bytes_sent, bytes_recv, packets_sent, packets_recv,
errin, errout, dropin, dropout)
return retdict | def network_io_counters():
"""Return network I/O statistics for every network interface
installed on the system as a dict of raw tuples.
"""
f = open("/proc/net/dev", "r")
try:
lines = f.readlines()
finally:
f.close()
retdict = {}
for line in lines[2:]:
colon = line.find(':')
assert colon > 0, line
name = line[:colon].strip()
fields = line[colon+1:].strip().split()
bytes_recv = int(fields[0])
packets_recv = int(fields[1])
errin = int(fields[2])
dropin = int(fields[2])
bytes_sent = int(fields[8])
packets_sent = int(fields[9])
errout = int(fields[10])
dropout = int(fields[11])
retdict[name] = (bytes_sent, bytes_recv, packets_sent, packets_recv,
errin, errout, dropin, dropout)
return retdict | [
"Return",
"network",
"I",
"/",
"O",
"statistics",
"for",
"every",
"network",
"interface",
"installed",
"on",
"the",
"system",
"as",
"a",
"dict",
"of",
"raw",
"tuples",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L276-L302 | [
"def",
"network_io_counters",
"(",
")",
":",
"f",
"=",
"open",
"(",
"\"/proc/net/dev\"",
",",
"\"r\"",
")",
"try",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"retdict",
"=",
"{",
"}",
"for",
"line",
"in",
"lines",
"[",
"2",
":",
"]",
":",
"colon",
"=",
"line",
".",
"find",
"(",
"':'",
")",
"assert",
"colon",
">",
"0",
",",
"line",
"name",
"=",
"line",
"[",
":",
"colon",
"]",
".",
"strip",
"(",
")",
"fields",
"=",
"line",
"[",
"colon",
"+",
"1",
":",
"]",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"bytes_recv",
"=",
"int",
"(",
"fields",
"[",
"0",
"]",
")",
"packets_recv",
"=",
"int",
"(",
"fields",
"[",
"1",
"]",
")",
"errin",
"=",
"int",
"(",
"fields",
"[",
"2",
"]",
")",
"dropin",
"=",
"int",
"(",
"fields",
"[",
"2",
"]",
")",
"bytes_sent",
"=",
"int",
"(",
"fields",
"[",
"8",
"]",
")",
"packets_sent",
"=",
"int",
"(",
"fields",
"[",
"9",
"]",
")",
"errout",
"=",
"int",
"(",
"fields",
"[",
"10",
"]",
")",
"dropout",
"=",
"int",
"(",
"fields",
"[",
"11",
"]",
")",
"retdict",
"[",
"name",
"]",
"=",
"(",
"bytes_sent",
",",
"bytes_recv",
",",
"packets_sent",
",",
"packets_recv",
",",
"errin",
",",
"errout",
",",
"dropin",
",",
"dropout",
")",
"return",
"retdict"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | disk_io_counters | Return disk I/O statistics for every disk installed on the
system as a dict of raw tuples. | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def disk_io_counters():
"""Return disk I/O statistics for every disk installed on the
system as a dict of raw tuples.
"""
# man iostat states that sectors are equivalent with blocks and
# have a size of 512 bytes since 2.4 kernels. This value is
# needed to calculate the amount of disk I/O in bytes.
SECTOR_SIZE = 512
# determine partitions we want to look for
partitions = []
f = open("/proc/partitions", "r")
try:
lines = f.readlines()[2:]
finally:
f.close()
for line in lines:
_, _, _, name = line.split()
if name[-1].isdigit():
partitions.append(name)
#
retdict = {}
f = open("/proc/diskstats", "r")
try:
lines = f.readlines()
finally:
f.close()
for line in lines:
_, _, name, reads, _, rbytes, rtime, writes, _, wbytes, wtime = \
line.split()[:11]
if name in partitions:
rbytes = int(rbytes) * SECTOR_SIZE
wbytes = int(wbytes) * SECTOR_SIZE
reads = int(reads)
writes = int(writes)
# TODO: times are expressed in milliseconds while OSX/BSD has
# these expressed in nanoseconds; figure this out.
rtime = int(rtime)
wtime = int(wtime)
retdict[name] = (reads, writes, rbytes, wbytes, rtime, wtime)
return retdict | def disk_io_counters():
"""Return disk I/O statistics for every disk installed on the
system as a dict of raw tuples.
"""
# man iostat states that sectors are equivalent with blocks and
# have a size of 512 bytes since 2.4 kernels. This value is
# needed to calculate the amount of disk I/O in bytes.
SECTOR_SIZE = 512
# determine partitions we want to look for
partitions = []
f = open("/proc/partitions", "r")
try:
lines = f.readlines()[2:]
finally:
f.close()
for line in lines:
_, _, _, name = line.split()
if name[-1].isdigit():
partitions.append(name)
#
retdict = {}
f = open("/proc/diskstats", "r")
try:
lines = f.readlines()
finally:
f.close()
for line in lines:
_, _, name, reads, _, rbytes, rtime, writes, _, wbytes, wtime = \
line.split()[:11]
if name in partitions:
rbytes = int(rbytes) * SECTOR_SIZE
wbytes = int(wbytes) * SECTOR_SIZE
reads = int(reads)
writes = int(writes)
# TODO: times are expressed in milliseconds while OSX/BSD has
# these expressed in nanoseconds; figure this out.
rtime = int(rtime)
wtime = int(wtime)
retdict[name] = (reads, writes, rbytes, wbytes, rtime, wtime)
return retdict | [
"Return",
"disk",
"I",
"/",
"O",
"statistics",
"for",
"every",
"disk",
"installed",
"on",
"the",
"system",
"as",
"a",
"dict",
"of",
"raw",
"tuples",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L304-L344 | [
"def",
"disk_io_counters",
"(",
")",
":",
"# man iostat states that sectors are equivalent with blocks and",
"# have a size of 512 bytes since 2.4 kernels. This value is",
"# needed to calculate the amount of disk I/O in bytes.",
"SECTOR_SIZE",
"=",
"512",
"# determine partitions we want to look for",
"partitions",
"=",
"[",
"]",
"f",
"=",
"open",
"(",
"\"/proc/partitions\"",
",",
"\"r\"",
")",
"try",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"[",
"2",
":",
"]",
"finally",
":",
"f",
".",
"close",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"_",
",",
"_",
",",
"_",
",",
"name",
"=",
"line",
".",
"split",
"(",
")",
"if",
"name",
"[",
"-",
"1",
"]",
".",
"isdigit",
"(",
")",
":",
"partitions",
".",
"append",
"(",
"name",
")",
"#",
"retdict",
"=",
"{",
"}",
"f",
"=",
"open",
"(",
"\"/proc/diskstats\"",
",",
"\"r\"",
")",
"try",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"_",
",",
"_",
",",
"name",
",",
"reads",
",",
"_",
",",
"rbytes",
",",
"rtime",
",",
"writes",
",",
"_",
",",
"wbytes",
",",
"wtime",
"=",
"line",
".",
"split",
"(",
")",
"[",
":",
"11",
"]",
"if",
"name",
"in",
"partitions",
":",
"rbytes",
"=",
"int",
"(",
"rbytes",
")",
"*",
"SECTOR_SIZE",
"wbytes",
"=",
"int",
"(",
"wbytes",
")",
"*",
"SECTOR_SIZE",
"reads",
"=",
"int",
"(",
"reads",
")",
"writes",
"=",
"int",
"(",
"writes",
")",
"# TODO: times are expressed in milliseconds while OSX/BSD has",
"# these expressed in nanoseconds; figure this out.",
"rtime",
"=",
"int",
"(",
"rtime",
")",
"wtime",
"=",
"int",
"(",
"wtime",
")",
"retdict",
"[",
"name",
"]",
"=",
"(",
"reads",
",",
"writes",
",",
"rbytes",
",",
"wbytes",
",",
"rtime",
",",
"wtime",
")",
"return",
"retdict"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | wrap_exceptions | Call callable into a try/except clause and translate ENOENT,
EACCES and EPERM in NoSuchProcess or AccessDenied exceptions. | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def wrap_exceptions(callable):
"""Call callable into a try/except clause and translate ENOENT,
EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
"""
def wrapper(self, *args, **kwargs):
try:
return callable(self, *args, **kwargs)
except EnvironmentError:
# ENOENT (no such file or directory) gets raised on open().
# ESRCH (no such process) can get raised on read() if
# process is gone in meantime.
err = sys.exc_info()[1]
if err.errno in (errno.ENOENT, errno.ESRCH):
raise NoSuchProcess(self.pid, self._process_name)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._process_name)
raise
return wrapper | def wrap_exceptions(callable):
"""Call callable into a try/except clause and translate ENOENT,
EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
"""
def wrapper(self, *args, **kwargs):
try:
return callable(self, *args, **kwargs)
except EnvironmentError:
# ENOENT (no such file or directory) gets raised on open().
# ESRCH (no such process) can get raised on read() if
# process is gone in meantime.
err = sys.exc_info()[1]
if err.errno in (errno.ENOENT, errno.ESRCH):
raise NoSuchProcess(self.pid, self._process_name)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._process_name)
raise
return wrapper | [
"Call",
"callable",
"into",
"a",
"try",
"/",
"except",
"clause",
"and",
"translate",
"ENOENT",
"EACCES",
"and",
"EPERM",
"in",
"NoSuchProcess",
"or",
"AccessDenied",
"exceptions",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L361-L378 | [
"def",
"wrap_exceptions",
"(",
"callable",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"callable",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"EnvironmentError",
":",
"# ENOENT (no such file or directory) gets raised on open().",
"# ESRCH (no such process) can get raised on read() if",
"# process is gone in meantime.",
"err",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"if",
"err",
".",
"errno",
"in",
"(",
"errno",
".",
"ENOENT",
",",
"errno",
".",
"ESRCH",
")",
":",
"raise",
"NoSuchProcess",
"(",
"self",
".",
"pid",
",",
"self",
".",
"_process_name",
")",
"if",
"err",
".",
"errno",
"in",
"(",
"errno",
".",
"EPERM",
",",
"errno",
".",
"EACCES",
")",
":",
"raise",
"AccessDenied",
"(",
"self",
".",
"pid",
",",
"self",
".",
"_process_name",
")",
"raise",
"return",
"wrapper"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Process.get_memory_maps | Return process's mapped memory regions as a list of nameduples.
Fields are explained in 'man proc'; here is an updated (Apr 2012)
version: http://goo.gl/fmebo | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def get_memory_maps(self):
"""Return process's mapped memory regions as a list of nameduples.
Fields are explained in 'man proc'; here is an updated (Apr 2012)
version: http://goo.gl/fmebo
"""
f = None
try:
f = open("/proc/%s/smaps" % self.pid)
first_line = f.readline()
current_block = [first_line]
def get_blocks():
data = {}
for line in f:
fields = line.split(None, 5)
if len(fields) >= 5:
yield (current_block.pop(), data)
current_block.append(line)
else:
data[fields[0]] = int(fields[1]) * 1024
yield (current_block.pop(), data)
if first_line: # smaps file can be empty
for header, data in get_blocks():
hfields = header.split(None, 5)
try:
addr, perms, offset, dev, inode, path = hfields
except ValueError:
addr, perms, offset, dev, inode, path = hfields + ['']
if not path:
path = '[anon]'
else:
path = path.strip()
yield (addr, perms, path,
data['Rss:'],
data['Size:'],
data.get('Pss:', 0),
data['Shared_Clean:'], data['Shared_Clean:'],
data['Private_Clean:'], data['Private_Dirty:'],
data['Referenced:'],
data['Anonymous:'],
data['Swap:'])
f.close()
except EnvironmentError:
# XXX - Can't use wrap_exceptions decorator as we're
# returning a generator; this probably needs some
# refactoring in order to avoid this code duplication.
if f is not None:
f.close()
err = sys.exc_info()[1]
if err.errno in (errno.ENOENT, errno.ESRCH):
raise NoSuchProcess(self.pid, self._process_name)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._process_name)
raise
except:
if f is not None:
f.close()
raise | def get_memory_maps(self):
"""Return process's mapped memory regions as a list of nameduples.
Fields are explained in 'man proc'; here is an updated (Apr 2012)
version: http://goo.gl/fmebo
"""
f = None
try:
f = open("/proc/%s/smaps" % self.pid)
first_line = f.readline()
current_block = [first_line]
def get_blocks():
data = {}
for line in f:
fields = line.split(None, 5)
if len(fields) >= 5:
yield (current_block.pop(), data)
current_block.append(line)
else:
data[fields[0]] = int(fields[1]) * 1024
yield (current_block.pop(), data)
if first_line: # smaps file can be empty
for header, data in get_blocks():
hfields = header.split(None, 5)
try:
addr, perms, offset, dev, inode, path = hfields
except ValueError:
addr, perms, offset, dev, inode, path = hfields + ['']
if not path:
path = '[anon]'
else:
path = path.strip()
yield (addr, perms, path,
data['Rss:'],
data['Size:'],
data.get('Pss:', 0),
data['Shared_Clean:'], data['Shared_Clean:'],
data['Private_Clean:'], data['Private_Dirty:'],
data['Referenced:'],
data['Anonymous:'],
data['Swap:'])
f.close()
except EnvironmentError:
# XXX - Can't use wrap_exceptions decorator as we're
# returning a generator; this probably needs some
# refactoring in order to avoid this code duplication.
if f is not None:
f.close()
err = sys.exc_info()[1]
if err.errno in (errno.ENOENT, errno.ESRCH):
raise NoSuchProcess(self.pid, self._process_name)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._process_name)
raise
except:
if f is not None:
f.close()
raise | [
"Return",
"process",
"s",
"mapped",
"memory",
"regions",
"as",
"a",
"list",
"of",
"nameduples",
".",
"Fields",
"are",
"explained",
"in",
"man",
"proc",
";",
"here",
"is",
"an",
"updated",
"(",
"Apr",
"2012",
")",
"version",
":",
"http",
":",
"//",
"goo",
".",
"gl",
"/",
"fmebo"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L551-L609 | [
"def",
"get_memory_maps",
"(",
"self",
")",
":",
"f",
"=",
"None",
"try",
":",
"f",
"=",
"open",
"(",
"\"/proc/%s/smaps\"",
"%",
"self",
".",
"pid",
")",
"first_line",
"=",
"f",
".",
"readline",
"(",
")",
"current_block",
"=",
"[",
"first_line",
"]",
"def",
"get_blocks",
"(",
")",
":",
"data",
"=",
"{",
"}",
"for",
"line",
"in",
"f",
":",
"fields",
"=",
"line",
".",
"split",
"(",
"None",
",",
"5",
")",
"if",
"len",
"(",
"fields",
")",
">=",
"5",
":",
"yield",
"(",
"current_block",
".",
"pop",
"(",
")",
",",
"data",
")",
"current_block",
".",
"append",
"(",
"line",
")",
"else",
":",
"data",
"[",
"fields",
"[",
"0",
"]",
"]",
"=",
"int",
"(",
"fields",
"[",
"1",
"]",
")",
"*",
"1024",
"yield",
"(",
"current_block",
".",
"pop",
"(",
")",
",",
"data",
")",
"if",
"first_line",
":",
"# smaps file can be empty",
"for",
"header",
",",
"data",
"in",
"get_blocks",
"(",
")",
":",
"hfields",
"=",
"header",
".",
"split",
"(",
"None",
",",
"5",
")",
"try",
":",
"addr",
",",
"perms",
",",
"offset",
",",
"dev",
",",
"inode",
",",
"path",
"=",
"hfields",
"except",
"ValueError",
":",
"addr",
",",
"perms",
",",
"offset",
",",
"dev",
",",
"inode",
",",
"path",
"=",
"hfields",
"+",
"[",
"''",
"]",
"if",
"not",
"path",
":",
"path",
"=",
"'[anon]'",
"else",
":",
"path",
"=",
"path",
".",
"strip",
"(",
")",
"yield",
"(",
"addr",
",",
"perms",
",",
"path",
",",
"data",
"[",
"'Rss:'",
"]",
",",
"data",
"[",
"'Size:'",
"]",
",",
"data",
".",
"get",
"(",
"'Pss:'",
",",
"0",
")",
",",
"data",
"[",
"'Shared_Clean:'",
"]",
",",
"data",
"[",
"'Shared_Clean:'",
"]",
",",
"data",
"[",
"'Private_Clean:'",
"]",
",",
"data",
"[",
"'Private_Dirty:'",
"]",
",",
"data",
"[",
"'Referenced:'",
"]",
",",
"data",
"[",
"'Anonymous:'",
"]",
",",
"data",
"[",
"'Swap:'",
"]",
")",
"f",
".",
"close",
"(",
")",
"except",
"EnvironmentError",
":",
"# XXX - Can't use wrap_exceptions decorator as we're",
"# returning a generator; this probably needs some",
"# refactoring in order to avoid this code duplication.",
"if",
"f",
"is",
"not",
"None",
":",
"f",
".",
"close",
"(",
")",
"err",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"if",
"err",
".",
"errno",
"in",
"(",
"errno",
".",
"ENOENT",
",",
"errno",
".",
"ESRCH",
")",
":",
"raise",
"NoSuchProcess",
"(",
"self",
".",
"pid",
",",
"self",
".",
"_process_name",
")",
"if",
"err",
".",
"errno",
"in",
"(",
"errno",
".",
"EPERM",
",",
"errno",
".",
"EACCES",
")",
":",
"raise",
"AccessDenied",
"(",
"self",
".",
"pid",
",",
"self",
".",
"_process_name",
")",
"raise",
"except",
":",
"if",
"f",
"is",
"not",
"None",
":",
"f",
".",
"close",
"(",
")",
"raise"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Process.get_connections | Return connections opened by process as a list of namedtuples.
The kind parameter filters for connections that fit the following
criteria:
Kind Value Number of connections using
inet IPv4 and IPv6
inet4 IPv4
inet6 IPv6
tcp TCP
tcp4 TCP over IPv4
tcp6 TCP over IPv6
udp UDP
udp4 UDP over IPv4
udp6 UDP over IPv6
all the sum of all the possible families and protocols | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def get_connections(self, kind='inet'):
"""Return connections opened by process as a list of namedtuples.
The kind parameter filters for connections that fit the following
criteria:
Kind Value Number of connections using
inet IPv4 and IPv6
inet4 IPv4
inet6 IPv6
tcp TCP
tcp4 TCP over IPv4
tcp6 TCP over IPv6
udp UDP
udp4 UDP over IPv4
udp6 UDP over IPv6
all the sum of all the possible families and protocols
"""
# Note: in case of UNIX sockets we're only able to determine the
# local bound path while the remote endpoint is not retrievable:
# http://goo.gl/R3GHM
inodes = {}
# os.listdir() is gonna raise a lot of access denied
# exceptions in case of unprivileged user; that's fine:
# lsof does the same so it's unlikely that we can to better.
for fd in os.listdir("/proc/%s/fd" % self.pid):
try:
inode = os.readlink("/proc/%s/fd/%s" % (self.pid, fd))
except OSError:
continue
if inode.startswith('socket:['):
# the process is using a socket
inode = inode[8:][:-1]
inodes[inode] = fd
if not inodes:
# no connections for this process
return []
def process(file, family, type_):
retlist = []
try:
f = open(file, 'r')
except IOError:
# IPv6 not supported on this platform
err = sys.exc_info()[1]
if err.errno == errno.ENOENT and file.endswith('6'):
return []
else:
raise
try:
f.readline() # skip the first line
for line in f:
# IPv4 / IPv6
if family in (socket.AF_INET, socket.AF_INET6):
_, laddr, raddr, status, _, _, _, _, _, inode = \
line.split()[:10]
if inode in inodes:
laddr = self._decode_address(laddr, family)
raddr = self._decode_address(raddr, family)
if type_ == socket.SOCK_STREAM:
status = _TCP_STATES_TABLE[status]
else:
status = ""
fd = int(inodes[inode])
conn = nt_connection(fd, family, type_, laddr,
raddr, status)
retlist.append(conn)
elif family == socket.AF_UNIX:
tokens = line.split()
_, _, _, _, type_, _, inode = tokens[0:7]
if inode in inodes:
if len(tokens) == 8:
path = tokens[-1]
else:
path = ""
fd = int(inodes[inode])
type_ = int(type_)
conn = nt_connection(fd, family, type_, path,
None, "")
retlist.append(conn)
else:
raise ValueError(family)
return retlist
finally:
f.close()
tcp4 = ("tcp" , socket.AF_INET , socket.SOCK_STREAM)
tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
udp4 = ("udp" , socket.AF_INET , socket.SOCK_DGRAM)
udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
unix = ("unix", socket.AF_UNIX, None)
tmap = {
"all" : (tcp4, tcp6, udp4, udp6, unix),
"tcp" : (tcp4, tcp6),
"tcp4" : (tcp4,),
"tcp6" : (tcp6,),
"udp" : (udp4, udp6),
"udp4" : (udp4,),
"udp6" : (udp6,),
"unix" : (unix,),
"inet" : (tcp4, tcp6, udp4, udp6),
"inet4": (tcp4, udp4),
"inet6": (tcp6, udp6),
}
if kind not in tmap:
raise ValueError("invalid %r kind argument; choose between %s"
% (kind, ', '.join([repr(x) for x in tmap])))
ret = []
for f, family, type_ in tmap[kind]:
ret += process("/proc/net/%s" % f, family, type_)
# raise NSP if the process disappeared on us
os.stat('/proc/%s' % self.pid)
return ret | def get_connections(self, kind='inet'):
"""Return connections opened by process as a list of namedtuples.
The kind parameter filters for connections that fit the following
criteria:
Kind Value Number of connections using
inet IPv4 and IPv6
inet4 IPv4
inet6 IPv6
tcp TCP
tcp4 TCP over IPv4
tcp6 TCP over IPv6
udp UDP
udp4 UDP over IPv4
udp6 UDP over IPv6
all the sum of all the possible families and protocols
"""
# Note: in case of UNIX sockets we're only able to determine the
# local bound path while the remote endpoint is not retrievable:
# http://goo.gl/R3GHM
inodes = {}
# os.listdir() is gonna raise a lot of access denied
# exceptions in case of unprivileged user; that's fine:
# lsof does the same so it's unlikely that we can to better.
for fd in os.listdir("/proc/%s/fd" % self.pid):
try:
inode = os.readlink("/proc/%s/fd/%s" % (self.pid, fd))
except OSError:
continue
if inode.startswith('socket:['):
# the process is using a socket
inode = inode[8:][:-1]
inodes[inode] = fd
if not inodes:
# no connections for this process
return []
def process(file, family, type_):
retlist = []
try:
f = open(file, 'r')
except IOError:
# IPv6 not supported on this platform
err = sys.exc_info()[1]
if err.errno == errno.ENOENT and file.endswith('6'):
return []
else:
raise
try:
f.readline() # skip the first line
for line in f:
# IPv4 / IPv6
if family in (socket.AF_INET, socket.AF_INET6):
_, laddr, raddr, status, _, _, _, _, _, inode = \
line.split()[:10]
if inode in inodes:
laddr = self._decode_address(laddr, family)
raddr = self._decode_address(raddr, family)
if type_ == socket.SOCK_STREAM:
status = _TCP_STATES_TABLE[status]
else:
status = ""
fd = int(inodes[inode])
conn = nt_connection(fd, family, type_, laddr,
raddr, status)
retlist.append(conn)
elif family == socket.AF_UNIX:
tokens = line.split()
_, _, _, _, type_, _, inode = tokens[0:7]
if inode in inodes:
if len(tokens) == 8:
path = tokens[-1]
else:
path = ""
fd = int(inodes[inode])
type_ = int(type_)
conn = nt_connection(fd, family, type_, path,
None, "")
retlist.append(conn)
else:
raise ValueError(family)
return retlist
finally:
f.close()
tcp4 = ("tcp" , socket.AF_INET , socket.SOCK_STREAM)
tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
udp4 = ("udp" , socket.AF_INET , socket.SOCK_DGRAM)
udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
unix = ("unix", socket.AF_UNIX, None)
tmap = {
"all" : (tcp4, tcp6, udp4, udp6, unix),
"tcp" : (tcp4, tcp6),
"tcp4" : (tcp4,),
"tcp6" : (tcp6,),
"udp" : (udp4, udp6),
"udp4" : (udp4,),
"udp6" : (udp6,),
"unix" : (unix,),
"inet" : (tcp4, tcp6, udp4, udp6),
"inet4": (tcp4, udp4),
"inet6": (tcp6, udp6),
}
if kind not in tmap:
raise ValueError("invalid %r kind argument; choose between %s"
% (kind, ', '.join([repr(x) for x in tmap])))
ret = []
for f, family, type_ in tmap[kind]:
ret += process("/proc/net/%s" % f, family, type_)
# raise NSP if the process disappeared on us
os.stat('/proc/%s' % self.pid)
return ret | [
"Return",
"connections",
"opened",
"by",
"process",
"as",
"a",
"list",
"of",
"namedtuples",
".",
"The",
"kind",
"parameter",
"filters",
"for",
"connections",
"that",
"fit",
"the",
"following",
"criteria",
":"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L804-L918 | [
"def",
"get_connections",
"(",
"self",
",",
"kind",
"=",
"'inet'",
")",
":",
"# Note: in case of UNIX sockets we're only able to determine the",
"# local bound path while the remote endpoint is not retrievable:",
"# http://goo.gl/R3GHM",
"inodes",
"=",
"{",
"}",
"# os.listdir() is gonna raise a lot of access denied",
"# exceptions in case of unprivileged user; that's fine:",
"# lsof does the same so it's unlikely that we can to better.",
"for",
"fd",
"in",
"os",
".",
"listdir",
"(",
"\"/proc/%s/fd\"",
"%",
"self",
".",
"pid",
")",
":",
"try",
":",
"inode",
"=",
"os",
".",
"readlink",
"(",
"\"/proc/%s/fd/%s\"",
"%",
"(",
"self",
".",
"pid",
",",
"fd",
")",
")",
"except",
"OSError",
":",
"continue",
"if",
"inode",
".",
"startswith",
"(",
"'socket:['",
")",
":",
"# the process is using a socket",
"inode",
"=",
"inode",
"[",
"8",
":",
"]",
"[",
":",
"-",
"1",
"]",
"inodes",
"[",
"inode",
"]",
"=",
"fd",
"if",
"not",
"inodes",
":",
"# no connections for this process",
"return",
"[",
"]",
"def",
"process",
"(",
"file",
",",
"family",
",",
"type_",
")",
":",
"retlist",
"=",
"[",
"]",
"try",
":",
"f",
"=",
"open",
"(",
"file",
",",
"'r'",
")",
"except",
"IOError",
":",
"# IPv6 not supported on this platform",
"err",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"if",
"err",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
"and",
"file",
".",
"endswith",
"(",
"'6'",
")",
":",
"return",
"[",
"]",
"else",
":",
"raise",
"try",
":",
"f",
".",
"readline",
"(",
")",
"# skip the first line",
"for",
"line",
"in",
"f",
":",
"# IPv4 / IPv6",
"if",
"family",
"in",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"AF_INET6",
")",
":",
"_",
",",
"laddr",
",",
"raddr",
",",
"status",
",",
"_",
",",
"_",
",",
"_",
",",
"_",
",",
"_",
",",
"inode",
"=",
"line",
".",
"split",
"(",
")",
"[",
":",
"10",
"]",
"if",
"inode",
"in",
"inodes",
":",
"laddr",
"=",
"self",
".",
"_decode_address",
"(",
"laddr",
",",
"family",
")",
"raddr",
"=",
"self",
".",
"_decode_address",
"(",
"raddr",
",",
"family",
")",
"if",
"type_",
"==",
"socket",
".",
"SOCK_STREAM",
":",
"status",
"=",
"_TCP_STATES_TABLE",
"[",
"status",
"]",
"else",
":",
"status",
"=",
"\"\"",
"fd",
"=",
"int",
"(",
"inodes",
"[",
"inode",
"]",
")",
"conn",
"=",
"nt_connection",
"(",
"fd",
",",
"family",
",",
"type_",
",",
"laddr",
",",
"raddr",
",",
"status",
")",
"retlist",
".",
"append",
"(",
"conn",
")",
"elif",
"family",
"==",
"socket",
".",
"AF_UNIX",
":",
"tokens",
"=",
"line",
".",
"split",
"(",
")",
"_",
",",
"_",
",",
"_",
",",
"_",
",",
"type_",
",",
"_",
",",
"inode",
"=",
"tokens",
"[",
"0",
":",
"7",
"]",
"if",
"inode",
"in",
"inodes",
":",
"if",
"len",
"(",
"tokens",
")",
"==",
"8",
":",
"path",
"=",
"tokens",
"[",
"-",
"1",
"]",
"else",
":",
"path",
"=",
"\"\"",
"fd",
"=",
"int",
"(",
"inodes",
"[",
"inode",
"]",
")",
"type_",
"=",
"int",
"(",
"type_",
")",
"conn",
"=",
"nt_connection",
"(",
"fd",
",",
"family",
",",
"type_",
",",
"path",
",",
"None",
",",
"\"\"",
")",
"retlist",
".",
"append",
"(",
"conn",
")",
"else",
":",
"raise",
"ValueError",
"(",
"family",
")",
"return",
"retlist",
"finally",
":",
"f",
".",
"close",
"(",
")",
"tcp4",
"=",
"(",
"\"tcp\"",
",",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"tcp6",
"=",
"(",
"\"tcp6\"",
",",
"socket",
".",
"AF_INET6",
",",
"socket",
".",
"SOCK_STREAM",
")",
"udp4",
"=",
"(",
"\"udp\"",
",",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"udp6",
"=",
"(",
"\"udp6\"",
",",
"socket",
".",
"AF_INET6",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"unix",
"=",
"(",
"\"unix\"",
",",
"socket",
".",
"AF_UNIX",
",",
"None",
")",
"tmap",
"=",
"{",
"\"all\"",
":",
"(",
"tcp4",
",",
"tcp6",
",",
"udp4",
",",
"udp6",
",",
"unix",
")",
",",
"\"tcp\"",
":",
"(",
"tcp4",
",",
"tcp6",
")",
",",
"\"tcp4\"",
":",
"(",
"tcp4",
",",
")",
",",
"\"tcp6\"",
":",
"(",
"tcp6",
",",
")",
",",
"\"udp\"",
":",
"(",
"udp4",
",",
"udp6",
")",
",",
"\"udp4\"",
":",
"(",
"udp4",
",",
")",
",",
"\"udp6\"",
":",
"(",
"udp6",
",",
")",
",",
"\"unix\"",
":",
"(",
"unix",
",",
")",
",",
"\"inet\"",
":",
"(",
"tcp4",
",",
"tcp6",
",",
"udp4",
",",
"udp6",
")",
",",
"\"inet4\"",
":",
"(",
"tcp4",
",",
"udp4",
")",
",",
"\"inet6\"",
":",
"(",
"tcp6",
",",
"udp6",
")",
",",
"}",
"if",
"kind",
"not",
"in",
"tmap",
":",
"raise",
"ValueError",
"(",
"\"invalid %r kind argument; choose between %s\"",
"%",
"(",
"kind",
",",
"', '",
".",
"join",
"(",
"[",
"repr",
"(",
"x",
")",
"for",
"x",
"in",
"tmap",
"]",
")",
")",
")",
"ret",
"=",
"[",
"]",
"for",
"f",
",",
"family",
",",
"type_",
"in",
"tmap",
"[",
"kind",
"]",
":",
"ret",
"+=",
"process",
"(",
"\"/proc/net/%s\"",
"%",
"f",
",",
"family",
",",
"type_",
")",
"# raise NSP if the process disappeared on us",
"os",
".",
"stat",
"(",
"'/proc/%s'",
"%",
"self",
".",
"pid",
")",
"return",
"ret"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Process._decode_address | Accept an "ip:port" address as displayed in /proc/net/*
and convert it into a human readable form, like:
"0500000A:0016" -> ("10.0.0.5", 22)
"0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)
The IP address portion is a little or big endian four-byte
hexadecimal number; that is, the least significant byte is listed
first, so we need to reverse the order of the bytes to convert it
to an IP address.
The port is represented as a two-byte hexadecimal number.
Reference:
http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html | environment/lib/python2.7/site-packages/psutil/_pslinux.py | def _decode_address(addr, family):
"""Accept an "ip:port" address as displayed in /proc/net/*
and convert it into a human readable form, like:
"0500000A:0016" -> ("10.0.0.5", 22)
"0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)
The IP address portion is a little or big endian four-byte
hexadecimal number; that is, the least significant byte is listed
first, so we need to reverse the order of the bytes to convert it
to an IP address.
The port is represented as a two-byte hexadecimal number.
Reference:
http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
"""
ip, port = addr.split(':')
port = int(port, 16)
if PY3:
ip = ip.encode('ascii')
# this usually refers to a local socket in listen mode with
# no end-points connected
if not port:
return ()
if family == socket.AF_INET:
# see: http://code.google.com/p/psutil/issues/detail?id=201
if sys.byteorder == 'little':
ip = socket.inet_ntop(family, base64.b16decode(ip)[::-1])
else:
ip = socket.inet_ntop(family, base64.b16decode(ip))
else: # IPv6
# old version - let's keep it, just in case...
#ip = ip.decode('hex')
#return socket.inet_ntop(socket.AF_INET6,
# ''.join(ip[i:i+4][::-1] for i in xrange(0, 16, 4)))
ip = base64.b16decode(ip)
# see: http://code.google.com/p/psutil/issues/detail?id=201
if sys.byteorder == 'little':
ip = socket.inet_ntop(socket.AF_INET6,
struct.pack('>4I', *struct.unpack('<4I', ip)))
else:
ip = socket.inet_ntop(socket.AF_INET6,
struct.pack('<4I', *struct.unpack('<4I', ip)))
return (ip, port) | def _decode_address(addr, family):
"""Accept an "ip:port" address as displayed in /proc/net/*
and convert it into a human readable form, like:
"0500000A:0016" -> ("10.0.0.5", 22)
"0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)
The IP address portion is a little or big endian four-byte
hexadecimal number; that is, the least significant byte is listed
first, so we need to reverse the order of the bytes to convert it
to an IP address.
The port is represented as a two-byte hexadecimal number.
Reference:
http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
"""
ip, port = addr.split(':')
port = int(port, 16)
if PY3:
ip = ip.encode('ascii')
# this usually refers to a local socket in listen mode with
# no end-points connected
if not port:
return ()
if family == socket.AF_INET:
# see: http://code.google.com/p/psutil/issues/detail?id=201
if sys.byteorder == 'little':
ip = socket.inet_ntop(family, base64.b16decode(ip)[::-1])
else:
ip = socket.inet_ntop(family, base64.b16decode(ip))
else: # IPv6
# old version - let's keep it, just in case...
#ip = ip.decode('hex')
#return socket.inet_ntop(socket.AF_INET6,
# ''.join(ip[i:i+4][::-1] for i in xrange(0, 16, 4)))
ip = base64.b16decode(ip)
# see: http://code.google.com/p/psutil/issues/detail?id=201
if sys.byteorder == 'little':
ip = socket.inet_ntop(socket.AF_INET6,
struct.pack('>4I', *struct.unpack('<4I', ip)))
else:
ip = socket.inet_ntop(socket.AF_INET6,
struct.pack('<4I', *struct.unpack('<4I', ip)))
return (ip, port) | [
"Accept",
"an",
"ip",
":",
"port",
"address",
"as",
"displayed",
"in",
"/",
"proc",
"/",
"net",
"/",
"*",
"and",
"convert",
"it",
"into",
"a",
"human",
"readable",
"form",
"like",
":"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_pslinux.py#L968-L1011 | [
"def",
"_decode_address",
"(",
"addr",
",",
"family",
")",
":",
"ip",
",",
"port",
"=",
"addr",
".",
"split",
"(",
"':'",
")",
"port",
"=",
"int",
"(",
"port",
",",
"16",
")",
"if",
"PY3",
":",
"ip",
"=",
"ip",
".",
"encode",
"(",
"'ascii'",
")",
"# this usually refers to a local socket in listen mode with",
"# no end-points connected",
"if",
"not",
"port",
":",
"return",
"(",
")",
"if",
"family",
"==",
"socket",
".",
"AF_INET",
":",
"# see: http://code.google.com/p/psutil/issues/detail?id=201",
"if",
"sys",
".",
"byteorder",
"==",
"'little'",
":",
"ip",
"=",
"socket",
".",
"inet_ntop",
"(",
"family",
",",
"base64",
".",
"b16decode",
"(",
"ip",
")",
"[",
":",
":",
"-",
"1",
"]",
")",
"else",
":",
"ip",
"=",
"socket",
".",
"inet_ntop",
"(",
"family",
",",
"base64",
".",
"b16decode",
"(",
"ip",
")",
")",
"else",
":",
"# IPv6",
"# old version - let's keep it, just in case...",
"#ip = ip.decode('hex')",
"#return socket.inet_ntop(socket.AF_INET6,",
"# ''.join(ip[i:i+4][::-1] for i in xrange(0, 16, 4)))",
"ip",
"=",
"base64",
".",
"b16decode",
"(",
"ip",
")",
"# see: http://code.google.com/p/psutil/issues/detail?id=201",
"if",
"sys",
".",
"byteorder",
"==",
"'little'",
":",
"ip",
"=",
"socket",
".",
"inet_ntop",
"(",
"socket",
".",
"AF_INET6",
",",
"struct",
".",
"pack",
"(",
"'>4I'",
",",
"*",
"struct",
".",
"unpack",
"(",
"'<4I'",
",",
"ip",
")",
")",
")",
"else",
":",
"ip",
"=",
"socket",
".",
"inet_ntop",
"(",
"socket",
".",
"AF_INET6",
",",
"struct",
".",
"pack",
"(",
"'<4I'",
",",
"*",
"struct",
".",
"unpack",
"(",
"'<4I'",
",",
"ip",
")",
")",
")",
"return",
"(",
"ip",
",",
"port",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | nice_pair | Make a nice string representation of a pair of numbers.
If the numbers are equal, just return the number, otherwise return the pair
with a dash between them, indicating the range. | virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py | def nice_pair(pair):
"""Make a nice string representation of a pair of numbers.
If the numbers are equal, just return the number, otherwise return the pair
with a dash between them, indicating the range.
"""
start, end = pair
if start == end:
return "%d" % start
else:
return "%d-%d" % (start, end) | def nice_pair(pair):
"""Make a nice string representation of a pair of numbers.
If the numbers are equal, just return the number, otherwise return the pair
with a dash between them, indicating the range.
"""
start, end = pair
if start == end:
return "%d" % start
else:
return "%d-%d" % (start, end) | [
"Make",
"a",
"nice",
"string",
"representation",
"of",
"a",
"pair",
"of",
"numbers",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py#L12-L23 | [
"def",
"nice_pair",
"(",
"pair",
")",
":",
"start",
",",
"end",
"=",
"pair",
"if",
"start",
"==",
"end",
":",
"return",
"\"%d\"",
"%",
"start",
"else",
":",
"return",
"\"%d-%d\"",
"%",
"(",
"start",
",",
"end",
")"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | format_lines | Nicely format a list of line numbers.
Format a list of line numbers for printing by coalescing groups of lines as
long as the lines represent consecutive statements. This will coalesce
even if there are gaps between statements.
For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and
`lines` is [1,2,5,10,11,13,14] then the result will be "1-2, 5-11, 13-14". | virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py | def format_lines(statements, lines):
"""Nicely format a list of line numbers.
Format a list of line numbers for printing by coalescing groups of lines as
long as the lines represent consecutive statements. This will coalesce
even if there are gaps between statements.
For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and
`lines` is [1,2,5,10,11,13,14] then the result will be "1-2, 5-11, 13-14".
"""
pairs = []
i = 0
j = 0
start = None
statements = sorted(statements)
lines = sorted(lines)
while i < len(statements) and j < len(lines):
if statements[i] == lines[j]:
if start == None:
start = lines[j]
end = lines[j]
j += 1
elif start:
pairs.append((start, end))
start = None
i += 1
if start:
pairs.append((start, end))
ret = ', '.join(map(nice_pair, pairs))
return ret | def format_lines(statements, lines):
"""Nicely format a list of line numbers.
Format a list of line numbers for printing by coalescing groups of lines as
long as the lines represent consecutive statements. This will coalesce
even if there are gaps between statements.
For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and
`lines` is [1,2,5,10,11,13,14] then the result will be "1-2, 5-11, 13-14".
"""
pairs = []
i = 0
j = 0
start = None
statements = sorted(statements)
lines = sorted(lines)
while i < len(statements) and j < len(lines):
if statements[i] == lines[j]:
if start == None:
start = lines[j]
end = lines[j]
j += 1
elif start:
pairs.append((start, end))
start = None
i += 1
if start:
pairs.append((start, end))
ret = ', '.join(map(nice_pair, pairs))
return ret | [
"Nicely",
"format",
"a",
"list",
"of",
"line",
"numbers",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py#L26-L56 | [
"def",
"format_lines",
"(",
"statements",
",",
"lines",
")",
":",
"pairs",
"=",
"[",
"]",
"i",
"=",
"0",
"j",
"=",
"0",
"start",
"=",
"None",
"statements",
"=",
"sorted",
"(",
"statements",
")",
"lines",
"=",
"sorted",
"(",
"lines",
")",
"while",
"i",
"<",
"len",
"(",
"statements",
")",
"and",
"j",
"<",
"len",
"(",
"lines",
")",
":",
"if",
"statements",
"[",
"i",
"]",
"==",
"lines",
"[",
"j",
"]",
":",
"if",
"start",
"==",
"None",
":",
"start",
"=",
"lines",
"[",
"j",
"]",
"end",
"=",
"lines",
"[",
"j",
"]",
"j",
"+=",
"1",
"elif",
"start",
":",
"pairs",
".",
"append",
"(",
"(",
"start",
",",
"end",
")",
")",
"start",
"=",
"None",
"i",
"+=",
"1",
"if",
"start",
":",
"pairs",
".",
"append",
"(",
"(",
"start",
",",
"end",
")",
")",
"ret",
"=",
"', '",
".",
"join",
"(",
"map",
"(",
"nice_pair",
",",
"pairs",
")",
")",
"return",
"ret"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | short_stack | Return a string summarizing the call stack. | virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py | def short_stack():
"""Return a string summarizing the call stack."""
stack = inspect.stack()[:0:-1]
return "\n".join(["%30s : %s @%d" % (t[3],t[1],t[2]) for t in stack]) | def short_stack():
"""Return a string summarizing the call stack."""
stack = inspect.stack()[:0:-1]
return "\n".join(["%30s : %s @%d" % (t[3],t[1],t[2]) for t in stack]) | [
"Return",
"a",
"string",
"summarizing",
"the",
"call",
"stack",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py#L59-L62 | [
"def",
"short_stack",
"(",
")",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
":",
"0",
":",
"-",
"1",
"]",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"\"%30s : %s @%d\"",
"%",
"(",
"t",
"[",
"3",
"]",
",",
"t",
"[",
"1",
"]",
",",
"t",
"[",
"2",
"]",
")",
"for",
"t",
"in",
"stack",
"]",
")"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | expensive | A decorator to cache the result of an expensive operation.
Only applies to methods with no arguments. | virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py | def expensive(fn):
"""A decorator to cache the result of an expensive operation.
Only applies to methods with no arguments.
"""
attr = "_cache_" + fn.__name__
def _wrapped(self):
"""Inner fn that checks the cache."""
if not hasattr(self, attr):
setattr(self, attr, fn(self))
return getattr(self, attr)
return _wrapped | def expensive(fn):
"""A decorator to cache the result of an expensive operation.
Only applies to methods with no arguments.
"""
attr = "_cache_" + fn.__name__
def _wrapped(self):
"""Inner fn that checks the cache."""
if not hasattr(self, attr):
setattr(self, attr, fn(self))
return getattr(self, attr)
return _wrapped | [
"A",
"decorator",
"to",
"cache",
"the",
"result",
"of",
"an",
"expensive",
"operation",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py#L65-L77 | [
"def",
"expensive",
"(",
"fn",
")",
":",
"attr",
"=",
"\"_cache_\"",
"+",
"fn",
".",
"__name__",
"def",
"_wrapped",
"(",
"self",
")",
":",
"\"\"\"Inner fn that checks the cache.\"\"\"",
"if",
"not",
"hasattr",
"(",
"self",
",",
"attr",
")",
":",
"setattr",
"(",
"self",
",",
"attr",
",",
"fn",
"(",
"self",
")",
")",
"return",
"getattr",
"(",
"self",
",",
"attr",
")",
"return",
"_wrapped"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | join_regex | Combine a list of regexes into one that matches any of them. | virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py | def join_regex(regexes):
"""Combine a list of regexes into one that matches any of them."""
if len(regexes) > 1:
return "|".join(["(%s)" % r for r in regexes])
elif regexes:
return regexes[0]
else:
return "" | def join_regex(regexes):
"""Combine a list of regexes into one that matches any of them."""
if len(regexes) > 1:
return "|".join(["(%s)" % r for r in regexes])
elif regexes:
return regexes[0]
else:
return "" | [
"Combine",
"a",
"list",
"of",
"regexes",
"into",
"one",
"that",
"matches",
"any",
"of",
"them",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py#L88-L95 | [
"def",
"join_regex",
"(",
"regexes",
")",
":",
"if",
"len",
"(",
"regexes",
")",
">",
"1",
":",
"return",
"\"|\"",
".",
"join",
"(",
"[",
"\"(%s)\"",
"%",
"r",
"for",
"r",
"in",
"regexes",
"]",
")",
"elif",
"regexes",
":",
"return",
"regexes",
"[",
"0",
"]",
"else",
":",
"return",
"\"\""
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | file_be_gone | Remove a file, and don't get annoyed if it doesn't exist. | virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py | def file_be_gone(path):
"""Remove a file, and don't get annoyed if it doesn't exist."""
try:
os.remove(path)
except OSError:
_, e, _ = sys.exc_info()
if e.errno != errno.ENOENT:
raise | def file_be_gone(path):
"""Remove a file, and don't get annoyed if it doesn't exist."""
try:
os.remove(path)
except OSError:
_, e, _ = sys.exc_info()
if e.errno != errno.ENOENT:
raise | [
"Remove",
"a",
"file",
"and",
"don",
"t",
"get",
"annoyed",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py#L98-L105 | [
"def",
"file_be_gone",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"path",
")",
"except",
"OSError",
":",
"_",
",",
"e",
",",
"_",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | Hasher.update | Add `v` to the hash, recursively if needed. | virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py | def update(self, v):
"""Add `v` to the hash, recursively if needed."""
self.md5.update(to_bytes(str(type(v))))
if isinstance(v, string_class):
self.md5.update(to_bytes(v))
elif v is None:
pass
elif isinstance(v, (int, float)):
self.md5.update(to_bytes(str(v)))
elif isinstance(v, (tuple, list)):
for e in v:
self.update(e)
elif isinstance(v, dict):
keys = v.keys()
for k in sorted(keys):
self.update(k)
self.update(v[k])
else:
for k in dir(v):
if k.startswith('__'):
continue
a = getattr(v, k)
if inspect.isroutine(a):
continue
self.update(k)
self.update(a) | def update(self, v):
"""Add `v` to the hash, recursively if needed."""
self.md5.update(to_bytes(str(type(v))))
if isinstance(v, string_class):
self.md5.update(to_bytes(v))
elif v is None:
pass
elif isinstance(v, (int, float)):
self.md5.update(to_bytes(str(v)))
elif isinstance(v, (tuple, list)):
for e in v:
self.update(e)
elif isinstance(v, dict):
keys = v.keys()
for k in sorted(keys):
self.update(k)
self.update(v[k])
else:
for k in dir(v):
if k.startswith('__'):
continue
a = getattr(v, k)
if inspect.isroutine(a):
continue
self.update(k)
self.update(a) | [
"Add",
"v",
"to",
"the",
"hash",
"recursively",
"if",
"needed",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/misc.py#L113-L138 | [
"def",
"update",
"(",
"self",
",",
"v",
")",
":",
"self",
".",
"md5",
".",
"update",
"(",
"to_bytes",
"(",
"str",
"(",
"type",
"(",
"v",
")",
")",
")",
")",
"if",
"isinstance",
"(",
"v",
",",
"string_class",
")",
":",
"self",
".",
"md5",
".",
"update",
"(",
"to_bytes",
"(",
"v",
")",
")",
"elif",
"v",
"is",
"None",
":",
"pass",
"elif",
"isinstance",
"(",
"v",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"self",
".",
"md5",
".",
"update",
"(",
"to_bytes",
"(",
"str",
"(",
"v",
")",
")",
")",
"elif",
"isinstance",
"(",
"v",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"for",
"e",
"in",
"v",
":",
"self",
".",
"update",
"(",
"e",
")",
"elif",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"keys",
"=",
"v",
".",
"keys",
"(",
")",
"for",
"k",
"in",
"sorted",
"(",
"keys",
")",
":",
"self",
".",
"update",
"(",
"k",
")",
"self",
".",
"update",
"(",
"v",
"[",
"k",
"]",
")",
"else",
":",
"for",
"k",
"in",
"dir",
"(",
"v",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"'__'",
")",
":",
"continue",
"a",
"=",
"getattr",
"(",
"v",
",",
"k",
")",
"if",
"inspect",
".",
"isroutine",
"(",
"a",
")",
":",
"continue",
"self",
".",
"update",
"(",
"k",
")",
"self",
".",
"update",
"(",
"a",
")"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | ClusterManager.update_profiles | List all profiles in the ipython_dir and cwd. | environment/lib/python2.7/site-packages/IPython/frontend/html/notebook/clustermanager.py | def update_profiles(self):
"""List all profiles in the ipython_dir and cwd.
"""
for path in [get_ipython_dir(), os.getcwdu()]:
for profile in list_profiles_in(path):
pd = self.get_profile_dir(profile, path)
if profile not in self.profiles:
self.log.debug("Adding cluster profile '%s'" % profile)
self.profiles[profile] = {
'profile': profile,
'profile_dir': pd,
'status': 'stopped'
} | def update_profiles(self):
"""List all profiles in the ipython_dir and cwd.
"""
for path in [get_ipython_dir(), os.getcwdu()]:
for profile in list_profiles_in(path):
pd = self.get_profile_dir(profile, path)
if profile not in self.profiles:
self.log.debug("Adding cluster profile '%s'" % profile)
self.profiles[profile] = {
'profile': profile,
'profile_dir': pd,
'status': 'stopped'
} | [
"List",
"all",
"profiles",
"in",
"the",
"ipython_dir",
"and",
"cwd",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/html/notebook/clustermanager.py#L76-L88 | [
"def",
"update_profiles",
"(",
"self",
")",
":",
"for",
"path",
"in",
"[",
"get_ipython_dir",
"(",
")",
",",
"os",
".",
"getcwdu",
"(",
")",
"]",
":",
"for",
"profile",
"in",
"list_profiles_in",
"(",
"path",
")",
":",
"pd",
"=",
"self",
".",
"get_profile_dir",
"(",
"profile",
",",
"path",
")",
"if",
"profile",
"not",
"in",
"self",
".",
"profiles",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Adding cluster profile '%s'\"",
"%",
"profile",
")",
"self",
".",
"profiles",
"[",
"profile",
"]",
"=",
"{",
"'profile'",
":",
"profile",
",",
"'profile_dir'",
":",
"pd",
",",
"'status'",
":",
"'stopped'",
"}"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ClusterManager.start_cluster | Start a cluster for a given profile. | environment/lib/python2.7/site-packages/IPython/frontend/html/notebook/clustermanager.py | def start_cluster(self, profile, n=None):
"""Start a cluster for a given profile."""
self.check_profile(profile)
data = self.profiles[profile]
if data['status'] == 'running':
raise web.HTTPError(409, u'cluster already running')
cl, esl, default_n = self.build_launchers(data['profile_dir'])
n = n if n is not None else default_n
def clean_data():
data.pop('controller_launcher',None)
data.pop('engine_set_launcher',None)
data.pop('n',None)
data['status'] = 'stopped'
def engines_stopped(r):
self.log.debug('Engines stopped')
if cl.running:
cl.stop()
clean_data()
esl.on_stop(engines_stopped)
def controller_stopped(r):
self.log.debug('Controller stopped')
if esl.running:
esl.stop()
clean_data()
cl.on_stop(controller_stopped)
dc = ioloop.DelayedCallback(lambda: cl.start(), 0, self.loop)
dc.start()
dc = ioloop.DelayedCallback(lambda: esl.start(n), 1000*self.delay, self.loop)
dc.start()
self.log.debug('Cluster started')
data['controller_launcher'] = cl
data['engine_set_launcher'] = esl
data['n'] = n
data['status'] = 'running'
return self.profile_info(profile) | def start_cluster(self, profile, n=None):
"""Start a cluster for a given profile."""
self.check_profile(profile)
data = self.profiles[profile]
if data['status'] == 'running':
raise web.HTTPError(409, u'cluster already running')
cl, esl, default_n = self.build_launchers(data['profile_dir'])
n = n if n is not None else default_n
def clean_data():
data.pop('controller_launcher',None)
data.pop('engine_set_launcher',None)
data.pop('n',None)
data['status'] = 'stopped'
def engines_stopped(r):
self.log.debug('Engines stopped')
if cl.running:
cl.stop()
clean_data()
esl.on_stop(engines_stopped)
def controller_stopped(r):
self.log.debug('Controller stopped')
if esl.running:
esl.stop()
clean_data()
cl.on_stop(controller_stopped)
dc = ioloop.DelayedCallback(lambda: cl.start(), 0, self.loop)
dc.start()
dc = ioloop.DelayedCallback(lambda: esl.start(n), 1000*self.delay, self.loop)
dc.start()
self.log.debug('Cluster started')
data['controller_launcher'] = cl
data['engine_set_launcher'] = esl
data['n'] = n
data['status'] = 'running'
return self.profile_info(profile) | [
"Start",
"a",
"cluster",
"for",
"a",
"given",
"profile",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/html/notebook/clustermanager.py#L110-L146 | [
"def",
"start_cluster",
"(",
"self",
",",
"profile",
",",
"n",
"=",
"None",
")",
":",
"self",
".",
"check_profile",
"(",
"profile",
")",
"data",
"=",
"self",
".",
"profiles",
"[",
"profile",
"]",
"if",
"data",
"[",
"'status'",
"]",
"==",
"'running'",
":",
"raise",
"web",
".",
"HTTPError",
"(",
"409",
",",
"u'cluster already running'",
")",
"cl",
",",
"esl",
",",
"default_n",
"=",
"self",
".",
"build_launchers",
"(",
"data",
"[",
"'profile_dir'",
"]",
")",
"n",
"=",
"n",
"if",
"n",
"is",
"not",
"None",
"else",
"default_n",
"def",
"clean_data",
"(",
")",
":",
"data",
".",
"pop",
"(",
"'controller_launcher'",
",",
"None",
")",
"data",
".",
"pop",
"(",
"'engine_set_launcher'",
",",
"None",
")",
"data",
".",
"pop",
"(",
"'n'",
",",
"None",
")",
"data",
"[",
"'status'",
"]",
"=",
"'stopped'",
"def",
"engines_stopped",
"(",
"r",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Engines stopped'",
")",
"if",
"cl",
".",
"running",
":",
"cl",
".",
"stop",
"(",
")",
"clean_data",
"(",
")",
"esl",
".",
"on_stop",
"(",
"engines_stopped",
")",
"def",
"controller_stopped",
"(",
"r",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Controller stopped'",
")",
"if",
"esl",
".",
"running",
":",
"esl",
".",
"stop",
"(",
")",
"clean_data",
"(",
")",
"cl",
".",
"on_stop",
"(",
"controller_stopped",
")",
"dc",
"=",
"ioloop",
".",
"DelayedCallback",
"(",
"lambda",
":",
"cl",
".",
"start",
"(",
")",
",",
"0",
",",
"self",
".",
"loop",
")",
"dc",
".",
"start",
"(",
")",
"dc",
"=",
"ioloop",
".",
"DelayedCallback",
"(",
"lambda",
":",
"esl",
".",
"start",
"(",
"n",
")",
",",
"1000",
"*",
"self",
".",
"delay",
",",
"self",
".",
"loop",
")",
"dc",
".",
"start",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Cluster started'",
")",
"data",
"[",
"'controller_launcher'",
"]",
"=",
"cl",
"data",
"[",
"'engine_set_launcher'",
"]",
"=",
"esl",
"data",
"[",
"'n'",
"]",
"=",
"n",
"data",
"[",
"'status'",
"]",
"=",
"'running'",
"return",
"self",
".",
"profile_info",
"(",
"profile",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ClusterManager.stop_cluster | Stop a cluster for a given profile. | environment/lib/python2.7/site-packages/IPython/frontend/html/notebook/clustermanager.py | def stop_cluster(self, profile):
"""Stop a cluster for a given profile."""
self.check_profile(profile)
data = self.profiles[profile]
if data['status'] == 'stopped':
raise web.HTTPError(409, u'cluster not running')
data = self.profiles[profile]
cl = data['controller_launcher']
esl = data['engine_set_launcher']
if cl.running:
cl.stop()
if esl.running:
esl.stop()
# Return a temp info dict, the real one is updated in the on_stop
# logic above.
result = {
'profile': data['profile'],
'profile_dir': data['profile_dir'],
'status': 'stopped'
}
return result | def stop_cluster(self, profile):
"""Stop a cluster for a given profile."""
self.check_profile(profile)
data = self.profiles[profile]
if data['status'] == 'stopped':
raise web.HTTPError(409, u'cluster not running')
data = self.profiles[profile]
cl = data['controller_launcher']
esl = data['engine_set_launcher']
if cl.running:
cl.stop()
if esl.running:
esl.stop()
# Return a temp info dict, the real one is updated in the on_stop
# logic above.
result = {
'profile': data['profile'],
'profile_dir': data['profile_dir'],
'status': 'stopped'
}
return result | [
"Stop",
"a",
"cluster",
"for",
"a",
"given",
"profile",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/html/notebook/clustermanager.py#L148-L168 | [
"def",
"stop_cluster",
"(",
"self",
",",
"profile",
")",
":",
"self",
".",
"check_profile",
"(",
"profile",
")",
"data",
"=",
"self",
".",
"profiles",
"[",
"profile",
"]",
"if",
"data",
"[",
"'status'",
"]",
"==",
"'stopped'",
":",
"raise",
"web",
".",
"HTTPError",
"(",
"409",
",",
"u'cluster not running'",
")",
"data",
"=",
"self",
".",
"profiles",
"[",
"profile",
"]",
"cl",
"=",
"data",
"[",
"'controller_launcher'",
"]",
"esl",
"=",
"data",
"[",
"'engine_set_launcher'",
"]",
"if",
"cl",
".",
"running",
":",
"cl",
".",
"stop",
"(",
")",
"if",
"esl",
".",
"running",
":",
"esl",
".",
"stop",
"(",
")",
"# Return a temp info dict, the real one is updated in the on_stop",
"# logic above.",
"result",
"=",
"{",
"'profile'",
":",
"data",
"[",
"'profile'",
"]",
",",
"'profile_dir'",
":",
"data",
"[",
"'profile_dir'",
"]",
",",
"'status'",
":",
"'stopped'",
"}",
"return",
"result"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | RegistrationFactory._propagate_url | Ensure self.url contains full transport://interface:port | environment/lib/python2.7/site-packages/IPython/parallel/factory.py | def _propagate_url(self):
"""Ensure self.url contains full transport://interface:port"""
if self.url:
iface = self.url.split('://',1)
if len(iface) == 2:
self.transport,iface = iface
iface = iface.split(':')
self.ip = iface[0]
if iface[1]:
self.regport = int(iface[1]) | def _propagate_url(self):
"""Ensure self.url contains full transport://interface:port"""
if self.url:
iface = self.url.split('://',1)
if len(iface) == 2:
self.transport,iface = iface
iface = iface.split(':')
self.ip = iface[0]
if iface[1]:
self.regport = int(iface[1]) | [
"Ensure",
"self",
".",
"url",
"contains",
"full",
"transport",
":",
"//",
"interface",
":",
"port"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/factory.py#L68-L77 | [
"def",
"_propagate_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"url",
":",
"iface",
"=",
"self",
".",
"url",
".",
"split",
"(",
"'://'",
",",
"1",
")",
"if",
"len",
"(",
"iface",
")",
"==",
"2",
":",
"self",
".",
"transport",
",",
"iface",
"=",
"iface",
"iface",
"=",
"iface",
".",
"split",
"(",
"':'",
")",
"self",
".",
"ip",
"=",
"iface",
"[",
"0",
"]",
"if",
"iface",
"[",
"1",
"]",
":",
"self",
".",
"regport",
"=",
"int",
"(",
"iface",
"[",
"1",
"]",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | _find_cmd | Find the full path to a .bat or .exe using the win32api module. | environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py | def _find_cmd(cmd):
"""Find the full path to a .bat or .exe using the win32api module."""
try:
from win32api import SearchPath
except ImportError:
raise ImportError('you need to have pywin32 installed for this to work')
else:
PATH = os.environ['PATH']
extensions = ['.exe', '.com', '.bat', '.py']
path = None
for ext in extensions:
try:
path = SearchPath(PATH, cmd + ext)[0]
except:
pass
if path is None:
raise OSError("command %r not found" % cmd)
else:
return path | def _find_cmd(cmd):
"""Find the full path to a .bat or .exe using the win32api module."""
try:
from win32api import SearchPath
except ImportError:
raise ImportError('you need to have pywin32 installed for this to work')
else:
PATH = os.environ['PATH']
extensions = ['.exe', '.com', '.bat', '.py']
path = None
for ext in extensions:
try:
path = SearchPath(PATH, cmd + ext)[0]
except:
pass
if path is None:
raise OSError("command %r not found" % cmd)
else:
return path | [
"Find",
"the",
"full",
"path",
"to",
"a",
".",
"bat",
"or",
".",
"exe",
"using",
"the",
"win32api",
"module",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py#L75-L93 | [
"def",
"_find_cmd",
"(",
"cmd",
")",
":",
"try",
":",
"from",
"win32api",
"import",
"SearchPath",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'you need to have pywin32 installed for this to work'",
")",
"else",
":",
"PATH",
"=",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
"extensions",
"=",
"[",
"'.exe'",
",",
"'.com'",
",",
"'.bat'",
",",
"'.py'",
"]",
"path",
"=",
"None",
"for",
"ext",
"in",
"extensions",
":",
"try",
":",
"path",
"=",
"SearchPath",
"(",
"PATH",
",",
"cmd",
"+",
"ext",
")",
"[",
"0",
"]",
"except",
":",
"pass",
"if",
"path",
"is",
"None",
":",
"raise",
"OSError",
"(",
"\"command %r not found\"",
"%",
"cmd",
")",
"else",
":",
"return",
"path"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | _system_body | Callback for _system. | environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py | def _system_body(p):
"""Callback for _system."""
enc = DEFAULT_ENCODING
for line in read_no_interrupt(p.stdout).splitlines():
line = line.decode(enc, 'replace')
print(line, file=sys.stdout)
for line in read_no_interrupt(p.stderr).splitlines():
line = line.decode(enc, 'replace')
print(line, file=sys.stderr)
# Wait to finish for returncode
return p.wait() | def _system_body(p):
"""Callback for _system."""
enc = DEFAULT_ENCODING
for line in read_no_interrupt(p.stdout).splitlines():
line = line.decode(enc, 'replace')
print(line, file=sys.stdout)
for line in read_no_interrupt(p.stderr).splitlines():
line = line.decode(enc, 'replace')
print(line, file=sys.stderr)
# Wait to finish for returncode
return p.wait() | [
"Callback",
"for",
"_system",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py#L96-L107 | [
"def",
"_system_body",
"(",
"p",
")",
":",
"enc",
"=",
"DEFAULT_ENCODING",
"for",
"line",
"in",
"read_no_interrupt",
"(",
"p",
".",
"stdout",
")",
".",
"splitlines",
"(",
")",
":",
"line",
"=",
"line",
".",
"decode",
"(",
"enc",
",",
"'replace'",
")",
"print",
"(",
"line",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
"for",
"line",
"in",
"read_no_interrupt",
"(",
"p",
".",
"stderr",
")",
".",
"splitlines",
"(",
")",
":",
"line",
"=",
"line",
".",
"decode",
"(",
"enc",
",",
"'replace'",
")",
"print",
"(",
"line",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"# Wait to finish for returncode",
"return",
"p",
".",
"wait",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | system | Win32 version of os.system() that works with network shares.
Note that this implementation returns None, as meant for use in IPython.
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
None : we explicitly do NOT return the subprocess status code, as this
utility is meant to be used extensively in IPython, where any return value
would trigger :func:`sys.displayhook` calls. | environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py | def system(cmd):
"""Win32 version of os.system() that works with network shares.
Note that this implementation returns None, as meant for use in IPython.
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
None : we explicitly do NOT return the subprocess status code, as this
utility is meant to be used extensively in IPython, where any return value
would trigger :func:`sys.displayhook` calls.
"""
# The controller provides interactivity with both
# stdin and stdout
#import _process_win32_controller
#_process_win32_controller.system(cmd)
with AvoidUNCPath() as path:
if path is not None:
cmd = '"pushd %s &&"%s' % (path, cmd)
return process_handler(cmd, _system_body) | def system(cmd):
"""Win32 version of os.system() that works with network shares.
Note that this implementation returns None, as meant for use in IPython.
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
None : we explicitly do NOT return the subprocess status code, as this
utility is meant to be used extensively in IPython, where any return value
would trigger :func:`sys.displayhook` calls.
"""
# The controller provides interactivity with both
# stdin and stdout
#import _process_win32_controller
#_process_win32_controller.system(cmd)
with AvoidUNCPath() as path:
if path is not None:
cmd = '"pushd %s &&"%s' % (path, cmd)
return process_handler(cmd, _system_body) | [
"Win32",
"version",
"of",
"os",
".",
"system",
"()",
"that",
"works",
"with",
"network",
"shares",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py#L110-L134 | [
"def",
"system",
"(",
"cmd",
")",
":",
"# The controller provides interactivity with both",
"# stdin and stdout",
"#import _process_win32_controller",
"#_process_win32_controller.system(cmd)",
"with",
"AvoidUNCPath",
"(",
")",
"as",
"path",
":",
"if",
"path",
"is",
"not",
"None",
":",
"cmd",
"=",
"'\"pushd %s &&\"%s'",
"%",
"(",
"path",
",",
"cmd",
")",
"return",
"process_handler",
"(",
"cmd",
",",
"_system_body",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | getoutput | Return standard output of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
stdout : str | environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py | def getoutput(cmd):
"""Return standard output of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
stdout : str
"""
with AvoidUNCPath() as path:
if path is not None:
cmd = '"pushd %s &&"%s' % (path, cmd)
out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT)
if out is None:
out = b''
return py3compat.bytes_to_str(out) | def getoutput(cmd):
"""Return standard output of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
stdout : str
"""
with AvoidUNCPath() as path:
if path is not None:
cmd = '"pushd %s &&"%s' % (path, cmd)
out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT)
if out is None:
out = b''
return py3compat.bytes_to_str(out) | [
"Return",
"standard",
"output",
"of",
"executing",
"cmd",
"in",
"a",
"shell",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py#L136-L158 | [
"def",
"getoutput",
"(",
"cmd",
")",
":",
"with",
"AvoidUNCPath",
"(",
")",
"as",
"path",
":",
"if",
"path",
"is",
"not",
"None",
":",
"cmd",
"=",
"'\"pushd %s &&\"%s'",
"%",
"(",
"path",
",",
"cmd",
")",
"out",
"=",
"process_handler",
"(",
"cmd",
",",
"lambda",
"p",
":",
"p",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
",",
"STDOUT",
")",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"b''",
"return",
"py3compat",
".",
"bytes_to_str",
"(",
"out",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | setup_partitioner | create a partitioner in the engine namespace | environment/share/doc/ipython/examples/parallel/wave2D/parallelwave.py | def setup_partitioner(comm, addrs, index, num_procs, gnum_cells, parts):
"""create a partitioner in the engine namespace"""
global partitioner
p = ZMQRectPartitioner2D(comm, addrs, my_id=index, num_procs=num_procs)
p.redim(global_num_cells=gnum_cells, num_parts=parts)
p.prepare_communication()
# put the partitioner into the global namespace:
partitioner=p | def setup_partitioner(comm, addrs, index, num_procs, gnum_cells, parts):
"""create a partitioner in the engine namespace"""
global partitioner
p = ZMQRectPartitioner2D(comm, addrs, my_id=index, num_procs=num_procs)
p.redim(global_num_cells=gnum_cells, num_parts=parts)
p.prepare_communication()
# put the partitioner into the global namespace:
partitioner=p | [
"create",
"a",
"partitioner",
"in",
"the",
"engine",
"namespace"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/wave2D/parallelwave.py#L33-L40 | [
"def",
"setup_partitioner",
"(",
"comm",
",",
"addrs",
",",
"index",
",",
"num_procs",
",",
"gnum_cells",
",",
"parts",
")",
":",
"global",
"partitioner",
"p",
"=",
"ZMQRectPartitioner2D",
"(",
"comm",
",",
"addrs",
",",
"my_id",
"=",
"index",
",",
"num_procs",
"=",
"num_procs",
")",
"p",
".",
"redim",
"(",
"global_num_cells",
"=",
"gnum_cells",
",",
"num_parts",
"=",
"parts",
")",
"p",
".",
"prepare_communication",
"(",
")",
"# put the partitioner into the global namespace:",
"partitioner",
"=",
"p"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | TranslationMixin.get_translations | Returns a list of (code, translation) tuples for codes | toolware/utils/translation.py | def get_translations(codes):
""" Returns a list of (code, translation) tuples for codes """
codes = codes or self.codes
return self._get_priority_translations(priority, codes) | def get_translations(codes):
""" Returns a list of (code, translation) tuples for codes """
codes = codes or self.codes
return self._get_priority_translations(priority, codes) | [
"Returns",
"a",
"list",
"of",
"(",
"code",
"translation",
")",
"tuples",
"for",
"codes"
] | un33k/django-toolware | python | https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/utils/translation.py#L68-L71 | [
"def",
"get_translations",
"(",
"codes",
")",
":",
"codes",
"=",
"codes",
"or",
"self",
".",
"codes",
"return",
"self",
".",
"_get_priority_translations",
"(",
"priority",
",",
"codes",
")"
] | 973f3e003dc38b812897dab88455bee37dcaf931 |
test | TranslationMixin.get_translations_sorted | Returns a sorted list of (code, translation) tuples for codes | toolware/utils/translation.py | def get_translations_sorted(codes):
""" Returns a sorted list of (code, translation) tuples for codes """
codes = codes or self.codes
return self._get_priority_translations(priority, codes) | def get_translations_sorted(codes):
""" Returns a sorted list of (code, translation) tuples for codes """
codes = codes or self.codes
return self._get_priority_translations(priority, codes) | [
"Returns",
"a",
"sorted",
"list",
"of",
"(",
"code",
"translation",
")",
"tuples",
"for",
"codes"
] | un33k/django-toolware | python | https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/utils/translation.py#L73-L76 | [
"def",
"get_translations_sorted",
"(",
"codes",
")",
":",
"codes",
"=",
"codes",
"or",
"self",
".",
"codes",
"return",
"self",
".",
"_get_priority_translations",
"(",
"priority",
",",
"codes",
")"
] | 973f3e003dc38b812897dab88455bee37dcaf931 |
test | TranslationMixin.get_priority_translations | Returns a list of (code, translation) tuples for priority, codes | toolware/utils/translation.py | def get_priority_translations(priority, codes):
""" Returns a list of (code, translation) tuples for priority, codes """
priority = priority or self.priority
codes = codes or self.codes
return self._get_priority_translations(priority, codes) | def get_priority_translations(priority, codes):
""" Returns a list of (code, translation) tuples for priority, codes """
priority = priority or self.priority
codes = codes or self.codes
return self._get_priority_translations(priority, codes) | [
"Returns",
"a",
"list",
"of",
"(",
"code",
"translation",
")",
"tuples",
"for",
"priority",
"codes"
] | un33k/django-toolware | python | https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/utils/translation.py#L78-L82 | [
"def",
"get_priority_translations",
"(",
"priority",
",",
"codes",
")",
":",
"priority",
"=",
"priority",
"or",
"self",
".",
"priority",
"codes",
"=",
"codes",
"or",
"self",
".",
"codes",
"return",
"self",
".",
"_get_priority_translations",
"(",
"priority",
",",
"codes",
")"
] | 973f3e003dc38b812897dab88455bee37dcaf931 |
test | Reporter.find_code_units | Find the code units we'll report on.
`morfs` is a list of modules or filenames. | virtualEnvironment/lib/python2.7/site-packages/coverage/report.py | def find_code_units(self, morfs):
"""Find the code units we'll report on.
`morfs` is a list of modules or filenames.
"""
morfs = morfs or self.coverage.data.measured_files()
file_locator = self.coverage.file_locator
self.code_units = code_unit_factory(morfs, file_locator)
if self.config.include:
patterns = prep_patterns(self.config.include)
filtered = []
for cu in self.code_units:
for pattern in patterns:
if fnmatch.fnmatch(cu.filename, pattern):
filtered.append(cu)
break
self.code_units = filtered
if self.config.omit:
patterns = prep_patterns(self.config.omit)
filtered = []
for cu in self.code_units:
for pattern in patterns:
if fnmatch.fnmatch(cu.filename, pattern):
break
else:
filtered.append(cu)
self.code_units = filtered
self.code_units.sort() | def find_code_units(self, morfs):
"""Find the code units we'll report on.
`morfs` is a list of modules or filenames.
"""
morfs = morfs or self.coverage.data.measured_files()
file_locator = self.coverage.file_locator
self.code_units = code_unit_factory(morfs, file_locator)
if self.config.include:
patterns = prep_patterns(self.config.include)
filtered = []
for cu in self.code_units:
for pattern in patterns:
if fnmatch.fnmatch(cu.filename, pattern):
filtered.append(cu)
break
self.code_units = filtered
if self.config.omit:
patterns = prep_patterns(self.config.omit)
filtered = []
for cu in self.code_units:
for pattern in patterns:
if fnmatch.fnmatch(cu.filename, pattern):
break
else:
filtered.append(cu)
self.code_units = filtered
self.code_units.sort() | [
"Find",
"the",
"code",
"units",
"we",
"ll",
"report",
"on",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/report.py#L28-L59 | [
"def",
"find_code_units",
"(",
"self",
",",
"morfs",
")",
":",
"morfs",
"=",
"morfs",
"or",
"self",
".",
"coverage",
".",
"data",
".",
"measured_files",
"(",
")",
"file_locator",
"=",
"self",
".",
"coverage",
".",
"file_locator",
"self",
".",
"code_units",
"=",
"code_unit_factory",
"(",
"morfs",
",",
"file_locator",
")",
"if",
"self",
".",
"config",
".",
"include",
":",
"patterns",
"=",
"prep_patterns",
"(",
"self",
".",
"config",
".",
"include",
")",
"filtered",
"=",
"[",
"]",
"for",
"cu",
"in",
"self",
".",
"code_units",
":",
"for",
"pattern",
"in",
"patterns",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"cu",
".",
"filename",
",",
"pattern",
")",
":",
"filtered",
".",
"append",
"(",
"cu",
")",
"break",
"self",
".",
"code_units",
"=",
"filtered",
"if",
"self",
".",
"config",
".",
"omit",
":",
"patterns",
"=",
"prep_patterns",
"(",
"self",
".",
"config",
".",
"omit",
")",
"filtered",
"=",
"[",
"]",
"for",
"cu",
"in",
"self",
".",
"code_units",
":",
"for",
"pattern",
"in",
"patterns",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"cu",
".",
"filename",
",",
"pattern",
")",
":",
"break",
"else",
":",
"filtered",
".",
"append",
"(",
"cu",
")",
"self",
".",
"code_units",
"=",
"filtered",
"self",
".",
"code_units",
".",
"sort",
"(",
")"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | Reporter.report_files | Run a reporting function on a number of morfs.
`report_fn` is called for each relative morf in `morfs`. It is called
as::
report_fn(code_unit, analysis)
where `code_unit` is the `CodeUnit` for the morf, and `analysis` is
the `Analysis` for the morf. | virtualEnvironment/lib/python2.7/site-packages/coverage/report.py | def report_files(self, report_fn, morfs, directory=None):
"""Run a reporting function on a number of morfs.
`report_fn` is called for each relative morf in `morfs`. It is called
as::
report_fn(code_unit, analysis)
where `code_unit` is the `CodeUnit` for the morf, and `analysis` is
the `Analysis` for the morf.
"""
self.find_code_units(morfs)
if not self.code_units:
raise CoverageException("No data to report.")
self.directory = directory
if self.directory and not os.path.exists(self.directory):
os.makedirs(self.directory)
for cu in self.code_units:
try:
report_fn(cu, self.coverage._analyze(cu))
except NoSource:
if not self.config.ignore_errors:
raise
except NotPython:
# Only report errors for .py files, and only if we didn't
# explicitly suppress those errors.
if cu.should_be_python() and not self.config.ignore_errors:
raise | def report_files(self, report_fn, morfs, directory=None):
"""Run a reporting function on a number of morfs.
`report_fn` is called for each relative morf in `morfs`. It is called
as::
report_fn(code_unit, analysis)
where `code_unit` is the `CodeUnit` for the morf, and `analysis` is
the `Analysis` for the morf.
"""
self.find_code_units(morfs)
if not self.code_units:
raise CoverageException("No data to report.")
self.directory = directory
if self.directory and not os.path.exists(self.directory):
os.makedirs(self.directory)
for cu in self.code_units:
try:
report_fn(cu, self.coverage._analyze(cu))
except NoSource:
if not self.config.ignore_errors:
raise
except NotPython:
# Only report errors for .py files, and only if we didn't
# explicitly suppress those errors.
if cu.should_be_python() and not self.config.ignore_errors:
raise | [
"Run",
"a",
"reporting",
"function",
"on",
"a",
"number",
"of",
"morfs",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/report.py#L61-L92 | [
"def",
"report_files",
"(",
"self",
",",
"report_fn",
",",
"morfs",
",",
"directory",
"=",
"None",
")",
":",
"self",
".",
"find_code_units",
"(",
"morfs",
")",
"if",
"not",
"self",
".",
"code_units",
":",
"raise",
"CoverageException",
"(",
"\"No data to report.\"",
")",
"self",
".",
"directory",
"=",
"directory",
"if",
"self",
".",
"directory",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"directory",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"directory",
")",
"for",
"cu",
"in",
"self",
".",
"code_units",
":",
"try",
":",
"report_fn",
"(",
"cu",
",",
"self",
".",
"coverage",
".",
"_analyze",
"(",
"cu",
")",
")",
"except",
"NoSource",
":",
"if",
"not",
"self",
".",
"config",
".",
"ignore_errors",
":",
"raise",
"except",
"NotPython",
":",
"# Only report errors for .py files, and only if we didn't",
"# explicitly suppress those errors.",
"if",
"cu",
".",
"should_be_python",
"(",
")",
"and",
"not",
"self",
".",
"config",
".",
"ignore_errors",
":",
"raise"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | make_decorator | Wraps a test decorator so as to properly replicate metadata
of the decorated function, including nose's additional stuff
(namely, setup and teardown). | environment/lib/python2.7/site-packages/nose/tools/nontrivial.py | def make_decorator(func):
"""
Wraps a test decorator so as to properly replicate metadata
of the decorated function, including nose's additional stuff
(namely, setup and teardown).
"""
def decorate(newfunc):
if hasattr(func, 'compat_func_name'):
name = func.compat_func_name
else:
name = func.__name__
newfunc.__dict__ = func.__dict__
newfunc.__doc__ = func.__doc__
newfunc.__module__ = func.__module__
if not hasattr(newfunc, 'compat_co_firstlineno'):
newfunc.compat_co_firstlineno = func.func_code.co_firstlineno
try:
newfunc.__name__ = name
except TypeError:
# can't set func name in 2.3
newfunc.compat_func_name = name
return newfunc
return decorate | def make_decorator(func):
"""
Wraps a test decorator so as to properly replicate metadata
of the decorated function, including nose's additional stuff
(namely, setup and teardown).
"""
def decorate(newfunc):
if hasattr(func, 'compat_func_name'):
name = func.compat_func_name
else:
name = func.__name__
newfunc.__dict__ = func.__dict__
newfunc.__doc__ = func.__doc__
newfunc.__module__ = func.__module__
if not hasattr(newfunc, 'compat_co_firstlineno'):
newfunc.compat_co_firstlineno = func.func_code.co_firstlineno
try:
newfunc.__name__ = name
except TypeError:
# can't set func name in 2.3
newfunc.compat_func_name = name
return newfunc
return decorate | [
"Wraps",
"a",
"test",
"decorator",
"so",
"as",
"to",
"properly",
"replicate",
"metadata",
"of",
"the",
"decorated",
"function",
"including",
"nose",
"s",
"additional",
"stuff",
"(",
"namely",
"setup",
"and",
"teardown",
")",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/tools/nontrivial.py#L14-L36 | [
"def",
"make_decorator",
"(",
"func",
")",
":",
"def",
"decorate",
"(",
"newfunc",
")",
":",
"if",
"hasattr",
"(",
"func",
",",
"'compat_func_name'",
")",
":",
"name",
"=",
"func",
".",
"compat_func_name",
"else",
":",
"name",
"=",
"func",
".",
"__name__",
"newfunc",
".",
"__dict__",
"=",
"func",
".",
"__dict__",
"newfunc",
".",
"__doc__",
"=",
"func",
".",
"__doc__",
"newfunc",
".",
"__module__",
"=",
"func",
".",
"__module__",
"if",
"not",
"hasattr",
"(",
"newfunc",
",",
"'compat_co_firstlineno'",
")",
":",
"newfunc",
".",
"compat_co_firstlineno",
"=",
"func",
".",
"func_code",
".",
"co_firstlineno",
"try",
":",
"newfunc",
".",
"__name__",
"=",
"name",
"except",
"TypeError",
":",
"# can't set func name in 2.3",
"newfunc",
".",
"compat_func_name",
"=",
"name",
"return",
"newfunc",
"return",
"decorate"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | raises | Test must raise one of expected exceptions to pass.
Example use::
@raises(TypeError, ValueError)
def test_raises_type_error():
raise TypeError("This test passes")
@raises(Exception)
def test_that_fails_by_passing():
pass
If you want to test many assertions about exceptions in a single test,
you may want to use `assert_raises` instead. | environment/lib/python2.7/site-packages/nose/tools/nontrivial.py | def raises(*exceptions):
"""Test must raise one of expected exceptions to pass.
Example use::
@raises(TypeError, ValueError)
def test_raises_type_error():
raise TypeError("This test passes")
@raises(Exception)
def test_that_fails_by_passing():
pass
If you want to test many assertions about exceptions in a single test,
you may want to use `assert_raises` instead.
"""
valid = ' or '.join([e.__name__ for e in exceptions])
def decorate(func):
name = func.__name__
def newfunc(*arg, **kw):
try:
func(*arg, **kw)
except exceptions:
pass
except:
raise
else:
message = "%s() did not raise %s" % (name, valid)
raise AssertionError(message)
newfunc = make_decorator(func)(newfunc)
return newfunc
return decorate | def raises(*exceptions):
"""Test must raise one of expected exceptions to pass.
Example use::
@raises(TypeError, ValueError)
def test_raises_type_error():
raise TypeError("This test passes")
@raises(Exception)
def test_that_fails_by_passing():
pass
If you want to test many assertions about exceptions in a single test,
you may want to use `assert_raises` instead.
"""
valid = ' or '.join([e.__name__ for e in exceptions])
def decorate(func):
name = func.__name__
def newfunc(*arg, **kw):
try:
func(*arg, **kw)
except exceptions:
pass
except:
raise
else:
message = "%s() did not raise %s" % (name, valid)
raise AssertionError(message)
newfunc = make_decorator(func)(newfunc)
return newfunc
return decorate | [
"Test",
"must",
"raise",
"one",
"of",
"expected",
"exceptions",
"to",
"pass",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/tools/nontrivial.py#L39-L70 | [
"def",
"raises",
"(",
"*",
"exceptions",
")",
":",
"valid",
"=",
"' or '",
".",
"join",
"(",
"[",
"e",
".",
"__name__",
"for",
"e",
"in",
"exceptions",
"]",
")",
"def",
"decorate",
"(",
"func",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"def",
"newfunc",
"(",
"*",
"arg",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"func",
"(",
"*",
"arg",
",",
"*",
"*",
"kw",
")",
"except",
"exceptions",
":",
"pass",
"except",
":",
"raise",
"else",
":",
"message",
"=",
"\"%s() did not raise %s\"",
"%",
"(",
"name",
",",
"valid",
")",
"raise",
"AssertionError",
"(",
"message",
")",
"newfunc",
"=",
"make_decorator",
"(",
"func",
")",
"(",
"newfunc",
")",
"return",
"newfunc",
"return",
"decorate"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | set_trace | Call pdb.set_trace in the calling frame, first restoring
sys.stdout to the real output stream. Note that sys.stdout is NOT
reset to whatever it was before the call once pdb is done! | environment/lib/python2.7/site-packages/nose/tools/nontrivial.py | def set_trace():
"""Call pdb.set_trace in the calling frame, first restoring
sys.stdout to the real output stream. Note that sys.stdout is NOT
reset to whatever it was before the call once pdb is done!
"""
import pdb
import sys
stdout = sys.stdout
sys.stdout = sys.__stdout__
pdb.Pdb().set_trace(sys._getframe().f_back) | def set_trace():
"""Call pdb.set_trace in the calling frame, first restoring
sys.stdout to the real output stream. Note that sys.stdout is NOT
reset to whatever it was before the call once pdb is done!
"""
import pdb
import sys
stdout = sys.stdout
sys.stdout = sys.__stdout__
pdb.Pdb().set_trace(sys._getframe().f_back) | [
"Call",
"pdb",
".",
"set_trace",
"in",
"the",
"calling",
"frame",
"first",
"restoring",
"sys",
".",
"stdout",
"to",
"the",
"real",
"output",
"stream",
".",
"Note",
"that",
"sys",
".",
"stdout",
"is",
"NOT",
"reset",
"to",
"whatever",
"it",
"was",
"before",
"the",
"call",
"once",
"pdb",
"is",
"done!"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/tools/nontrivial.py#L73-L82 | [
"def",
"set_trace",
"(",
")",
":",
"import",
"pdb",
"import",
"sys",
"stdout",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdout",
"=",
"sys",
".",
"__stdout__",
"pdb",
".",
"Pdb",
"(",
")",
".",
"set_trace",
"(",
"sys",
".",
"_getframe",
"(",
")",
".",
"f_back",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | timed | Test must finish within specified time limit to pass.
Example use::
@timed(.1)
def test_that_fails():
time.sleep(.2) | environment/lib/python2.7/site-packages/nose/tools/nontrivial.py | def timed(limit):
"""Test must finish within specified time limit to pass.
Example use::
@timed(.1)
def test_that_fails():
time.sleep(.2)
"""
def decorate(func):
def newfunc(*arg, **kw):
start = time.time()
func(*arg, **kw)
end = time.time()
if end - start > limit:
raise TimeExpired("Time limit (%s) exceeded" % limit)
newfunc = make_decorator(func)(newfunc)
return newfunc
return decorate | def timed(limit):
"""Test must finish within specified time limit to pass.
Example use::
@timed(.1)
def test_that_fails():
time.sleep(.2)
"""
def decorate(func):
def newfunc(*arg, **kw):
start = time.time()
func(*arg, **kw)
end = time.time()
if end - start > limit:
raise TimeExpired("Time limit (%s) exceeded" % limit)
newfunc = make_decorator(func)(newfunc)
return newfunc
return decorate | [
"Test",
"must",
"finish",
"within",
"specified",
"time",
"limit",
"to",
"pass",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/tools/nontrivial.py#L85-L103 | [
"def",
"timed",
"(",
"limit",
")",
":",
"def",
"decorate",
"(",
"func",
")",
":",
"def",
"newfunc",
"(",
"*",
"arg",
",",
"*",
"*",
"kw",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"func",
"(",
"*",
"arg",
",",
"*",
"*",
"kw",
")",
"end",
"=",
"time",
".",
"time",
"(",
")",
"if",
"end",
"-",
"start",
">",
"limit",
":",
"raise",
"TimeExpired",
"(",
"\"Time limit (%s) exceeded\"",
"%",
"limit",
")",
"newfunc",
"=",
"make_decorator",
"(",
"func",
")",
"(",
"newfunc",
")",
"return",
"newfunc",
"return",
"decorate"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | with_setup | Decorator to add setup and/or teardown methods to a test function::
@with_setup(setup, teardown)
def test_something():
" ... "
Note that `with_setup` is useful *only* for test functions, not for test
methods or inside of TestCase subclasses. | environment/lib/python2.7/site-packages/nose/tools/nontrivial.py | def with_setup(setup=None, teardown=None):
"""Decorator to add setup and/or teardown methods to a test function::
@with_setup(setup, teardown)
def test_something():
" ... "
Note that `with_setup` is useful *only* for test functions, not for test
methods or inside of TestCase subclasses.
"""
def decorate(func, setup=setup, teardown=teardown):
if setup:
if hasattr(func, 'setup'):
_old_s = func.setup
def _s():
setup()
_old_s()
func.setup = _s
else:
func.setup = setup
if teardown:
if hasattr(func, 'teardown'):
_old_t = func.teardown
def _t():
_old_t()
teardown()
func.teardown = _t
else:
func.teardown = teardown
return func
return decorate | def with_setup(setup=None, teardown=None):
"""Decorator to add setup and/or teardown methods to a test function::
@with_setup(setup, teardown)
def test_something():
" ... "
Note that `with_setup` is useful *only* for test functions, not for test
methods or inside of TestCase subclasses.
"""
def decorate(func, setup=setup, teardown=teardown):
if setup:
if hasattr(func, 'setup'):
_old_s = func.setup
def _s():
setup()
_old_s()
func.setup = _s
else:
func.setup = setup
if teardown:
if hasattr(func, 'teardown'):
_old_t = func.teardown
def _t():
_old_t()
teardown()
func.teardown = _t
else:
func.teardown = teardown
return func
return decorate | [
"Decorator",
"to",
"add",
"setup",
"and",
"/",
"or",
"teardown",
"methods",
"to",
"a",
"test",
"function",
"::"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/tools/nontrivial.py#L106-L136 | [
"def",
"with_setup",
"(",
"setup",
"=",
"None",
",",
"teardown",
"=",
"None",
")",
":",
"def",
"decorate",
"(",
"func",
",",
"setup",
"=",
"setup",
",",
"teardown",
"=",
"teardown",
")",
":",
"if",
"setup",
":",
"if",
"hasattr",
"(",
"func",
",",
"'setup'",
")",
":",
"_old_s",
"=",
"func",
".",
"setup",
"def",
"_s",
"(",
")",
":",
"setup",
"(",
")",
"_old_s",
"(",
")",
"func",
".",
"setup",
"=",
"_s",
"else",
":",
"func",
".",
"setup",
"=",
"setup",
"if",
"teardown",
":",
"if",
"hasattr",
"(",
"func",
",",
"'teardown'",
")",
":",
"_old_t",
"=",
"func",
".",
"teardown",
"def",
"_t",
"(",
")",
":",
"_old_t",
"(",
")",
"teardown",
"(",
")",
"func",
".",
"teardown",
"=",
"_t",
"else",
":",
"func",
".",
"teardown",
"=",
"teardown",
"return",
"func",
"return",
"decorate"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InteractiveShellApp.init_gui_pylab | Enable GUI event loop integration, taking pylab into account. | environment/lib/python2.7/site-packages/IPython/core/shellapp.py | def init_gui_pylab(self):
"""Enable GUI event loop integration, taking pylab into account."""
if self.gui or self.pylab:
shell = self.shell
try:
if self.pylab:
gui, backend = pylabtools.find_gui_and_backend(self.pylab)
self.log.info("Enabling GUI event loop integration, "
"toolkit=%s, pylab=%s" % (gui, self.pylab))
shell.enable_pylab(gui, import_all=self.pylab_import_all)
else:
self.log.info("Enabling GUI event loop integration, "
"toolkit=%s" % self.gui)
shell.enable_gui(self.gui)
except Exception:
self.log.warn("GUI event loop or pylab initialization failed")
self.shell.showtraceback() | def init_gui_pylab(self):
"""Enable GUI event loop integration, taking pylab into account."""
if self.gui or self.pylab:
shell = self.shell
try:
if self.pylab:
gui, backend = pylabtools.find_gui_and_backend(self.pylab)
self.log.info("Enabling GUI event loop integration, "
"toolkit=%s, pylab=%s" % (gui, self.pylab))
shell.enable_pylab(gui, import_all=self.pylab_import_all)
else:
self.log.info("Enabling GUI event loop integration, "
"toolkit=%s" % self.gui)
shell.enable_gui(self.gui)
except Exception:
self.log.warn("GUI event loop or pylab initialization failed")
self.shell.showtraceback() | [
"Enable",
"GUI",
"event",
"loop",
"integration",
"taking",
"pylab",
"into",
"account",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/shellapp.py#L191-L207 | [
"def",
"init_gui_pylab",
"(",
"self",
")",
":",
"if",
"self",
".",
"gui",
"or",
"self",
".",
"pylab",
":",
"shell",
"=",
"self",
".",
"shell",
"try",
":",
"if",
"self",
".",
"pylab",
":",
"gui",
",",
"backend",
"=",
"pylabtools",
".",
"find_gui_and_backend",
"(",
"self",
".",
"pylab",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"Enabling GUI event loop integration, \"",
"\"toolkit=%s, pylab=%s\"",
"%",
"(",
"gui",
",",
"self",
".",
"pylab",
")",
")",
"shell",
".",
"enable_pylab",
"(",
"gui",
",",
"import_all",
"=",
"self",
".",
"pylab_import_all",
")",
"else",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Enabling GUI event loop integration, \"",
"\"toolkit=%s\"",
"%",
"self",
".",
"gui",
")",
"shell",
".",
"enable_gui",
"(",
"self",
".",
"gui",
")",
"except",
"Exception",
":",
"self",
".",
"log",
".",
"warn",
"(",
"\"GUI event loop or pylab initialization failed\"",
")",
"self",
".",
"shell",
".",
"showtraceback",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InteractiveShellApp.init_extensions | Load all IPython extensions in IPythonApp.extensions.
This uses the :meth:`ExtensionManager.load_extensions` to load all
the extensions listed in ``self.extensions``. | environment/lib/python2.7/site-packages/IPython/core/shellapp.py | def init_extensions(self):
"""Load all IPython extensions in IPythonApp.extensions.
This uses the :meth:`ExtensionManager.load_extensions` to load all
the extensions listed in ``self.extensions``.
"""
try:
self.log.debug("Loading IPython extensions...")
extensions = self.default_extensions + self.extensions
for ext in extensions:
try:
self.log.info("Loading IPython extension: %s" % ext)
self.shell.extension_manager.load_extension(ext)
except:
self.log.warn("Error in loading extension: %s" % ext +
"\nCheck your config files in %s" % self.profile_dir.location
)
self.shell.showtraceback()
except:
self.log.warn("Unknown error in loading extensions:")
self.shell.showtraceback() | def init_extensions(self):
"""Load all IPython extensions in IPythonApp.extensions.
This uses the :meth:`ExtensionManager.load_extensions` to load all
the extensions listed in ``self.extensions``.
"""
try:
self.log.debug("Loading IPython extensions...")
extensions = self.default_extensions + self.extensions
for ext in extensions:
try:
self.log.info("Loading IPython extension: %s" % ext)
self.shell.extension_manager.load_extension(ext)
except:
self.log.warn("Error in loading extension: %s" % ext +
"\nCheck your config files in %s" % self.profile_dir.location
)
self.shell.showtraceback()
except:
self.log.warn("Unknown error in loading extensions:")
self.shell.showtraceback() | [
"Load",
"all",
"IPython",
"extensions",
"in",
"IPythonApp",
".",
"extensions",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/shellapp.py#L209-L229 | [
"def",
"init_extensions",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Loading IPython extensions...\"",
")",
"extensions",
"=",
"self",
".",
"default_extensions",
"+",
"self",
".",
"extensions",
"for",
"ext",
"in",
"extensions",
":",
"try",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Loading IPython extension: %s\"",
"%",
"ext",
")",
"self",
".",
"shell",
".",
"extension_manager",
".",
"load_extension",
"(",
"ext",
")",
"except",
":",
"self",
".",
"log",
".",
"warn",
"(",
"\"Error in loading extension: %s\"",
"%",
"ext",
"+",
"\"\\nCheck your config files in %s\"",
"%",
"self",
".",
"profile_dir",
".",
"location",
")",
"self",
".",
"shell",
".",
"showtraceback",
"(",
")",
"except",
":",
"self",
".",
"log",
".",
"warn",
"(",
"\"Unknown error in loading extensions:\"",
")",
"self",
".",
"shell",
".",
"showtraceback",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InteractiveShellApp.init_code | run the pre-flight code, specified via exec_lines | environment/lib/python2.7/site-packages/IPython/core/shellapp.py | def init_code(self):
"""run the pre-flight code, specified via exec_lines"""
self._run_startup_files()
self._run_exec_lines()
self._run_exec_files()
self._run_cmd_line_code()
self._run_module()
# flush output, so itwon't be attached to the first cell
sys.stdout.flush()
sys.stderr.flush()
# Hide variables defined here from %who etc.
self.shell.user_ns_hidden.update(self.shell.user_ns) | def init_code(self):
"""run the pre-flight code, specified via exec_lines"""
self._run_startup_files()
self._run_exec_lines()
self._run_exec_files()
self._run_cmd_line_code()
self._run_module()
# flush output, so itwon't be attached to the first cell
sys.stdout.flush()
sys.stderr.flush()
# Hide variables defined here from %who etc.
self.shell.user_ns_hidden.update(self.shell.user_ns) | [
"run",
"the",
"pre",
"-",
"flight",
"code",
"specified",
"via",
"exec_lines"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/shellapp.py#L231-L244 | [
"def",
"init_code",
"(",
"self",
")",
":",
"self",
".",
"_run_startup_files",
"(",
")",
"self",
".",
"_run_exec_lines",
"(",
")",
"self",
".",
"_run_exec_files",
"(",
")",
"self",
".",
"_run_cmd_line_code",
"(",
")",
"self",
".",
"_run_module",
"(",
")",
"# flush output, so itwon't be attached to the first cell",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"# Hide variables defined here from %who etc.",
"self",
".",
"shell",
".",
"user_ns_hidden",
".",
"update",
"(",
"self",
".",
"shell",
".",
"user_ns",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InteractiveShellApp._run_exec_lines | Run lines of code in IPythonApp.exec_lines in the user's namespace. | environment/lib/python2.7/site-packages/IPython/core/shellapp.py | def _run_exec_lines(self):
"""Run lines of code in IPythonApp.exec_lines in the user's namespace."""
if not self.exec_lines:
return
try:
self.log.debug("Running code from IPythonApp.exec_lines...")
for line in self.exec_lines:
try:
self.log.info("Running code in user namespace: %s" %
line)
self.shell.run_cell(line, store_history=False)
except:
self.log.warn("Error in executing line in user "
"namespace: %s" % line)
self.shell.showtraceback()
except:
self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
self.shell.showtraceback() | def _run_exec_lines(self):
"""Run lines of code in IPythonApp.exec_lines in the user's namespace."""
if not self.exec_lines:
return
try:
self.log.debug("Running code from IPythonApp.exec_lines...")
for line in self.exec_lines:
try:
self.log.info("Running code in user namespace: %s" %
line)
self.shell.run_cell(line, store_history=False)
except:
self.log.warn("Error in executing line in user "
"namespace: %s" % line)
self.shell.showtraceback()
except:
self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
self.shell.showtraceback() | [
"Run",
"lines",
"of",
"code",
"in",
"IPythonApp",
".",
"exec_lines",
"in",
"the",
"user",
"s",
"namespace",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/shellapp.py#L246-L263 | [
"def",
"_run_exec_lines",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"exec_lines",
":",
"return",
"try",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Running code from IPythonApp.exec_lines...\"",
")",
"for",
"line",
"in",
"self",
".",
"exec_lines",
":",
"try",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Running code in user namespace: %s\"",
"%",
"line",
")",
"self",
".",
"shell",
".",
"run_cell",
"(",
"line",
",",
"store_history",
"=",
"False",
")",
"except",
":",
"self",
".",
"log",
".",
"warn",
"(",
"\"Error in executing line in user \"",
"\"namespace: %s\"",
"%",
"line",
")",
"self",
".",
"shell",
".",
"showtraceback",
"(",
")",
"except",
":",
"self",
".",
"log",
".",
"warn",
"(",
"\"Unknown error in handling IPythonApp.exec_lines:\"",
")",
"self",
".",
"shell",
".",
"showtraceback",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InteractiveShellApp._run_startup_files | Run files from profile startup directory | environment/lib/python2.7/site-packages/IPython/core/shellapp.py | def _run_startup_files(self):
"""Run files from profile startup directory"""
startup_dir = self.profile_dir.startup_dir
startup_files = glob.glob(os.path.join(startup_dir, '*.py'))
startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
if not startup_files:
return
self.log.debug("Running startup files from %s...", startup_dir)
try:
for fname in sorted(startup_files):
self._exec_file(fname)
except:
self.log.warn("Unknown error in handling startup files:")
self.shell.showtraceback() | def _run_startup_files(self):
"""Run files from profile startup directory"""
startup_dir = self.profile_dir.startup_dir
startup_files = glob.glob(os.path.join(startup_dir, '*.py'))
startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
if not startup_files:
return
self.log.debug("Running startup files from %s...", startup_dir)
try:
for fname in sorted(startup_files):
self._exec_file(fname)
except:
self.log.warn("Unknown error in handling startup files:")
self.shell.showtraceback() | [
"Run",
"files",
"from",
"profile",
"startup",
"directory"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/shellapp.py#L297-L311 | [
"def",
"_run_startup_files",
"(",
"self",
")",
":",
"startup_dir",
"=",
"self",
".",
"profile_dir",
".",
"startup_dir",
"startup_files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"startup_dir",
",",
"'*.py'",
")",
")",
"startup_files",
"+=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"startup_dir",
",",
"'*.ipy'",
")",
")",
"if",
"not",
"startup_files",
":",
"return",
"self",
".",
"log",
".",
"debug",
"(",
"\"Running startup files from %s...\"",
",",
"startup_dir",
")",
"try",
":",
"for",
"fname",
"in",
"sorted",
"(",
"startup_files",
")",
":",
"self",
".",
"_exec_file",
"(",
"fname",
")",
"except",
":",
"self",
".",
"log",
".",
"warn",
"(",
"\"Unknown error in handling startup files:\"",
")",
"self",
".",
"shell",
".",
"showtraceback",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | InteractiveShellApp._run_exec_files | Run files from IPythonApp.exec_files | environment/lib/python2.7/site-packages/IPython/core/shellapp.py | def _run_exec_files(self):
"""Run files from IPythonApp.exec_files"""
if not self.exec_files:
return
self.log.debug("Running files in IPythonApp.exec_files...")
try:
for fname in self.exec_files:
self._exec_file(fname)
except:
self.log.warn("Unknown error in handling IPythonApp.exec_files:")
self.shell.showtraceback() | def _run_exec_files(self):
"""Run files from IPythonApp.exec_files"""
if not self.exec_files:
return
self.log.debug("Running files in IPythonApp.exec_files...")
try:
for fname in self.exec_files:
self._exec_file(fname)
except:
self.log.warn("Unknown error in handling IPythonApp.exec_files:")
self.shell.showtraceback() | [
"Run",
"files",
"from",
"IPythonApp",
".",
"exec_files"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/shellapp.py#L313-L324 | [
"def",
"_run_exec_files",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"exec_files",
":",
"return",
"self",
".",
"log",
".",
"debug",
"(",
"\"Running files in IPythonApp.exec_files...\"",
")",
"try",
":",
"for",
"fname",
"in",
"self",
".",
"exec_files",
":",
"self",
".",
"_exec_file",
"(",
"fname",
")",
"except",
":",
"self",
".",
"log",
".",
"warn",
"(",
"\"Unknown error in handling IPythonApp.exec_files:\"",
")",
"self",
".",
"shell",
".",
"showtraceback",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.