INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Interpret a template string. This returns a callable taking one argument -- this context -- and returning a string rendered from the template.
def template(self, string): """ Interpret a template string. This returns a callable taking one argument--this context--and returning a string rendered from the template. :param string: The template string. :returns: A callable of one argument that will return the ...
Interpret an expression string. This returns a callable taking one argument -- this context -- and returning the result of evaluating the expression.
def expression(self, string): """ Interpret an expression string. This returns a callable taking one argument--this context--and returning the result of evaluating the expression. :param string: The expression. :returns: A callable of one argument that will return the ...
Get the output of the last command exevuted.
def last_error(self): """Get the output of the last command exevuted.""" if not len(self.log): raise RuntimeError('Nothing executed') try: errs = [l for l in self.log if l[1] != 0] return errs[-1][2] except IndexError: # odd case where th...
Wrapper for subprocess. check_output.
def check_output(self, cmd): """Wrapper for subprocess.check_output.""" ret, output = self._exec(cmd) if not ret == 0: raise CommandError(self) return output
Fake the interface of subprocess. call ().
def check_call(self, cmd): """Fake the interface of subprocess.call().""" ret, _ = self._exec(cmd) if not ret == 0: raise CommandError(self) return ret
Unpack multidict and positional args into a list appropriate for subprocess.: param param_kwargs: ParamDict storing -- param style data.: param positional_args: flags: param gnu: if True long - name args are unpacked as: -- parameter = argument otherwise they are unpacked as: -- parameter argument: returns: list approp...
def unpack_pargs(positional_args, param_kwargs, gnu=False): """Unpack multidict and positional args into a list appropriate for subprocess. :param param_kwargs: ``ParamDict`` storing '--param' style data. :param positional_args: flags :param gnu: if True...
Find the source for filename.
def find_source(self, filename): """Find the source for `filename`. Returns two values: the actual filename, and the source. The source returned depends on which of these cases holds: * The filename seems to be a non-source file: returns None * The filename is a sourc...
Returns a sorted list of the arcs actually executed in the code.
def arcs_executed(self): """Returns a sorted list of the arcs actually executed in the code.""" executed = self.coverage.data.executed_arcs(self.filename) m2fl = self.parser.first_line executed = [(m2fl(l1), m2fl(l2)) for (l1,l2) in executed] return sorted(executed)
Returns a sorted list of the arcs in the code not executed.
def arcs_missing(self): """Returns a sorted list of the arcs in the code not executed.""" possible = self.arc_possibilities() executed = self.arcs_executed() missing = [ p for p in possible if p not in executed and p[0] not in self.no_branc...
Returns a sorted list of the executed arcs missing from the code.
def arcs_unpredicted(self): """Returns a sorted list of the executed arcs missing from the code.""" possible = self.arc_possibilities() executed = self.arcs_executed() # Exclude arcs here which connect a line to itself. They can occur # in executed data in some cases. This is w...
Returns a list of line numbers that have more than one exit.
def branch_lines(self): """Returns a list of line numbers that have more than one exit.""" exit_counts = self.parser.exit_counts() return [l1 for l1,count in iitems(exit_counts) if count > 1]
How many total branches are there?
def total_branches(self): """How many total branches are there?""" exit_counts = self.parser.exit_counts() return sum([count for count in exit_counts.values() if count > 1])
Return arcs that weren t executed from branch lines.
def missing_branch_arcs(self): """Return arcs that weren't executed from branch lines. Returns {l1:[l2a,l2b,...], ...} """ missing = self.arcs_missing() branch_lines = set(self.branch_lines()) mba = {} for l1, l2 in missing: if l1 in branch_lines: ...
Get stats about branches.
def branch_stats(self): """Get stats about branches. Returns a dict mapping line numbers to a tuple: (total_exits, taken_exits). """ exit_counts = self.parser.exit_counts() missing_arcs = self.missing_branch_arcs() stats = {} for lnum in self.branch_line...
Set the number of decimal places used to report percentages.
def set_precision(cls, precision): """Set the number of decimal places used to report percentages.""" assert 0 <= precision < 10 cls._precision = precision cls._near0 = 1.0 / 10**precision cls._near100 = 100.0 - cls._near0
Returns a single percentage value for coverage.
def _get_pc_covered(self): """Returns a single percentage value for coverage.""" if self.n_statements > 0: pc_cov = (100.0 * (self.n_executed + self.n_executed_branches) / (self.n_statements + self.n_branches)) else: pc_cov = 100.0 return p...
Returns the percent covered as a string without a percent sign.
def _get_pc_covered_str(self): """Returns the percent covered, as a string, without a percent sign. Note that "0" is only returned when the value is truly zero, and "100" is only returned when the value is truly 100. Rounding can never result in either "0" or "100". """ ...
Applies cls_name to all needles found in haystack.
def highlight_text(needles, haystack, cls_name='highlighted', words=False, case=False): """ Applies cls_name to all needles found in haystack. """ if not needles: return haystack if not haystack: return '' if words: pattern = r"(%s)" % "|".join(['\\b{}\\b'.format(re.escape(n)) ...
Given an list of words this function highlights the matched text in the given string.
def highlight(string, keywords, cls_name='highlighted'): """ Given an list of words, this function highlights the matched text in the given string. """ if not keywords: return string if not string: return '' include, exclude = get_text_tokenizer(keywords) highlighted = highlight_tex...
Given an list of words this function highlights the matched words in the given string.
def highlight_words(string, keywords, cls_name='highlighted'): """ Given an list of words, this function highlights the matched words in the given string. """ if not keywords: return string if not string: return '' include, exclude = get_text_tokenizer(keywords) highlighted = highli...
Run a distutils setup script sandboxed in its directory
def run_setup(setup_script, args): """Run a distutils setup script, sandboxed in its directory""" old_dir = os.getcwd() save_argv = sys.argv[:] save_path = sys.path[:] setup_dir = os.path.abspath(os.path.dirname(setup_script)) temp_dir = os.path.join(setup_dir,'temp') if not os.path.isdir(te...
Run func under os sandboxing
def run(self, func): """Run 'func' under os sandboxing""" try: self._copy(self) if _file: __builtin__.file = self._file __builtin__.open = self._open self._active = True return func() finally: self._active = ...
Called for low - level os. open ()
def open(self, file, flags, mode=0777): """Called for low-level os.open()""" if flags & WRITE_FLAGS and not self._ok(file): self._violation("os.open", file, flags, mode) return _os.open(file,flags,mode)
Remove a single pair of quotes from the endpoints of a string.
def unquote_ends(istr): """Remove a single pair of quotes from the endpoints of a string.""" if not istr: return istr if (istr[0]=="'" and istr[-1]=="'") or \ (istr[0]=='"' and istr[-1]=='"'): return istr[1:-1] else: return istr
Similar to Perl s qw () operator but with some more options.
def qw(words,flat=0,sep=None,maxsplit=-1): """Similar to Perl's qw() operator, but with some more options. qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) words can also be a list itself, and with flat=1, the output will be recursively flattened. Examples: >>> qw('1 2') ...
Simple minded grep - like function. grep ( pat list ) returns occurrences of pat in list None on failure.
def grep(pat,list,case=1): """Simple minded grep-like function. grep(pat,list) returns occurrences of pat in list, None on failure. It only does simple string matching, with no support for regexps. Use the option case=0 for case-insensitive matching.""" # This is pretty crude. At least it should i...
Return grep () on dir () + dir ( __builtins__ ).
def dgrep(pat,*opts): """Return grep() on dir()+dir(__builtins__). A very common use of grep() when working interactively.""" return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
Indent a string a given number of spaces or tabstops.
def indent(instr,nspaces=4, ntabs=0, flatten=False): """Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number...
Convert ( in - place ) a file to line - ends native to the current OS.
def native_line_ends(filename,backup=1): """Convert (in-place) a file to line-ends native to the current OS. If the optional backup argument is given as false, no backup of the original file is left. """ backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} bak_filename = filenam...
Return the input string centered in a marquee.
def marquee(txt='',width=78,mark='*'): """Return the input string centered in a 'marquee'. :Examples: In [16]: marquee('A test',40) Out[16]: '**************** A test ****************' In [17]: marquee('A test',40,'-') Out[17]: '---------------- A test ----------------' ...
Format a string for screen printing.
def format_screen(strng): """Format a string for screen printing. This removes some latex-type format codes.""" # Paragraph continue par_re = re.compile(r'\\$',re.MULTILINE) strng = par_re.sub('',strng) return strng
Equivalent of textwrap. dedent that ignores unindented first line.
def dedent(text): """Equivalent of textwrap.dedent that ignores unindented first line. This means it will still dedent strings like: '''foo is a bar ''' For use in wrap_paragraphs. """ if text.startswith('\n'): # text starts with blank line, don't ignore the first line ...
Wrap multiple paragraphs to fit a specified width.
def wrap_paragraphs(text, ncols=80): """Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns. """ para...
Return the longest common substring in a list of strings. Credit: http:// stackoverflow. com/ questions/ 2892931/ longest - common - substring - from - more - than - two - strings - python
def long_substr(data): """Return the longest common substring in a list of strings. Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python """ substr = '' if len(data) > 1 and len(data[0]) > 0: for i in range(len(data[0])): ...
Strip leading email quotation characters ( > ).
def strip_email_quotes(text): """Strip leading email quotation characters ('>'). Removes any combination of leading '>' interspersed with whitespace that appears *identically* in all lines of the input text. Parameters ---------- text : str Examples -------- Simple uses:: ...
Calculate optimal info to columnize a list of string
def _find_optimal(rlist , separator_size=2 , displaywidth=80): """Calculate optimal info to columnize a list of string""" for nrow in range(1, len(rlist)+1) : chk = map(max,_chunks(rlist, nrow)) sumlength = sum(chk) ncols = len(chk) if sumlength+separator_size*(ncols-1) <= displa...
return list item number or default if don t exist
def _get_or_default(mylist, i, default=None): """return list item number, or default if don't exist""" if i >= len(mylist): return default else : return mylist[i]
Returns a nested list and info to columnize items
def compute_item_matrix(items, empty=None, *args, **kwargs) : """Returns a nested list, and info to columnize items Parameters : ------------ items : list of strings to columize empty : (default None) default value to fill list if needed separator_size : int (default=2) ...
Transform a list of strings into a single string with columns.
def columnize(items, separator=' ', displaywidth=80): """ Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. separator : str, optional [default is two spaces] The string that separates columns. ...
Return all strings matching pattern ( a regex or callable )
def grep(self, pattern, prune = False, field = None): """ Return all strings matching 'pattern' (a regex or callable) This is case-insensitive. If prune is true, return all items NOT matching the pattern. If field is specified, the match must occur in the specified whitespace-s...
Collect whitespace - separated fields from string list
def fields(self, *fields): """ Collect whitespace-separated fields from string list Allows quick awk-like usage of string lists. Example data (in var a, created by 'a = !ls -l'):: -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog drwxrwxrwx+ 6 ville None 0 O...
sort by specified fields ( see fields () )
def sort(self,field= None, nums = False): """ sort by specified fields (see fields()) Example:: a.sort(1, nums = True) Sorts a by second field, in numerical order (so that 21 > 3) """ #decorate, sort, undecorate if field is not None: dsu = [[S...
Read a Python file using the encoding declared inside the file. Parameters ---------- filename: str The path to the file to read. skip_encoding_cookie: bool If True ( the default ) and the encoding declaration is found in the first two lines that line will be excluded from the output - compiling a unicode string with a...
def read_py_file(filename, skip_encoding_cookie=True): """Read a Python file, using the encoding declared inside the file. Parameters ---------- filename : str The path to the file to read. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in t...
Read a Python file from a URL using the encoding declared inside the file. Parameters ---------- url: str The URL from which to fetch the file. errors: str How to handle decoding errors in the file. Options are the same as for bytes. decode () but here replace is the default. skip_encoding_cookie: bool If True ( the de...
def read_py_url(url, errors='replace', skip_encoding_cookie=True): """Read a Python file from a URL, using the encoding declared inside the file. Parameters ---------- url : str The URL from which to fetch the file. errors : str How to handle decoding errors in the file. Options are...
build argv to be passed to kernel subprocess
def build_kernel_argv(self, argv=None): """build argv to be passed to kernel subprocess""" if argv is None: argv = sys.argv[1:] self.kernel_argv = swallow_argv(argv, self.frontend_aliases, self.frontend_flags) # kernel should inherit default config file from frontend ...
find the connection file and load the info if found. The current working directory and the current profile s security directory will be searched for the file if it is not given by absolute path. When attempting to connect to an existing kernel and the -- existing argument does not match an existing file it will be inte...
def init_connection_file(self): """find the connection file, and load the info if found. The current working directory and the current profile's security directory will be searched for the file if it is not given by absolute path. When attempting to connect to a...
set up ssh tunnels if needed.
def init_ssh(self): """set up ssh tunnels, if needed.""" if not self.sshserver and not self.sshkey: return if self.sshkey and not self.sshserver: # specifying just the key implies that we are connecting directly self.sshserver = self.ip se...
Classes which mix this class in should call: IPythonConsoleApp. initialize ( self argv )
def initialize(self, argv=None): """ Classes which mix this class in should call: IPythonConsoleApp.initialize(self,argv) """ self.init_connection_file() default_secure(self.config) self.init_ssh() self.init_kernel_manager()
Return message as dict: return dict
def prepare_message(self, data=None): """ Return message as dict :return dict """ message = { 'protocol': self.protocol, 'node': self._node, 'chip_id': self._chip_id, 'event': '', 'parameters': {}, 'response'...
Decode json string to dict. Validate against node name ( targets ) and protocol version: return dict | None
def decode_message(self, message): """ Decode json string to dict. Validate against node name(targets) and protocol version :return dict | None """ try: message = json.loads(message) if not self._validate_message(message): message = None ...
: return boolean
def _validate_message(self, message): """:return boolean""" if 'protocol' not in message or 'targets' not in message or \ type(message['targets']) is not list: return False if message['protocol'] != self.protocol: return False if self.node not in...
Pretty print the object s representation.
def pretty(obj, verbose=False, max_width=79, newline='\n'): """ Pretty print the object's representation. """ stream = StringIO() printer = RepresentationPrinter(stream, verbose, max_width, newline) printer.pretty(obj) printer.flush() return stream.getvalue()
Like pretty but print to stdout.
def pprint(obj, verbose=False, max_width=79, newline='\n'): """ Like `pretty` but print to stdout. """ printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline) printer.pretty(obj) printer.flush() sys.stdout.write(newline) sys.stdout.flush()
Get a reasonable method resolution order of a class and its superclasses for both old - style and new - style classes.
def _get_mro(obj_class): """ Get a reasonable method resolution order of a class and its superclasses for both old-style and new-style classes. """ if not hasattr(obj_class, '__mro__'): # Old-style class. Mix in object to make a fake new-style class. try: obj_class = type(obj...
The default print function. Used if an object does not provide one and it s none of the builtin objects.
def _default_pprint(obj, p, cycle): """ The default print function. Used if an object does not provide one and it's none of the builtin objects. """ klass = getattr(obj, '__class__', None) or type(obj) if getattr(klass, '__repr__', None) not in _baseclass_reprs: # A user-provided repr. ...
Factory that returns a pprint function useful for sequences. Used by the default pprint for tuples dicts lists sets and frozensets.
def _seq_pprinter_factory(start, end, basetype): """ Factory that returns a pprint function useful for sequences. Used by the default pprint for tuples, dicts, lists, sets and frozensets. """ def inner(obj, p, cycle): typ = type(obj) if basetype is not None and typ is not basetype a...
Factory that returns a pprint function used by the default pprint of dicts and dict proxies.
def _dict_pprinter_factory(start, end, basetype=None): """ Factory that returns a pprint function used by the default pprint of dicts and dict proxies. """ def inner(obj, p, cycle): typ = type(obj) if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:...
The pprint for the super type.
def _super_pprint(obj, p, cycle): """The pprint for the super type.""" p.begin_group(8, '<super: ') p.pretty(obj.__self_class__) p.text(',') p.breakable() p.pretty(obj.__self__) p.end_group(8, '>')
The pprint function for regular expression patterns.
def _re_pattern_pprint(obj, p, cycle): """The pprint function for regular expression patterns.""" p.text('re.compile(') pattern = repr(obj.pattern) if pattern[:1] in 'uU': pattern = pattern[1:] prefix = 'ur' else: prefix = 'r' pattern = prefix + pattern.replace('\\\\', '\...
The pprint for classes and types.
def _type_pprint(obj, p, cycle): """The pprint for classes and types.""" if obj.__module__ in ('__builtin__', 'exceptions'): name = obj.__name__ else: name = obj.__module__ + '.' + obj.__name__ p.text(name)
Base pprint for all functions and builtin functions.
def _function_pprint(obj, p, cycle): """Base pprint for all functions and builtin functions.""" if obj.__module__ in ('__builtin__', 'exceptions') or not obj.__module__: name = obj.__name__ else: name = obj.__module__ + '.' + obj.__name__ p.text('<function %s>' % name)
Base pprint for all exceptions.
def _exception_pprint(obj, p, cycle): """Base pprint for all exceptions.""" if obj.__class__.__module__ in ('exceptions', 'builtins'): name = obj.__class__.__name__ else: name = '%s.%s' % ( obj.__class__.__module__, obj.__class__.__name__ ) step = len(name...
Add a pretty printer for a given type.
def for_type(typ, func): """ Add a pretty printer for a given type. """ oldfunc = _type_pprinters.get(typ, None) if func is not None: # To support easy restoration of old pprinters, we need to ignore Nones. _type_pprinters[typ] = func return oldfunc
Add a pretty printer for a type specified by the module and name of a type rather than the type object itself.
def for_type_by_name(type_module, type_name, func): """ Add a pretty printer for a type specified by the module and name of a type rather than the type object itself. """ key = (type_module, type_name) oldfunc = _deferred_type_pprinters.get(key, None) if func is not None: # To suppor...
like begin_group/ end_group but for the with statement.
def group(self, indent=0, open='', close=''): """like begin_group / end_group but for the with statement.""" self.begin_group(indent, open) try: yield finally: self.end_group(indent, close)
Add literal text to the output.
def text(self, obj): """Add literal text to the output.""" width = len(obj) if self.buffer: text = self.buffer[-1] if not isinstance(text, Text): text = Text() self.buffer.append(text) text.add(obj, width) self.buffe...
Add a breakable separator to the output. This does not mean that it will automatically break here. If no breaking on this position takes place the sep is inserted which default to one space.
def breakable(self, sep=' '): """ Add a breakable separator to the output. This does not mean that it will automatically break here. If no breaking on this position takes place the `sep` is inserted which default to one space. """ width = len(sep) group = self.g...
Begin a group. If you want support for python < 2. 5 which doesn t has the with statement this is the preferred way:
def begin_group(self, indent=0, open=''): """ Begin a group. If you want support for python < 2.5 which doesn't has the with statement this is the preferred way: p.begin_group(1, '{') ... p.end_group(1, '}') The python 2.5 expression would be this: ...
End a group. See begin_group for more details.
def end_group(self, dedent=0, close=''): """End a group. See `begin_group` for more details.""" self.indentation -= dedent group = self.group_stack.pop() if not group.breakables: self.group_queue.remove(group) if close: self.text(close)
Flush data that is left in the buffer.
def flush(self): """Flush data that is left in the buffer.""" for data in self.buffer: self.output_width += data.output(self.output, self.output_width) self.buffer.clear() self.buffer_width = 0
Pretty print the given object.
def pretty(self, obj): """Pretty print the given object.""" obj_id = id(obj) cycle = obj_id in self.stack self.stack.append(obj_id) self.begin_group() try: obj_class = getattr(obj, '__class__', None) or type(obj) # First try to find registered sing...
Check if the given class is specified in the deferred type registry.
def _in_deferred_types(self, cls): """ Check if the given class is specified in the deferred type registry. Returns the printer from the registry if it exists, and None if the class is not in the registry. Successful matches will be moved to the regular type registry for future ...
Return a color table with fields for exception reporting.
def exception_colors(): """Return a color table with fields for exception reporting. The table is an instance of ColorSchemeTable with schemes added for 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled in. Examples: >>> ec = exception_colors() >>> ec.active_scheme...
As patterns () in django.
def patterns(prefix, *args): """As patterns() in django.""" pattern_list = [] for t in args: if isinstance(t, (list, tuple)): t = url(prefix=prefix, *t) elif isinstance(t, RegexURLPattern): t.add_prefix(prefix) pattern_list.append(t) return pattern_list
As url () in Django.
def url(regex, view, kwargs=None, name=None, prefix=''): """As url() in Django.""" if isinstance(view, (list, tuple)): # For include(...) processing. urlconf_module, app_name, namespace = view return URLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace) e...
Prepare columns in new ods file create new sheet for metadata set columns color and width. Set formatting style info in your settings. py file in ~/. c3po/ folder.
def _prepare_ods_columns(ods, trans_title_row): """ Prepare columns in new ods file, create new sheet for metadata, set columns color and width. Set formatting style info in your settings.py file in ~/.c3po/ folder. """ ods.content.getSheet(0).setSheetName('Translations') ods.content.makeShe...
Write translations from po files into ods one file. Assumes a directory structure: <locale_root >/ <lang >/ <po_files_path >/ <filename >.
def _write_trans_into_ods(ods, languages, locale_root, po_files_path, po_filename, start_row): """ Write translations from po files into ods one file. Assumes a directory structure: <locale_root>/<lang>/<po_files_path>/<filename>. """ ods.content.getSheet(0) for i, ...
Write row with translations to ods file into specified sheet and row_no.
def _write_row_into_ods(ods, sheet_no, row_no, row): """ Write row with translations to ods file into specified sheet and row_no. """ ods.content.getSheet(sheet_no) for j, col in enumerate(row): cell = ods.content.getCell(j, row_no+1) cell.stringValue(_escape_apostrophe(col)) ...
Converts po file to csv GDocs spreadsheet readable format.: 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 temp_file_path: path where temporary files will be saved
def po_to_ods(languages, locale_root, po_files_path, temp_file_path): """ Converts po file to csv GDocs spreadsheet readable format. :param languages: list of language codes :param locale_root: path to locale root folder containing directories with languages :param po_files_p...
Converts csv files to one ods file: param trans_csv: path to csv file with translations: param meta_csv: path to csv file with metadata: param local_ods: path to new ods file
def csv_to_ods(trans_csv, meta_csv, local_ods): """ Converts csv files to one ods file :param trans_csv: path to csv file with translations :param meta_csv: path to csv file with metadata :param local_ods: path to new ods file """ trans_reader = UnicodeReader(trans_csv) meta_reader = Uni...
Get the current clipboard s text on Windows.
def win32_clipboard_get(): """ Get the current clipboard's text on Windows. Requires Mark Hammond's pywin32 extensions. """ try: import win32clipboard except ImportError: raise TryNext("Getting text from the clipboard requires the pywin32 " "extensions: http://...
Get the clipboard s text on OS X.
def osx_clipboard_get(): """ Get the clipboard's text on OS X. """ p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'], stdout=subprocess.PIPE) text, stderr = p.communicate() # Text comes in with old Mac \r line endings. Change them to \n. text = text.replace('\r', '\n') return text
Get the clipboard s text using Tkinter.
def tkinter_clipboard_get(): """ Get the clipboard's text using Tkinter. This is the default on systems that are not Windows or OS X. It may interfere with other UI toolkits and should be replaced with an implementation that uses that toolkit. """ try: import Tkinter except ImportEr...
Returns a safe build_prefix
def _get_build_prefix(): """ Returns a safe build_prefix """ path = os.path.join( tempfile.gettempdir(), 'pip_build_%s' % __get_username().replace(' ', '_') ) if WINDOWS: """ on windows(tested on 7) temp dirs are isolated """ return path try: os.mkdir(path) ...
Find the subdomain rank ( tuple ) for each processor and determine the neighbor info.
def prepare_communication (self): """ Find the subdomain rank (tuple) for each processor and determine the neighbor info. """ nsd_ = self.nsd if nsd_<1: print('Number of space dimensions is %d, nothing to do' %nsd_) return ...
Prepare the buffers to be used for later communications
def prepare_communication (self): """ Prepare the buffers to be used for later communications """ RectPartitioner.prepare_communication (self) if self.lower_neighbors[0]>=0: self.in_lower_buffers = [zeros(1, float)] self.out_lower_buffers...
Prepare the buffers to be used for later communications
def prepare_communication (self): """ Prepare the buffers to be used for later communications """ RectPartitioner.prepare_communication (self) self.in_lower_buffers = [[], []] self.out_lower_buffers = [[], []] self.in_upper_buffers = [[], []] ...
update the inner boundary with the same send/ recv pattern as the MPIPartitioner
def update_internal_boundary_x_y (self, solution_array): """update the inner boundary with the same send/recv pattern as the MPIPartitioner""" nsd_ = self.nsd dtype = solution_array.dtype if nsd_!=len(self.in_lower_buffers) | nsd_!=len(self.out_lower_buffers): print("Buffers ...
Rekey a dict that has been forced to use str keys where there should be ints by json.
def rekey(dikt): """Rekey a dict that has been forced to use str keys where there should be ints by json.""" for k in dikt.iterkeys(): if isinstance(k, basestring): ik=fk=None try: ik = int(k) except ValueError: try: ...
extract ISO8601 dates from unpacked JSON
def extract_dates(obj): """extract ISO8601 dates from unpacked JSON""" if isinstance(obj, dict): obj = dict(obj) # don't clobber for k,v in obj.iteritems(): obj[k] = extract_dates(v) elif isinstance(obj, (list, tuple)): obj = [ extract_dates(o) for o in obj ] elif isi...
squash datetime objects into ISO8601 strings
def squash_dates(obj): """squash datetime objects into ISO8601 strings""" if isinstance(obj, dict): obj = dict(obj) # don't clobber for k,v in obj.iteritems(): obj[k] = squash_dates(v) elif isinstance(obj, (list, tuple)): obj = [ squash_dates(o) for o in obj ] elif is...
default function for packing datetime objects in JSON.
def date_default(obj): """default function for packing datetime objects in JSON.""" if isinstance(obj, datetime): return obj.strftime(ISO8601) else: raise TypeError("%r is not JSON serializable"%obj)
b64 - encodes images in a displaypub format dict Perhaps this should be handled in json_clean itself? Parameters ---------- format_dict: dict A dictionary of display data keyed by mime - type Returns ------- format_dict: dict A copy of the same dictionary but binary image data ( image/ png or image/ jpeg ) is base64 - ...
def encode_images(format_dict): """b64-encodes images in a displaypub format dict Perhaps this should be handled in json_clean itself? Parameters ---------- format_dict : dict A dictionary of display data keyed by mime-type Returns ------- format_dict : d...
Clean an object to ensure it s safe to encode in JSON. Atomic immutable objects are returned unmodified. Sets and tuples are converted to lists lists are copied and dicts are also copied.
def json_clean(obj): """Clean an object to ensure it's safe to encode in JSON. Atomic, immutable objects are returned unmodified. Sets and tuples are converted to lists, lists are copied and dicts are also copied. Note: dicts whose keys could cause collisions upon encoding (such as a dict wit...
Verify that self. install_dir is. pth - capable dir if needed
def check_site_dir(self): """Verify that self.install_dir is .pth-capable dir, if needed""" instdir = normalize_path(self.install_dir) pth_file = os.path.join(instdir, 'easy-install.pth') # Is it a configured, PYTHONPATH, implicit, or explicit site dir? is_site_dir = instdir in...
Write an executable file to the scripts directory
def write_script(self, script_name, contents, mode="t", *ignored): """Write an executable file to the scripts directory""" from setuptools.command.easy_install import chmod, current_umask log.info("Installing %s script to %s", script_name, self.install_dir) target = os.path.join(self.ins...
simple function that takes args prints a short message sleeps for a time and returns the same args
def sleep_here(count, t): """simple function that takes args, prints a short message, sleeps for a time, and returns the same args""" import time,sys print("hi from engine %i" % id) sys.stdout.flush() time.sleep(t) return count,t
Save the args and kwargs to get/ post/ put/ delete for future use.
def _save_method_args(self, *args, **kwargs): """Save the args and kwargs to get/post/put/delete for future use. These arguments are not saved in the request or handler objects, but are often needed by methods such as get_stream(). """ self._method_args = args self._met...
Set up any environment changes requested ( e. g. Python path and Django settings ) then run this command.
def run_from_argv(self, argv): """ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. """ parser = self.create_parser(argv[0], argv[1]) self.arguments = parser.parse_args(argv[2:]) handle_default_options(self....
Create and return the ArgumentParser which will be used to parse the arguments to this command.
def create_parser(self, prog_name, subcommand): """ Create and return the ``ArgumentParser`` which will be used to parse the arguments to this command. """ parser = ArgumentParser( description=self.description, epilog=self.epilog, add_...