INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return dct [ key ] and delete dct [ key ]. | def popkey(dct,key,default=NotGiven):
"""Return dct[key] and delete dct[key].
If default is given, return it if dct[key] doesn't exist, otherwise raise
KeyError. """
try:
val = dct[key]
except KeyError:
if default is NotGiven:
raise
else:
return def... |
Show all figures as SVG/ PNG payloads sent to the IPython clients. | def show(close=None):
"""Show all figures as SVG/PNG payloads sent to the IPython clients.
Parameters
----------
close : bool, optional
If true, a ``plt.close('all')`` call is automatically issued after
sending all the figures. If this is set, the figures will entirely
removed from th... |
Is called after every pylab drawing command | def draw_if_interactive():
"""
Is called after every pylab drawing command
"""
# signal that the current active figure should be sent at the end of
# execution. Also sets the _draw_called flag, signaling that there will be
# something to send. At the end of the code execution, a separate call ... |
Send all figures that changed | def flush_figures():
"""Send all figures that changed
This is meant to be called automatically and will call show() if, during
prior code execution, there had been any calls to draw_if_interactive.
This function is meant to be used as a post_execute callback in IPython,
so user-caused errors a... |
Draw the given figure and send it as a PNG payload. | def send_figure(fig):
"""Draw the given figure and send it as a PNG payload.
"""
fmt = InlineBackend.instance().figure_format
data = print_figure(fig, fmt)
# print_figure will return None if there's nothing to draw:
if data is None:
return
mimetypes = { 'png' : 'image/png', 'svg' : '... |
Load an IPython extension by its module name. | def load_extension(self, module_str):
"""Load an IPython extension by its module name.
If :func:`load_ipython_extension` returns anything, this function
will return that object.
"""
from IPython.utils.syspathcontext import prepended_to_syspath
if module_str not in sys.m... |
Unload an IPython extension by its module name. | def unload_extension(self, module_str):
"""Unload an IPython extension by its module name.
This function looks up the extension's name in ``sys.modules`` and
simply calls ``mod.unload_ipython_extension(self)``.
"""
if module_str in sys.modules:
mod = sys.modules[modu... |
Download and install an IPython extension. If filename is given the file will be so named ( inside the extension directory ). Otherwise the name from the URL will be used. The file must have a. py or. zip extension ; otherwise a ValueError will be raised. Returns the full path to the installed file. | def install_extension(self, url, filename=None):
"""Download and install an IPython extension.
If filename is given, the file will be so named (inside the extension
directory). Otherwise, the name from the URL will be used. The file must
have a .py or .zip extension; otherwise,... |
Find any svn: externals directories | def externals_finder(dirname, filename):
"""Find any 'svn:externals' directories"""
found = False
f = open(filename,'rt')
for line in iter(f.readline, ''): # can't use direct iter!
parts = line.split()
if len(parts)==2:
kind,length = parts
data = f.read(int(len... |
Generate a list of n random ports near the given port. | def random_ports(port, n):
"""Generate a list of n random ports near the given port.
The first 5 ports will be sequential, and the remaining n-5 will be
randomly selected in the range [port-2*n, port+2*n].
"""
for i in range(min(5, n)):
yield port + i
for i in range(n-5):
yield ... |
initialize tornado webapp and httpserver | def init_webapp(self):
"""initialize tornado webapp and httpserver"""
self.web_app = NotebookWebApplication(
self, self.kernel_manager, self.notebook_manager,
self.cluster_manager, self.log,
self.base_project_url, self.webapp_settings
)
if self.certfi... |
SIGINT handler spawns confirmation dialog | def _handle_sigint(self, sig, frame):
"""SIGINT handler spawns confirmation dialog"""
# register more forceful signal handler for ^C^C case
signal.signal(signal.SIGINT, self._signal_stop)
# request confirmation dialog in bg thread, to avoid
# blocking the App
thread = thr... |
confirm shutdown on ^C A second ^C or answering y within 5s will cause shutdown otherwise original SIGINT handler will be restored. This doesn t work on Windows. | def _confirm_exit(self):
"""confirm shutdown on ^C
A second ^C, or answering 'y' within 5s will cause shutdown,
otherwise original SIGINT handler will be restored.
This doesn't work on Windows.
"""
# FIXME: remove this delay when pyzmq dependency is >= 2... |
shutdown all kernels The kernels will shutdown themselves when this process no longer exists but explicit shutdown allows the KernelManagers to cleanup the connection files. | def cleanup_kernels(self):
"""shutdown all kernels
The kernels will shutdown themselves when this process no longer exists,
but explicit shutdown allows the KernelManagers to cleanup the connection files.
"""
self.log.info('Shutting down kernels')
km = self.kerne... |
Price European and Asian options using a Monte Carlo method. | def price_options(S=100.0, K=100.0, sigma=0.25, r=0.05, days=260, paths=10000):
"""
Price European and Asian options using a Monte Carlo method.
Parameters
----------
S : float
The initial price of the stock.
K : float
The strike price of the option.
sigma : float
Th... |
Replace in text all occurences of any key in the given dictionary by its corresponding value. Returns the new string. | def multiple_replace(dict, text):
""" Replace in 'text' all occurences of any key in the given
dictionary by its corresponding value. Returns the new string."""
# Function by Xavier Defrang, originally found at:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
# Create a regular ex... |
Return the last depth elements of the current working directory. | def cwd_filt(depth):
"""Return the last depth elements of the current working directory.
$HOME is always replaced with '~'.
If depth==0, the full path is returned."""
cwd = os.getcwdu().replace(HOME,"~")
out = os.sep.join(cwd.split(os.sep)[-depth:])
return out or os.sep |
Return the last depth elements of the current working directory. | def cwd_filt2(depth):
"""Return the last depth elements of the current working directory.
$HOME is always replaced with '~'.
If depth==0, the full path is returned."""
full_cwd = os.getcwdu()
cwd = full_cwd.replace(HOME,"~").split(os.sep)
if '~' in cwd and len(cwd) == depth+1:
depth +=... |
This is called when a prompt template is updated. It processes abbreviations used in the prompt template ( like \ # ) and calculates how many invisible characters ( ANSI colour escapes ) the resulting prompt contains. It is also called for each prompt on changing the colour scheme. In both cases traitlets should take c... | def update_prompt(self, name, new_template=None):
"""This is called when a prompt template is updated. It processes
abbreviations used in the prompt template (like \#) and calculates how
many invisible characters (ANSI colour escapes) the resulting prompt
contains.
It is... |
Render but don t justify or update the width or txtwidth attributes. | def _render(self, name, color=True, **kwargs):
"""Render but don't justify, or update the width or txtwidth attributes.
"""
if name == 'rewrite':
return self._render_rewrite(color=color)
if color:
scheme = self.color_scheme_table.active_colors
... |
Render the --- > rewrite prompt. | def _render_rewrite(self, color=True):
"""Render the ---> rewrite prompt."""
if color:
scheme = self.color_scheme_table.active_colors
# We need a non-input version of these escapes
color_prompt = scheme.in_prompt.replace("\001","").replace("\002","")
color... |
Render the selected prompt. Parameters ---------- name: str Which prompt to render. One of in in2 out rewrite color: bool If True ( default ) include ANSI escape sequences for a coloured prompt. just: bool If True justify the prompt to the width of the last prompt. The default is stored in self. justify. ** kwargs: Add... | def render(self, name, color=True, just=None, **kwargs):
"""
Render the selected prompt.
Parameters
----------
name : str
Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
color : bool
If True (default), include ANSI escape sequence... |
Generates a JSON config file including the selection of random ports. Parameters ---------- | def write_connection_file(fname=None, shell_port=0, iopub_port=0, stdin_port=0, hb_port=0,
ip=LOCALHOST, key=b''):
"""Generates a JSON config file, including the selection of random ports.
Parameters
----------
fname : unicode
The path to the file to write
she... |
Launches a localhost kernel binding to the specified ports. | def base_launch_kernel(code, fname, stdin=None, stdout=None, stderr=None,
executable=None, independent=False, extra_arguments=[],
cwd=None):
""" Launches a localhost kernel, binding to the specified ports.
Parameters
----------
code : str,
A strin... |
This is the actual zest. releaser entry point | def create_zipfile(context):
"""This is the actual zest.releaser entry point
Relevant items in the context dict:
name
Name of the project being released
tagdir
Directory where the tag checkout is placed (*if* a tag
checkout has been made)
version
Version we're rel... |
Fix the version in metadata. txt | def fix_version(context):
"""Fix the version in metadata.txt
Relevant context dict item for both prerelease and postrelease:
``new_version``.
"""
if not prerequisites_ok():
return
lines = codecs.open('metadata.txt', 'rU', 'utf-8').readlines()
for index, line in enumerate(lines):
... |
return whether an object is mappable or not. | def mappable(obj):
"""return whether an object is mappable or not."""
if isinstance(obj, (tuple,list)):
return True
for m in arrayModules:
if isinstance(obj,m['type']):
return True
return False |
Returns the pth partition of q partitions of seq. | def getPartition(self, seq, p, q):
"""Returns the pth partition of q partitions of seq."""
# Test for error conditions here
if p<0 or p>=q:
print "No partition exists."
return
remainder = len(seq)%q
basesize = len(seq)//q
hi = []
... |
Patch pexpect to prevent unhandled exceptions at VM teardown. | def pexpect_monkeypatch():
"""Patch pexpect to prevent unhandled exceptions at VM teardown.
Calling this function will monkeypatch the pexpect.spawn class and modify
its __del__ method to make it more robust in the face of failures that can
occur if it is called when the Python VM is shutting down.
... |
Run as a command - line script. | def main():
"""Run as a command-line script."""
parser = optparse.OptionParser(usage=MAIN_USAGE)
newopt = parser.add_option
newopt('--ipython',action='store_const',dest='mode',const='ipython',
help='IPython interactive runner (default).')
newopt('--python',action='store_const',dest='mode... |
Run the given file interactively. | def run_file(self,fname,interact=False,get_output=False):
"""Run the given file interactively.
Inputs:
-fname: name of the file to execute.
See the run_source docstring for the meaning of the optional
arguments."""
fobj = open(fname,'r')
try:
out... |
Run the given source code interactively. | def run_source(self,source,interact=False,get_output=False):
"""Run the given source code interactively.
Inputs:
- source: a string of code to be executed, or an open file object we
can iterate over.
Optional inputs:
- interact(False): if true, start to interact... |
Run as a command - line script. | def main(self,argv=None):
"""Run as a command-line script."""
parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
newopt = parser.add_option
newopt('-i','--interact',action='store_true',default=False,
help='Interact with the program after the script is r... |
Generate a Cobertura - compatible XML report for morfs. | def report(self, morfs, outfile=None):
"""Generate a Cobertura-compatible XML report for `morfs`.
`morfs` is a list of modules or filenames.
`outfile` is a file object to write the XML to.
"""
# Initial setup.
outfile = outfile or sys.stdout
# Create the DOM t... |
Add to the XML report for a single file. | def xml_file(self, cu, analysis):
"""Add to the XML report for a single file."""
# Create the 'lines' and 'package' XML elements, which
# are populated later. Note that a package == a directory.
package_name = rpartition(cu.name, ".")[0]
className = cu.name
package = s... |
Compute the histogram of a remote array a. Parameters ---------- view IPython DirectView instance a: str String name of the remote array bins: int Number of histogram bins rng: ( float float ) Tuple of min max of the range to histogram normed: boolean Should the histogram counts be normalized to 1 | def phistogram(view, a, bins=10, rng=None, normed=False):
"""Compute the histogram of a remote array a.
Parameters
----------
view
IPython DirectView instance
a : str
String name of the remote array
bins : int
Number of histogram bins
... |
This will download a segment of pi from super - computing. org if the file is not already present. | def fetch_pi_file(filename):
"""This will download a segment of pi from super-computing.org
if the file is not already present.
"""
import os, urllib
ftpdir="ftp://pi.super-computing.org/.2/pi200m/"
if os.path.exists(filename):
# we already have it
return
else:
# down... |
Add up a list of freq counts to get the total counts. | def reduce_freqs(freqlist):
"""
Add up a list of freq counts to get the total counts.
"""
allfreqs = np.zeros_like(freqlist[0])
for f in freqlist:
allfreqs += f
return allfreqs |
Read digits of pi from a file and compute the n digit frequencies. | def compute_n_digit_freqs(filename, n):
"""
Read digits of pi from a file and compute the n digit frequencies.
"""
d = txt_file_to_digits(filename)
freqs = n_digit_freqs(d, n)
return freqs |
Yield the digits of pi read from a. txt file. | def txt_file_to_digits(filename, the_type=str):
"""
Yield the digits of pi read from a .txt file.
"""
with open(filename, 'r') as f:
for line in f.readlines():
for c in line:
if c != '\n' and c!= ' ':
yield the_type(c) |
Consume digits of pi and compute 1 digit freq. counts. | def one_digit_freqs(digits, normalize=False):
"""
Consume digits of pi and compute 1 digit freq. counts.
"""
freqs = np.zeros(10, dtype='i4')
for d in digits:
freqs[int(d)] += 1
if normalize:
freqs = freqs/freqs.sum()
return freqs |
Consume digits of pi and compute 2 digits freq. counts. | def two_digit_freqs(digits, normalize=False):
"""
Consume digits of pi and compute 2 digits freq. counts.
"""
freqs = np.zeros(100, dtype='i4')
last = digits.next()
this = digits.next()
for d in digits:
index = int(last + this)
freqs[index] += 1
last = this
th... |
Consume digits of pi and compute n digits freq. counts. | def n_digit_freqs(digits, n, normalize=False):
"""
Consume digits of pi and compute n digits freq. counts.
This should only be used for 1-6 digits.
"""
freqs = np.zeros(pow(10,n), dtype='i4')
current = np.zeros(n, dtype=int)
for i in range(n):
current[i] = digits.next()
for d in... |
Plot two digits frequency counts using matplotlib. | def plot_two_digit_freqs(f2):
"""
Plot two digits frequency counts using matplotlib.
"""
f2_copy = f2.copy()
f2_copy.shape = (10,10)
ax = plt.matshow(f2_copy)
plt.colorbar()
for i in range(10):
for j in range(10):
plt.text(i-0.2, j+0.2, str(j)+str(i))
plt.ylabel('... |
Plot one digit frequency counts using matplotlib. | def plot_one_digit_freqs(f1):
"""
Plot one digit frequency counts using matplotlib.
"""
ax = plt.plot(f1,'bo-')
plt.title('Single digit counts in pi')
plt.xlabel('Digit')
plt.ylabel('Count')
return ax |
Extend a prefixed uri with the help of a specific dictionary of prefixes: param short: Prefixed uri to be extended: return: | def __extend_uri(self, short):
"""
Extend a prefixed uri with the help of a specific dictionary of prefixes
:param short: Prefixed uri to be extended
:return:
"""
if short == 'a':
return RDF.type
for prefix in sorted(self.__prefixes, key=lambda x: len(... |
Try to retrieve a model and return None if it is not found. Useful if you do not want to bother with the try/ except block. | def get_object_or_none(qs, *args, **kwargs):
"""
Try to retrieve a model, and return None if
it is not found.
Useful if you do not want to bother with the try/except block.
"""
try:
return qs.get(*args, **kwargs)
except models.ObjectDoesNotExist:
return None |
Extract a set of variables by name from another frame. | def extract_vars(*names,**kw):
"""Extract a set of variables by name from another frame.
:Parameters:
- `*names`: strings
One or more variable names which will be extracted from the caller's
frame.
:Keywords:
- `depth`: integer (0)
How many frames in the stack to walk when ... |
Extract a set of variables by name from another frame. | def extract_vars_above(*names):
"""Extract a set of variables by name from another frame.
Similar to extractVars(), but with a specified depth of 1, so that names
are exctracted exactly from above the caller.
This is simply a convenience function so that the very common case (for us)
of skipping e... |
Print the value of an expression from the caller s frame. | def debugx(expr,pre_msg=''):
"""Print the value of an expression from the caller's frame.
Takes an expression, evaluates it in the caller's frame and prints both
the given expression and the resulting value (as well as a debug mark
indicating the name of the calling function. The input must be of a fo... |
Returns ( module locals ) of the funciton depth frames away from the caller | def extract_module_locals(depth=0):
"""Returns (module, locals) of the funciton `depth` frames away from the caller"""
f = sys._getframe(depth + 1)
global_ns = f.f_globals
module = sys.modules[global_ns['__name__']]
return (module, f.f_locals) |
User - friendly reverse. Pass arguments and keyword arguments to Django s reverse as args and kwargs arguments respectively. | def reverse(view, *args, **kwargs):
'''
User-friendly reverse. Pass arguments and keyword arguments to Django's `reverse`
as `args` and `kwargs` arguments, respectively.
The special optional keyword argument `query` is a dictionary of query (or GET) parameters
that can be appended to the `reverse`d URL.
Example... |
prefix base - > true iff name prefix +. + base is private. | def is_private(prefix, base):
"""prefix, base -> true iff name prefix + "." + base is "private".
Prefix may be an empty string, and base does not contain a period.
Prefix is ignored (although functions you write conforming to this
protocol may make use of it).
Return true iff base begins with an (a... |
Return the compiler - flags associated with the future features that have been imported into the given namespace ( globs ). | def _extract_future_flags(globs):
"""
Return the compiler-flags associated with the future features that
have been imported into the given namespace (globs).
"""
flags = 0
for fname in __future__.all_feature_names:
feature = globs.get(fname, None)
if feature is getattr(__future__... |
Return the module specified by module. In particular: - If module is a module then return module. - If module is a string then import and return the module with that name. - If module is None then return the calling module. The calling module is assumed to be the module of the stack frame at the given depth in the call... | def _normalize_module(module, depth=2):
"""
Return the module specified by `module`. In particular:
- If `module` is a module, then return module.
- If `module` is a string, then import and return the
module with that name.
- If `module` is None, then return the calling module.
... |
Return a string containing a traceback message for the given exc_info tuple ( as returned by sys. exc_info () ). | def _exception_traceback(exc_info):
"""
Return a string containing a traceback message for the given
exc_info tuple (as returned by sys.exc_info()).
"""
# Get a traceback message.
excout = StringIO()
exc_type, exc_val, exc_tb = exc_info
traceback.print_exception(exc_type, exc_val, exc_tb... |
Test examples in the given object s docstring ( f ) using globs as globals. Optional argument name is used in failure messages. If the optional argument verbose is true then generate output even if there are no failures. | def run_docstring_examples(f, globs, verbose=False, name="NoName",
compileflags=None, optionflags=0):
"""
Test examples in the given object's docstring (`f`), using `globs`
as globals. Optional argument `name` is used in failure messages.
If the optional argument `verbose` is... |
A unittest suite for one or more doctest files. | def DocFileSuite(*paths, **kw):
"""A unittest suite for one or more doctest files.
The path to each doctest file is given as a string; the
interpretation of that string depends on the keyword argument
"module_relative".
A number of options may be provided as keyword arguments:
module_relative... |
Debug a single doctest docstring in argument src | def debug_src(src, pm=False, globs=None):
"""Debug a single doctest docstring, in argument `src`'"""
testsrc = script_from_examples(src)
debug_script(testsrc, pm, globs) |
Debug a test script. src is the script as a string. | def debug_script(src, pm=False, globs=None):
"Debug a test script. `src` is the script, as a string."
import pdb
# Note that tempfile.NameTemporaryFile() cannot be used. As the
# docs say, a file so created cannot be opened by name a second time
# on modern Windows boxes, and execfile() needs to ... |
Debug a single doctest docstring. | def debug(module, name, pm=False):
"""Debug a single doctest docstring.
Provide the module (or dotted name of the module) containing the
test to be debugged and the name (within the module) of the object
with the docstring with tests to be debugged.
"""
module = _normalize_module(module)
te... |
Return True iff the actual output from an example ( got ) matches the expected output ( want ). These strings are always considered to match if they are identical ; but depending on what option flags the test runner is using several non - exact match types are also possible. See the documentation for TestRunner for mor... | def check_output(self, want, got, optionflags):
"""
Return True iff the actual output from an example (`got`)
matches the expected output (`want`). These strings are
always considered to match if they are identical; but
depending on what option flags the test runner is using,
... |
Return a string describing the differences between the expected output for a given example ( example ) and the actual output ( got ). optionflags is the set of option flags used to compare want and got. | def output_difference(self, example, got, optionflags):
"""
Return a string describing the differences between the
expected output for a given example (`example`) and the actual
output (`got`). `optionflags` is the set of option flags used
to compare `want` and `got`.
""... |
hashed set | def hset(self, hashroot, key, value):
""" hashed set """
hroot = self.root / hashroot
if not hroot.isdir():
hroot.makedirs()
hfile = hroot / gethashfile(key)
d = self.get(hfile, {})
d.update( {key : value})
self[hfile] = d |
Get all data contained in hashed category hashroot as dict | def hdict(self, hashroot):
""" Get all data contained in hashed category 'hashroot' as dict """
hfiles = self.keys(hashroot + "/*")
hfiles.sort()
last = len(hfiles) and hfiles[-1] or ''
if last.endswith('xx'):
# print "using xx"
hfiles = [last] + hfiles[:-... |
Compress category hashroot so hset is fast again | def hcompress(self, hashroot):
""" Compress category 'hashroot', so hset is fast again
hget will fail if fast_only is True for compressed items (that were
hset before hcompress).
"""
hfiles = self.keys(hashroot + "/*")
all = {}
for f in hfiles:
# pri... |
All keys in DB or all keys matching a glob | def keys(self, globpat = None):
""" All keys in DB, or all keys matching a glob"""
if globpat is None:
files = self.root.walkfiles()
else:
files = [Path(p) for p in glob.glob(self.root/globpat)]
return [self._normalized(p) for p in files if p.isfile()] |
Reimplemented to handle keyboard input and to auto - hide when the text edit loses focus. | def eventFilter(self, obj, event):
""" Reimplemented to handle keyboard input and to auto-hide when the
text edit loses focus.
"""
if obj == self._text_edit:
etype = event.type()
if etype in( QtCore.QEvent.KeyPress, QtCore.QEvent.FocusOut ):
s... |
Shows the completion widget with items at the position specified by cursor. | def show_items(self, cursor, items):
""" Shows the completion widget with 'items' at the position specified
by 'cursor'.
"""
if not items :
return
self.cancel_completion()
strng = text.columnize(items)
self._console_widget._fill_temporary_buffer(cu... |
returns whether this record should be printed | def allow(self, record):
"""returns whether this record should be printed"""
if not self:
# nothing to filter
return True
return self._allow(record) and not self._deny(record) |
return the bool of whether record starts with any item in matchers | def _any_match(matchers, record):
"""return the bool of whether `record` starts with
any item in `matchers`"""
def record_matches_key(key):
return record == key or record.startswith(key + '.')
return anyp(bool, map(record_matches_key, matchers)) |
Register commandline options. | def options(self, parser, env):
"""Register commandline options.
"""
parser.add_option(
"--nologcapture", action="store_false",
default=not env.get(self.env_opt), dest="logcapture",
help="Disable logging capture plugin. "
"Logging configurtion... |
Configure plugin. | def configure(self, options, conf):
"""Configure plugin.
"""
self.conf = conf
# Disable if explicitly disabled, or if logging is
# configured via logging config file
if not options.logcapture or conf.loggingConfig:
self.enabled = False
self.logformat =... |
Add captured log messages to error output. | def formatError(self, test, err):
"""Add captured log messages to error output.
"""
# logic flow copied from Capture.formatError
test.capturedLogging = records = self.formatLogRecords()
if not records:
return err
ec, ev, tb = err
return (ec, self.addCa... |
Call this to embed IPython at the current point in your program. | def embed(**kwargs):
"""Call this to embed IPython at the current point in your program.
The first invocation of this will create an :class:`InteractiveShellEmbed`
instance and then call it. Consecutive calls just call the already
created instance.
Here is a simple example::
from IPython... |
Embeds IPython into a running python program. | def mainloop(self, local_ns=None, module=None, stack_depth=0,
display_banner=None, global_ns=None):
"""Embeds IPython into a running python program.
Input:
- header: An optional header message can be specified.
- local_ns, module: working local namespace (a dict) ... |
dir2 ( obj ) - > list of strings | def dir2(obj):
"""dir2(obj) -> list of strings
Extended version of the Python builtin dir(), which does a few extra
checks, and supports common objects with unusual internals that confuse
dir(), such as Traits and PyCrust.
This version is guaranteed to return only a list of true strings, whereas
... |
Get all po filenames from locale folder and return list of them. Assumes a directory structure: <locale_root >/ <lang >/ <po_files_path >/ <filename >. | def _get_all_po_filenames(locale_root, lang, po_files_path):
"""
Get all po filenames from locale folder and return list of them.
Assumes a directory structure:
<locale_root>/<lang>/<po_files_path>/<filename>.
"""
all_files = os.listdir(os.path.join(locale_root, lang, po_files_path))
return ... |
Prepare new csv writers write title rows and return them. | def _get_new_csv_writers(trans_title, meta_title,
trans_csv_path, meta_csv_path):
"""
Prepare new csv writers, write title rows and return them.
"""
trans_writer = UnicodeWriter(trans_csv_path)
trans_writer.writerow(trans_title)
meta_writer = UnicodeWriter(meta_csv_path... |
Prepare locale dirs for writing po files. Create new directories if they doesn t exist. | def _prepare_locale_dirs(languages, locale_root):
"""
Prepare locale dirs for writing po files.
Create new directories if they doesn't exist.
"""
trans_languages = []
for i, t in enumerate(languages):
lang = t.split(':')[0]
trans_languages.append(lang)
lang_path = os.path... |
Prepare polib file object for writing/ reading from them. Create directories and write header if needed. For each language ensure there s a translation file named filename in the correct place. Assumes ( and creates ) a directory structure: <locale_root >/ <lang >/ <po_files_path >/ <filename >. | def _prepare_polib_files(files_dict, filename, languages,
locale_root, po_files_path, header):
"""
Prepare polib file object for writing/reading from them.
Create directories and write header if needed. For each language,
ensure there's a translation file named "filename" in the... |
Write msgstr for every language with all needed metadata and comment. Metadata are parser from string into dict so read them only from gdocs. | def _write_entries(po_files, languages, msgid, msgstrs, metadata, comment):
"""
Write msgstr for every language with all needed metadata and comment.
Metadata are parser from string into dict, so read them only from gdocs.
"""
start = re.compile(r'^[\s]+')
end = re.compile(r'[\s]+$')
for i, ... |
Write header into po file for specific lang. Metadata are read from settings file. | def _write_header(po_path, lang, header):
"""
Write header into po file for specific lang.
Metadata are read from settings file.
"""
po_file = open(po_path, 'w')
po_file.write(header + '\n')
po_file.write(
'msgid ""' +
'\nmsgstr ""' +
'\n"MIME-Version: ' + settings.ME... |
Write new msgids which appeared in po files with empty msgstrs values and metadata. Look for all new msgids which are diffed with msgids list provided as an argument. | def _write_new_messages(po_file_path, trans_writer, meta_writer,
msgids, msgstrs, languages):
"""
Write new msgids which appeared in po files with empty msgstrs values
and metadata. Look for all new msgids which are diffed with msgids list
provided as an argument.
"""
po_... |
Write new msgids which appeared in po files with empty msgstrs values and metadata. Look for all new msgids which are diffed with msgids list provided as an argument. | def _get_new_msgstrs(po_file_path, msgids):
"""
Write new msgids which appeared in po files with empty msgstrs values
and metadata. Look for all new msgids which are diffed with msgids list
provided as an argument.
"""
po_file = polib.pofile(po_file_path)
msgstrs = {}
for entry in po_f... |
Converts po file to csv GDocs spreadsheet readable format. Merges them if some msgid aren t in the spreadsheet.: param languages: list of language codes: param locale_root: path to locale root folder containing directories with languages: param po_files_path: path from lang directory to po file: param local_trans_csv: ... | def po_to_csv_merge(languages, locale_root, po_files_path,
local_trans_csv, local_meta_csv,
gdocs_trans_csv, gdocs_meta_csv):
"""
Converts po file to csv GDocs spreadsheet readable format.
Merges them if some msgid aren't in the spreadsheet.
:param languages: list... |
Converts GDocs spreadsheet generated csv file into po file.: param trans_csv_path: path to temporary file with translations: param meta_csv_path: path to temporary file with meta information: param locale_root: path to locale root folder containing directories with languages: param po_files_path: path from lang directo... | def csv_to_po(trans_csv_path, meta_csv_path, locale_root,
po_files_path, header=None):
"""
Converts GDocs spreadsheet generated csv file into po file.
:param trans_csv_path: path to temporary file with translations
:param meta_csv_path: path to temporary file with meta information
:par... |
method to subscribe a user to a service | def subscribe_user(self, user):
""" method to subscribe a user to a service
"""
url = self.root_url + "subscribe_user"
values = {}
values["username"] = user
return self._query(url, values) |
method to send a message to a user | def send_notification(self, to=None, msg=None, label=None,
title=None, uri=None):
""" method to send a message to a user
Parameters:
to -> recipient
msg -> message to send
label -> application description
titl... |
method to send a message to a user | def send_message(self, to=None, msg=None):
""" method to send a message to a user
Parameters:
to -> recipient
msg -> message to send
"""
url = self.root_url + "send_message"
values = {}
if to is not None:
values["to"] = to
... |
query method to do HTTP POST/ GET | def _query(self, url, data = None):
""" query method to do HTTP POST/GET
Parameters:
url -> the url to POST/GET
data -> header_data as a dict (only for POST)
Returns:
Parsed JSON data as dict
or
None on err... |
function to init option parser | def init_parser():
""" function to init option parser """
usage = "usage: %prog -u user -s secret -n name [-l label] \
[-t title] [-c callback] [TEXT]"
parser = OptionParser(usage, version="%prog " + notifo.__version__)
parser.add_option("-u", "--user", action="store", dest="user",
... |
main function | def main():
""" main function """
# get options and arguments
(parser, options, args) = init_parser()
# initialize result variable
result = None
# check for values which are always needed
if not options.user:
parser.error("No user given.")
if not options.secret:
parser.... |
The same as s. rsplit ( sep 1 ) but works in 2. 3 | def rsplit1(s, sep):
"""The same as s.rsplit(sep, 1), but works in 2.3"""
parts = s.split(sep)
return sep.join(parts[:-1]), parts[-1] |
Run a python module as though with python - m name args.... | def run_python_module(modulename, args):
"""Run a python module, as though with ``python -m name args...``.
`modulename` is the name of the module, possibly a dot-separated name.
`args` is the argument array to present as sys.argv, including the first
element naming the module being executed.
"""
... |
Run a python file as if it were the main program on the command line. | def run_python_file(filename, args, package=None):
"""Run a python file as if it were the main program on the command line.
`filename` is the path to the file to execute, it need not be a .py file.
`args` is the argument array to present as sys.argv, including the first
element naming the file being ex... |
Get source from filename and make a code object of it. | def make_code_from_py(filename):
"""Get source from `filename` and make a code object of it."""
# Open the source file.
try:
source_file = open_source(filename)
except IOError:
raise NoSource("No file to run: %r" % filename)
try:
source = source_file.read()
finally:
... |
Get a code object from a. pyc file. | def make_code_from_pyc(filename):
"""Get a code object from a .pyc file."""
try:
fpyc = open(filename, "rb")
except IOError:
raise NoCode("No file to run: %r" % filename)
try:
# First four bytes are a version-specific magic number. It has to
# match or we won't run the ... |
returnr a string for an html table | def html_tableify(item_matrix, select=None, header=None , footer=None) :
""" returnr a string for an html table"""
if not item_matrix :
return ''
html_cols = []
tds = lambda text : u'<td>'+text+u' </td>'
trs = lambda text : u'<tr>'+text+u'</tr>'
tds_items = [map(tds, row) for row in ite... |
set current cursor position | def current(self, value):
"""set current cursor position"""
current = min(max(self._min, value), self._max)
self._current = current
if current > self._stop :
self._stop = current
self._start = current-self._width
elif current < self._start :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.