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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | spitOut | r"""Write string `s` into `file` (which can be a string (`str` or
`unicode`) or a `file` instance). | src/mlab/awmstools.py | def spitOut(s, file, binary=False, expand=False):
r"""Write string `s` into `file` (which can be a string (`str` or
`unicode`) or a `file` instance)."""
mode = "w" + ["b",""][not binary]
file = _normalizeToFile(file, mode=mode, expand=expand)
try: file.write(s)
finally: file.close() | def spitOut(s, file, binary=False, expand=False):
r"""Write string `s` into `file` (which can be a string (`str` or
`unicode`) or a `file` instance)."""
mode = "w" + ["b",""][not binary]
file = _normalizeToFile(file, mode=mode, expand=expand)
try: file.write(s)
finally: file.close() | [
"r",
"Write",
"string",
"s",
"into",
"file",
"(",
"which",
"can",
"be",
"a",
"string",
"(",
"str",
"or",
"unicode",
")",
"or",
"a",
"file",
"instance",
")",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L369-L375 | [
"def",
"spitOut",
"(",
"s",
",",
"file",
",",
"binary",
"=",
"False",
",",
"expand",
"=",
"False",
")",
":",
"mode",
"=",
"\"w\"",
"+",
"[",
"\"b\"",
",",
"\"\"",
"]",
"[",
"not",
"binary",
"]",
"file",
"=",
"_normalizeToFile",
"(",
"file",
",",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | spitOutLines | r"""Write all the `lines` to `file` (which can be a string/unicode or a
file handler). | src/mlab/awmstools.py | def spitOutLines(lines, file, expand=False):
r"""Write all the `lines` to `file` (which can be a string/unicode or a
file handler)."""
file = _normalizeToFile(file, mode="w", expand=expand)
try: file.writelines(lines)
finally: file.close() | def spitOutLines(lines, file, expand=False):
r"""Write all the `lines` to `file` (which can be a string/unicode or a
file handler)."""
file = _normalizeToFile(file, mode="w", expand=expand)
try: file.writelines(lines)
finally: file.close() | [
"r",
"Write",
"all",
"the",
"lines",
"to",
"file",
"(",
"which",
"can",
"be",
"a",
"string",
"/",
"unicode",
"or",
"a",
"file",
"handler",
")",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L377-L382 | [
"def",
"spitOutLines",
"(",
"lines",
",",
"file",
",",
"expand",
"=",
"False",
")",
":",
"file",
"=",
"_normalizeToFile",
"(",
"file",
",",
"mode",
"=",
"\"w\"",
",",
"expand",
"=",
"expand",
")",
"try",
":",
"file",
".",
"writelines",
"(",
"lines",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | readProcess | r"""Similar to `os.popen3`, but returns 2 strings (stdin, stdout) and the
exit code (unlike popen2, exit is 0 if no problems occured (for some
bizarre reason popen2 returns None... <sigh>).
FIXME: only works for UNIX; handling of signalled processes. | src/mlab/awmstools.py | def readProcess(cmd, *args):
r"""Similar to `os.popen3`, but returns 2 strings (stdin, stdout) and the
exit code (unlike popen2, exit is 0 if no problems occured (for some
bizarre reason popen2 returns None... <sigh>).
FIXME: only works for UNIX; handling of signalled processes.
"""
import pope... | def readProcess(cmd, *args):
r"""Similar to `os.popen3`, but returns 2 strings (stdin, stdout) and the
exit code (unlike popen2, exit is 0 if no problems occured (for some
bizarre reason popen2 returns None... <sigh>).
FIXME: only works for UNIX; handling of signalled processes.
"""
import pope... | [
"r",
"Similar",
"to",
"os",
".",
"popen3",
"but",
"returns",
"2",
"strings",
"(",
"stdin",
"stdout",
")",
"and",
"the",
"exit",
"code",
"(",
"unlike",
"popen2",
"exit",
"is",
"0",
"if",
"no",
"problems",
"occured",
"(",
"for",
"some",
"bizarre",
"reaso... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L386-L424 | [
"def",
"readProcess",
"(",
"cmd",
",",
"*",
"args",
")",
":",
"import",
"popen2",
"BUFSIZE",
"=",
"1024",
"import",
"select",
"popen",
"=",
"popen2",
".",
"Popen3",
"(",
"(",
"cmd",
",",
")",
"+",
"args",
",",
"capturestderr",
"=",
"True",
")",
"whic... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | runProcess | Run `cmd` (which is searched for in the executable path) with `args` and
return the exit status.
In general (unless you know what you're doing) use::
runProcess('program', filename)
rather than::
os.system('program %s' % filename)
because the latter will not work as expected if `filename`... | src/mlab/awmstools.py | def runProcess(cmd, *args):
"""Run `cmd` (which is searched for in the executable path) with `args` and
return the exit status.
In general (unless you know what you're doing) use::
runProcess('program', filename)
rather than::
os.system('program %s' % filename)
because the latter will... | def runProcess(cmd, *args):
"""Run `cmd` (which is searched for in the executable path) with `args` and
return the exit status.
In general (unless you know what you're doing) use::
runProcess('program', filename)
rather than::
os.system('program %s' % filename)
because the latter will... | [
"Run",
"cmd",
"(",
"which",
"is",
"searched",
"for",
"in",
"the",
"executable",
"path",
")",
"with",
"args",
"and",
"return",
"the",
"exit",
"status",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L432-L450 | [
"def",
"runProcess",
"(",
"cmd",
",",
"*",
"args",
")",
":",
"from",
"os",
"import",
"spawnvp",
",",
"P_WAIT",
"return",
"spawnvp",
"(",
"P_WAIT",
",",
"cmd",
",",
"(",
"cmd",
",",
")",
"+",
"args",
")"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | splitext | r"""Like the normal splitext (in posixpath), but doesn't treat dotfiles
(e.g. .emacs) as extensions. Also uses os.sep instead of '/'. | src/mlab/awmstools.py | def splitext(p):
r"""Like the normal splitext (in posixpath), but doesn't treat dotfiles
(e.g. .emacs) as extensions. Also uses os.sep instead of '/'."""
root, ext = os.path.splitext(p)
# check for dotfiles
if (not root or root[-1] == os.sep): # XXX: use '/' or os.sep here???
return (root +... | def splitext(p):
r"""Like the normal splitext (in posixpath), but doesn't treat dotfiles
(e.g. .emacs) as extensions. Also uses os.sep instead of '/'."""
root, ext = os.path.splitext(p)
# check for dotfiles
if (not root or root[-1] == os.sep): # XXX: use '/' or os.sep here???
return (root +... | [
"r",
"Like",
"the",
"normal",
"splitext",
"(",
"in",
"posixpath",
")",
"but",
"doesn",
"t",
"treat",
"dotfiles",
"(",
"e",
".",
"g",
".",
".",
"emacs",
")",
"as",
"extensions",
".",
"Also",
"uses",
"os",
".",
"sep",
"instead",
"of",
"/",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L463-L472 | [
"def",
"splitext",
"(",
"p",
")",
":",
"root",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"p",
")",
"# check for dotfiles",
"if",
"(",
"not",
"root",
"or",
"root",
"[",
"-",
"1",
"]",
"==",
"os",
".",
"sep",
")",
":",
"# XXX: use '... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | bipart | r"""Like a partitioning version of `filter`. Returns
``[itemsForWhichFuncReturnedFalse, itemsForWhichFuncReturnedTrue]``.
Example:
>>> bipart(bool, [1,None,2,3,0,[],[0]])
[[None, 0, []], [1, 2, 3, [0]]] | src/mlab/awmstools.py | def bipart(func, seq):
r"""Like a partitioning version of `filter`. Returns
``[itemsForWhichFuncReturnedFalse, itemsForWhichFuncReturnedTrue]``.
Example:
>>> bipart(bool, [1,None,2,3,0,[],[0]])
[[None, 0, []], [1, 2, 3, [0]]]
"""
if func is None: func = bool
res = [[],[]]
for i in... | def bipart(func, seq):
r"""Like a partitioning version of `filter`. Returns
``[itemsForWhichFuncReturnedFalse, itemsForWhichFuncReturnedTrue]``.
Example:
>>> bipart(bool, [1,None,2,3,0,[],[0]])
[[None, 0, []], [1, 2, 3, [0]]]
"""
if func is None: func = bool
res = [[],[]]
for i in... | [
"r",
"Like",
"a",
"partitioning",
"version",
"of",
"filter",
".",
"Returns",
"[",
"itemsForWhichFuncReturnedFalse",
"itemsForWhichFuncReturnedTrue",
"]",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L478-L491 | [
"def",
"bipart",
"(",
"func",
",",
"seq",
")",
":",
"if",
"func",
"is",
"None",
":",
"func",
"=",
"bool",
"res",
"=",
"[",
"[",
"]",
",",
"[",
"]",
"]",
"for",
"i",
"in",
"seq",
":",
"res",
"[",
"not",
"not",
"func",
"(",
"i",
")",
"]",
"... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | binarySearchPos | r"""Return the position of `item` in ordered sequence `seq`, using comparison
function `cmpfunc` (defaults to ``cmp``) and return the first found
position of `item`, or -1 if `item` is not in `seq`. The returned position
is NOT guaranteed to be the first occurence of `item` in `seq`. | src/mlab/awmstools.py | def binarySearchPos(seq, item, cmpfunc=cmp):
r"""Return the position of `item` in ordered sequence `seq`, using comparison
function `cmpfunc` (defaults to ``cmp``) and return the first found
position of `item`, or -1 if `item` is not in `seq`. The returned position
is NOT guaranteed to be the first occu... | def binarySearchPos(seq, item, cmpfunc=cmp):
r"""Return the position of `item` in ordered sequence `seq`, using comparison
function `cmpfunc` (defaults to ``cmp``) and return the first found
position of `item`, or -1 if `item` is not in `seq`. The returned position
is NOT guaranteed to be the first occu... | [
"r",
"Return",
"the",
"position",
"of",
"item",
"in",
"ordered",
"sequence",
"seq",
"using",
"comparison",
"function",
"cmpfunc",
"(",
"defaults",
"to",
"cmp",
")",
"and",
"return",
"the",
"first",
"found",
"position",
"of",
"item",
"or",
"-",
"1",
"if",
... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L499-L516 | [
"def",
"binarySearchPos",
"(",
"seq",
",",
"item",
",",
"cmpfunc",
"=",
"cmp",
")",
":",
"if",
"not",
"seq",
":",
"return",
"-",
"1",
"left",
",",
"right",
"=",
"0",
",",
"len",
"(",
"seq",
")",
"-",
"1",
"if",
"cmpfunc",
"(",
"seq",
"[",
"left... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | binarySearchItem | r""" Search an ordered sequence `seq` for `item`, using comparison function
`cmpfunc` (defaults to ``cmp``) and return the first found instance of
`item`, or `None` if item is not in `seq`. The returned item is NOT
guaranteed to be the first occurrence of item in `seq`. | src/mlab/awmstools.py | def binarySearchItem(seq, item, cmpfunc=cmp):
r""" Search an ordered sequence `seq` for `item`, using comparison function
`cmpfunc` (defaults to ``cmp``) and return the first found instance of
`item`, or `None` if item is not in `seq`. The returned item is NOT
guaranteed to be the first occurrence of it... | def binarySearchItem(seq, item, cmpfunc=cmp):
r""" Search an ordered sequence `seq` for `item`, using comparison function
`cmpfunc` (defaults to ``cmp``) and return the first found instance of
`item`, or `None` if item is not in `seq`. The returned item is NOT
guaranteed to be the first occurrence of it... | [
"r",
"Search",
"an",
"ordered",
"sequence",
"seq",
"for",
"item",
"using",
"comparison",
"function",
"cmpfunc",
"(",
"defaults",
"to",
"cmp",
")",
"and",
"return",
"the",
"first",
"found",
"instance",
"of",
"item",
"or",
"None",
"if",
"item",
"is",
"not",
... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L536-L543 | [
"def",
"binarySearchItem",
"(",
"seq",
",",
"item",
",",
"cmpfunc",
"=",
"cmp",
")",
":",
"pos",
"=",
"binarySearchPos",
"(",
"seq",
",",
"item",
",",
"cmpfunc",
")",
"if",
"pos",
"==",
"-",
"1",
":",
"raise",
"KeyError",
"(",
"\"Item not in seq\"",
")... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | rotate | r"""Rotates a list `l` `steps` to the left. Accepts
`steps` > `len(l)` or < 0.
>>> rotate([1,2,3])
[2, 3, 1]
>>> rotate([1,2,3,4],-2)
[3, 4, 1, 2]
>>> rotate([1,2,3,4],-5)
[4, 1, 2, 3]
>>> rotate([1,2,3,4],1)
[2, 3, 4, 1]
>>> l = [1,2,3]; rotate(l) is not l
True | src/mlab/awmstools.py | def rotate(l, steps=1):
r"""Rotates a list `l` `steps` to the left. Accepts
`steps` > `len(l)` or < 0.
>>> rotate([1,2,3])
[2, 3, 1]
>>> rotate([1,2,3,4],-2)
[3, 4, 1, 2]
>>> rotate([1,2,3,4],-5)
[4, 1, 2, 3]
>>> rotate([1,2,3,4],1)
[2, 3, 4, 1]
>>> l = [1,2,3]; rotate(l) is... | def rotate(l, steps=1):
r"""Rotates a list `l` `steps` to the left. Accepts
`steps` > `len(l)` or < 0.
>>> rotate([1,2,3])
[2, 3, 1]
>>> rotate([1,2,3,4],-2)
[3, 4, 1, 2]
>>> rotate([1,2,3,4],-5)
[4, 1, 2, 3]
>>> rotate([1,2,3,4],1)
[2, 3, 4, 1]
>>> l = [1,2,3]; rotate(l) is... | [
"r",
"Rotates",
"a",
"list",
"l",
"steps",
"to",
"the",
"left",
".",
"Accepts",
"steps",
">",
"len",
"(",
"l",
")",
"or",
"<",
"0",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L546-L566 | [
"def",
"rotate",
"(",
"l",
",",
"steps",
"=",
"1",
")",
":",
"if",
"len",
"(",
"l",
")",
":",
"steps",
"%=",
"len",
"(",
"l",
")",
"if",
"steps",
":",
"res",
"=",
"l",
"[",
"steps",
":",
"]",
"res",
".",
"extend",
"(",
"l",
"[",
":",
"ste... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | iprotate | r"""Like rotate, but modifies `l` in-place.
>>> l = [1,2,3]
>>> iprotate(l) is l
True
>>> l
[2, 3, 1]
>>> iprotate(iprotate(l, 2), -3)
[1, 2, 3] | src/mlab/awmstools.py | def iprotate(l, steps=1):
r"""Like rotate, but modifies `l` in-place.
>>> l = [1,2,3]
>>> iprotate(l) is l
True
>>> l
[2, 3, 1]
>>> iprotate(iprotate(l, 2), -3)
[1, 2, 3]
"""
if len(l):
steps %= len(l)
if steps:
firstPart = l[:steps]
del ... | def iprotate(l, steps=1):
r"""Like rotate, but modifies `l` in-place.
>>> l = [1,2,3]
>>> iprotate(l) is l
True
>>> l
[2, 3, 1]
>>> iprotate(iprotate(l, 2), -3)
[1, 2, 3]
"""
if len(l):
steps %= len(l)
if steps:
firstPart = l[:steps]
del ... | [
"r",
"Like",
"rotate",
"but",
"modifies",
"l",
"in",
"-",
"place",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L568-L586 | [
"def",
"iprotate",
"(",
"l",
",",
"steps",
"=",
"1",
")",
":",
"if",
"len",
"(",
"l",
")",
":",
"steps",
"%=",
"len",
"(",
"l",
")",
"if",
"steps",
":",
"firstPart",
"=",
"l",
"[",
":",
"steps",
"]",
"del",
"l",
"[",
":",
"steps",
"]",
"l",... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | unique | r"""Returns all unique items in `iterable` in the *same* order (only works
if items in `seq` are hashable). | src/mlab/awmstools.py | def unique(iterable):
r"""Returns all unique items in `iterable` in the *same* order (only works
if items in `seq` are hashable).
"""
d = {}
return (d.setdefault(x,x) for x in iterable if x not in d) | def unique(iterable):
r"""Returns all unique items in `iterable` in the *same* order (only works
if items in `seq` are hashable).
"""
d = {}
return (d.setdefault(x,x) for x in iterable if x not in d) | [
"r",
"Returns",
"all",
"unique",
"items",
"in",
"iterable",
"in",
"the",
"*",
"same",
"*",
"order",
"(",
"only",
"works",
"if",
"items",
"in",
"seq",
"are",
"hashable",
")",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L594-L599 | [
"def",
"unique",
"(",
"iterable",
")",
":",
"d",
"=",
"{",
"}",
"return",
"(",
"d",
".",
"setdefault",
"(",
"x",
",",
"x",
")",
"for",
"x",
"in",
"iterable",
"if",
"x",
"not",
"in",
"d",
")"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | notUnique | Returns the elements in `iterable` that aren't unique; stops after it found
`reportMax` non-unique elements.
Examples:
>>> list(notUnique([1,1,2,2,3,3]))
[1, 2, 3]
>>> list(notUnique([1,1,2,2,3,3], 1))
[1] | src/mlab/awmstools.py | def notUnique(iterable, reportMax=INF):
"""Returns the elements in `iterable` that aren't unique; stops after it found
`reportMax` non-unique elements.
Examples:
>>> list(notUnique([1,1,2,2,3,3]))
[1, 2, 3]
>>> list(notUnique([1,1,2,2,3,3], 1))
[1]
"""
hash = {}
n=0
if repo... | def notUnique(iterable, reportMax=INF):
"""Returns the elements in `iterable` that aren't unique; stops after it found
`reportMax` non-unique elements.
Examples:
>>> list(notUnique([1,1,2,2,3,3]))
[1, 2, 3]
>>> list(notUnique([1,1,2,2,3,3], 1))
[1]
"""
hash = {}
n=0
if repo... | [
"Returns",
"the",
"elements",
"in",
"iterable",
"that",
"aren",
"t",
"unique",
";",
"stops",
"after",
"it",
"found",
"reportMax",
"non",
"-",
"unique",
"elements",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L614-L635 | [
"def",
"notUnique",
"(",
"iterable",
",",
"reportMax",
"=",
"INF",
")",
":",
"hash",
"=",
"{",
"}",
"n",
"=",
"0",
"if",
"reportMax",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"`reportMax` must be >= 1 and is %r\"",
"%",
"reportMax",
")",
"for",
"item",... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | unweave | r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to
list `n`.
Example:
>>> unweave((1,2,3,4,5), 3)
[[1, 4], [2, 5], [3]] | src/mlab/awmstools.py | def unweave(iterable, n=2):
r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to
list `n`.
Example:
>>> unweave((1,2,3,4,5), 3)
[[1, 4], [2, 5], [3]]
"""
res = [[] for i in range(n)]
i = 0
for x in iterable:
res[i % n].append(x)
i += 1
retu... | def unweave(iterable, n=2):
r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to
list `n`.
Example:
>>> unweave((1,2,3,4,5), 3)
[[1, 4], [2, 5], [3]]
"""
res = [[] for i in range(n)]
i = 0
for x in iterable:
res[i % n].append(x)
i += 1
retu... | [
"r",
"Divide",
"iterable",
"in",
"n",
"lists",
"so",
"that",
"every",
"n",
"th",
"element",
"belongs",
"to",
"list",
"n",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L655-L669 | [
"def",
"unweave",
"(",
"iterable",
",",
"n",
"=",
"2",
")",
":",
"res",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"i",
"=",
"0",
"for",
"x",
"in",
"iterable",
":",
"res",
"[",
"i",
"%",
"n",
"]",
".",
"append",
"(... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | weave | r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]).
>>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C']))
[1, 4, 6, 2, 5, 7, 3, 6, 8]
Any iterable will work. The first exhausted iterable determines when to
stop. FIXME rethink stopping semantics.
>>> list(weave(iter(('is','psu')), ... | src/mlab/awmstools.py | def weave(*iterables):
r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]).
>>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C']))
[1, 4, 6, 2, 5, 7, 3, 6, 8]
Any iterable will work. The first exhausted iterable determines when to
stop. FIXME rethink stopping semantics.
>>> list... | def weave(*iterables):
r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]).
>>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C']))
[1, 4, 6, 2, 5, 7, 3, 6, 8]
Any iterable will work. The first exhausted iterable determines when to
stop. FIXME rethink stopping semantics.
>>> list... | [
"r",
"weave",
"(",
"seq1",
"[",
"seq2",
"]",
"[",
"...",
"]",
")",
"-",
">",
"iter",
"(",
"[",
"seq1",
"[",
"0",
"]",
"seq2",
"[",
"0",
"]",
"...",
"]",
")",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L674-L690 | [
"def",
"weave",
"(",
"*",
"iterables",
")",
":",
"iterables",
"=",
"map",
"(",
"iter",
",",
"iterables",
")",
"while",
"True",
":",
"for",
"it",
"in",
"iterables",
":",
"yield",
"it",
".",
"next",
"(",
")"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | atIndices | r"""Return a list of items in `indexable` at positions `indices`.
Examples:
>>> atIndices([1,2,3], [1,1,0])
[2, 2, 1]
>>> atIndices([1,2,3], [1,1,0,4], 'default')
[2, 2, 1, 'default']
>>> atIndices({'a':3, 'b':0}, ['a'])
[3] | src/mlab/awmstools.py | def atIndices(indexable, indices, default=__unique):
r"""Return a list of items in `indexable` at positions `indices`.
Examples:
>>> atIndices([1,2,3], [1,1,0])
[2, 2, 1]
>>> atIndices([1,2,3], [1,1,0,4], 'default')
[2, 2, 1, 'default']
>>> atIndices({'a':3, 'b':0}, ['a'])
[3]
"""
... | def atIndices(indexable, indices, default=__unique):
r"""Return a list of items in `indexable` at positions `indices`.
Examples:
>>> atIndices([1,2,3], [1,1,0])
[2, 2, 1]
>>> atIndices([1,2,3], [1,1,0,4], 'default')
[2, 2, 1, 'default']
>>> atIndices({'a':3, 'b':0}, ['a'])
[3]
"""
... | [
"r",
"Return",
"a",
"list",
"of",
"items",
"in",
"indexable",
"at",
"positions",
"indices",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L692-L713 | [
"def",
"atIndices",
"(",
"indexable",
",",
"indices",
",",
"default",
"=",
"__unique",
")",
":",
"if",
"default",
"is",
"__unique",
":",
"return",
"[",
"indexable",
"[",
"i",
"]",
"for",
"i",
"in",
"indices",
"]",
"else",
":",
"res",
"=",
"[",
"]",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | window | r"""Move an `n`-item (default 2) windows `s` steps (default 1) at a time
over `iterable`.
Examples:
>>> list(window(range(6),2))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> list(window(range(6),3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
>>> list(window(range(6),3, 2))
[(0, 1, 2)... | src/mlab/awmstools.py | def window(iterable, n=2, s=1):
r"""Move an `n`-item (default 2) windows `s` steps (default 1) at a time
over `iterable`.
Examples:
>>> list(window(range(6),2))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> list(window(range(6),3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
>>> list(w... | def window(iterable, n=2, s=1):
r"""Move an `n`-item (default 2) windows `s` steps (default 1) at a time
over `iterable`.
Examples:
>>> list(window(range(6),2))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> list(window(range(6),3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
>>> list(w... | [
"r",
"Move",
"an",
"n",
"-",
"item",
"(",
"default",
"2",
")",
"windows",
"s",
"steps",
"(",
"default",
"1",
")",
"at",
"a",
"time",
"over",
"iterable",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L733-L752 | [
"def",
"window",
"(",
"iterable",
",",
"n",
"=",
"2",
",",
"s",
"=",
"1",
")",
":",
"assert",
"n",
">=",
"s",
"last",
"=",
"[",
"]",
"for",
"elt",
"in",
"iterable",
":",
"last",
".",
"append",
"(",
"elt",
")",
"if",
"len",
"(",
"last",
")",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | group | r"""Iterate `n`-wise (default pairwise) over `iter`.
Examples:
>>> for (first, last) in group("Akira Kurosawa John Ford".split()):
... print "given name: %s surname: %s" % (first, last)
...
given name: Akira surname: Kurosawa
given name: John surname: Ford
>>>
>>> # both contain th... | src/mlab/awmstools.py | def group(iterable, n=2, pad=__unique):
r"""Iterate `n`-wise (default pairwise) over `iter`.
Examples:
>>> for (first, last) in group("Akira Kurosawa John Ford".split()):
... print "given name: %s surname: %s" % (first, last)
...
given name: Akira surname: Kurosawa
given name: John sur... | def group(iterable, n=2, pad=__unique):
r"""Iterate `n`-wise (default pairwise) over `iter`.
Examples:
>>> for (first, last) in group("Akira Kurosawa John Ford".split()):
... print "given name: %s surname: %s" % (first, last)
...
given name: Akira surname: Kurosawa
given name: John sur... | [
"r",
"Iterate",
"n",
"-",
"wise",
"(",
"default",
"pairwise",
")",
"over",
"iter",
".",
"Examples",
":"
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L756-L780 | [
"def",
"group",
"(",
"iterable",
",",
"n",
"=",
"2",
",",
"pad",
"=",
"__unique",
")",
":",
"assert",
"n",
">",
"0",
"# ensure it doesn't loop forever",
"if",
"pad",
"is",
"not",
"__unique",
":",
"it",
"=",
"chain",
"(",
"iterable",
",",
"(",
"pad",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | iterate | >>> list(iterate(lambda x:x//2)(128))
[128, 64, 32, 16, 8, 4, 2, 1, 0]
>>> list(iterate(lambda x:x//2, n=2)(128))
[128, 64] | src/mlab/awmstools.py | def iterate(f, n=None, last=__unique):
"""
>>> list(iterate(lambda x:x//2)(128))
[128, 64, 32, 16, 8, 4, 2, 1, 0]
>>> list(iterate(lambda x:x//2, n=2)(128))
[128, 64]
"""
if n is not None:
def funciter(start):
for i in xrange(n): yield start; start = f(start)
else:
... | def iterate(f, n=None, last=__unique):
"""
>>> list(iterate(lambda x:x//2)(128))
[128, 64, 32, 16, 8, 4, 2, 1, 0]
>>> list(iterate(lambda x:x//2, n=2)(128))
[128, 64]
"""
if n is not None:
def funciter(start):
for i in xrange(n): yield start; start = f(start)
else:
... | [
">>>",
"list",
"(",
"iterate",
"(",
"lambda",
"x",
":",
"x",
"//",
"2",
")",
"(",
"128",
"))",
"[",
"128",
"64",
"32",
"16",
"8",
"4",
"2",
"1",
"0",
"]",
">>>",
"list",
"(",
"iterate",
"(",
"lambda",
"x",
":",
"x",
"//",
"2",
"n",
"=",
"... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L782-L799 | [
"def",
"iterate",
"(",
"f",
",",
"n",
"=",
"None",
",",
"last",
"=",
"__unique",
")",
":",
"if",
"n",
"is",
"not",
"None",
":",
"def",
"funciter",
"(",
"start",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"n",
")",
":",
"yield",
"start",
"start"... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | dropwhilenot | >>> list(dropwhilenot(lambda x:x==3, range(10)))
[3, 4, 5, 6, 7, 8, 9] | src/mlab/awmstools.py | def dropwhilenot(func, iterable):
"""
>>> list(dropwhilenot(lambda x:x==3, range(10)))
[3, 4, 5, 6, 7, 8, 9]
"""
iterable = iter(iterable)
for x in iterable:
if func(x): break
else: return
yield x
for x in iterable:
yield x | def dropwhilenot(func, iterable):
"""
>>> list(dropwhilenot(lambda x:x==3, range(10)))
[3, 4, 5, 6, 7, 8, 9]
"""
iterable = iter(iterable)
for x in iterable:
if func(x): break
else: return
yield x
for x in iterable:
yield x | [
">>>",
"list",
"(",
"dropwhilenot",
"(",
"lambda",
"x",
":",
"x",
"==",
"3",
"range",
"(",
"10",
")))",
"[",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"]"
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L802-L813 | [
"def",
"dropwhilenot",
"(",
"func",
",",
"iterable",
")",
":",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"for",
"x",
"in",
"iterable",
":",
"if",
"func",
"(",
"x",
")",
":",
"break",
"else",
":",
"return",
"yield",
"x",
"for",
"x",
"in",
"iter... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | stretch | r"""Repeat each item in `iterable` `n` times.
Example:
>>> list(stretch(range(3), 2))
[0, 0, 1, 1, 2, 2] | src/mlab/awmstools.py | def stretch(iterable, n=2):
r"""Repeat each item in `iterable` `n` times.
Example:
>>> list(stretch(range(3), 2))
[0, 0, 1, 1, 2, 2]
"""
times = range(n)
for item in iterable:
for i in times: yield item | def stretch(iterable, n=2):
r"""Repeat each item in `iterable` `n` times.
Example:
>>> list(stretch(range(3), 2))
[0, 0, 1, 1, 2, 2]
"""
times = range(n)
for item in iterable:
for i in times: yield item | [
"r",
"Repeat",
"each",
"item",
"in",
"iterable",
"n",
"times",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L816-L826 | [
"def",
"stretch",
"(",
"iterable",
",",
"n",
"=",
"2",
")",
":",
"times",
"=",
"range",
"(",
"n",
")",
"for",
"item",
"in",
"iterable",
":",
"for",
"i",
"in",
"times",
":",
"yield",
"item"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | splitAt | r"""Yield chunks of `iterable`, split at the points in `indices`:
>>> [l for l in splitAt(range(10), [2,5])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
splits past the length of `iterable` are ignored:
>>> [l for l in splitAt(range(10), [2,5,10])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]] | src/mlab/awmstools.py | def splitAt(iterable, indices):
r"""Yield chunks of `iterable`, split at the points in `indices`:
>>> [l for l in splitAt(range(10), [2,5])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
splits past the length of `iterable` are ignored:
>>> [l for l in splitAt(range(10), [2,5,10])]
[[0, 1], [2, 3, 4],... | def splitAt(iterable, indices):
r"""Yield chunks of `iterable`, split at the points in `indices`:
>>> [l for l in splitAt(range(10), [2,5])]
[[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]]
splits past the length of `iterable` are ignored:
>>> [l for l in splitAt(range(10), [2,5,10])]
[[0, 1], [2, 3, 4],... | [
"r",
"Yield",
"chunks",
"of",
"iterable",
"split",
"at",
"the",
"points",
"in",
"indices",
":"
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L829-L852 | [
"def",
"splitAt",
"(",
"iterable",
",",
"indices",
")",
":",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"now",
"=",
"0",
"for",
"to",
"in",
"indices",
":",
"try",
":",
"res",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"now",
",",
"to",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | update | Return a copy of dict `d` updated with dict `e`. | src/mlab/awmstools.py | def update(d, e):
"""Return a copy of dict `d` updated with dict `e`."""
res = copy.copy(d)
res.update(e)
return res | def update(d, e):
"""Return a copy of dict `d` updated with dict `e`."""
res = copy.copy(d)
res.update(e)
return res | [
"Return",
"a",
"copy",
"of",
"dict",
"d",
"updated",
"with",
"dict",
"e",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L875-L879 | [
"def",
"update",
"(",
"d",
",",
"e",
")",
":",
"res",
"=",
"copy",
".",
"copy",
"(",
"d",
")",
"res",
".",
"update",
"(",
"e",
")",
"return",
"res"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | invertDict | r"""Return an inverted version of dict `d`, so that values become keys and
vice versa. If multiple keys in `d` have the same value an error is
raised, unless `allowManyToOne` is true, in which case one of those
key-value pairs is chosen at random for the inversion.
Examples:
>>> invertDict({1: 2, ... | src/mlab/awmstools.py | def invertDict(d, allowManyToOne=False):
r"""Return an inverted version of dict `d`, so that values become keys and
vice versa. If multiple keys in `d` have the same value an error is
raised, unless `allowManyToOne` is true, in which case one of those
key-value pairs is chosen at random for the inversio... | def invertDict(d, allowManyToOne=False):
r"""Return an inverted version of dict `d`, so that values become keys and
vice versa. If multiple keys in `d` have the same value an error is
raised, unless `allowManyToOne` is true, in which case one of those
key-value pairs is chosen at random for the inversio... | [
"r",
"Return",
"an",
"inverted",
"version",
"of",
"dict",
"d",
"so",
"that",
"values",
"become",
"keys",
"and",
"vice",
"versa",
".",
"If",
"multiple",
"keys",
"in",
"d",
"have",
"the",
"same",
"value",
"an",
"error",
"is",
"raised",
"unless",
"allowMany... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L881-L901 | [
"def",
"invertDict",
"(",
"d",
",",
"allowManyToOne",
"=",
"False",
")",
":",
"res",
"=",
"dict",
"(",
"izip",
"(",
"d",
".",
"itervalues",
"(",
")",
",",
"d",
".",
"iterkeys",
"(",
")",
")",
")",
"if",
"not",
"allowManyToOne",
"and",
"len",
"(",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | iflatten | r"""Like `flatten` but lazy. | src/mlab/awmstools.py | def iflatten(seq, isSeq=isSeq):
r"""Like `flatten` but lazy."""
for elt in seq:
if isSeq(elt):
for x in iflatten(elt, isSeq):
yield x
else:
yield elt | def iflatten(seq, isSeq=isSeq):
r"""Like `flatten` but lazy."""
for elt in seq:
if isSeq(elt):
for x in iflatten(elt, isSeq):
yield x
else:
yield elt | [
"r",
"Like",
"flatten",
"but",
"lazy",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L907-L914 | [
"def",
"iflatten",
"(",
"seq",
",",
"isSeq",
"=",
"isSeq",
")",
":",
"for",
"elt",
"in",
"seq",
":",
"if",
"isSeq",
"(",
"elt",
")",
":",
"for",
"x",
"in",
"iflatten",
"(",
"elt",
",",
"isSeq",
")",
":",
"yield",
"x",
"else",
":",
"yield",
"elt... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | flatten | r"""Returns a flattened version of a sequence `seq` as a `list`.
Parameters:
- `seq`: The sequence to be flattened (any iterable).
- `isSeq`: The function called to determine whether something is a
sequence (default: `isSeq`). *Beware that this function should
**never** test positive for ... | src/mlab/awmstools.py | def flatten(seq, isSeq=isSeq):
r"""Returns a flattened version of a sequence `seq` as a `list`.
Parameters:
- `seq`: The sequence to be flattened (any iterable).
- `isSeq`: The function called to determine whether something is a
sequence (default: `isSeq`). *Beware that this function should
... | def flatten(seq, isSeq=isSeq):
r"""Returns a flattened version of a sequence `seq` as a `list`.
Parameters:
- `seq`: The sequence to be flattened (any iterable).
- `isSeq`: The function called to determine whether something is a
sequence (default: `isSeq`). *Beware that this function should
... | [
"r",
"Returns",
"a",
"flattened",
"version",
"of",
"a",
"sequence",
"seq",
"as",
"a",
"list",
".",
"Parameters",
":"
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L929-L955 | [
"def",
"flatten",
"(",
"seq",
",",
"isSeq",
"=",
"isSeq",
")",
":",
"return",
"[",
"a",
"for",
"elt",
"in",
"seq",
"for",
"a",
"in",
"(",
"isSeq",
"(",
"elt",
")",
"and",
"flatten",
"(",
"elt",
",",
"isSeq",
")",
"or",
"[",
"elt",
"]",
")",
"... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | positionIf | >>> positionIf(lambda x: x > 3, range(10))
4 | src/mlab/awmstools.py | def positionIf(pred, seq):
"""
>>> positionIf(lambda x: x > 3, range(10))
4
"""
for i,e in enumerate(seq):
if pred(e):
return i
return -1 | def positionIf(pred, seq):
"""
>>> positionIf(lambda x: x > 3, range(10))
4
"""
for i,e in enumerate(seq):
if pred(e):
return i
return -1 | [
">>>",
"positionIf",
"(",
"lambda",
"x",
":",
"x",
">",
"3",
"range",
"(",
"10",
"))",
"4"
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L969-L977 | [
"def",
"positionIf",
"(",
"pred",
",",
"seq",
")",
":",
"for",
"i",
",",
"e",
"in",
"enumerate",
"(",
"seq",
")",
":",
"if",
"pred",
"(",
"e",
")",
":",
"return",
"i",
"return",
"-",
"1"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | union | r"""Return the set union of `seq1` and `seqs`, duplicates removed, order random.
Examples:
>>> union()
[]
>>> union([1,2,3])
[1, 2, 3]
>>> union([1,2,3], {1:2, 5:1})
[1, 2, 3, 5]
>>> union((1,2,3), ['a'], "bcd")
['a', 1, 2, 3, 'd', 'b', 'c']
>>> union([1,2,3], iter([0,1,1,1]))
... | src/mlab/awmstools.py | def union(seq1=(), *seqs):
r"""Return the set union of `seq1` and `seqs`, duplicates removed, order random.
Examples:
>>> union()
[]
>>> union([1,2,3])
[1, 2, 3]
>>> union([1,2,3], {1:2, 5:1})
[1, 2, 3, 5]
>>> union((1,2,3), ['a'], "bcd")
['a', 1, 2, 3, 'd', 'b', 'c']
>>> un... | def union(seq1=(), *seqs):
r"""Return the set union of `seq1` and `seqs`, duplicates removed, order random.
Examples:
>>> union()
[]
>>> union([1,2,3])
[1, 2, 3]
>>> union([1,2,3], {1:2, 5:1})
[1, 2, 3, 5]
>>> union((1,2,3), ['a'], "bcd")
['a', 1, 2, 3, 'd', 'b', 'c']
>>> un... | [
"r",
"Return",
"the",
"set",
"union",
"of",
"seq1",
"and",
"seqs",
"duplicates",
"removed",
"order",
"random",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L981-L1001 | [
"def",
"union",
"(",
"seq1",
"=",
"(",
")",
",",
"*",
"seqs",
")",
":",
"if",
"not",
"seqs",
":",
"return",
"list",
"(",
"seq1",
")",
"res",
"=",
"set",
"(",
"seq1",
")",
"for",
"seq",
"in",
"seqs",
":",
"res",
".",
"update",
"(",
"set",
"(",... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | without | r"""Return a list with all elements in `seq2` removed from `seq1`, order
preserved.
Examples:
>>> without([1,2,3,1,2], [1])
[2, 3, 2] | src/mlab/awmstools.py | def without(seq1, seq2):
r"""Return a list with all elements in `seq2` removed from `seq1`, order
preserved.
Examples:
>>> without([1,2,3,1,2], [1])
[2, 3, 2]
"""
if isSet(seq2): d2 = seq2
else: d2 = set(seq2)
return [elt for elt in seq1 if elt not in d2] | def without(seq1, seq2):
r"""Return a list with all elements in `seq2` removed from `seq1`, order
preserved.
Examples:
>>> without([1,2,3,1,2], [1])
[2, 3, 2]
"""
if isSet(seq2): d2 = seq2
else: d2 = set(seq2)
return [elt for elt in seq1 if elt not in d2] | [
"r",
"Return",
"a",
"list",
"with",
"all",
"elements",
"in",
"seq2",
"removed",
"from",
"seq1",
"order",
"preserved",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1011-L1022 | [
"def",
"without",
"(",
"seq1",
",",
"seq2",
")",
":",
"if",
"isSet",
"(",
"seq2",
")",
":",
"d2",
"=",
"seq2",
"else",
":",
"d2",
"=",
"set",
"(",
"seq2",
")",
"return",
"[",
"elt",
"for",
"elt",
"in",
"seq1",
"if",
"elt",
"not",
"in",
"d2",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | some | >>> some(lambda x: x, [0, False, None])
False
>>> some(lambda x: x, [None, 0, 2, 3])
2
>>> some(operator.eq, [0,1,2], [2,1,0])
True
>>> some(operator.eq, [1,2], [2,1])
False | src/mlab/awmstools.py | def some(predicate, *seqs):
"""
>>> some(lambda x: x, [0, False, None])
False
>>> some(lambda x: x, [None, 0, 2, 3])
2
>>> some(operator.eq, [0,1,2], [2,1,0])
True
>>> some(operator.eq, [1,2], [2,1])
False
"""
try:
if len(seqs) == 1: return ifilter(bool,imap(predicate... | def some(predicate, *seqs):
"""
>>> some(lambda x: x, [0, False, None])
False
>>> some(lambda x: x, [None, 0, 2, 3])
2
>>> some(operator.eq, [0,1,2], [2,1,0])
True
>>> some(operator.eq, [1,2], [2,1])
False
"""
try:
if len(seqs) == 1: return ifilter(bool,imap(predicate... | [
">>>",
"some",
"(",
"lambda",
"x",
":",
"x",
"[",
"0",
"False",
"None",
"]",
")",
"False",
">>>",
"some",
"(",
"lambda",
"x",
":",
"x",
"[",
"None",
"0",
"2",
"3",
"]",
")",
"2",
">>>",
"some",
"(",
"operator",
".",
"eq",
"[",
"0",
"1",
"2"... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1037-L1051 | [
"def",
"some",
"(",
"predicate",
",",
"*",
"seqs",
")",
":",
"try",
":",
"if",
"len",
"(",
"seqs",
")",
"==",
"1",
":",
"return",
"ifilter",
"(",
"bool",
",",
"imap",
"(",
"predicate",
",",
"seqs",
"[",
"0",
"]",
")",
")",
".",
"next",
"(",
"... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | every | r"""Like `some`, but only returns `True` if all the elements of `iterables`
satisfy `predicate`.
Examples:
>>> every(bool, [])
True
>>> every(bool, [0])
False
>>> every(bool, [1,1])
True
>>> every(operator.eq, [1,2,3],[1,2])
True
>>> every(operator.eq, [1,2,3],[0,2])
Fal... | src/mlab/awmstools.py | def every(predicate, *iterables):
r"""Like `some`, but only returns `True` if all the elements of `iterables`
satisfy `predicate`.
Examples:
>>> every(bool, [])
True
>>> every(bool, [0])
False
>>> every(bool, [1,1])
True
>>> every(operator.eq, [1,2,3],[1,2])
True
>>> eve... | def every(predicate, *iterables):
r"""Like `some`, but only returns `True` if all the elements of `iterables`
satisfy `predicate`.
Examples:
>>> every(bool, [])
True
>>> every(bool, [0])
False
>>> every(bool, [1,1])
True
>>> every(operator.eq, [1,2,3],[1,2])
True
>>> eve... | [
"r",
"Like",
"some",
"but",
"only",
"returns",
"True",
"if",
"all",
"the",
"elements",
"of",
"iterables",
"satisfy",
"predicate",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1053-L1073 | [
"def",
"every",
"(",
"predicate",
",",
"*",
"iterables",
")",
":",
"try",
":",
"if",
"len",
"(",
"iterables",
")",
"==",
"1",
":",
"ifilterfalse",
"(",
"predicate",
",",
"iterables",
"[",
"0",
"]",
")",
".",
"next",
"(",
")",
"else",
":",
"ifilterf... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | nTimes | r"""Call `f` `n` times with `args` and `kwargs`.
Useful e.g. for simplistic timing.
Examples:
>>> nTimes(3, sys.stdout.write, 'hallo\n')
hallo
hallo
hallo | src/mlab/awmstools.py | def nTimes(n, f, *args, **kwargs):
r"""Call `f` `n` times with `args` and `kwargs`.
Useful e.g. for simplistic timing.
Examples:
>>> nTimes(3, sys.stdout.write, 'hallo\n')
hallo
hallo
hallo
"""
for i in xrange(n): f(*args, **kwargs) | def nTimes(n, f, *args, **kwargs):
r"""Call `f` `n` times with `args` and `kwargs`.
Useful e.g. for simplistic timing.
Examples:
>>> nTimes(3, sys.stdout.write, 'hallo\n')
hallo
hallo
hallo
"""
for i in xrange(n): f(*args, **kwargs) | [
"r",
"Call",
"f",
"n",
"times",
"with",
"args",
"and",
"kwargs",
".",
"Useful",
"e",
".",
"g",
".",
"for",
"simplistic",
"timing",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1082-L1094 | [
"def",
"nTimes",
"(",
"n",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"n",
")",
":",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | timeCall | r"""Return the time (in ms) it takes to call a function (the first
argument) with the remaining arguments and `kwargs`.
Examples:
To find out how long ``func('foo', spam=1)`` takes to execute, do:
``timeCall(func, foo, spam=1)`` | src/mlab/awmstools.py | def timeCall(*funcAndArgs, **kwargs):
r"""Return the time (in ms) it takes to call a function (the first
argument) with the remaining arguments and `kwargs`.
Examples:
To find out how long ``func('foo', spam=1)`` takes to execute, do:
``timeCall(func, foo, spam=1)``
"""
func, args = func... | def timeCall(*funcAndArgs, **kwargs):
r"""Return the time (in ms) it takes to call a function (the first
argument) with the remaining arguments and `kwargs`.
Examples:
To find out how long ``func('foo', spam=1)`` takes to execute, do:
``timeCall(func, foo, spam=1)``
"""
func, args = func... | [
"r",
"Return",
"the",
"time",
"(",
"in",
"ms",
")",
"it",
"takes",
"to",
"call",
"a",
"function",
"(",
"the",
"first",
"argument",
")",
"with",
"the",
"remaining",
"arguments",
"and",
"kwargs",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1097-L1111 | [
"def",
"timeCall",
"(",
"*",
"funcAndArgs",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
",",
"args",
"=",
"funcAndArgs",
"[",
"0",
"]",
",",
"funcAndArgs",
"[",
"1",
":",
"]",
"start",
"=",
"time",
".",
"time",
"(",
")",
"func",
"(",
"*",
"args",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | replaceStrs | r"""Replace all ``(frm, to)`` tuples in `args` in string `s`.
>>> replaceStrs("nothing is better than warm beer",
... ('nothing','warm beer'), ('warm beer','nothing'))
'warm beer is better than nothing' | src/mlab/awmstools.py | def replaceStrs(s, *args):
r"""Replace all ``(frm, to)`` tuples in `args` in string `s`.
>>> replaceStrs("nothing is better than warm beer",
... ('nothing','warm beer'), ('warm beer','nothing'))
'warm beer is better than nothing'
"""
if args == (): return s
mapping = dict((frm,... | def replaceStrs(s, *args):
r"""Replace all ``(frm, to)`` tuples in `args` in string `s`.
>>> replaceStrs("nothing is better than warm beer",
... ('nothing','warm beer'), ('warm beer','nothing'))
'warm beer is better than nothing'
"""
if args == (): return s
mapping = dict((frm,... | [
"r",
"Replace",
"all",
"(",
"frm",
"to",
")",
"tuples",
"in",
"args",
"in",
"string",
"s",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1148-L1159 | [
"def",
"replaceStrs",
"(",
"s",
",",
"*",
"args",
")",
":",
"if",
"args",
"==",
"(",
")",
":",
"return",
"s",
"mapping",
"=",
"dict",
"(",
"(",
"frm",
",",
"to",
")",
"for",
"frm",
",",
"to",
"in",
"args",
")",
"return",
"re",
".",
"sub",
"("... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | unescape | r"""Inverse of `escape`.
>>> unescape(r'\x41\n\x42\n\x43')
'A\nB\nC'
>>> unescape(r'\u86c7')
u'\u86c7'
>>> unescape(u'ah')
u'ah' | src/mlab/awmstools.py | def unescape(s):
r"""Inverse of `escape`.
>>> unescape(r'\x41\n\x42\n\x43')
'A\nB\nC'
>>> unescape(r'\u86c7')
u'\u86c7'
>>> unescape(u'ah')
u'ah'
"""
if re.search(r'(?<!\\)\\(\\\\)*[uU]', s) or isinstance(s, unicode):
return unescapeUnicode(s)
else:
return unescap... | def unescape(s):
r"""Inverse of `escape`.
>>> unescape(r'\x41\n\x42\n\x43')
'A\nB\nC'
>>> unescape(r'\u86c7')
u'\u86c7'
>>> unescape(u'ah')
u'ah'
"""
if re.search(r'(?<!\\)\\(\\\\)*[uU]', s) or isinstance(s, unicode):
return unescapeUnicode(s)
else:
return unescap... | [
"r",
"Inverse",
"of",
"escape",
".",
">>>",
"unescape",
"(",
"r",
"\\",
"x41",
"\\",
"n",
"\\",
"x42",
"\\",
"n",
"\\",
"x43",
")",
"A",
"\\",
"nB",
"\\",
"nC",
">>>",
"unescape",
"(",
"r",
"\\",
"u86c7",
")",
"u",
"\\",
"u86c7",
">>>",
"unesca... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1178-L1190 | [
"def",
"unescape",
"(",
"s",
")",
":",
"if",
"re",
".",
"search",
"(",
"r'(?<!\\\\)\\\\(\\\\\\\\)*[uU]'",
",",
"s",
")",
"or",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"return",
"unescapeUnicode",
"(",
"s",
")",
"else",
":",
"return",
"unescapeA... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | lineAndColumnAt | r"""Return line and column of `pos` (0-based!) in `s`. Lines start with
1, columns with 0.
Examples:
>>> lineAndColumnAt("0123\n56", 5)
(2, 0)
>>> lineAndColumnAt("0123\n56", 6)
(2, 1)
>>> lineAndColumnAt("0123\n56", 0)
(1, 0) | src/mlab/awmstools.py | def lineAndColumnAt(s, pos):
r"""Return line and column of `pos` (0-based!) in `s`. Lines start with
1, columns with 0.
Examples:
>>> lineAndColumnAt("0123\n56", 5)
(2, 0)
>>> lineAndColumnAt("0123\n56", 6)
(2, 1)
>>> lineAndColumnAt("0123\n56", 0)
(1, 0)
"""
if pos >= len(... | def lineAndColumnAt(s, pos):
r"""Return line and column of `pos` (0-based!) in `s`. Lines start with
1, columns with 0.
Examples:
>>> lineAndColumnAt("0123\n56", 5)
(2, 0)
>>> lineAndColumnAt("0123\n56", 6)
(2, 1)
>>> lineAndColumnAt("0123\n56", 0)
(1, 0)
"""
if pos >= len(... | [
"r",
"Return",
"line",
"and",
"column",
"of",
"pos",
"(",
"0",
"-",
"based!",
")",
"in",
"s",
".",
"Lines",
"start",
"with",
"1",
"columns",
"with",
"0",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1198-L1218 | [
"def",
"lineAndColumnAt",
"(",
"s",
",",
"pos",
")",
":",
"if",
"pos",
">=",
"len",
"(",
"s",
")",
":",
"raise",
"IndexError",
"(",
"\"`pos` %d not in string\"",
"%",
"pos",
")",
"# *don't* count last '\\n', if it is at pos!",
"line",
"=",
"s",
".",
"count",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | prin | r"""Like ``print``, but a function. I.e. prints out all arguments as
``print`` would do. Specify output stream like this::
print('ERROR', `out="sys.stderr"``). | src/mlab/awmstools.py | def prin(*args, **kwargs):
r"""Like ``print``, but a function. I.e. prints out all arguments as
``print`` would do. Specify output stream like this::
print('ERROR', `out="sys.stderr"``).
"""
print >> kwargs.get('out',None), " ".join([str(arg) for arg in args]) | def prin(*args, **kwargs):
r"""Like ``print``, but a function. I.e. prints out all arguments as
``print`` would do. Specify output stream like this::
print('ERROR', `out="sys.stderr"``).
"""
print >> kwargs.get('out',None), " ".join([str(arg) for arg in args]) | [
"r",
"Like",
"print",
"but",
"a",
"function",
".",
"I",
".",
"e",
".",
"prints",
"out",
"all",
"arguments",
"as",
"print",
"would",
"do",
".",
"Specify",
"output",
"stream",
"like",
"this",
"::"
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1222-L1229 | [
"def",
"prin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
">>",
"kwargs",
".",
"get",
"(",
"'out'",
",",
"None",
")",
",",
"\" \"",
".",
"join",
"(",
"[",
"str",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
")"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | fitString | r"""Truncate `s` if necessary to fit into a line of width `maxCol`
(default: 79), also replacing newlines with `newlineReplacement` (default
`None`: in which case everything after the first newline is simply
discarded).
Examples:
>>> fitString('12345', maxCol=5)
'12345'
>>> fitString('1234... | src/mlab/awmstools.py | def fitString(s, maxCol=79, newlineReplacement=None):
r"""Truncate `s` if necessary to fit into a line of width `maxCol`
(default: 79), also replacing newlines with `newlineReplacement` (default
`None`: in which case everything after the first newline is simply
discarded).
Examples:
>>> fitStr... | def fitString(s, maxCol=79, newlineReplacement=None):
r"""Truncate `s` if necessary to fit into a line of width `maxCol`
(default: 79), also replacing newlines with `newlineReplacement` (default
`None`: in which case everything after the first newline is simply
discarded).
Examples:
>>> fitStr... | [
"r",
"Truncate",
"s",
"if",
"necessary",
"to",
"fit",
"into",
"a",
"line",
"of",
"width",
"maxCol",
"(",
"default",
":",
"79",
")",
"also",
"replacing",
"newlines",
"with",
"newlineReplacement",
"(",
"default",
"None",
":",
"in",
"which",
"case",
"everythi... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1249-L1274 | [
"def",
"fitString",
"(",
"s",
",",
"maxCol",
"=",
"79",
",",
"newlineReplacement",
"=",
"None",
")",
":",
"assert",
"isString",
"(",
"s",
")",
"if",
"'\\n'",
"in",
"s",
":",
"if",
"newlineReplacement",
"is",
"None",
":",
"s",
"=",
"s",
"[",
":",
"s... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | saveVars | r"""Pickle name and value of all those variables in `outOf` (default: all
global variables (as seen from the caller)) that are named in
`varNamesStr` into a file called `filename` (if no extension is given,
'.bpickle' is appended). Overwrites file without asking, unless you
specify `overwrite=0`. Load a... | src/mlab/awmstools.py | def saveVars(filename, varNamesStr, outOf=None, **opts):
r"""Pickle name and value of all those variables in `outOf` (default: all
global variables (as seen from the caller)) that are named in
`varNamesStr` into a file called `filename` (if no extension is given,
'.bpickle' is appended). Overwrites file... | def saveVars(filename, varNamesStr, outOf=None, **opts):
r"""Pickle name and value of all those variables in `outOf` (default: all
global variables (as seen from the caller)) that are named in
`varNamesStr` into a file called `filename` (if no extension is given,
'.bpickle' is appended). Overwrites file... | [
"r",
"Pickle",
"name",
"and",
"value",
"of",
"all",
"those",
"variables",
"in",
"outOf",
"(",
"default",
":",
"all",
"global",
"variables",
"(",
"as",
"seen",
"from",
"the",
"caller",
"))",
"that",
"are",
"named",
"in",
"varNamesStr",
"into",
"a",
"file"... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1305-L1328 | [
"def",
"saveVars",
"(",
"filename",
",",
"varNamesStr",
",",
"outOf",
"=",
"None",
",",
"*",
"*",
"opts",
")",
":",
"filename",
",",
"varnames",
",",
"outOf",
"=",
"__saveVarsHelper",
"(",
"filename",
",",
"varNamesStr",
",",
"outOf",
",",
"*",
"*",
"o... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | addVars | r"""Like `saveVars`, but appends additional variables to file. | src/mlab/awmstools.py | def addVars(filename, varNamesStr, outOf=None):
r"""Like `saveVars`, but appends additional variables to file."""
filename, varnames, outOf = __saveVarsHelper(filename, varNamesStr, outOf)
f = None
try:
f = open(filename, "rb")
h = cPickle.load(f)
f.close()
h.update(dict... | def addVars(filename, varNamesStr, outOf=None):
r"""Like `saveVars`, but appends additional variables to file."""
filename, varnames, outOf = __saveVarsHelper(filename, varNamesStr, outOf)
f = None
try:
f = open(filename, "rb")
h = cPickle.load(f)
f.close()
h.update(dict... | [
"r",
"Like",
"saveVars",
"but",
"appends",
"additional",
"variables",
"to",
"file",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1336-L1349 | [
"def",
"addVars",
"(",
"filename",
",",
"varNamesStr",
",",
"outOf",
"=",
"None",
")",
":",
"filename",
",",
"varnames",
",",
"outOf",
"=",
"__saveVarsHelper",
"(",
"filename",
",",
"varNamesStr",
",",
"outOf",
")",
"f",
"=",
"None",
"try",
":",
"f",
"... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | loadDict | Return the variables pickled pickled into `filename` with `saveVars`
as a dict. | src/mlab/awmstools.py | def loadDict(filename):
"""Return the variables pickled pickled into `filename` with `saveVars`
as a dict."""
filename = os.path.expanduser(filename)
if not splitext(filename)[1]: filename += ".bpickle"
f = None
try:
f = open(filename, "rb")
varH = cPickle.load(f)
finally:
... | def loadDict(filename):
"""Return the variables pickled pickled into `filename` with `saveVars`
as a dict."""
filename = os.path.expanduser(filename)
if not splitext(filename)[1]: filename += ".bpickle"
f = None
try:
f = open(filename, "rb")
varH = cPickle.load(f)
finally:
... | [
"Return",
"the",
"variables",
"pickled",
"pickled",
"into",
"filename",
"with",
"saveVars",
"as",
"a",
"dict",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1351-L1362 | [
"def",
"loadDict",
"(",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"if",
"not",
"splitext",
"(",
"filename",
")",
"[",
"1",
"]",
":",
"filename",
"+=",
"\".bpickle\"",
"f",
"=",
"None",
"try",
"... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | loadVars | r"""Load variables pickled with `saveVars`.
Parameters:
- `ask`: If `True` then don't overwrite existing variables without
asking.
- `only`: A list to limit the variables to or `None`.
- `into`: The dictionary the variables should be loaded into (defaults
... | src/mlab/awmstools.py | def loadVars(filename, ask=True, into=None, only=None):
r"""Load variables pickled with `saveVars`.
Parameters:
- `ask`: If `True` then don't overwrite existing variables without
asking.
- `only`: A list to limit the variables to or `None`.
- `into`: The dictionary the ... | def loadVars(filename, ask=True, into=None, only=None):
r"""Load variables pickled with `saveVars`.
Parameters:
- `ask`: If `True` then don't overwrite existing variables without
asking.
- `only`: A list to limit the variables to or `None`.
- `into`: The dictionary the ... | [
"r",
"Load",
"variables",
"pickled",
"with",
"saveVars",
".",
"Parameters",
":"
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1364-L1393 | [
"def",
"loadVars",
"(",
"filename",
",",
"ask",
"=",
"True",
",",
"into",
"=",
"None",
",",
"only",
"=",
"None",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"if",
"into",
"is",
"None",
":",
"into",
"=",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | runInfo | r"""Create a short info string detailing how a program was invoked. This is
meant to be added to a history comment field of a data file were it is
important to keep track of what programs modified it and how.
!!!:`args` should be a **``list``** not a ``str``. | src/mlab/awmstools.py | def runInfo(prog=None,vers=None,date=None,user=None,dir=None,args=None):
r"""Create a short info string detailing how a program was invoked. This is
meant to be added to a history comment field of a data file were it is
important to keep track of what programs modified it and how.
!!!:`args` should be ... | def runInfo(prog=None,vers=None,date=None,user=None,dir=None,args=None):
r"""Create a short info string detailing how a program was invoked. This is
meant to be added to a history comment field of a data file were it is
important to keep track of what programs modified it and how.
!!!:`args` should be ... | [
"r",
"Create",
"a",
"short",
"info",
"string",
"detailing",
"how",
"a",
"program",
"was",
"invoked",
".",
"This",
"is",
"meant",
"to",
"be",
"added",
"to",
"a",
"history",
"comment",
"field",
"of",
"a",
"data",
"file",
"were",
"it",
"is",
"important",
... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1401-L1415 | [
"def",
"runInfo",
"(",
"prog",
"=",
"None",
",",
"vers",
"=",
"None",
",",
"date",
"=",
"None",
",",
"user",
"=",
"None",
",",
"dir",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"return",
"\"%(prog)s %(vers)s;\"",
"\" run %(date)s by %(usr)s in %(dir)... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | makePrintReturner | r"""Creates functions that print out their argument, (between optional
`pre` and `post` strings) and return it unmodified. This is usefull for
debugging e.g. parts of expressions, without having to modify the behavior
of the program.
Example:
>>> makePrintReturner(pre="The value is:", post="[retur... | src/mlab/awmstools.py | def makePrintReturner(pre="", post="" ,out=None):
r"""Creates functions that print out their argument, (between optional
`pre` and `post` strings) and return it unmodified. This is usefull for
debugging e.g. parts of expressions, without having to modify the behavior
of the program.
Example:
>... | def makePrintReturner(pre="", post="" ,out=None):
r"""Creates functions that print out their argument, (between optional
`pre` and `post` strings) and return it unmodified. This is usefull for
debugging e.g. parts of expressions, without having to modify the behavior
of the program.
Example:
>... | [
"r",
"Creates",
"functions",
"that",
"print",
"out",
"their",
"argument",
"(",
"between",
"optional",
"pre",
"and",
"post",
"strings",
")",
"and",
"return",
"it",
"unmodified",
".",
"This",
"is",
"usefull",
"for",
"debugging",
"e",
".",
"g",
".",
"parts",
... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1543-L1560 | [
"def",
"makePrintReturner",
"(",
"pre",
"=",
"\"\"",
",",
"post",
"=",
"\"\"",
",",
"out",
"=",
"None",
")",
":",
"def",
"printReturner",
"(",
"arg",
")",
":",
"myArgs",
"=",
"[",
"pre",
",",
"arg",
",",
"post",
"]",
"prin",
"(",
"*",
"myArgs",
"... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | asVerboseContainer | Returns a 'verbose' version of container instance `cont`, that will
execute `onGet`, `onSet` and `onDel` (if not `None`) every time
__getitem__, __setitem__ and __delitem__ are called, passing `self`, `key`
(and `value` in the case of set). E.g:
>>> l = [1,2,3]
>>> l = asVerboseConta... | src/mlab/awmstools.py | def asVerboseContainer(cont, onGet=None, onSet=None, onDel=None):
"""Returns a 'verbose' version of container instance `cont`, that will
execute `onGet`, `onSet` and `onDel` (if not `None`) every time
__getitem__, __setitem__ and __delitem__ are called, passing `self`, `key`
(and `value` in the... | def asVerboseContainer(cont, onGet=None, onSet=None, onDel=None):
"""Returns a 'verbose' version of container instance `cont`, that will
execute `onGet`, `onSet` and `onDel` (if not `None`) every time
__getitem__, __setitem__ and __delitem__ are called, passing `self`, `key`
(and `value` in the... | [
"Returns",
"a",
"verbose",
"version",
"of",
"container",
"instance",
"cont",
"that",
"will",
"execute",
"onGet",
"onSet",
"and",
"onDel",
"(",
"if",
"not",
"None",
")",
"every",
"time",
"__getitem__",
"__setitem__",
"and",
"__delitem__",
"are",
"called",
"pass... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1599-L1638 | [
"def",
"asVerboseContainer",
"(",
"cont",
",",
"onGet",
"=",
"None",
",",
"onSet",
"=",
"None",
",",
"onDel",
"=",
"None",
")",
":",
"class",
"VerboseContainer",
"(",
"type",
"(",
"cont",
")",
")",
":",
"if",
"onGet",
":",
"def",
"__getitem__",
"(",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | mkRepr | r"""Convinience function to implement ``__repr__``. `kwargs` values are
``repr`` ed. Special behavior for ``instance=None``: just the
arguments are formatted.
Example:
>>> class Thing:
... def __init__(self, color, shape, taste=None):
... self.color, self.shape,... | src/mlab/awmstools.py | def mkRepr(instance, *argls, **kwargs):
r"""Convinience function to implement ``__repr__``. `kwargs` values are
``repr`` ed. Special behavior for ``instance=None``: just the
arguments are formatted.
Example:
>>> class Thing:
... def __init__(self, color, shape, taste=None):... | def mkRepr(instance, *argls, **kwargs):
r"""Convinience function to implement ``__repr__``. `kwargs` values are
``repr`` ed. Special behavior for ``instance=None``: just the
arguments are formatted.
Example:
>>> class Thing:
... def __init__(self, color, shape, taste=None):... | [
"r",
"Convinience",
"function",
"to",
"implement",
"__repr__",
".",
"kwargs",
"values",
"are",
"repr",
"ed",
".",
"Special",
"behavior",
"for",
"instance",
"=",
"None",
":",
"just",
"the",
"arguments",
"are",
"formatted",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1724-L1764 | [
"def",
"mkRepr",
"(",
"instance",
",",
"*",
"argls",
",",
"*",
"*",
"kwargs",
")",
":",
"width",
"=",
"79",
"maxIndent",
"=",
"15",
"minIndent",
"=",
"2",
"args",
"=",
"(",
"map",
"(",
"repr",
",",
"argls",
")",
"+",
"[",
"\"%s=%r\"",
"%",
"(",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | d2attrs | Utility function to remove ``**kwargs`` parsing boiler-plate in
``__init__``:
>>> kwargs = dict(name='Bill', age=51, income=1e7)
>>> self = ezstruct(); d2attrs(kwargs, self, 'income', 'name'); self
ezstruct(income=10000000.0, name='Bill')
>>> self = ezstruct(); d2attrs(kwargs, se... | src/mlab/awmstools.py | def d2attrs(*args, **kwargs):
"""Utility function to remove ``**kwargs`` parsing boiler-plate in
``__init__``:
>>> kwargs = dict(name='Bill', age=51, income=1e7)
>>> self = ezstruct(); d2attrs(kwargs, self, 'income', 'name'); self
ezstruct(income=10000000.0, name='Bill')
>>> ... | def d2attrs(*args, **kwargs):
"""Utility function to remove ``**kwargs`` parsing boiler-plate in
``__init__``:
>>> kwargs = dict(name='Bill', age=51, income=1e7)
>>> self = ezstruct(); d2attrs(kwargs, self, 'income', 'name'); self
ezstruct(income=10000000.0, name='Bill')
>>> ... | [
"Utility",
"function",
"to",
"remove",
"**",
"kwargs",
"parsing",
"boiler",
"-",
"plate",
"in",
"__init__",
":"
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1787-L1814 | [
"def",
"d2attrs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"(",
"d",
",",
"self",
")",
",",
"args",
"=",
"args",
"[",
":",
"2",
"]",
",",
"args",
"[",
"2",
":",
"]",
"if",
"args",
"[",
"0",
"]",
"==",
"'all!'",
":",
"assert",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | pairwise | >>> pairwise(operator.sub, [4,3,2,1,-10])
[1, 1, 1, 11]
>>> import numpy
>>> pairwise(numpy.subtract, numpy.array([4,3,2,1,-10]))
array([ 1, 1, 1, 11]) | src/mlab/awmstools.py | def pairwise(fun, v):
"""
>>> pairwise(operator.sub, [4,3,2,1,-10])
[1, 1, 1, 11]
>>> import numpy
>>> pairwise(numpy.subtract, numpy.array([4,3,2,1,-10]))
array([ 1, 1, 1, 11])
"""
if not hasattr(v, 'shape'):
return list(ipairwise(fun,v))
else:
return fun(v[:-1],v[... | def pairwise(fun, v):
"""
>>> pairwise(operator.sub, [4,3,2,1,-10])
[1, 1, 1, 11]
>>> import numpy
>>> pairwise(numpy.subtract, numpy.array([4,3,2,1,-10]))
array([ 1, 1, 1, 11])
"""
if not hasattr(v, 'shape'):
return list(ipairwise(fun,v))
else:
return fun(v[:-1],v[... | [
">>>",
"pairwise",
"(",
"operator",
".",
"sub",
"[",
"4",
"3",
"2",
"1",
"-",
"10",
"]",
")",
"[",
"1",
"1",
"1",
"11",
"]",
">>>",
"import",
"numpy",
">>>",
"pairwise",
"(",
"numpy",
".",
"subtract",
"numpy",
".",
"array",
"(",
"[",
"4",
"3",
... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1819-L1830 | [
"def",
"pairwise",
"(",
"fun",
",",
"v",
")",
":",
"if",
"not",
"hasattr",
"(",
"v",
",",
"'shape'",
")",
":",
"return",
"list",
"(",
"ipairwise",
"(",
"fun",
",",
"v",
")",
")",
"else",
":",
"return",
"fun",
"(",
"v",
"[",
":",
"-",
"1",
"]"... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | argmax | >>> argmax([4,2,-5])
0
>>> argmax([4,2,-5], key=abs)
2
>>> argmax([4,2,-5], key=abs, both=True)
(2, 5) | src/mlab/awmstools.py | def argmax(iterable, key=None, both=False):
"""
>>> argmax([4,2,-5])
0
>>> argmax([4,2,-5], key=abs)
2
>>> argmax([4,2,-5], key=abs, both=True)
(2, 5)
"""
if key is not None:
it = imap(key, iterable)
else:
it = iter(iterable)
score, argmax = reduce(max, izip(i... | def argmax(iterable, key=None, both=False):
"""
>>> argmax([4,2,-5])
0
>>> argmax([4,2,-5], key=abs)
2
>>> argmax([4,2,-5], key=abs, both=True)
(2, 5)
"""
if key is not None:
it = imap(key, iterable)
else:
it = iter(iterable)
score, argmax = reduce(max, izip(i... | [
">>>",
"argmax",
"(",
"[",
"4",
"2",
"-",
"5",
"]",
")",
"0",
">>>",
"argmax",
"(",
"[",
"4",
"2",
"-",
"5",
"]",
"key",
"=",
"abs",
")",
"2",
">>>",
"argmax",
"(",
"[",
"4",
"2",
"-",
"5",
"]",
"key",
"=",
"abs",
"both",
"=",
"True",
"... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1846-L1862 | [
"def",
"argmax",
"(",
"iterable",
",",
"key",
"=",
"None",
",",
"both",
"=",
"False",
")",
":",
"if",
"key",
"is",
"not",
"None",
":",
"it",
"=",
"imap",
"(",
"key",
",",
"iterable",
")",
"else",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"s... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | argmin | See `argmax`. | src/mlab/awmstools.py | def argmin(iterable, key=None, both=False):
"""See `argmax`.
"""
if key is not None:
it = imap(key, iterable)
else:
it = iter(iterable)
score, argmin = reduce(min, izip(it, count()))
if both:
return argmin, score
return argmin | def argmin(iterable, key=None, both=False):
"""See `argmax`.
"""
if key is not None:
it = imap(key, iterable)
else:
it = iter(iterable)
score, argmin = reduce(min, izip(it, count()))
if both:
return argmin, score
return argmin | [
"See",
"argmax",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1864-L1874 | [
"def",
"argmin",
"(",
"iterable",
",",
"key",
"=",
"None",
",",
"both",
"=",
"False",
")",
":",
"if",
"key",
"is",
"not",
"None",
":",
"it",
"=",
"imap",
"(",
"key",
",",
"iterable",
")",
"else",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"s... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | isInt | Returns true if `num` is (sort of) an integer.
>>> isInt(3) == isInt(3.0) == 1
True
>>> isInt(3.2)
False
>>> import numpy
>>> isInt(numpy.array(1))
True
>>> isInt(numpy.array([1]))
False | src/mlab/awmstools.py | def isInt(num):
"""Returns true if `num` is (sort of) an integer.
>>> isInt(3) == isInt(3.0) == 1
True
>>> isInt(3.2)
False
>>> import numpy
>>> isInt(numpy.array(1))
True
>>> isInt(numpy.array([1]))
False
"""
try:
len(num) # FIXME fails for Numeric but Numeric is... | def isInt(num):
"""Returns true if `num` is (sort of) an integer.
>>> isInt(3) == isInt(3.0) == 1
True
>>> isInt(3.2)
False
>>> import numpy
>>> isInt(numpy.array(1))
True
>>> isInt(numpy.array([1]))
False
"""
try:
len(num) # FIXME fails for Numeric but Numeric is... | [
"Returns",
"true",
"if",
"num",
"is",
"(",
"sort",
"of",
")",
"an",
"integer",
".",
">>>",
"isInt",
"(",
"3",
")",
"==",
"isInt",
"(",
"3",
".",
"0",
")",
"==",
"1",
"True",
">>>",
"isInt",
"(",
"3",
".",
"2",
")",
"False",
">>>",
"import",
"... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1881-L1899 | [
"def",
"isInt",
"(",
"num",
")",
":",
"try",
":",
"len",
"(",
"num",
")",
"# FIXME fails for Numeric but Numeric is obsolete",
"except",
":",
"try",
":",
"return",
"(",
"num",
"-",
"math",
".",
"floor",
"(",
"num",
")",
"==",
"0",
")",
"==",
"True",
"e... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | mapConcat | Similar to `map` but the instead of collecting the return values of
`func` in a list, the items of each return value are instaed collected
(so `func` must return an iterable type).
Examples:
>>> mapConcat(lambda x:[x], [1,2,3])
[1, 2, 3]
>>> mapConcat(lambda x: [x,str(x)], [1,2,3])
[1, '1'... | src/mlab/awmstools.py | def mapConcat(func, *iterables):
"""Similar to `map` but the instead of collecting the return values of
`func` in a list, the items of each return value are instaed collected
(so `func` must return an iterable type).
Examples:
>>> mapConcat(lambda x:[x], [1,2,3])
[1, 2, 3]
>>> mapConcat(la... | def mapConcat(func, *iterables):
"""Similar to `map` but the instead of collecting the return values of
`func` in a list, the items of each return value are instaed collected
(so `func` must return an iterable type).
Examples:
>>> mapConcat(lambda x:[x], [1,2,3])
[1, 2, 3]
>>> mapConcat(la... | [
"Similar",
"to",
"map",
"but",
"the",
"instead",
"of",
"collecting",
"the",
"return",
"values",
"of",
"func",
"in",
"a",
"list",
"the",
"items",
"of",
"each",
"return",
"value",
"are",
"instaed",
"collected",
"(",
"so",
"func",
"must",
"return",
"an",
"i... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1917-L1929 | [
"def",
"mapConcat",
"(",
"func",
",",
"*",
"iterables",
")",
":",
"return",
"[",
"e",
"for",
"l",
"in",
"imap",
"(",
"func",
",",
"*",
"iterables",
")",
"for",
"e",
"in",
"l",
"]"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | unfold | >>> list(unfold(1234, lambda x: divmod(x,10)))[::-1]
[1, 2, 3, 4]
>>> sum(imap(operator.mul,unfold(1234, lambda x:divmod(x,10)), iterate(lambda x:x*10)(1)))
1234
>>> g = unfold(1234, lambda x:divmod(x,10))
>>> reduce((lambda (total,pow),digit:(total+pow*digit, 10*pow)), g, (0,1))
(1234, 10000) | src/mlab/awmstools.py | def unfold(seed, by, last = __unique):
"""
>>> list(unfold(1234, lambda x: divmod(x,10)))[::-1]
[1, 2, 3, 4]
>>> sum(imap(operator.mul,unfold(1234, lambda x:divmod(x,10)), iterate(lambda x:x*10)(1)))
1234
>>> g = unfold(1234, lambda x:divmod(x,10))
>>> reduce((lambda (total,pow),digit:(total... | def unfold(seed, by, last = __unique):
"""
>>> list(unfold(1234, lambda x: divmod(x,10)))[::-1]
[1, 2, 3, 4]
>>> sum(imap(operator.mul,unfold(1234, lambda x:divmod(x,10)), iterate(lambda x:x*10)(1)))
1234
>>> g = unfold(1234, lambda x:divmod(x,10))
>>> reduce((lambda (total,pow),digit:(total... | [
">>>",
"list",
"(",
"unfold",
"(",
"1234",
"lambda",
"x",
":",
"divmod",
"(",
"x",
"10",
")))",
"[",
"::",
"-",
"1",
"]",
"[",
"1",
"2",
"3",
"4",
"]",
">>>",
"sum",
"(",
"imap",
"(",
"operator",
".",
"mul",
"unfold",
"(",
"1234",
"lambda",
"... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1935-L1949 | [
"def",
"unfold",
"(",
"seed",
",",
"by",
",",
"last",
"=",
"__unique",
")",
":",
"while",
"True",
":",
"seed",
",",
"val",
"=",
"by",
"(",
"seed",
")",
"if",
"last",
"==",
"seed",
":",
"return",
"last",
"=",
"seed",
"yield",
"val"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | reduceR | *R*ight reduce.
>>> reduceR(lambda x,y:x/y, [1.,2.,3.,4]) == 1./(2./(3./4.)) == (1./2.)*(3./4.)
True
>>> reduceR(lambda x,y:x-y, iter([1,2,3]),4) == 1-(2-(3-4)) == (1-2)+(3-4)
True | src/mlab/awmstools.py | def reduceR(f, sequence, initial=__unique):
"""*R*ight reduce.
>>> reduceR(lambda x,y:x/y, [1.,2.,3.,4]) == 1./(2./(3./4.)) == (1./2.)*(3./4.)
True
>>> reduceR(lambda x,y:x-y, iter([1,2,3]),4) == 1-(2-(3-4)) == (1-2)+(3-4)
True
"""
try: rev = reversed(sequence)
except TypeError: rev = re... | def reduceR(f, sequence, initial=__unique):
"""*R*ight reduce.
>>> reduceR(lambda x,y:x/y, [1.,2.,3.,4]) == 1./(2./(3./4.)) == (1./2.)*(3./4.)
True
>>> reduceR(lambda x,y:x-y, iter([1,2,3]),4) == 1-(2-(3-4)) == (1-2)+(3-4)
True
"""
try: rev = reversed(sequence)
except TypeError: rev = re... | [
"*",
"R",
"*",
"ight",
"reduce",
".",
">>>",
"reduceR",
"(",
"lambda",
"x",
"y",
":",
"x",
"/",
"y",
"[",
"1",
".",
"2",
".",
"3",
".",
"4",
"]",
")",
"==",
"1",
".",
"/",
"(",
"2",
".",
"/",
"(",
"3",
".",
"/",
"4",
".",
"))",
"==",
... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1951-L1961 | [
"def",
"reduceR",
"(",
"f",
",",
"sequence",
",",
"initial",
"=",
"__unique",
")",
":",
"try",
":",
"rev",
"=",
"reversed",
"(",
"sequence",
")",
"except",
"TypeError",
":",
"rev",
"=",
"reversed",
"(",
"list",
"(",
"sequence",
")",
")",
"if",
"initi... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | compose | Compose `funcs` to a single function.
>>> compose(operator.abs, operator.add)(-2,-3)
5
>>> compose()('nada')
'nada'
>>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2)
[1, 2] | src/mlab/awmstools.py | def compose(*funcs):
"""Compose `funcs` to a single function.
>>> compose(operator.abs, operator.add)(-2,-3)
5
>>> compose()('nada')
'nada'
>>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2)
[1, 2]
"""
# slightly optimized for most common cases and hence verbose
i... | def compose(*funcs):
"""Compose `funcs` to a single function.
>>> compose(operator.abs, operator.add)(-2,-3)
5
>>> compose()('nada')
'nada'
>>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2)
[1, 2]
"""
# slightly optimized for most common cases and hence verbose
i... | [
"Compose",
"funcs",
"to",
"a",
"single",
"function",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1964-L1984 | [
"def",
"compose",
"(",
"*",
"funcs",
")",
":",
"# slightly optimized for most common cases and hence verbose",
"if",
"len",
"(",
"funcs",
")",
"==",
"2",
":",
"f0",
",",
"f1",
"=",
"funcs",
"return",
"lambda",
"*",
"a",
",",
"*",
"*",
"kw",
":",
"f0",
"(... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | romanNumeral | >>> romanNumeral(13)
'XIII'
>>> romanNumeral(2944)
'MMCMXLIV' | src/mlab/awmstools.py | def romanNumeral(n):
"""
>>> romanNumeral(13)
'XIII'
>>> romanNumeral(2944)
'MMCMXLIV'
"""
if 0 > n > 4000: raise ValueError('``n`` must lie between 1 and 3999: %d' % n)
roman = 'I IV V IX X XL L XC C CD D CM M'.split()
arabic = [1, 4, 5, 9, 10, 40, 50, 90, 10... | def romanNumeral(n):
"""
>>> romanNumeral(13)
'XIII'
>>> romanNumeral(2944)
'MMCMXLIV'
"""
if 0 > n > 4000: raise ValueError('``n`` must lie between 1 and 3999: %d' % n)
roman = 'I IV V IX X XL L XC C CD D CM M'.split()
arabic = [1, 4, 5, 9, 10, 40, 50, 90, 10... | [
">>>",
"romanNumeral",
"(",
"13",
")",
"XIII",
">>>",
"romanNumeral",
"(",
"2944",
")",
"MMCMXLIV"
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1987-L2002 | [
"def",
"romanNumeral",
"(",
"n",
")",
":",
"if",
"0",
">",
"n",
">",
"4000",
":",
"raise",
"ValueError",
"(",
"'``n`` must lie between 1 and 3999: %d'",
"%",
"n",
")",
"roman",
"=",
"'I IV V IX X XL L XC C CD D CM M'",
".",
"split",
"(",
")",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | first | >>> first(3,iter([1,2,3,4]))
[1, 2, 3]
>>> first(3,iter([1,2,3,4]), iter) #doctest: +ELLIPSIS
<itertools.islice object at ...>
>>> first(3,iter([1,2,3,4]), tuple)
(1, 2, 3) | src/mlab/awmstools.py | def first(n, it, constructor=list):
"""
>>> first(3,iter([1,2,3,4]))
[1, 2, 3]
>>> first(3,iter([1,2,3,4]), iter) #doctest: +ELLIPSIS
<itertools.islice object at ...>
>>> first(3,iter([1,2,3,4]), tuple)
(1, 2, 3)
"""
return constructor(itertools.islice(it,n)) | def first(n, it, constructor=list):
"""
>>> first(3,iter([1,2,3,4]))
[1, 2, 3]
>>> first(3,iter([1,2,3,4]), iter) #doctest: +ELLIPSIS
<itertools.islice object at ...>
>>> first(3,iter([1,2,3,4]), tuple)
(1, 2, 3)
"""
return constructor(itertools.islice(it,n)) | [
">>>",
"first",
"(",
"3",
"iter",
"(",
"[",
"1",
"2",
"3",
"4",
"]",
"))",
"[",
"1",
"2",
"3",
"]",
">>>",
"first",
"(",
"3",
"iter",
"(",
"[",
"1",
"2",
"3",
"4",
"]",
")",
"iter",
")",
"#doctest",
":",
"+",
"ELLIPSIS",
"<itertools",
".",
... | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L2011-L2020 | [
"def",
"first",
"(",
"n",
",",
"it",
",",
"constructor",
"=",
"list",
")",
":",
"return",
"constructor",
"(",
"itertools",
".",
"islice",
"(",
"it",
",",
"n",
")",
")"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | drop | >>> first(10,drop(10,xrange(sys.maxint),iter))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19] | src/mlab/awmstools.py | def drop(n, it, constructor=list):
"""
>>> first(10,drop(10,xrange(sys.maxint),iter))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
"""
return constructor(itertools.islice(it,n,None)) | def drop(n, it, constructor=list):
"""
>>> first(10,drop(10,xrange(sys.maxint),iter))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
"""
return constructor(itertools.islice(it,n,None)) | [
">>>",
"first",
"(",
"10",
"drop",
"(",
"10",
"xrange",
"(",
"sys",
".",
"maxint",
")",
"iter",
"))",
"[",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"]"
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L2021-L2026 | [
"def",
"drop",
"(",
"n",
",",
"it",
",",
"constructor",
"=",
"list",
")",
":",
"return",
"constructor",
"(",
"itertools",
".",
"islice",
"(",
"it",
",",
"n",
",",
"None",
")",
")"
] | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | DryRun.run | Same as ``self.dryRun`` if ``self.dry``, else same as ``self.wetRun``. | src/mlab/awmstools.py | def run(self, func, *args, **kwargs):
"""Same as ``self.dryRun`` if ``self.dry``, else same as ``self.wetRun``."""
if self.dry:
return self.dryRun(func, *args, **kwargs)
else:
return self.wetRun(func, *args, **kwargs) | def run(self, func, *args, **kwargs):
"""Same as ``self.dryRun`` if ``self.dry``, else same as ``self.wetRun``."""
if self.dry:
return self.dryRun(func, *args, **kwargs)
else:
return self.wetRun(func, *args, **kwargs) | [
"Same",
"as",
"self",
".",
"dryRun",
"if",
"self",
".",
"dry",
"else",
"same",
"as",
"self",
".",
"wetRun",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1516-L1521 | [
"def",
"run",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"dry",
":",
"return",
"self",
".",
"dryRun",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | DryRun.dryRun | Instead of running function with `*args` and `**kwargs`, just print
out the function call. | src/mlab/awmstools.py | def dryRun(self, func, *args, **kwargs):
"""Instead of running function with `*args` and `**kwargs`, just print
out the function call."""
print >> self.out, \
self.formatterDict.get(func, self.defaultFormatter)(func, *args, **kwargs) | def dryRun(self, func, *args, **kwargs):
"""Instead of running function with `*args` and `**kwargs`, just print
out the function call."""
print >> self.out, \
self.formatterDict.get(func, self.defaultFormatter)(func, *args, **kwargs) | [
"Instead",
"of",
"running",
"function",
"with",
"*",
"args",
"and",
"**",
"kwargs",
"just",
"print",
"out",
"the",
"function",
"call",
"."
] | ewiger/mlab | python | https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1528-L1533 | [
"def",
"dryRun",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
">>",
"self",
".",
"out",
",",
"self",
".",
"formatterDict",
".",
"get",
"(",
"func",
",",
"self",
".",
"defaultFormatter",
")",
"(",
"func",
... | 72a98adf6499f548848ad44c604f74d68f07fe4f |
train | iterbridges | Iterate over all the bridges in the system. | pynetlinux/brctl.py | def iterbridges():
''' Iterate over all the bridges in the system. '''
net_files = os.listdir(SYSFS_NET_PATH)
for d in net_files:
path = os.path.join(SYSFS_NET_PATH, d)
if not os.path.isdir(path):
continue
if os.path.exists(os.path.join(path, b"bridge")):
yiel... | def iterbridges():
''' Iterate over all the bridges in the system. '''
net_files = os.listdir(SYSFS_NET_PATH)
for d in net_files:
path = os.path.join(SYSFS_NET_PATH, d)
if not os.path.isdir(path):
continue
if os.path.exists(os.path.join(path, b"bridge")):
yiel... | [
"Iterate",
"over",
"all",
"the",
"bridges",
"in",
"the",
"system",
"."
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L97-L105 | [
"def",
"iterbridges",
"(",
")",
":",
"net_files",
"=",
"os",
".",
"listdir",
"(",
"SYSFS_NET_PATH",
")",
"for",
"d",
"in",
"net_files",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SYSFS_NET_PATH",
",",
"d",
")",
"if",
"not",
"os",
".",
... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | addbr | Create new bridge with the given name | pynetlinux/brctl.py | def addbr(name):
''' Create new bridge with the given name '''
fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name)
return Bridge(name) | def addbr(name):
''' Create new bridge with the given name '''
fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name)
return Bridge(name) | [
"Create",
"new",
"bridge",
"with",
"the",
"given",
"name"
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L113-L116 | [
"def",
"addbr",
"(",
"name",
")",
":",
"fcntl",
".",
"ioctl",
"(",
"ifconfig",
".",
"sockfd",
",",
"SIOCBRADDBR",
",",
"name",
")",
"return",
"Bridge",
"(",
"name",
")"
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | Bridge.iterifs | Iterate over all the interfaces in this bridge. | pynetlinux/brctl.py | def iterifs(self):
''' Iterate over all the interfaces in this bridge. '''
if_path = os.path.join(SYSFS_NET_PATH, self.name, b"brif")
net_files = os.listdir(if_path)
for iface in net_files:
yield iface | def iterifs(self):
''' Iterate over all the interfaces in this bridge. '''
if_path = os.path.join(SYSFS_NET_PATH, self.name, b"brif")
net_files = os.listdir(if_path)
for iface in net_files:
yield iface | [
"Iterate",
"over",
"all",
"the",
"interfaces",
"in",
"this",
"bridge",
"."
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L32-L37 | [
"def",
"iterifs",
"(",
"self",
")",
":",
"if_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SYSFS_NET_PATH",
",",
"self",
".",
"name",
",",
"b\"brif\"",
")",
"net_files",
"=",
"os",
".",
"listdir",
"(",
"if_path",
")",
"for",
"iface",
"in",
"net_f... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | Bridge.addif | Add the interface with the given name to this bridge. Equivalent to
brctl addif [bridge] [interface]. | pynetlinux/brctl.py | def addif(self, iface):
''' Add the interface with the given name to this bridge. Equivalent to
brctl addif [bridge] [interface]. '''
if type(iface) == ifconfig.Interface:
devindex = iface.index
else:
devindex = ifconfig.Interface(iface).index
ifreq = ... | def addif(self, iface):
''' Add the interface with the given name to this bridge. Equivalent to
brctl addif [bridge] [interface]. '''
if type(iface) == ifconfig.Interface:
devindex = iface.index
else:
devindex = ifconfig.Interface(iface).index
ifreq = ... | [
"Add",
"the",
"interface",
"with",
"the",
"given",
"name",
"to",
"this",
"bridge",
".",
"Equivalent",
"to",
"brctl",
"addif",
"[",
"bridge",
"]",
"[",
"interface",
"]",
"."
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L45-L54 | [
"def",
"addif",
"(",
"self",
",",
"iface",
")",
":",
"if",
"type",
"(",
"iface",
")",
"==",
"ifconfig",
".",
"Interface",
":",
"devindex",
"=",
"iface",
".",
"index",
"else",
":",
"devindex",
"=",
"ifconfig",
".",
"Interface",
"(",
"iface",
")",
".",... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | Bridge.delif | Remove the interface with the given name from this bridge.
Equivalent to brctl delif [bridge] [interface] | pynetlinux/brctl.py | def delif(self, iface):
''' Remove the interface with the given name from this bridge.
Equivalent to brctl delif [bridge] [interface]'''
if type(iface) == ifconfig.Interface:
devindex = iface.index
else:
devindex = ifconfig.Interface(iface).index
ifreq... | def delif(self, iface):
''' Remove the interface with the given name from this bridge.
Equivalent to brctl delif [bridge] [interface]'''
if type(iface) == ifconfig.Interface:
devindex = iface.index
else:
devindex = ifconfig.Interface(iface).index
ifreq... | [
"Remove",
"the",
"interface",
"with",
"the",
"given",
"name",
"from",
"this",
"bridge",
".",
"Equivalent",
"to",
"brctl",
"delif",
"[",
"bridge",
"]",
"[",
"interface",
"]"
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L57-L66 | [
"def",
"delif",
"(",
"self",
",",
"iface",
")",
":",
"if",
"type",
"(",
"iface",
")",
"==",
"ifconfig",
".",
"Interface",
":",
"devindex",
"=",
"iface",
".",
"index",
"else",
":",
"devindex",
"=",
"ifconfig",
".",
"Interface",
"(",
"iface",
")",
".",... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | Bridge.delete | Brings down the bridge interface, and removes it. Equivalent to
ifconfig [bridge] down && brctl delbr [bridge]. | pynetlinux/brctl.py | def delete(self):
''' Brings down the bridge interface, and removes it. Equivalent to
ifconfig [bridge] down && brctl delbr [bridge]. '''
self.down()
fcntl.ioctl(ifconfig.sockfd, SIOCBRDELBR, self.name)
return self | def delete(self):
''' Brings down the bridge interface, and removes it. Equivalent to
ifconfig [bridge] down && brctl delbr [bridge]. '''
self.down()
fcntl.ioctl(ifconfig.sockfd, SIOCBRDELBR, self.name)
return self | [
"Brings",
"down",
"the",
"bridge",
"interface",
"and",
"removes",
"it",
".",
"Equivalent",
"to",
"ifconfig",
"[",
"bridge",
"]",
"down",
"&&",
"brctl",
"delbr",
"[",
"bridge",
"]",
"."
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L76-L81 | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"down",
"(",
")",
"fcntl",
".",
"ioctl",
"(",
"ifconfig",
".",
"sockfd",
",",
"SIOCBRDELBR",
",",
"self",
".",
"name",
")",
"return",
"self"
] | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | _get_random_id | Get a random (i.e., unique) string identifier | d3py/core.py | def _get_random_id():
""" Get a random (i.e., unique) string identifier"""
symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.choice(symbols) for _ in range(15)) | def _get_random_id():
""" Get a random (i.e., unique) string identifier"""
symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.choice(symbols) for _ in range(15)) | [
"Get",
"a",
"random",
"(",
"i",
".",
"e",
".",
"unique",
")",
"string",
"identifier"
] | jluttine/d3py | python | https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L16-L19 | [
"def",
"_get_random_id",
"(",
")",
":",
"symbols",
"=",
"string",
".",
"ascii_uppercase",
"+",
"string",
".",
"ascii_lowercase",
"+",
"string",
".",
"digits",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"symbols",
")",
"for",
"_",
"in... | 2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0 |
train | get_lib_filename | Get a filename of a built-in library file. | d3py/core.py | def get_lib_filename(category, name):
""" Get a filename of a built-in library file. """
base_dir = os.path.dirname(os.path.abspath(__file__))
if category == 'js':
filename = os.path.join('js', '{0}.js'.format(name))
elif category == 'css':
filename = os.path.join('css', '{0}.css'.format... | def get_lib_filename(category, name):
""" Get a filename of a built-in library file. """
base_dir = os.path.dirname(os.path.abspath(__file__))
if category == 'js':
filename = os.path.join('js', '{0}.js'.format(name))
elif category == 'css':
filename = os.path.join('css', '{0}.css'.format... | [
"Get",
"a",
"filename",
"of",
"a",
"built",
"-",
"in",
"library",
"file",
"."
] | jluttine/d3py | python | https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L29-L40 | [
"def",
"get_lib_filename",
"(",
"category",
",",
"name",
")",
":",
"base_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"if",
"category",
"==",
"'js'",
":",
"filename",
"=",
"os",
".",... | 2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0 |
train | output_notebook | Import required Javascript libraries to Jupyter Notebook. | d3py/core.py | def output_notebook(
d3js_url="//d3js.org/d3.v3.min",
requirejs_url="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js",
html_template=None
):
""" Import required Javascript libraries to Jupyter Notebook. """
if html_template is None:
html_template = read_lib('ht... | def output_notebook(
d3js_url="//d3js.org/d3.v3.min",
requirejs_url="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js",
html_template=None
):
""" Import required Javascript libraries to Jupyter Notebook. """
if html_template is None:
html_template = read_lib('ht... | [
"Import",
"required",
"Javascript",
"libraries",
"to",
"Jupyter",
"Notebook",
"."
] | jluttine/d3py | python | https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L59-L76 | [
"def",
"output_notebook",
"(",
"d3js_url",
"=",
"\"//d3js.org/d3.v3.min\"",
",",
"requirejs_url",
"=",
"\"//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js\"",
",",
"html_template",
"=",
"None",
")",
":",
"if",
"html_template",
"is",
"None",
":",
"html_templ... | 2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0 |
train | create_graph_html | Create HTML code block given the graph Javascript and CSS. | d3py/core.py | def create_graph_html(js_template, css_template, html_template=None):
""" Create HTML code block given the graph Javascript and CSS. """
if html_template is None:
html_template = read_lib('html', 'graph')
# Create div ID for the graph and give it to the JS and CSS templates so
# they can refere... | def create_graph_html(js_template, css_template, html_template=None):
""" Create HTML code block given the graph Javascript and CSS. """
if html_template is None:
html_template = read_lib('html', 'graph')
# Create div ID for the graph and give it to the JS and CSS templates so
# they can refere... | [
"Create",
"HTML",
"code",
"block",
"given",
"the",
"graph",
"Javascript",
"and",
"CSS",
"."
] | jluttine/d3py | python | https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L79-L95 | [
"def",
"create_graph_html",
"(",
"js_template",
",",
"css_template",
",",
"html_template",
"=",
"None",
")",
":",
"if",
"html_template",
"is",
"None",
":",
"html_template",
"=",
"read_lib",
"(",
"'html'",
",",
"'graph'",
")",
"# Create div ID for the graph and give ... | 2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0 |
train | get_newest_possible_languagetool_version | Return newest compatible version.
>>> version = get_newest_possible_languagetool_version()
>>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION]
True | download_lt.py | def get_newest_possible_languagetool_version():
"""Return newest compatible version.
>>> version = get_newest_possible_languagetool_version()
>>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION]
True
"""
java_path = find_executable('java')
if not java_path:
# Just ignore this... | def get_newest_possible_languagetool_version():
"""Return newest compatible version.
>>> version = get_newest_possible_languagetool_version()
>>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION]
True
"""
java_path = find_executable('java')
if not java_path:
# Just ignore this... | [
"Return",
"newest",
"compatible",
"version",
"."
] | viraja1/grammar-check | python | https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/download_lt.py#L33-L69 | [
"def",
"get_newest_possible_languagetool_version",
"(",
")",
":",
"java_path",
"=",
"find_executable",
"(",
"'java'",
")",
"if",
"not",
"java_path",
":",
"# Just ignore this and assume an old version of Java. It might not be",
"# found because of a PATHEXT-related issue",
"# (https... | 103bf27119b85b4ef26c8f8d4089b6c882cabe5c |
train | iterifs | Iterate over all the interfaces in the system. If physical is
true, then return only real physical interfaces (not 'lo', etc). | pynetlinux/ifconfig.py | def iterifs(physical=True):
''' Iterate over all the interfaces in the system. If physical is
true, then return only real physical interfaces (not 'lo', etc).'''
net_files = os.listdir(SYSFS_NET_PATH)
interfaces = set()
virtual = set()
for d in net_files:
path = os.path.join(SYSFS_NE... | def iterifs(physical=True):
''' Iterate over all the interfaces in the system. If physical is
true, then return only real physical interfaces (not 'lo', etc).'''
net_files = os.listdir(SYSFS_NET_PATH)
interfaces = set()
virtual = set()
for d in net_files:
path = os.path.join(SYSFS_NE... | [
"Iterate",
"over",
"all",
"the",
"interfaces",
"in",
"the",
"system",
".",
"If",
"physical",
"is",
"true",
"then",
"return",
"only",
"real",
"physical",
"interfaces",
"(",
"not",
"lo",
"etc",
")",
"."
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L353-L388 | [
"def",
"iterifs",
"(",
"physical",
"=",
"True",
")",
":",
"net_files",
"=",
"os",
".",
"listdir",
"(",
"SYSFS_NET_PATH",
")",
"interfaces",
"=",
"set",
"(",
")",
"virtual",
"=",
"set",
"(",
")",
"for",
"d",
"in",
"net_files",
":",
"path",
"=",
"os",
... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | init | Initialize the library | pynetlinux/ifconfig.py | def init():
''' Initialize the library '''
globals()["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
globals()["sockfd"] = globals()["sock"].fileno() | def init():
''' Initialize the library '''
globals()["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
globals()["sockfd"] = globals()["sock"].fileno() | [
"Initialize",
"the",
"library"
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L403-L406 | [
"def",
"init",
"(",
")",
":",
"globals",
"(",
")",
"[",
"\"sock\"",
"]",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"globals",
"(",
")",
"[",
"\"sockfd\"",
"]",
"=",
"globals",
"(",
")",
"["... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | Interface.up | Bring up the bridge interface. Equivalent to ifconfig [iface] up. | pynetlinux/ifconfig.py | def up(self):
''' Bring up the bridge interface. Equivalent to ifconfig [iface] up. '''
# Get existing device flags
ifreq = struct.pack('16sh', self.name, 0)
flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1]
# Set new flags
flags = flags | IFF_U... | def up(self):
''' Bring up the bridge interface. Equivalent to ifconfig [iface] up. '''
# Get existing device flags
ifreq = struct.pack('16sh', self.name, 0)
flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1]
# Set new flags
flags = flags | IFF_U... | [
"Bring",
"up",
"the",
"bridge",
"interface",
".",
"Equivalent",
"to",
"ifconfig",
"[",
"iface",
"]",
"up",
"."
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L142-L152 | [
"def",
"up",
"(",
"self",
")",
":",
"# Get existing device flags",
"ifreq",
"=",
"struct",
".",
"pack",
"(",
"'16sh'",
",",
"self",
".",
"name",
",",
"0",
")",
"flags",
"=",
"struct",
".",
"unpack",
"(",
"'16sh'",
",",
"fcntl",
".",
"ioctl",
"(",
"so... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | Interface.is_up | Return True if the interface is up, False otherwise. | pynetlinux/ifconfig.py | def is_up(self):
''' Return True if the interface is up, False otherwise. '''
# Get existing device flags
ifreq = struct.pack('16sh', self.name, 0)
flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1]
# Set new flags
if flags & IFF_UP:
... | def is_up(self):
''' Return True if the interface is up, False otherwise. '''
# Get existing device flags
ifreq = struct.pack('16sh', self.name, 0)
flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1]
# Set new flags
if flags & IFF_UP:
... | [
"Return",
"True",
"if",
"the",
"interface",
"is",
"up",
"False",
"otherwise",
"."
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L166-L177 | [
"def",
"is_up",
"(",
"self",
")",
":",
"# Get existing device flags",
"ifreq",
"=",
"struct",
".",
"pack",
"(",
"'16sh'",
",",
"self",
".",
"name",
",",
"0",
")",
"flags",
"=",
"struct",
".",
"unpack",
"(",
"'16sh'",
",",
"fcntl",
".",
"ioctl",
"(",
... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | Interface.get_mac | Obtain the device's mac address. | pynetlinux/ifconfig.py | def get_mac(self):
''' Obtain the device's mac address. '''
ifreq = struct.pack('16sH14s', self.name, AF_UNIX, b'\x00'*14)
res = fcntl.ioctl(sockfd, SIOCGIFHWADDR, ifreq)
address = struct.unpack('16sH14s', res)[2]
mac = struct.unpack('6B8x', address)
return ":".join(['%0... | def get_mac(self):
''' Obtain the device's mac address. '''
ifreq = struct.pack('16sH14s', self.name, AF_UNIX, b'\x00'*14)
res = fcntl.ioctl(sockfd, SIOCGIFHWADDR, ifreq)
address = struct.unpack('16sH14s', res)[2]
mac = struct.unpack('6B8x', address)
return ":".join(['%0... | [
"Obtain",
"the",
"device",
"s",
"mac",
"address",
"."
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L179-L186 | [
"def",
"get_mac",
"(",
"self",
")",
":",
"ifreq",
"=",
"struct",
".",
"pack",
"(",
"'16sH14s'",
",",
"self",
".",
"name",
",",
"AF_UNIX",
",",
"b'\\x00'",
"*",
"14",
")",
"res",
"=",
"fcntl",
".",
"ioctl",
"(",
"sockfd",
",",
"SIOCGIFHWADDR",
",",
... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | Interface.set_mac | Set the device's mac address. Device must be down for this to
succeed. | pynetlinux/ifconfig.py | def set_mac(self, newmac):
''' Set the device's mac address. Device must be down for this to
succeed. '''
macbytes = [int(i, 16) for i in newmac.split(':')]
ifreq = struct.pack('16sH6B8x', self.name, AF_UNIX, *macbytes)
fcntl.ioctl(sockfd, SIOCSIFHWADDR, ifreq) | def set_mac(self, newmac):
''' Set the device's mac address. Device must be down for this to
succeed. '''
macbytes = [int(i, 16) for i in newmac.split(':')]
ifreq = struct.pack('16sH6B8x', self.name, AF_UNIX, *macbytes)
fcntl.ioctl(sockfd, SIOCSIFHWADDR, ifreq) | [
"Set",
"the",
"device",
"s",
"mac",
"address",
".",
"Device",
"must",
"be",
"down",
"for",
"this",
"to",
"succeed",
"."
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L189-L194 | [
"def",
"set_mac",
"(",
"self",
",",
"newmac",
")",
":",
"macbytes",
"=",
"[",
"int",
"(",
"i",
",",
"16",
")",
"for",
"i",
"in",
"newmac",
".",
"split",
"(",
"':'",
")",
"]",
"ifreq",
"=",
"struct",
".",
"pack",
"(",
"'16sH6B8x'",
",",
"self",
... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | Interface.get_index | Convert an interface name to an index value. | pynetlinux/ifconfig.py | def get_index(self):
''' Convert an interface name to an index value. '''
ifreq = struct.pack('16si', self.name, 0)
res = fcntl.ioctl(sockfd, SIOCGIFINDEX, ifreq)
return struct.unpack("16si", res)[1] | def get_index(self):
''' Convert an interface name to an index value. '''
ifreq = struct.pack('16si', self.name, 0)
res = fcntl.ioctl(sockfd, SIOCGIFINDEX, ifreq)
return struct.unpack("16si", res)[1] | [
"Convert",
"an",
"interface",
"name",
"to",
"an",
"index",
"value",
"."
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L233-L237 | [
"def",
"get_index",
"(",
"self",
")",
":",
"ifreq",
"=",
"struct",
".",
"pack",
"(",
"'16si'",
",",
"self",
".",
"name",
",",
"0",
")",
"res",
"=",
"fcntl",
".",
"ioctl",
"(",
"sockfd",
",",
"SIOCGIFINDEX",
",",
"ifreq",
")",
"return",
"struct",
".... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | Interface.set_pause_param | Ethernet has flow control! The inter-frame pause can be adjusted, by
auto-negotiation through an ethernet frame type with a simple two-field
payload, and by setting it explicitly.
http://en.wikipedia.org/wiki/Ethernet_flow_control | pynetlinux/ifconfig.py | def set_pause_param(self, autoneg, rx_pause, tx_pause):
"""
Ethernet has flow control! The inter-frame pause can be adjusted, by
auto-negotiation through an ethernet frame type with a simple two-field
payload, and by setting it explicitly.
http://en.wikipedia.org/wiki/Ethernet_f... | def set_pause_param(self, autoneg, rx_pause, tx_pause):
"""
Ethernet has flow control! The inter-frame pause can be adjusted, by
auto-negotiation through an ethernet frame type with a simple two-field
payload, and by setting it explicitly.
http://en.wikipedia.org/wiki/Ethernet_f... | [
"Ethernet",
"has",
"flow",
"control!",
"The",
"inter",
"-",
"frame",
"pause",
"can",
"be",
"adjusted",
"by",
"auto",
"-",
"negotiation",
"through",
"an",
"ethernet",
"frame",
"type",
"with",
"a",
"simple",
"two",
"-",
"field",
"payload",
"and",
"by",
"sett... | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L306-L320 | [
"def",
"set_pause_param",
"(",
"self",
",",
"autoneg",
",",
"rx_pause",
",",
"tx_pause",
")",
":",
"# create a struct ethtool_pauseparm",
"# create a struct ifreq with its .ifr_data pointing at the above",
"ecmd",
"=",
"array",
".",
"array",
"(",
"'B'",
",",
"struct",
"... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | get_version | Return version string. | setup.py | def get_version():
"""Return version string."""
with io.open('grammar_check/__init__.py', encoding='utf-8') as input_file:
for line in input_file:
if line.startswith('__version__'):
return ast.parse(line).body[0].value.s | def get_version():
"""Return version string."""
with io.open('grammar_check/__init__.py', encoding='utf-8') as input_file:
for line in input_file:
if line.startswith('__version__'):
return ast.parse(line).body[0].value.s | [
"Return",
"version",
"string",
"."
] | viraja1/grammar-check | python | https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/setup.py#L129-L134 | [
"def",
"get_version",
"(",
")",
":",
"with",
"io",
".",
"open",
"(",
"'grammar_check/__init__.py'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"input_file",
":",
"for",
"line",
"in",
"input_file",
":",
"if",
"line",
".",
"startswith",
"(",
"'__version__'",
... | 103bf27119b85b4ef26c8f8d4089b6c882cabe5c |
train | split_elements | Split a string with comma or space-separated elements into a list. | setup.py | def split_elements(value):
"""Split a string with comma or space-separated elements into a list."""
l = [v.strip() for v in value.split(',')]
if len(l) == 1:
l = value.split()
return l | def split_elements(value):
"""Split a string with comma or space-separated elements into a list."""
l = [v.strip() for v in value.split(',')]
if len(l) == 1:
l = value.split()
return l | [
"Split",
"a",
"string",
"with",
"comma",
"or",
"space",
"-",
"separated",
"elements",
"into",
"a",
"list",
"."
] | viraja1/grammar-check | python | https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/setup.py#L194-L199 | [
"def",
"split_elements",
"(",
"value",
")",
":",
"l",
"=",
"[",
"v",
".",
"strip",
"(",
")",
"for",
"v",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]",
"if",
"len",
"(",
"l",
")",
"==",
"1",
":",
"l",
"=",
"value",
".",
"split",
"(",
")... | 103bf27119b85b4ef26c8f8d4089b6c882cabe5c |
train | generate_py2k | Generate Python 2 code from Python 3 code. | setup.py | def generate_py2k(config, py2k_dir=PY2K_DIR, run_tests=False):
"""Generate Python 2 code from Python 3 code."""
def copy(src, dst):
if (not os.path.isfile(dst) or
os.path.getmtime(src) > os.path.getmtime(dst)):
shutil.copy(src, dst)
return dst
return None
... | def generate_py2k(config, py2k_dir=PY2K_DIR, run_tests=False):
"""Generate Python 2 code from Python 3 code."""
def copy(src, dst):
if (not os.path.isfile(dst) or
os.path.getmtime(src) > os.path.getmtime(dst)):
shutil.copy(src, dst)
return dst
return None
... | [
"Generate",
"Python",
"2",
"code",
"from",
"Python",
"3",
"code",
"."
] | viraja1/grammar-check | python | https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/setup.py#L448-L551 | [
"def",
"generate_py2k",
"(",
"config",
",",
"py2k_dir",
"=",
"PY2K_DIR",
",",
"run_tests",
"=",
"False",
")",
":",
"def",
"copy",
"(",
"src",
",",
"dst",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"dst",
")",
"or",
"os",
"... | 103bf27119b85b4ef26c8f8d4089b6c882cabe5c |
train | default_hook | Default setup hook. | setup.py | def default_hook(config):
"""Default setup hook."""
if (any(arg.startswith('bdist') for arg in sys.argv) and
os.path.isdir(PY2K_DIR) != IS_PY2K and os.path.isdir(LIB_DIR)):
shutil.rmtree(LIB_DIR)
if IS_PY2K and any(arg.startswith('install') or
arg.startswith('buil... | def default_hook(config):
"""Default setup hook."""
if (any(arg.startswith('bdist') for arg in sys.argv) and
os.path.isdir(PY2K_DIR) != IS_PY2K and os.path.isdir(LIB_DIR)):
shutil.rmtree(LIB_DIR)
if IS_PY2K and any(arg.startswith('install') or
arg.startswith('buil... | [
"Default",
"setup",
"hook",
"."
] | viraja1/grammar-check | python | https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/setup.py#L566-L578 | [
"def",
"default_hook",
"(",
"config",
")",
":",
"if",
"(",
"any",
"(",
"arg",
".",
"startswith",
"(",
"'bdist'",
")",
"for",
"arg",
"in",
"sys",
".",
"argv",
")",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"PY2K_DIR",
")",
"!=",
"IS_PY2K",
"and",... | 103bf27119b85b4ef26c8f8d4089b6c882cabe5c |
train | get_default_if | Returns the default interface | pynetlinux/route.py | def get_default_if():
""" Returns the default interface """
f = open ('/proc/net/route', 'r')
for line in f:
words = line.split()
dest = words[1]
try:
if (int (dest) == 0):
interf = words[0]
break
except ValueError:
pass... | def get_default_if():
""" Returns the default interface """
f = open ('/proc/net/route', 'r')
for line in f:
words = line.split()
dest = words[1]
try:
if (int (dest) == 0):
interf = words[0]
break
except ValueError:
pass... | [
"Returns",
"the",
"default",
"interface"
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/route.py#L1-L13 | [
"def",
"get_default_if",
"(",
")",
":",
"f",
"=",
"open",
"(",
"'/proc/net/route'",
",",
"'r'",
")",
"for",
"line",
"in",
"f",
":",
"words",
"=",
"line",
".",
"split",
"(",
")",
"dest",
"=",
"words",
"[",
"1",
"]",
"try",
":",
"if",
"(",
"int",
... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | get_default_gw | Returns the default gateway | pynetlinux/route.py | def get_default_gw():
""" Returns the default gateway """
octet_list = []
gw_from_route = None
f = open ('/proc/net/route', 'r')
for line in f:
words = line.split()
dest = words[1]
try:
if (int (dest) == 0):
gw_from_route = words[2]
... | def get_default_gw():
""" Returns the default gateway """
octet_list = []
gw_from_route = None
f = open ('/proc/net/route', 'r')
for line in f:
words = line.split()
dest = words[1]
try:
if (int (dest) == 0):
gw_from_route = words[2]
... | [
"Returns",
"the",
"default",
"gateway"
] | rlisagor/pynetlinux | python | https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/route.py#L15-L40 | [
"def",
"get_default_gw",
"(",
")",
":",
"octet_list",
"=",
"[",
"]",
"gw_from_route",
"=",
"None",
"f",
"=",
"open",
"(",
"'/proc/net/route'",
",",
"'r'",
")",
"for",
"line",
"in",
"f",
":",
"words",
"=",
"line",
".",
"split",
"(",
")",
"dest",
"=",
... | e3f16978855c6649685f0c43d4c3fcf768427ae5 |
train | init | Create the module instance of the GraphiteClient. | graphitesend/graphitesend.py | def init(init_type='plaintext_tcp', *args, **kwargs):
"""
Create the module instance of the GraphiteClient.
"""
global _module_instance
reset()
validate_init_types = ['plaintext_tcp', 'plaintext', 'pickle_tcp',
'pickle', 'plain']
if init_type not in validate_init... | def init(init_type='plaintext_tcp', *args, **kwargs):
"""
Create the module instance of the GraphiteClient.
"""
global _module_instance
reset()
validate_init_types = ['plaintext_tcp', 'plaintext', 'pickle_tcp',
'pickle', 'plain']
if init_type not in validate_init... | [
"Create",
"the",
"module",
"instance",
"of",
"the",
"GraphiteClient",
"."
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L526-L550 | [
"def",
"init",
"(",
"init_type",
"=",
"'plaintext_tcp'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_module_instance",
"reset",
"(",
")",
"validate_init_types",
"=",
"[",
"'plaintext_tcp'",
",",
"'plaintext'",
",",
"'pickle_tcp'",
",",
"... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | send | Make sure that we have an instance of the GraphiteClient.
Then send the metrics to the graphite server.
User consumable method. | graphitesend/graphitesend.py | def send(*args, **kwargs):
""" Make sure that we have an instance of the GraphiteClient.
Then send the metrics to the graphite server.
User consumable method.
"""
if not _module_instance:
raise GraphiteSendException(
"Must call graphitesend.init() before sending")
_module_in... | def send(*args, **kwargs):
""" Make sure that we have an instance of the GraphiteClient.
Then send the metrics to the graphite server.
User consumable method.
"""
if not _module_instance:
raise GraphiteSendException(
"Must call graphitesend.init() before sending")
_module_in... | [
"Make",
"sure",
"that",
"we",
"have",
"an",
"instance",
"of",
"the",
"GraphiteClient",
".",
"Then",
"send",
"the",
"metrics",
"to",
"the",
"graphite",
"server",
".",
"User",
"consumable",
"method",
"."
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L553-L563 | [
"def",
"send",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"_module_instance",
":",
"raise",
"GraphiteSendException",
"(",
"\"Must call graphitesend.init() before sending\"",
")",
"_module_instance",
".",
"send",
"(",
"*",
"args",
",",
"*",... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | send_dict | Make sure that we have an instance of the GraphiteClient.
Then send the metrics to the graphite server.
User consumable method. | graphitesend/graphitesend.py | def send_dict(*args, **kwargs):
""" Make sure that we have an instance of the GraphiteClient.
Then send the metrics to the graphite server.
User consumable method.
"""
if not _module_instance:
raise GraphiteSendException(
"Must call graphitesend.init() before sending")
_modul... | def send_dict(*args, **kwargs):
""" Make sure that we have an instance of the GraphiteClient.
Then send the metrics to the graphite server.
User consumable method.
"""
if not _module_instance:
raise GraphiteSendException(
"Must call graphitesend.init() before sending")
_modul... | [
"Make",
"sure",
"that",
"we",
"have",
"an",
"instance",
"of",
"the",
"GraphiteClient",
".",
"Then",
"send",
"the",
"metrics",
"to",
"the",
"graphite",
"server",
".",
"User",
"consumable",
"method",
"."
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L566-L575 | [
"def",
"send_dict",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"_module_instance",
":",
"raise",
"GraphiteSendException",
"(",
"\"Must call graphitesend.init() before sending\"",
")",
"_module_instance",
".",
"send_dict",
"(",
"*",
"args",
"... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | send_list | Make sure that we have an instance of the GraphiteClient.
Then send the metrics to the graphite server.
User consumable method. | graphitesend/graphitesend.py | def send_list(*args, **kwargs):
""" Make sure that we have an instance of the GraphiteClient.
Then send the metrics to the graphite server.
User consumable method.
"""
if not _module_instance:
raise GraphiteSendException(
"Must call graphitesend.init() before sending")
_modul... | def send_list(*args, **kwargs):
""" Make sure that we have an instance of the GraphiteClient.
Then send the metrics to the graphite server.
User consumable method.
"""
if not _module_instance:
raise GraphiteSendException(
"Must call graphitesend.init() before sending")
_modul... | [
"Make",
"sure",
"that",
"we",
"have",
"an",
"instance",
"of",
"the",
"GraphiteClient",
".",
"Then",
"send",
"the",
"metrics",
"to",
"the",
"graphite",
"server",
".",
"User",
"consumable",
"method",
"."
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L578-L587 | [
"def",
"send_list",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"_module_instance",
":",
"raise",
"GraphiteSendException",
"(",
"\"Must call graphitesend.init() before sending\"",
")",
"_module_instance",
".",
"send_list",
"(",
"*",
"args",
"... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | cli | Allow the module to be called from the cli. | graphitesend/graphitesend.py | def cli():
""" Allow the module to be called from the cli. """
import argparse
parser = argparse.ArgumentParser(description='Send data to graphite')
# Core of the application is to accept a metric and a value.
parser.add_argument('metric', metavar='metric', type=str,
help='... | def cli():
""" Allow the module to be called from the cli. """
import argparse
parser = argparse.ArgumentParser(description='Send data to graphite')
# Core of the application is to accept a metric and a value.
parser.add_argument('metric', metavar='metric', type=str,
help='... | [
"Allow",
"the",
"module",
"to",
"be",
"called",
"from",
"the",
"cli",
"."
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L600-L617 | [
"def",
"cli",
"(",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Send data to graphite'",
")",
"# Core of the application is to accept a metric and a value.",
"parser",
".",
"add_argument",
"(",
"'metric'",
... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | GraphiteClient.connect | Make a TCP connection to the graphite server on port self.port | graphitesend/graphitesend.py | def connect(self):
"""
Make a TCP connection to the graphite server on port self.port
"""
self.socket = socket.socket()
self.socket.settimeout(self.timeout_in_seconds)
try:
self.socket.connect(self.addr)
except socket.timeout:
raise Graphit... | def connect(self):
"""
Make a TCP connection to the graphite server on port self.port
"""
self.socket = socket.socket()
self.socket.settimeout(self.timeout_in_seconds)
try:
self.socket.connect(self.addr)
except socket.timeout:
raise Graphit... | [
"Make",
"a",
"TCP",
"connection",
"to",
"the",
"graphite",
"server",
"on",
"port",
"self",
".",
"port"
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L148-L169 | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"socket",
"=",
"socket",
".",
"socket",
"(",
")",
"self",
".",
"socket",
".",
"settimeout",
"(",
"self",
".",
"timeout_in_seconds",
")",
"try",
":",
"self",
".",
"socket",
".",
"connect",
"(",
"se... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | GraphiteClient.autoreconnect | Tries to reconnect with some delay:
exponential=False: up to `attempt` times with `sleep` seconds between
each try
exponential=True: up to `attempt` times with exponential growing `sleep`
and random delay in range 1..`jitter` (exponential backoff)
:param sleep: time to sleep ... | graphitesend/graphitesend.py | def autoreconnect(self, sleep=1, attempt=3, exponential=True, jitter=5):
"""
Tries to reconnect with some delay:
exponential=False: up to `attempt` times with `sleep` seconds between
each try
exponential=True: up to `attempt` times with exponential growing `sleep`
and r... | def autoreconnect(self, sleep=1, attempt=3, exponential=True, jitter=5):
"""
Tries to reconnect with some delay:
exponential=False: up to `attempt` times with `sleep` seconds between
each try
exponential=True: up to `attempt` times with exponential growing `sleep`
and r... | [
"Tries",
"to",
"reconnect",
"with",
"some",
"delay",
":"
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L175-L213 | [
"def",
"autoreconnect",
"(",
"self",
",",
"sleep",
"=",
"1",
",",
"attempt",
"=",
"3",
",",
"exponential",
"=",
"True",
",",
"jitter",
"=",
"5",
")",
":",
"p",
"=",
"0",
"while",
"attempt",
"is",
"None",
"or",
"attempt",
">",
"0",
":",
"try",
":"... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | GraphiteClient.disconnect | Close the TCP connection with the graphite server. | graphitesend/graphitesend.py | def disconnect(self):
"""
Close the TCP connection with the graphite server.
"""
try:
self.socket.shutdown(1)
# If its currently a socket, set it to None
except AttributeError:
self.socket = None
except Exception:
self.socket =... | def disconnect(self):
"""
Close the TCP connection with the graphite server.
"""
try:
self.socket.shutdown(1)
# If its currently a socket, set it to None
except AttributeError:
self.socket = None
except Exception:
self.socket =... | [
"Close",
"the",
"TCP",
"connection",
"with",
"the",
"graphite",
"server",
"."
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L221-L236 | [
"def",
"disconnect",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"socket",
".",
"shutdown",
"(",
"1",
")",
"# If its currently a socket, set it to None",
"except",
"AttributeError",
":",
"self",
".",
"socket",
"=",
"None",
"except",
"Exception",
":",
"self... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | GraphiteClient._dispatch_send | Dispatch the different steps of sending | graphitesend/graphitesend.py | def _dispatch_send(self, message):
"""
Dispatch the different steps of sending
"""
if self.dryrun:
return message
if not self.socket:
raise GraphiteSendException(
"Socket was not created before send"
)
sending_functio... | def _dispatch_send(self, message):
"""
Dispatch the different steps of sending
"""
if self.dryrun:
return message
if not self.socket:
raise GraphiteSendException(
"Socket was not created before send"
)
sending_functio... | [
"Dispatch",
"the",
"different",
"steps",
"of",
"sending"
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L238-L263 | [
"def",
"_dispatch_send",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"dryrun",
":",
"return",
"message",
"if",
"not",
"self",
".",
"socket",
":",
"raise",
"GraphiteSendException",
"(",
"\"Socket was not created before send\"",
")",
"sending_function"... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | GraphiteClient._send_and_reconnect | Send _message_ to Graphite Server and attempt reconnect on failure.
If _autoreconnect_ was specified, attempt to reconnect if first send
fails.
:raises AttributeError: When the socket has not been set.
:raises socket.error: When the socket connection is no longer valid. | graphitesend/graphitesend.py | def _send_and_reconnect(self, message):
"""Send _message_ to Graphite Server and attempt reconnect on failure.
If _autoreconnect_ was specified, attempt to reconnect if first send
fails.
:raises AttributeError: When the socket has not been set.
:raises socket.error: When the so... | def _send_and_reconnect(self, message):
"""Send _message_ to Graphite Server and attempt reconnect on failure.
If _autoreconnect_ was specified, attempt to reconnect if first send
fails.
:raises AttributeError: When the socket has not been set.
:raises socket.error: When the so... | [
"Send",
"_message_",
"to",
"Graphite",
"Server",
"and",
"attempt",
"reconnect",
"on",
"failure",
"."
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L292-L307 | [
"def",
"_send_and_reconnect",
"(",
"self",
",",
"message",
")",
":",
"try",
":",
"self",
".",
"socket",
".",
"sendall",
"(",
"message",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
"except",
"(",
"AttributeError",
",",
"socket",
".",
"error",
")",
":",
"... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | GraphiteClient.send | Format a single metric/value pair, and send it to the graphite
server.
:param metric: name of the metric
:type prefix: string
:param value: value of the metric
:type prefix: float or int
:param timestmap: epoch time of the event
:type prefix: float or int
... | graphitesend/graphitesend.py | def send(self, metric, value, timestamp=None, formatter=None):
"""
Format a single metric/value pair, and send it to the graphite
server.
:param metric: name of the metric
:type prefix: string
:param value: value of the metric
:type prefix: float or int
:... | def send(self, metric, value, timestamp=None, formatter=None):
"""
Format a single metric/value pair, and send it to the graphite
server.
:param metric: name of the metric
:type prefix: string
:param value: value of the metric
:type prefix: float or int
:... | [
"Format",
"a",
"single",
"metric",
"/",
"value",
"pair",
"and",
"send",
"it",
"to",
"the",
"graphite",
"server",
"."
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L316-L345 | [
"def",
"send",
"(",
"self",
",",
"metric",
",",
"value",
",",
"timestamp",
"=",
"None",
",",
"formatter",
"=",
"None",
")",
":",
"if",
"formatter",
"is",
"None",
":",
"formatter",
"=",
"self",
".",
"formatter",
"message",
"=",
"formatter",
"(",
"metric... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | GraphiteClient.send_dict | Format a dict of metric/values pairs, and send them all to the
graphite server.
:param data: key,value pair of metric name and metric value
:type prefix: dict
:param timestmap: epoch time of the event
:type prefix: float or int
:param formatter: option non-default format... | graphitesend/graphitesend.py | def send_dict(self, data, timestamp=None, formatter=None):
"""
Format a dict of metric/values pairs, and send them all to the
graphite server.
:param data: key,value pair of metric name and metric value
:type prefix: dict
:param timestmap: epoch time of the event
... | def send_dict(self, data, timestamp=None, formatter=None):
"""
Format a dict of metric/values pairs, and send them all to the
graphite server.
:param data: key,value pair of metric name and metric value
:type prefix: dict
:param timestmap: epoch time of the event
... | [
"Format",
"a",
"dict",
"of",
"metric",
"/",
"values",
"pairs",
"and",
"send",
"them",
"all",
"to",
"the",
"graphite",
"server",
"."
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L347-L375 | [
"def",
"send_dict",
"(",
"self",
",",
"data",
",",
"timestamp",
"=",
"None",
",",
"formatter",
"=",
"None",
")",
":",
"if",
"formatter",
"is",
"None",
":",
"formatter",
"=",
"self",
".",
"formatter",
"metric_list",
"=",
"[",
"]",
"for",
"metric",
",",
... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | GraphiteClient.enable_asynchronous | Check if socket have been monkey patched by gevent | graphitesend/graphitesend.py | def enable_asynchronous(self):
"""Check if socket have been monkey patched by gevent"""
def is_monkey_patched():
try:
from gevent import monkey, socket
except ImportError:
return False
if hasattr(monkey, "saved"):
retur... | def enable_asynchronous(self):
"""Check if socket have been monkey patched by gevent"""
def is_monkey_patched():
try:
from gevent import monkey, socket
except ImportError:
return False
if hasattr(monkey, "saved"):
retur... | [
"Check",
"if",
"socket",
"have",
"been",
"monkey",
"patched",
"by",
"gevent"
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L425-L440 | [
"def",
"enable_asynchronous",
"(",
"self",
")",
":",
"def",
"is_monkey_patched",
"(",
")",
":",
"try",
":",
"from",
"gevent",
"import",
"monkey",
",",
"socket",
"except",
"ImportError",
":",
"return",
"False",
"if",
"hasattr",
"(",
"monkey",
",",
"\"saved\""... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | GraphitePickleClient.str2listtuple | Covert a string that is ready to be sent to graphite into a tuple | graphitesend/graphitesend.py | def str2listtuple(self, string_message):
"Covert a string that is ready to be sent to graphite into a tuple"
if type(string_message).__name__ not in ('str', 'unicode'):
raise TypeError("Must provide a string or unicode")
if not string_message.endswith('\n'):
string_mess... | def str2listtuple(self, string_message):
"Covert a string that is ready to be sent to graphite into a tuple"
if type(string_message).__name__ not in ('str', 'unicode'):
raise TypeError("Must provide a string or unicode")
if not string_message.endswith('\n'):
string_mess... | [
"Covert",
"a",
"string",
"that",
"is",
"ready",
"to",
"be",
"sent",
"to",
"graphite",
"into",
"a",
"tuple"
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L455-L490 | [
"def",
"str2listtuple",
"(",
"self",
",",
"string_message",
")",
":",
"if",
"type",
"(",
"string_message",
")",
".",
"__name__",
"not",
"in",
"(",
"'str'",
",",
"'unicode'",
")",
":",
"raise",
"TypeError",
"(",
"\"Must provide a string or unicode\"",
")",
"if"... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | GraphitePickleClient._send | Given a message send it to the graphite server. | graphitesend/graphitesend.py | def _send(self, message):
""" Given a message send it to the graphite server. """
# An option to lowercase the entire message
if self.lowercase_metric_names:
message = message.lower()
# convert the message into a pickled payload.
message = self.str2listtuple(message... | def _send(self, message):
""" Given a message send it to the graphite server. """
# An option to lowercase the entire message
if self.lowercase_metric_names:
message = message.lower()
# convert the message into a pickled payload.
message = self.str2listtuple(message... | [
"Given",
"a",
"message",
"send",
"it",
"to",
"the",
"graphite",
"server",
"."
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L492-L523 | [
"def",
"_send",
"(",
"self",
",",
"message",
")",
":",
"# An option to lowercase the entire message",
"if",
"self",
".",
"lowercase_metric_names",
":",
"message",
"=",
"message",
".",
"lower",
"(",
")",
"# convert the message into a pickled payload.",
"message",
"=",
... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
train | GraphiteStructuredFormatter.clean_metric_name | Make sure the metric is free of control chars, spaces, tabs, etc. | graphitesend/formatter.py | def clean_metric_name(self, metric_name):
"""
Make sure the metric is free of control chars, spaces, tabs, etc.
"""
if not self._clean_metric_name:
return metric_name
metric_name = str(metric_name)
for _from, _to in self.cleaning_replacement_list:
... | def clean_metric_name(self, metric_name):
"""
Make sure the metric is free of control chars, spaces, tabs, etc.
"""
if not self._clean_metric_name:
return metric_name
metric_name = str(metric_name)
for _from, _to in self.cleaning_replacement_list:
... | [
"Make",
"sure",
"the",
"metric",
"is",
"free",
"of",
"control",
"chars",
"spaces",
"tabs",
"etc",
"."
] | daniellawrence/graphitesend | python | https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/formatter.py#L69-L78 | [
"def",
"clean_metric_name",
"(",
"self",
",",
"metric_name",
")",
":",
"if",
"not",
"self",
".",
"_clean_metric_name",
":",
"return",
"metric_name",
"metric_name",
"=",
"str",
"(",
"metric_name",
")",
"for",
"_from",
",",
"_to",
"in",
"self",
".",
"cleaning_... | 02281263e642f9b6e146886d4544e1d7aebd7753 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.