text stringlengths 81 112k |
|---|
Semi-raw execution of a matlab command.
Smartly handle calls to matlab, figure out what to do with `args`,
and when to use function call syntax and not.
If no `args` are specified, the ``cmd`` not ``result = cmd()`` form is
used in Matlab -- this also makes literal Matlab commands lega... |
r"""Directly access a variable in matlab space.
This should normally not be used by user code.
def _get(self, name, remove=False):
r"""Directly access a variable in matlab space.
This should normally not be used by user code."""
# FIXME should this really be needed in normal operation... |
r"""Directly set a variable `name` in matlab space to `value`.
This should normally not be used in user code.
def _set(self, name, value):
r"""Directly set a variable `name` in matlab space to `value`.
This should normally not be used in user code."""
if isinstance(value, MlabObjectPr... |
Dispatches the matlab COM client.
Note: If this method fails, try running matlab with the -regserver flag.
def open(self, visible=False):
""" Dispatches the matlab COM client.
Note: If this method fails, try running matlab with the -regserver flag.
"""
if self.client:
raise MatlabConnection... |
Evaluates a matlab expression synchronously.
If identify_erros is true, and the last output line after evaluating the
expressions begins with '???' an excpetion is thrown with the matlab error
following the '???'.
The return value of the function is the matlab output following the call.
def eval(self,... |
Loads the requested variables from the matlab com client.
names_to_get can be either a variable name or a list of variable names.
If it is a variable name, the values is returned.
If it is a list, a dictionary of variable_name -> value is returned.
If convert_to_numpy is true, the method will all arra... |
Loads a dictionary of variable names into the matlab com client.
def put(self, name_to_val):
""" Loads a dictionary of variable names into the matlab com client.
"""
self._check_open()
for name, val in name_to_val.iteritems():
# First try to put data as a matrix:
try:
self.client.Pu... |
Opens MATLAB using specified connection (or DCOM+ protocol on Windows)where matlab_location
def open():
global _MATLAB_RELEASE
'''Opens MATLAB using specified connection (or DCOM+ protocol on Windows)where matlab_location '''
if is_win:
ret = MatlabConnection()
ret.open()
return re... |
Tries to guess matlab process release version and location path on
osx machines.
The paths we will search are in the format:
/Applications/MATLAB_R[YEAR][VERSION].app/bin/matlab
We will try the latest version first. If no path is found, None is reutrned.
def _list_releases():
'''
Tries to gues... |
Checks that the given version code is valid.
def is_valid_release_version(version):
'''Checks that the given version code is valid.'''
return version is not None and len(version) == 6 and version[0] == 'R' \
and int(version[1:5]) in range(1990, 2050) \
and version[5] in ('h', 'g', 'f', ... |
Tries to guess matlab's version according to its process path.
If we couldn't gues the version, None is returned.
def find_matlab_version(process_path):
""" Tries to guess matlab's version according to its process path.
If we couldn't gues the version, None is returned.
"""
bin_path = os.path.dir... |
Opens the matlab process.
def open(self, print_matlab_welcome=False):
'''Opens the matlab process.'''
if self.process and not self.process.returncode:
raise MatlabConnectionError('Matlab(TM) process is still active. Use close to '
'close it')
... |
Evaluates a matlab expression synchronously.
If identify_erros is true, and the last output line after evaluating the
expressions begins with '???' and excpetion is thrown with the matlab error
following the '???'.
If on_new_output is not None, it will be called whenever a new output is... |
Loads a dictionary of variable names into the matlab shell.
oned_as is the same as in scipy.io.matlab.savemat function:
oned_as : {'column', 'row'}, optional
If 'column', write 1-D numpy arrays as column vectors.
If 'row', write 1D numpy arrays as row vectors.
def put(self, name_to_val... |
Loads the requested variables from the matlab shell.
names_to_get can be either a variable name, a list of variable names, or
None.
If it is a variable name, the values is returned.
If it is a list, a dictionary of variable_name -> value is returned.
If it is None, a dictionary ... |
Return the named groups in a regular expression (compiled or as string)
in occuring order.
>>> rexGroups(r'(?P<name>\w+) +(?P<surname>\w+)')
('name', 'surname')
def rexGroups(rex):
"""Return the named groups in a regular expression (compiled or as string)
in occuring order.
>>> rexGroups(r'(?... |
``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise
an `ValueError` is raised.
>>> div(10,2)
5
>>> div(10,3)
Traceback (most recent call last):
...
ValueError: 3 does not divide 10
def div(a,b):
"""``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise
an `... |
r"""Shuffle list `l` inplace and return it.
def ipshuffle(l, random=None):
r"""Shuffle list `l` inplace and return it."""
import random as _random
_random.shuffle(l, random)
return l |
r"""Return shuffled *copy* of `seq`.
def shuffle(seq, random=None):
r"""Return shuffled *copy* of `seq`."""
if isinstance(seq, list):
return ipshuffle(seq[:], random)
elif isString(seq):
# seq[0:0] == "" or u""
return seq[0:0].join(ipshuffle(list(seq)),random)
else:
ret... |
r"""Read in a complete file `file` as a string
Parameters:
- `file`: a file handle or a string (`str` or `unicode`).
- `binary`: whether to read in the file in binary mode (default: False).
def slurp(file, binary=False, expand=False):
r"""Read in a complete file `file` as a string
Parameters:
... |
Pass `file` to `func` and ensure the file is closed afterwards. If
`file` is a string, open according to `mode`; if `expand` is true also
expand user and vars.
def withFile(file, func, mode='r', expand=False):
"""Pass `file` to `func` and ensure the file is closed afterwards. If
`file` is a st... |
r"""Read in a complete file (specified by a file handler or a filename
string/unicode string) as list of lines
def slurpLines(file, expand=False):
r"""Read in a complete file (specified by a file handler or a filename
string/unicode string) as list of lines"""
file = _normalizeToFile(file, "r", expand)... |
r"""Return ``file`` a list of chomped lines. See `slurpLines`.
def slurpChompedLines(file, expand=False):
r"""Return ``file`` a list of chomped lines. See `slurpLines`."""
f=_normalizeToFile(file, "r", expand)
try: return list(chompLines(f))
finally: f.close() |
Create a new tempfile, write ``s`` to it and return the filename.
`suffix`, `prefix` and `dir` are like in `tempfile.mkstemp`.
def strToTempfile(s, suffix=None, prefix=None, dir=None, binary=False):
"""Create a new tempfile, write ``s`` to it and return the filename.
`suffix`, `prefix` and `dir` are like i... |
r"""Write string `s` into `file` (which can be a string (`str` or
`unicode`) or a `file` instance).
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 = _norm... |
r"""Write all the `lines` to `file` (which can be a string/unicode or a
file handler).
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.wr... |
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.
def readProcess(cmd, *args):
r"""Similar to `os.pop... |
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`... |
r"""Like the normal splitext (in posixpath), but doesn't treat dotfiles
(e.g. .emacs) as extensions. Also uses os.sep instead of '/'.
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... |
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]]]
def bipart(func, seq):
r"""Like a partitioning version of `filter`. Returns
``[itemsForWhi... |
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`.
def binarySearchPos(se... |
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`.
def binarySearchItem(seq, item, cmpf... |
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
def rotate(... |
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]
def iprotate(l, steps=1):
r"""Like rotate, but modifies `l` in-place.
>>> l = [1,2,3]
>>> iprotate(l) is l
True
>>> l
[2... |
r"""Returns all unique items in `iterable` in the *same* order (only works
if items in `seq` are hashable).
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... |
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]
def notUnique(iterable, reportMax=INF):
"""Returns the elements in `iterable` that ... |
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]]
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,... |
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')), ... |
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"""Ret... |
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)... |
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... |
>>> 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]
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, ... |
>>> list(dropwhilenot(lambda x:x==3, range(10)))
[3, 4, 5, 6, 7, 8, 9]
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... |
r"""Repeat each item in `iterable` `n` times.
Example:
>>> list(stretch(range(3), 2))
[0, 0, 1, 1, 2, 2]
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 iter... |
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]]
def splitAt(itera... |
Return a copy of dict `d` updated with dict `e`.
def update(d, e):
"""Return a copy of dict `d` updated with dict `e`."""
res = copy.copy(d)
res.update(e)
return res |
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, ... |
r"""Like `flatten` but lazy.
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"""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 ... |
>>> positionIf(lambda x: x > 3, range(10))
4
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 |
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]))
... |
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]
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])
... |
>>> 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
def some(predicate, *seqs):
"""
>>> some(lambda x: x, [0, False, None])
False
>>> some(lambda x: x, [... |
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... |
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
def nTimes(n, f, *args, **kwargs):
r"""Call `f` `n` times with `args` and `kwargs`.
Useful e.g. for simplistic timing.
Exampl... |
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)``
def timeCall(*funcAndArgs, **kwargs):
r"""Return the time (in ms) i... |
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'
def replaceStrs(s, *args):
r"""Replace all ``(frm, to)`` tuples in `args` in string `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'
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')
... |
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)
def lineAndColumnAt(s, pos):
r"""Return line and colum... |
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"``).
def prin(*args, **kwargs):
r"""Like ``print``, but a function. I.e. prints out all arguments as
``print`` would do. Specify output stream li... |
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... |
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... |
r"""Like `saveVars`, but appends additional variables to file.
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")
... |
Return the variables pickled pickled into `filename` with `saveVars`
as a dict.
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
... |
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
... |
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``.
def runInfo(prog=None,vers=None,date=None,user... |
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... |
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... |
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,... |
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... |
>>> 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])
def pairwise(fun, v):
"""
>>> pairwise(operator.sub, [4,3,2,1,-10])
[1, 1, 1, 11]
>>> import numpy
>>> pairwise(numpy.subtract, n... |
>>> argmax([4,2,-5])
0
>>> argmax([4,2,-5], key=abs)
2
>>> argmax([4,2,-5], key=abs, both=True)
(2, 5)
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 ke... |
See `argmax`.
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 |
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
def isInt(num):
"""Returns true if `num` is (sort of) an integer.
>>> isInt(3) == isInt(... |
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'... |
>>> 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)
... |
*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
def reduceR(f, sequence, initial=__unique):
"""*R*ight reduce.
>>> reduceR(lambda x,y:x/y, [1.,2.,3.,4]) == 1./(2.... |
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]
def compose(*funcs):
"""Compose `funcs` to a single function.
>>> compose(operator.abs, operator... |
>>> romanNumeral(13)
'XIII'
>>> romanNumeral(2944)
'MMCMXLIV'
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 ... |
>>> 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)
def first(n, it, constructor=list):
"""
>>> first(3,iter([1,2,3,4]))
[1, 2, 3]
>>> first(3,iter([1,2,3,4]), it... |
>>> first(10,drop(10,xrange(sys.maxint),iter))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
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)) |
Same as ``self.dryRun`` if ``self.dry``, else same as ``self.wetRun``.
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,... |
Instead of running function with `*args` and `**kwargs`, just print
out the function call.
def dryRun(self, func, *args, **kwargs):
"""Instead of running function with `*args` and `**kwargs`, just print
out the function call."""
print >> self.out, \
self.formatterDi... |
Iterate over all the bridges in the system.
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.... |
Create new bridge with the given name
def addbr(name):
''' Create new bridge with the given name '''
fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name)
return Bridge(name) |
Iterate over all the interfaces in this bridge.
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 |
Add the interface with the given name to this bridge. Equivalent to
brctl addif [bridge] [interface].
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:
... |
Remove the interface with the given name from this bridge.
Equivalent to brctl delif [bridge] [interface]
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... |
Brings down the bridge interface, and removes it. Equivalent to
ifconfig [bridge] down && brctl delbr [bridge].
def delete(self):
''' Brings down the bridge interface, and removes it. Equivalent to
ifconfig [bridge] down && brctl delbr [bridge]. '''
self.down()
fcntl.ioctl(ifcon... |
Get a random (i.e., unique) string identifier
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 filename of a built-in library file.
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':
fil... |
Import required Javascript libraries to Jupyter Notebook.
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 ... |
Create HTML code block given the graph Javascript and CSS.
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 ... |
Return newest compatible version.
>>> version = get_newest_possible_languagetool_version()
>>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION]
True
def get_newest_possible_languagetool_version():
"""Return newest compatible version.
>>> version = get_newest_possible_languagetool_version()
... |
Iterate over all the interfaces in the system. If physical is
true, then return only real physical interfaces (not 'lo', etc).
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_fi... |
Initialize the library
def init():
''' Initialize the library '''
globals()["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
globals()["sockfd"] = globals()["sock"].fileno() |
Bring up the bridge interface. Equivalent to ifconfig [iface] up.
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... |
Return True if the interface is up, False otherwise.
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]
#... |
Obtain the device's mac address.
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', addr... |
Set the device's mac address. Device must be down for this to
succeed.
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, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.