text
stringlengths
81
112k
Dump function defintion, doc string, and function body. This code is specialied for Python 2. def make_function2(self, node, is_lambda, nested=1, code_node=None): """ Dump function defintion, doc string, and function body. This code is specialied for Python 2. """ # FIXME: call make_function3 ...
Dump function definition, doc string, and function body in Python version 3.0 and above def make_function3(self, node, is_lambda, nested=1, code_node=None): """Dump function definition, doc string, and function body in Python version 3.0 and above """ # For Python 3.3, the evaluation stack in ...
Compare two code-objects. This is the main part of this module. def cmp_code_objects(version, is_pypy, code_obj1, code_obj2, verify, name=''): """ Compare two code-objects. This is the main part of this module. """ # print code_obj1, type(code_obj2) assert iscode(code...
Compare a .pyc with a source code file. If everything is okay, None is returned. Otherwise a string message describing the mismatch is returned. def compare_code_with_srcfile(pyc_filename, src_filename, verify): """Compare a .pyc with a source code file. If everything is okay, None is returned. Otherwise a...
Compare two .pyc files. def compare_files(pyc_filename1, pyc_filename2, verify): """Compare two .pyc files.""" (version1, timestamp, magic_int1, code_obj1, is_pypy, source_size) = uncompyle6.load_module(pyc_filename1) (version2, timestamp, magic_int2, code_obj2, is_pypy, source_size) = uncompy...
Convert the code object co into a python source fragment. :param version: The python version this code is from as a float, for example 2.6, 2.7, 3.2, 3.3, 3.4, 3.5 etc. :param co: The code object to parse. :param out: File like object to write th...
Like deparse_code(), but given a function/module name and offset, finds the node closest to offset. If offset is not an instruction boundary, we raise an IndexError. def code_deparse_around_offset(name, offset, co, out=StringIO(), version=None, is_pypy=None, ...
Return the instruction name at code[loc] using opc to look up instruction names. Returns 'got IndexError' if code[loc] is invalid. `code` is instruction bytecode, `loc` is an offset (integer) and `opc` is an opcode module from `xdis`. def op_at_code_loc(code, loc, opc): """Return the instruction n...
Return a NodeInfo nametuple for a fragment-deparsed `deparsed` at `tup`. `tup` is a name and offset tuple, `deparsed` is a fragment object and `code` is instruction bytecode. def deparsed_find(tup, deparsed, code): """Return a NodeInfo nametuple for a fragment-deparsed `deparsed` at `tup`. `tup` is a...
General pattern where the last node should should get the text span attributes of the entire tree def table_r_node(self, node): """General pattern where the last node should should get the text span attributes of the entire tree""" start = len(self.f.getvalue()) try: ...
exec_stmt ::= expr exprlist DUP_TOP EXEC_STMT exec_stmt ::= expr exprlist EXEC_STMT def n_exec_stmt(self, node): """ exec_stmt ::= expr exprlist DUP_TOP EXEC_STMT exec_stmt ::= expr exprlist EXEC_STMT """ start = len(self.f.getvalue()) + len(self.indent) try: ...
List comprehensions def n_list_comp(self, node): """List comprehensions""" p = self.prec self.prec = 27 n = node[-1] assert n == 'list_iter' # find innermost node while n == 'list_iter': n = n[0] # recurse one step if n == 'list_for': n ...
List comprehensions the way they are done in Python3. They're more other comprehensions, e.g. set comprehensions See if we can combine code. def comprehension_walk3(self, node, iter_index, code_index=-5): """ List comprehensions the way they are done in Python3. They're more oth...
List comprehensions the way they are done in Python3. They're more other comprehensions, e.g. set comprehensions See if we can combine code. def setcomprehension_walk3(self, node, collection_index): """List comprehensions the way they are done in Python3. They're more other comprehensio...
Make sure each node has a parent def fixup_parents(self, node, parent): """Make sure each node has a parent""" start, finish = 0, self.last_finish # We assume anything with a start has a finish. needs_range = not hasattr(node, 'start') if not hasattr(node, 'parent'): ...
Adjust all offsets under node def fixup_offsets(self, new_start, node): """Adjust all offsets under node""" if hasattr(node, 'start'): node.start += new_start node.finish += new_start for n in node: if hasattr(n, 'offset'): if hasattr(n, 'star...
Set positions under node def set_pos_info_recurse(self, node, start, finish, parent=None): """Set positions under node""" self.set_pos_info(node, start, finish) if parent is None: parent = node for n in node: n.parent = parent if hasattr(n, 'offset'):...
prettyprint a dict 'dict' is something like k = {'a': 1, 'b': 42 }" def n_dict(self, node): """ prettyprint a dict 'dict' is something like k = {'a': 1, 'b': 42 }" """ p = self.prec self.prec = 100 self.indent_more(INDENT_PER_LEVEL) line_seperato...
prettyprint a list or tuple def n_list(self, node): """ prettyprint a list or tuple """ p = self.prec self.prec = 100 n = node.pop() lastnode = n.kind start = len(self.f.getvalue()) if lastnode.startswith('BUILD_LIST'): self.write('[')...
The format template interpetation engine. See the comment at the beginning of this module for the how we interpret format specifications such as %c, %C, and so on. def template_engine(self, entry, startnode): """The format template interpetation engine. See the comment at the beginnin...
Augment write routine to keep track of current line def write(self, *data): """Augment write routine to keep track of current line""" for l in data: ## print("XXX write: '%s'" % l) for i in str(l): if i == '\n': self.current_line_number += 1 ...
Augment write default routine to record line number changes def default(self, node): """Augment write default routine to record line number changes""" if hasattr(node, 'linestart'): if node.linestart: self.source_linemap[self.current_line_number] = node.linestart ret...
Pick out tokens from an uncompyle6 code object, and transform them, returning a list of uncompyle6 'Token's. The transformations are made to assist the deparsing grammar. Specificially: - various types of LOAD_CONST's are categorized in terms of what they load - COME_FRO...
Search Syntax Tree node to find variable names that are global. def find_all_globals(node, globs): """Search Syntax Tree node to find variable names that are global.""" for n in node: if isinstance(n, SyntaxTree): globs = find_all_globals(n, globs) elif n.kind in read_write_global_o...
search a node of parse tree to find variable names that need a either 'global' or 'nonlocal' statements added. def find_globals_and_nonlocals(node, globs, nonlocals, code, version): """search a node of parse tree to find variable names that need a either 'global' or 'nonlocal' statements added.""" for ...
List of expressions may be nested in groups of 32 and 1024 items. flatten that out and return the list def flatten_list(node): """ List of expressions may be nested in groups of 32 and 1024 items. flatten that out and return the list """ flat_elems = [] for elem in node: if elem == ...
takes anything and attempts to return a py2 string or py3 bytes. this is typically used when creating command + arguments to be executed via os.exec* def encode_to_py3bytes_or_py2str(s): """ takes anything and attempts to return a py2 string or py3 bytes. this is typically used when creating command ...
takes an exception name, like: ErrorReturnCode_1 SignalException_9 SignalException_SIGHUP and returns the corresponding exception. this is primarily used for importing exceptions from sh into user code, for instance, to capture those exceptions def get_exc_from_name(name): ""...
takes a exit code or negative signal number and produces an exception that corresponds to that return code. positive return codes yield ErrorReturnCode exception, negative return codes yield SignalException we also cache the generated exception so that only one signal of that type exists, preserving i...
takes a program name or full path, plus an optional collection of search paths, and returns the full path of the requested executable. if paths is specified, it is the entire list of search paths, and the PATH env is not used at all. otherwise, PATH env is used to look for the program def which(program, ...
checks if an object (like a file-like object) is a tty. def ob_is_tty(ob): """ checks if an object (like a file-like object) is a tty. """ fileno = get_fileno(ob) is_tty = False if fileno: is_tty = os.isatty(fileno) return is_tty
a validator to prevent a user from saying that they want custom buffering when they're using an in/out object that will be os.dup'd to the process, and has its own buffering. an example is a pipe or a tty. it doesn't make sense to tell them to have a custom buffering, since the os controls this. def ...
takes args and kwargs, as they were passed into the command instance being executed with __call__, and compose them into a flat list that will eventually be fed into exec. example: with this call: sh.ls("-l", "/tmp", color="never") this function receives args = ['-l', '/tmp'] ...
take our keyword arguments, and a separator, and compose the list of flat long (and short) arguments. example {'color': 'never', 't': True, 'something': True} with sep '=' becomes ['--color=never', '-t', '--something'] the `raw` argument indicates whether or not we should leave the argu...
set the terminal size of a tty file descriptor. borrowed logic from pexpect.py def setwinsize(fd, rows_cols): """ set the terminal size of a tty file descriptor. borrowed logic from pexpect.py """ rows, cols = rows_cols TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561) s = struct.pack...
here we're constructing a closure for our streamreader callback. this is used in the case that we pass a callback into _out or _err, meaning we want to our callback to handle each bit of output we construct the closure based on how many arguments it takes. the reason for this is to make it as easy as...
this should only ever be called once for each child process def handle_process_exit_code(exit_code): """ this should only ever be called once for each child process """ # if we exited from a signal, let our exit code reflect that if os.WIFSIGNALED(exit_code): exit_code = -os.WTERMSIG(exit_code) ...
a helper for making system calls immune to EINTR def no_interrupt(syscall, *args, **kwargs): """ a helper for making system calls immune to EINTR """ ret = None while True: try: ret = syscall(*args, **kwargs) except OSError as e: if e.errno == errno.EINTR: ...
this is run in a separate thread. it writes into our process's stdin (a streamwriter) and waits the process to end AND everything that can be written to be written def input_thread(log, stdin, is_alive, quit, close_before_term): """ this is run in a separate thread. it writes into our process's stdin...
handles the timeout logic def background_thread(timeout_fn, timeout_event, handle_exit_code, is_alive, quit): """ handles the timeout logic """ # if there's a timeout event, loop if timeout_event: while not quit.is_set(): timed_out = event_wait(timeout_event, 0.1) ...
this function is run in a separate thread. it reads from the process's stdout stream (a streamreader), and waits for it to claim that its done def output_thread(log, stdout, stderr, timeout_event, is_alive, quit, stop_output_event): """ this function is run in a separate thread. it reads from the...
given some kind of input object, return a function that knows how to read chunks of that input object. each reader function should return a chunk and raise a DoneReadingForever exception, or return None, when there's no more data to read NOTE: the function returned does not need to care much about...
return an iterator that returns a chunk of a string every time it is called. notice that even though bufsize_type might be line buffered, we're not doing any line buffering here. that's because our StreamBufferer handles all buffering. we just need to return a reasonable-sized chunk. def get_iter_string...
pushd changes the actual working directory for the duration of the context, unlike the _cwd arg this will work with other built-ins such as sh.glob correctly def pushd(path): """ pushd changes the actual working directory for the duration of the context, unlike the _cwd arg this will work with other bu...
allows us to temporarily override all the special keyword parameters in a with context def args(**kwargs): """ allows us to temporarily override all the special keyword parameters in a with context """ kwargs_str = ",".join(["%s=%r" % (k,v) for k,v in kwargs.items()]) raise DeprecationWarning("""...
a nicer version of sudo that uses getpass to ask for a password, or allows the first argument to be a string password def sudo(orig): # pragma: no cover """ a nicer version of sudo that uses getpass to ask for a password, or allows the first argument to be a string password """ prompt = "[sudo] passwo...
registers our fancy importer that can let us import from a module name, like: import sh tmp = sh() from tmp import ls def register_importer(): """ registers our fancy importer that can let us import from a module name, like: import sh tmp = sh() from tmp im...
waits for the running command to finish. this is called on all running commands, eventually, except for ones that run in the background def wait(self): """ waits for the running command to finish. this is called on all running commands, eventually, except for ones that run in the background ...
here we determine if we had an exception, or an error code that we weren't expecting to see. if we did, we create and raise an exception def handle_command_exit_code(self, code): """ here we determine if we had an exception, or an error code that we weren't expecting to see. if we did, we cre...
allow us to iterate over the output of our command def next(self): """ allow us to iterate over the output of our command """ if self._stopped_iteration: raise StopIteration() # we do this because if get blocks, we can't catch a KeyboardInterrupt # so the slight timeout al...
takes kwargs that were passed to a command's __call__ and extracts out the special keyword arguments, we return a tuple of special keyword args, and kwargs that will go to the execd command def _extract_call_args(kwargs): """ takes kwargs that were passed to a command's __call__ and extracts ...
polls if our child process has completed, without blocking. this method has side-effects, such as setting our exit_code, if we happen to see our child exit while this is running def is_alive(self): """ polls if our child process has completed, without blocking. this method has side-ef...
waits for the process to complete, handles the exit code def wait(self): """ waits for the process to complete, handles the exit code """ self.log.debug("acquiring wait lock to wait for completion") # using the lock in a with-context blocks, which is what we want if # we're running wai...
attempt to get a chunk of data to write to our child process's stdin, then write it. the return value answers the questions "are we done writing forever?" def write(self): """ attempt to get a chunk of data to write to our child process's stdin, then write it. the return value answers...
mod_fullname doubles as the name of the VARIABLE holding our new sh context. for example: derp = sh() from derp import ls here, mod_fullname will be "derp". keep that in mind as we go throug the rest of this function def find_module(self, mod_fullname, path=None): ...
a simplified json_normalize converts a nested dict into a flat dict ("record"), unlike json_normalize, it does not attempt to extract a subset of the data. Parameters ---------- ds : dict or list of dicts prefix: the prefix, optional, default: "" sep : string, default '.' Nested re...
"Normalize" semi-structured JSON data into a flat table Parameters ---------- data : dict or list of dicts Unserialized JSON objects record_path : string or list of strings, default None Path in each object to list of records. If not passed, data will be assumed to be an array o...
Convert a NumPy / pandas type to its corresponding json_table. Parameters ---------- x : array or dtype Returns ------- t : str the Table Schema data types Notes ----- This table shows the relationship between NumPy / pandas dtypes, and Table Schema dtypes. ======...
Sets index names to 'index' for regular, or 'level_x' for Multi def set_default_names(data): """Sets index names to 'index' for regular, or 'level_x' for Multi""" if all(name is not None for name in data.index.names): return data data = data.copy() if data.index.nlevels > 1: names = [n...
Convert a JSON string to pandas object Parameters ---------- path_or_buf : a valid JSON string or file-like, default: None The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be ``file://lo...
try to parse a ndarray like into a column by inferring dtype def _try_convert_data(self, name, data, use_dtypes=True, convert_dates=True): """ try to parse a ndarray like into a column by inferring dtype """ # don't try to coerce, unless a force conversion if use_dtyp...
try to parse a ndarray like into a date column try to coerce object in epoch/iso formats and integer/float in epcoh formats, return a boolean if parsing was successful def _try_convert_to_date(self, data): """ try to parse a ndarray like into a date column try to...
Set the default qgrid options. The options that you can set here are the same ones that you can pass into ``QgridWidget`` constructor, with the exception of the ``df`` option, for which a default value wouldn't be particularly useful (since the purpose of qgrid is to display a DataFrame). See the docu...
Automatically use qgrid to display all DataFrames and/or Series instances in the notebook. Parameters ---------- dataframe : bool Whether to automatically use qgrid to display DataFrames instances. series : bool Whether to automatically use qgrid to display Series instances. def en...
Renders a DataFrame or Series as an interactive qgrid, represented by an instance of the ``QgridWidget`` class. The ``QgridWidget`` instance is constructed using the options passed in to this function. The ``data_frame`` argument to this function is used as the ``df`` kwarg in call to the QgridWidget ...
decorator for building minified js/css prior to another command def js_prerelease(command, strict=False): """decorator for building minified js/css prior to another command""" class DecoratedCommand(command): def run(self): jsdeps = self.distribution.get_command_obj('jsdeps') if...
return list of available themes def get_themes(): """ return list of available themes """ styles_dir = os.path.join(package_dir, 'styles') themes = [os.path.basename(theme).replace('.less', '') for theme in glob('{0}/*.less'.format(styles_dir))] return themes
Install theme to jupyter_customcss with specified font, fontsize, md layout, and toolbar pref def install_theme(theme=None, monofont=None, monosize=11, nbfont=None, nbfontsize=13, tcfont=None, tcfontsize=13, ...
checks jupyter_config_dir() for text file containing theme name (updated whenever user installs a new theme) def infer_theme(): """ checks jupyter_config_dir() for text file containing theme name (updated whenever user installs a new theme) """ themes = [os.path.basename(theme).replace('.less', '')...
main function for styling matplotlib according to theme ::Arguments:: theme (str): 'oceans16', 'grade3', 'chesterish', 'onedork', 'monokai', 'solarizedl', 'solarizedd'. If no theme name supplied the currently installed notebook theme will be used. context (str): 'paper' (Default), 'notebook', 'tal...
This code has been modified from seaborn.rcmod.set_style() ::Arguments:: rcdict (str): dict of "context" properties (filled by set_context()) theme (str): name of theme to use when setting color properties grid (bool): turns off axis grid if False (default: True) ticks (bool): remove...
Most of this code has been copied/modified from seaborn.rcmod.plotting_context() ::Arguments:: context (str): 'paper', 'notebook', 'talk', or 'poster' fscale (float): font-size scalar applied to axes ticks, legend, labels, etc. def set_context(context='paper', fscale=1., figsize=(8., 7.)): """ ...
manually set the default figure size of plots ::Arguments:: x (float): x-axis size y (float): y-axis size aspect (float): aspect ratio scalar def figsize(x=8, y=7., aspect=1.): """ manually set the default figure size of plots ::Arguments:: x (float): x-axis size y (...
read-in theme style info and populate styleMap (dict of with mpl.rcParams) and clist (list of hex codes passed to color cylcler) ::Arguments:: theme (str): theme name ::Returns:: styleMap (dict): dict containing theme-specific colors for figure properties clist (list): list of colors...
full reset of matplotlib default style and colors def reset(): """ full reset of matplotlib default style and colors """ colors = [(0., 0., 1.), (0., .5, 0.), (1., 0., 0.), (.75, .75, 0.), (.75, .75, 0.), (0., .75, .75), (0., 0., 0.)] for code, color in zip("bgrmyck", colors): rgb =...
write less-compiled css file to jupyter_customcss in jupyter_dir def less_to_css(style_less): """ write less-compiled css file to jupyter_customcss in jupyter_dir """ with fileOpen(tempfile, 'w') as f: f.write(style_less) os.chdir(package_dir) style_css = lesscpy.compile(tempfile) s...
Parent function for setting notebook, text/md, and codecell font-properties def set_font_properties(style_less, nbfont=None, tcfont=None, monofont=None, monosize=11, tcfontsize=13, ...
Copy all custom fonts to ~/.jupyter/custom/fonts/ and write import statements to style_less def import_fonts(style_less, fontname, font_subdir): """Copy all custom fonts to ~/.jupyter/custom/fonts/ and write import statements to style_less """ ftype_dict = {'woff2': 'woff2', 'wof...
Set general layout and style properties of text and code cells def style_layout(style_less, theme='grade3', cursorwidth=2, cursorcolor='default', cellwidth='980', lineheight=170, margins='auto', vimex...
Toggle main notebook toolbar (e.g., buttons), filename, and kernel logo. def toggle_settings( toolbar=False, nbname=False, hideprompt=False, kernellogo=False): """Toggle main notebook toolbar (e.g., buttons), filename, and kernel logo.""" toggle = '' if toolbar: toggle += 'div#main...
Write mathjax settings, set math fontsize def set_mathjax_style(style_css, mathfontsize): """Write mathjax settings, set math fontsize """ jax_style = """<script> MathJax.Hub.Config({ "HTML-CSS": { /*preferredFont: "TeX",*/ /*availableFonts: ["TeX", "STIX"],*/ ...
Add style and compatibility with vim notebook extension def set_vim_style(theme): """Add style and compatibility with vim notebook extension""" vim_jupyter_nbext = os.path.join(jupyter_nbext, 'vim_binding') if not os.path.isdir(vim_jupyter_nbext): os.makedirs(vim_jupyter_nbext) vim_less = '@...
Remove custom.css and custom fonts def reset_default(verbose=False): """Remove custom.css and custom fonts""" paths = [jupyter_custom, jupyter_nbext] for fpath in paths: custom = '{0}{1}{2}.css'.format(fpath, os.sep, 'custom') try: os.remove(custom) except Exception: ...
Set theme from within notebook def set_nb_theme(name): """Set theme from within notebook """ from IPython.core.display import HTML styles_dir = os.path.join(package_dir, 'styles/compiled/') css_path = glob('{0}/{1}.css'.format(styles_dir, name))[0] customcss = open(css_path, "r").read() return...
Return split readme. def split_readme(readme_path, before_key, after_key, options_key, end_key): """Return split readme.""" with open(readme_path) as readme_file: readme = readme_file.read() top, rest = readme.split(before_key) before, rest = rest.split(after_key) _, rest = rest.split(opti...
Return help output. def help_message(): """Return help output.""" parser = autopep8.create_parser() string_io = io.StringIO() parser.print_help(string_io) # Undo home directory expansion. return string_io.getvalue().replace(os.path.expanduser('~'), '~')
Check code. def check(source): """Check code.""" compile(source, '<string>', 'exec', dont_inherit=True) reporter = pyflakes.reporter.Reporter(sys.stderr, sys.stderr) pyflakes.api.check(source, filename='<string>', reporter=reporter)
Override pycodestyle's function to provide indentation information. def continued_indentation(logical_line, tokens, indent_level, hang_closing, indent_char, noqa): """Override pycodestyle's function to provide indentation information.""" first_row = tokens[0][2][0] nrows = 1 + tok...
workaround get pointing out position by W605. def get_w605_position(tokens): """workaround get pointing out position by W605.""" # TODO: When this PR(*) change is released, use pos of pycodestyle # *: https://github.com/PyCQA/pycodestyle/pull/747 valid = [ '\n', '\\', '\'', '"', 'a', 'b', 'f', ...
return import or from keyword position example: > 0: import sys 1: import os 2: 3: def function(): def get_module_imports_on_top_of_file(source, import_line_index): """return import or from keyword position example: > 0: import sys 1: import os 2: ...
Break up long line and return result. Do this by generating multiple reformatted candidates and then ranking the candidates to heuristically select the best option. def get_fixed_long_line(target, previous_line, original, indent_word=' ', max_line_length=79, ...
Return single line based on logical line input. def join_logical_line(logical_line): """Return single line based on logical line input.""" indentation = _get_indentation(logical_line) return indentation + untokenize_without_newlines( generate_tokens(logical_line.lstrip())) + '\n'
Return source code based on tokens. def untokenize_without_newlines(tokens): """Return source code based on tokens.""" text = '' last_row = 0 last_column = -1 for t in tokens: token_string = t[1] (start_row, start_column) = t[2] (end_row, end_column) = t[3] if star...
Return the logical line corresponding to the result. Assumes input is already E702-clean. def _get_logical(source_lines, result, logical_start, logical_end): """Return the logical line corresponding to the result. Assumes input is already E702-clean. """ row = result['line'] - 1 col = result...
Return True if code is similar. Ignore whitespace when comparing specific line. def code_almost_equal(a, b): """Return True if code is similar. Ignore whitespace when comparing specific line. """ split_a = split_and_strip_non_empty_lines(a) split_b = split_and_strip_non_empty_lines(b) i...
Fix various deprecated code (via lib2to3). def fix_2to3(source, aggressive=True, select=None, ignore=None, filename='', where='global', verbose=False): """Fix various deprecated code (via lib2to3).""" if not aggressive: return source select = select or [] ignore = ign...
Return type of newline used in source. Input is a list of lines. def find_newline(source): """Return type of newline used in source. Input is a list of lines. """ assert not isinstance(source, unicode) counter = collections.defaultdict(int) for line in source: if line.endswith(C...
Return indentation type. def _get_indentword(source): """Return indentation type.""" indent_word = ' ' # Default in case source has no indentation try: for t in generate_tokens(source): if t[0] == token.INDENT: indent_word = t[1] break except (Syn...
Return text of unified diff between old and new. def get_diff_text(old, new, filename): """Return text of unified diff between old and new.""" newline = '\n' diff = difflib.unified_diff( old, new, 'original/' + filename, 'fixed/' + filename, lineterm=newline) text = '' ...
Separate line at OPERATOR. Multiple candidates will be yielded. def shorten_line(tokens, source, indentation, indent_word, max_line_length, aggressive=False, experimental=False, previous_line=''): """Separate line at OPERATOR. Multiple candidates will be yielded. """ for candida...