INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Sets the width ( in terms of space characters ) for tab characters.
def _set_tab_width(self, tab_width): """ Sets the width (in terms of space characters) for tab characters. """ font_metrics = QtGui.QFontMetrics(self.font) self._control.setTabStopWidth(tab_width * font_metrics.width(' ')) self._tab_width = tab_width
A low - level method for appending content to the end of the buffer.
def _append_custom(self, insert, input, before_prompt=False): """ A low-level method for appending content to the end of the buffer. If 'before_prompt' is enabled, the content will be inserted before the current prompt, if there is one. """ # Determine where to insert the conten...
Appends HTML at the end of the console buffer.
def _append_html(self, html, before_prompt=False): """ Appends HTML at the end of the console buffer. """ self._append_custom(self._insert_html, html, before_prompt)
Appends HTML then returns the plain text version of it.
def _append_html_fetching_plain_text(self, html, before_prompt=False): """ Appends HTML, then returns the plain text version of it. """ return self._append_custom(self._insert_html_fetching_plain_text, html, before_prompt)
Appends plain text processing ANSI codes if enabled.
def _append_plain_text(self, text, before_prompt=False): """ Appends plain text, processing ANSI codes if enabled. """ self._append_custom(self._insert_plain_text, text, before_prompt)
Clears the temporary text buffer i. e. all the text following the prompt region.
def _clear_temporary_buffer(self): """ Clears the "temporary text" buffer, i.e. all the text following the prompt region. """ # Select and remove all text below the input buffer. cursor = self._get_prompt_cursor() prompt = self._continuation_prompt.lstrip() if...
Performs completion with items at the specified cursor location.
def _complete_with_items(self, cursor, items): """ Performs completion with 'items' at the specified cursor location. """ self._cancel_completion() if len(items) == 1: cursor.setPosition(self._control.textCursor().position(), QtGui.QTextCursor....
fill the area below the active editting zone with text
def _fill_temporary_buffer(self, cursor, text, html=False): """fill the area below the active editting zone with text""" current_pos = self._control.textCursor().position() cursor.beginEditBlock() self._append_plain_text('\n') self._page(text, html=html) cursor.endEditB...
Creates a context menu for the given QPoint ( in widget coordinates ).
def _context_menu_make(self, pos): """ Creates a context menu for the given QPoint (in widget coordinates). """ menu = QtGui.QMenu(self) self.cut_action = menu.addAction('Cut', self.cut) self.cut_action.setEnabled(self.can_cut()) self.cut_action.setShortcut(QtGui.QKeySeq...
Given a KeyboardModifiers flags object return whether the Control key is down.
def _control_key_down(self, modifiers, include_command=False): """ Given a KeyboardModifiers flags object, return whether the Control key is down. Parameters: ----------- include_command : bool, optional (default True) Whether to treat the Command key as a (mutually ...
Creates and connects the underlying text widget.
def _create_control(self): """ Creates and connects the underlying text widget. """ # Create the underlying control. if self.custom_control: control = self.custom_control() elif self.kind == 'plain': control = QtGui.QPlainTextEdit() elif self.kind ...
Creates and connects the underlying paging widget.
def _create_page_control(self): """ Creates and connects the underlying paging widget. """ if self.custom_page_control: control = self.custom_page_control() elif self.kind == 'plain': control = QtGui.QPlainTextEdit() elif self.kind == 'rich': c...
Filter key events for the underlying text widget to create a console - like interface.
def _event_filter_console_keypress(self, event): """ Filter key events for the underlying text widget to create a console-like interface. """ intercepted = False cursor = self._control.textCursor() position = cursor.position() key = event.key() ctrl_do...
Filter key events for the paging widget to create console - like interface.
def _event_filter_page_keypress(self, event): """ Filter key events for the paging widget to create console-like interface. """ key = event.key() ctrl_down = self._control_key_down(event.modifiers()) alt_down = event.modifiers() & QtCore.Qt.AltModifier if ctr...
Transform a list of strings into a single string with columns.
def _format_as_columns(self, items, separator=' '): """ 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...
Given a QTextBlock return its unformatted text.
def _get_block_plain_text(self, block): """ Given a QTextBlock, return its unformatted text. """ cursor = QtGui.QTextCursor(block) cursor.movePosition(QtGui.QTextCursor.StartOfBlock) cursor.movePosition(QtGui.QTextCursor.EndOfBlock, QtGui.QTextCursor.K...
Convenience method that returns a cursor for the last character.
def _get_end_cursor(self): """ Convenience method that returns a cursor for the last character. """ cursor = self._control.textCursor() cursor.movePosition(QtGui.QTextCursor.End) return cursor
Returns the column of the cursor in the input buffer excluding the contribution by the prompt or - 1 if there is no such column.
def _get_input_buffer_cursor_column(self): """ Returns the column of the cursor in the input buffer, excluding the contribution by the prompt, or -1 if there is no such column. """ prompt = self._get_input_buffer_cursor_prompt() if prompt is None: return -1 ...
Returns the text of the line of the input buffer that contains the cursor or None if there is no such line.
def _get_input_buffer_cursor_line(self): """ Returns the text of the line of the input buffer that contains the cursor, or None if there is no such line. """ prompt = self._get_input_buffer_cursor_prompt() if prompt is None: return None else: c...
Returns the ( plain text ) prompt for line of the input buffer that contains the cursor or None if there is no such line.
def _get_input_buffer_cursor_prompt(self): """ Returns the (plain text) prompt for line of the input buffer that contains the cursor, or None if there is no such line. """ if self._executing: return None cursor = self._control.textCursor() if cursor.positi...
Convenience method that returns a cursor for the prompt position.
def _get_prompt_cursor(self): """ Convenience method that returns a cursor for the prompt position. """ cursor = self._control.textCursor() cursor.setPosition(self._prompt_pos) return cursor
Convenience method that returns a cursor with text selected between the positions start and end.
def _get_selection_cursor(self, start, end): """ Convenience method that returns a cursor with text selected between the positions 'start' and 'end'. """ cursor = self._control.textCursor() cursor.setPosition(start) cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor...
Find the start of the word to the left the given position. If a sequence of non - word characters precedes the first word skip over them. ( This emulates the behavior of bash emacs etc. )
def _get_word_start_cursor(self, position): """ Find the start of the word to the left the given position. If a sequence of non-word characters precedes the first word, skip over them. (This emulates the behavior of bash, emacs, etc.) """ document = self._control.document...
Find the end of the word to the right the given position. If a sequence of non - word characters precedes the first word skip over them. ( This emulates the behavior of bash emacs etc. )
def _get_word_end_cursor(self, position): """ Find the end of the word to the right the given position. If a sequence of non-word characters precedes the first word, skip over them. (This emulates the behavior of bash, emacs, etc.) """ document = self._control.document() ...
Inserts new continuation prompt using the specified cursor.
def _insert_continuation_prompt(self, cursor): """ Inserts new continuation prompt using the specified cursor. """ if self._continuation_prompt_html is None: self._insert_plain_text(cursor, self._continuation_prompt) else: self._continuation_prompt = self._insert_...
Inserts HTML using the specified cursor in such a way that future formatting is unaffected.
def _insert_html(self, cursor, html): """ Inserts HTML using the specified cursor in such a way that future formatting is unaffected. """ cursor.beginEditBlock() cursor.insertHtml(html) # After inserting HTML, the text document "remembers" it's in "html # mod...
Inserts HTML using the specified cursor then returns its plain text version.
def _insert_html_fetching_plain_text(self, cursor, html): """ Inserts HTML using the specified cursor, then returns its plain text version. """ cursor.beginEditBlock() cursor.removeSelectedText() start = cursor.position() self._insert_html(cursor, html) ...
Inserts plain text using the specified cursor processing ANSI codes if enabled.
def _insert_plain_text(self, cursor, text): """ Inserts plain text using the specified cursor, processing ANSI codes if enabled. """ cursor.beginEditBlock() if self.ansi_codes: for substring in self._ansi_processor.split_string(text): for act in se...
Inserts text into the input buffer using the specified cursor ( which must be in the input buffer ) ensuring that continuation prompts are inserted as necessary.
def _insert_plain_text_into_buffer(self, cursor, text): """ Inserts text into the input buffer using the specified cursor (which must be in the input buffer), ensuring that continuation prompts are inserted as necessary. """ lines = text.splitlines(True) if lines:...
Returns whether the current cursor ( or if specified a position ) is inside the editing region.
def _in_buffer(self, position=None): """ Returns whether the current cursor (or, if specified, a position) is inside the editing region. """ cursor = self._control.textCursor() if position is None: position = cursor.position() else: cursor.setP...
Ensures that the cursor is inside the editing region. Returns whether the cursor was moved.
def _keep_cursor_in_buffer(self): """ Ensures that the cursor is inside the editing region. Returns whether the cursor was moved. """ moved = not self._in_buffer() if moved: cursor = self._control.textCursor() cursor.movePosition(QtGui.QTextCursor.End)...
Cancels the current editing task ala Ctrl - G in Emacs.
def _keyboard_quit(self): """ Cancels the current editing task ala Ctrl-G in Emacs. """ if self._temp_buffer_filled : self._cancel_completion() self._clear_temporary_buffer() else: self.input_buffer = ''
Displays text using the pager if it exceeds the height of the viewport.
def _page(self, text, html=False): """ Displays text using the pager if it exceeds the height of the viewport. Parameters: ----------- html : bool, optional (default False) If set, the text will be interpreted as HTML instead of plain text. """ line_h...
Called immediately after a new prompt is displayed.
def _prompt_started(self): """ Called immediately after a new prompt is displayed. """ # Temporarily disable the maximum block count to permit undo/redo and # to ensure that the prompt position does not change due to truncation. self._control.document().setMaximumBlockCount(0) ...
Reads one line of input from the user.
def _readline(self, prompt='', callback=None): """ Reads one line of input from the user. Parameters ---------- prompt : str, optional The prompt to print before reading the line. callback : callable, optional A callback to execute with the read line. If...
Sets the continuation prompt.
def _set_continuation_prompt(self, prompt, html=False): """ Sets the continuation prompt. Parameters ---------- prompt : str The prompt to show when more input is needed. html : bool, optional (default False) If set, the prompt will be inserted as format...
Scrolls the viewport so that the specified cursor is at the top.
def _set_top_cursor(self, cursor): """ Scrolls the viewport so that the specified cursor is at the top. """ scrollbar = self._control.verticalScrollBar() scrollbar.setValue(scrollbar.maximum()) original_cursor = self._control.textCursor() self._control.setTextCursor(curso...
Writes a new prompt at the end of the buffer.
def _show_prompt(self, prompt=None, html=False, newline=True): """ Writes a new prompt at the end of the buffer. Parameters ---------- prompt : str, optional The prompt to show. If not specified, the previous prompt is used. html : bool, optional (default False) ...
Expands the vertical scrollbar beyond the range set by Qt.
def _adjust_scrollbars(self): """ Expands the vertical scrollbar beyond the range set by Qt. """ # This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp # and qtextedit.cpp. document = self._control.document() scrollbar = self._control.verticalScrollBar() ...
Shows a context menu at the given QPoint ( in widget coordinates ).
def _custom_context_menu_requested(self, pos): """ Shows a context menu at the given QPoint (in widget coordinates). """ menu = self._context_menu_make(pos) menu.exec_(self._control.mapToGlobal(pos))
Return True if given Distribution is installed in user site.
def dist_in_usersite(dist): """ Return True if given Distribution is installed in user site. """ if user_site: return normalize_path(dist_location(dist)).startswith(normalize_path(user_site)) else: return False
Print the informations from installed distributions found.
def print_results(distributions, list_all_files): """ Print the informations from installed distributions found. """ results_printed = False for dist in distributions: results_printed = True logger.info("---") logger.info("Name: %s" % dist['name']) logger.info("Versio...
Entry point for pkginfo tool
def main(args=None): """Entry point for pkginfo tool """ options, paths = _parse_options(args) format = getattr(options, 'output', 'simple') formatter = _FORMATTERS[format](options) for path in paths: meta = get_metadata(path, options.metadata_version) if meta is None: ...
Assuming the cursor is at the end of the specified string get the context ( a list of names ) for the symbol at cursor position.
def get_context(self, string): """ Assuming the cursor is at the end of the specified string, get the context (a list of names) for the symbol at cursor position. """ context = [] reversed_tokens = list(self._lexer.get_tokens(string)) reversed_tokens.reverse() ...
Copy a default config file into the active profile directory.
def copy_config_file(self, config_file, path=None, overwrite=False): """Copy a default config file into the active profile directory. Default configuration files are kept in :mod:`IPython.config.default`. This function moves these from that location to the working profile directory. ...
Create a profile dir by profile name and path.
def create_profile_dir_by_name(cls, path, name=u'default', config=None): """Create a profile dir by profile name and path. Parameters ---------- path : unicode The path (directory) to put the profile directory in. name : unicode The name of the profile. ...
Find an existing profile dir by profile name return its ProfileDir.
def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None): """Find an existing profile dir by profile name, return its ProfileDir. This searches through a sequence of paths for a profile dir. If it is not found, a :class:`ProfileDirError` exception will be raised. T...
Find/ create a profile dir and return its ProfileDir.
def find_profile_dir(cls, profile_dir, config=None): """Find/create a profile dir and return its ProfileDir. This will create the profile directory if it doesn't exist. Parameters ---------- profile_dir : unicode or str The path of the profile directory. This is ex...
Convert a cmp = function into a key = function
def cmp_to_key(mycmp): 'Convert a cmp= function into a key= function' class Key(object): def __init__(self, obj): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) >...
Read a file and close it. Returns the file source.
def file_read(filename): """Read a file and close it. Returns the file source.""" fobj = open(filename,'r'); source = fobj.read(); fobj.close() return source
Read a file and close it. Returns the file source using readlines ().
def file_readlines(filename): """Read a file and close it. Returns the file source using readlines().""" fobj = open(filename,'r'); lines = fobj.readlines(); fobj.close() return lines
Take multiple lines of input.
def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): """Take multiple lines of input. A list with each line of input as a separate element is returned when a termination string is entered (defaults to a single '.'). Input can also terminate via EOF (^D in Unix, ^Z-RET in Windows)...
Similar to raw_input () but accepts extended lines if input ends with \\.
def raw_input_ext(prompt='', ps2='... '): """Similar to raw_input(), but accepts extended lines if input ends with \\.""" line = raw_input(prompt) while line.endswith('\\'): line = line[:-1] + raw_input(ps2) return line
Asks a question and returns a boolean ( y/ n ) answer.
def ask_yes_no(prompt,default=None): """Asks a question and returns a boolean (y/n) answer. If default is given (one of 'y','n'), it is used if the user input is empty. Otherwise the question is repeated until an answer is given. An EOF is treated as the default answer. If there is no default, an ...
Make a temporary python file return filename and filehandle.
def temp_pyfile(src, ext='.py'): """Make a temporary python file, return filename and filehandle. Parameters ---------- src : string or list of strings (no need for ending newlines if list) Source code to be written to the file. ext : optional, string Extension for the generated file. ...
Raw print to sys. __stdout__ otherwise identical interface to print ().
def raw_print(*args, **kw): """Raw print to sys.__stdout__, otherwise identical interface to print().""" print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'), file=sys.__stdout__) sys.__stdout__.flush()
Raw print to sys. __stderr__ otherwise identical interface to print ().
def raw_print_err(*args, **kw): """Raw print to sys.__stderr__, otherwise identical interface to print().""" print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'), file=sys.__stderr__) sys.__stderr__.flush()
Close the file and restore the channel.
def close(self): """Close the file and restore the channel.""" self.flush() setattr(sys, self.channel, self.ostream) self.file.close() self._closed = True
Write data to both channels.
def write(self, data): """Write data to both channels.""" self.file.write(data) self.ostream.write(data) self.ostream.flush()
write my output to sys. stdout/ err as appropriate
def show(self): """write my output to sys.stdout/err as appropriate""" sys.stdout.write(self.stdout) sys.stderr.write(self.stderr) sys.stdout.flush() sys.stderr.flush()
add a new handler for new hearts
def add_new_heart_handler(self, handler): """add a new handler for new hearts""" self.log.debug("heartbeat::new_heart_handler: %s", handler) self._new_handlers.add(handler)
add a new handler for heart failure
def add_heart_failure_handler(self, handler): """add a new handler for heart failure""" self.log.debug("heartbeat::new heart failure handler: %s", handler) self._failure_handlers.add(handler)
a heart just beat
def handle_pong(self, msg): "a heart just beat" current = str_to_bytes(str(self.lifetime)) last = str_to_bytes(str(self.last_ping)) if msg[1] == current: delta = time.time()-self.tic # self.log.debug("heartbeat::heart %r took %.2f ms to respond"%(msg[0], 1000*delt...
try: retrun fcn ( * args ** kwargs ) except: print traceback if spit in kwargs. keys (): return kwargs [ spit ]
def catch(fcn, *args, **kwargs): '''try: retrun fcn(*args, **kwargs) except: print traceback if 'spit' in kwargs.keys(): return kwargs['spit'] Parameters ---------- fcn : function *args : unnamed parameters of fcn **kwargs : named parameter...
Converts a list into a list of lists with equal batch_size.
def batch_list(sequence, batch_size, mod = 0, randomize = False): ''' Converts a list into a list of lists with equal batch_size. Parameters ---------- sequence : list list of items to be placed in batches batch_size : int length of each sub list mod : int remainder ...
http:// stackoverflow. com/ questions/ 7900944/ read - write - classes - to - files - in - an - efficent - way
def to_pickle(obj, filename, clean_memory=False): '''http://stackoverflow.com/questions/7900944/read-write-classes-to-files-in-an-efficent-way''' path, filename = path_to_filename(filename) create_dir(path) with open(path + filename, "wb") as output: pickle.dump(obj, output, pickle.HIGHEST_PRO...
Takes a path filename string and returns the split between the path and the filename
def path_to_filename(pathfile): ''' Takes a path filename string and returns the split between the path and the filename if filename is not given, filename = '' if path is not given, path = './' ''' path = pathfile[:pathfile.rfind('/') + 1] if path == '': path = './' filename...
Tries to create a new directory in the given path. ** create_dir ** can also create subfolders according to the dictionnary given as second argument.
def create_dir(path, dir_dict={}): ''' Tries to create a new directory in the given path. **create_dir** can also create subfolders according to the dictionnary given as second argument. Parameters ---------- path : string string giving the path of the location to create the directory, ...
Generator for walking a directory tree. Starts at specified root folder returning files that match our pattern. Optionally will also recurse through sub - folders.
def Walk(root='.', recurse=True, pattern='*'): ''' Generator for walking a directory tree. Starts at specified root folder, returning files that match our pattern. Optionally will also recurse through sub-folders. Parameters ---------- root : string (default is *'.'*) Path for the...
Runs a loop over the: doc: Walk<relpy. utils. Walk > Generator to find all file paths in the root directory with the given pattern. If recurse is * True *: matching paths are identified for all sub directories.
def scan_path(root='.', recurse=False, pattern='*'): ''' Runs a loop over the :doc:`Walk<relpy.utils.Walk>` Generator to find all file paths in the root directory with the given pattern. If recurse is *True*: matching paths are identified for all sub directories. Parameters ---------- r...
Displays time if verbose is true and count is within the display amount
def displayAll(elapsed, display_amt, est_end, nLoops, count, numPrints): '''Displays time if verbose is true and count is within the display amount''' if numPrints > nLoops: display_amt = 1 else: display_amt = round(nLoops / numPrints) if count % display_amt == 0: avg = elapse...
calculates unit of time to display
def timeUnit(elapsed, avg, est_end): '''calculates unit of time to display''' minute = 60 hr = 3600 day = 86400 if elapsed <= 3 * minute: unit_elapsed = (elapsed, "secs") if elapsed > 3 * minute: unit_elapsed = ((elapsed / 60), "mins") if elapsed > 3 * hr: unit_elaps...
Tracks the time in a loop. The estimated time to completion can be calculated and if verbose is set to * True * the object will print estimated time to completion and percent complete. Actived in every loop to keep track
def loop(self): ''' Tracks the time in a loop. The estimated time to completion can be calculated and if verbose is set to *True*, the object will print estimated time to completion, and percent complete. Actived in every loop to keep track''' self.count += 1 sel...
Ensure that the path or the root of the current package ( if path is in a package ) is in sys. path.
def add_path(path, config=None): """Ensure that the path, or the root of the current package (if path is in a package), is in sys.path. """ # FIXME add any src-looking dirs seen too... need to get config for that log.debug('Add path %s' % path) if not path: return [] added ...
Import a dotted - name package whose tail is at path. In other words given foo. bar and path/ to/ foo/ bar. py import foo from path/ to/ foo then bar from path/ to/ foo/ bar returning bar.
def importFromPath(self, path, fqname): """Import a dotted-name package whose tail is at path. In other words, given foo.bar and path/to/foo/bar.py, import foo from path/to/foo then bar from path/to/foo/bar, returning bar. """ # find the base dir of the package path_parts...
Import a module * only * from path ignoring sys. path and reloading if the version in sys. modules is not the one we want.
def importFromDir(self, dir, fqname): """Import a module *only* from path, ignoring sys.path and reloading if the version in sys.modules is not the one we want. """ dir = os.path.normpath(os.path.abspath(dir)) log.debug("Import %s from %s", fqname, dir) # FIXME reimpleme...
Extract configuration data from a bdist_wininst. exe
def extract_wininst_cfg(dist_filename): """Extract configuration data from a bdist_wininst .exe Returns a ConfigParser.RawConfigParser, or None """ f = open(dist_filename,'rb') try: endrec = zipfile._EndRecData(f) if endrec is None: return None prepended = (endr...
Create a #! line getting options ( if any ) from script_text
def get_script_header(script_text, executable=sys_executable, wininst=False): """Create a #! line, getting options (if any) from script_text""" from distutils.command.build_scripts import first_line_re # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern. if not isinstance(first_line_re.pat...
Ensure that the importer caches dont have stale info for path
def uncache_zipdir(path): """Ensure that the importer caches dont have stale info for `path`""" from zipimport import _zip_directory_cache as zdc _uncache(path, zdc) _uncache(path, sys.path_importer_cache)
Determine if the specified executable is a. sh ( contains a #! line )
def is_sh(executable): """Determine if the specified executable is a .sh (contains a #! line)""" try: fp = open(executable) magic = fp.read(2) fp.close() except (OSError,IOError): return executable return magic == '#!'
Quote a command line argument according to Windows parsing rules
def nt_quote_arg(arg): """Quote a command line argument according to Windows parsing rules""" result = [] needquote = False nb = 0 needquote = (" " in arg) or ("\t" in arg) if needquote: result.append('"') for c in arg: if c == '\\': nb += 1 elif c == '...
Yield write_script () argument tuples for a distribution s entrypoints
def get_script_args(dist, executable=sys_executable, wininst=False): """Yield write_script() argument tuples for a distribution's entrypoints""" spec = str(dist.as_requirement()) header = get_script_header("", executable, wininst) for group in 'console_scripts', 'gui_scripts': for name, ep in di...
Return a pseudo - tempname base in the install directory. This code is intentionally naive ; if a malicious party can write to the target directory you re already in deep doodoo.
def pseudo_tempname(self): """Return a pseudo-tempname base in the install directory. This code is intentionally naive; if a malicious party can write to the target directory you're already in deep doodoo. """ try: pid = os.getpid() except: pid = r...
Generate a legacy script wrapper and install it
def install_script(self, dist, script_name, script_text, dev_path=None): """Generate a legacy script wrapper and install it""" spec = str(dist.as_requirement()) is_script = is_python_script(script_text, script_name) def get_template(filename): """ There are a cou...
Verify that there are no conflicting old - style packages
def check_conflicts(self, dist): """Verify that there are no conflicting "old-style" packages""" return dist # XXX temporarily disable until new strategy is stable from imp import find_module, get_suffixes from glob import glob blockers = [] names = dict.fromkeys(di...
When easy_install is about to run bdist_egg on a source dist that source dist might have setup_requires directives requiring additional fetching. Ensure the fetcher options given to easy_install are available to that command as well.
def _set_fetcher_options(self, base): """ When easy_install is about to run bdist_egg on a source dist, that source dist might have 'setup_requires' directives, requiring additional fetching. Ensure the fetcher options given to easy_install are available to that command as well. ...
Create directories under ~.
def create_home_path(self): """Create directories under ~.""" if not self.user: return home = convert_path(os.path.expanduser("~")) for name, path in self.config_vars.iteritems(): if path.startswith(home) and not os.path.isdir(path): self.debug_pri...
Return True if name is a considered as an archive file.
def is_archive_file(name): """Return True if `name` is a considered as an archive file.""" archives = ( '.zip', '.tar.gz', '.tar.bz2', '.tgz', '.tar', '.whl' ) ext = splitext(name)[1].lower() if ext in archives: return True return False
return a mutable proxy for the obj.
def mutable(obj): ''' return a mutable proxy for the `obj`. all modify on the proxy will not apply on origin object. ''' base_cls = type(obj) class Proxy(base_cls): def __getattribute__(self, name): try: return super().__getattribute__(name) exce...
return a readonly proxy for the obj.
def readonly(obj, *, error_on_set = False): ''' return a readonly proxy for the `obj`. all modify on the proxy will not apply on origin object. ''' base_cls = type(obj) class ReadonlyProxy(base_cls): def __getattribute__(self, name): return getattr(obj, name) def _...
Create a new code cell with input and output
def new_output(output_type=None, output_text=None, output_png=None, output_html=None, output_svg=None, output_latex=None, output_json=None, output_javascript=None, output_jpeg=None, prompt_number=None, etype=None, evalue=None, traceback=None): """Create a new code cell with input and output""" outpu...
Create a new code cell with input and output
def new_code_cell(input=None, prompt_number=None, outputs=None, language=u'python', collapsed=False, metadata=None): """Create a new code cell with input and output""" cell = NotebookNode() cell.cell_type = u'code' if language is not None: cell.language = unicode(language) if input is no...
Create a new text cell.
def new_text_cell(cell_type, source=None, rendered=None, metadata=None): """Create a new text cell.""" cell = NotebookNode() # VERSIONHACK: plaintext -> raw # handle never-released plaintext name for raw cells if cell_type == 'plaintext': cell_type = 'raw' if source is not None: ...
Create a new section cell with a given integer level.
def new_heading_cell(source=None, rendered=None, level=1, metadata=None): """Create a new section cell with a given integer level.""" cell = NotebookNode() cell.cell_type = u'heading' if source is not None: cell.source = unicode(source) if rendered is not None: cell.rendered = unicod...
Create a notebook by name id and a list of worksheets.
def new_notebook(name=None, metadata=None, worksheets=None): """Create a notebook by name, id and a list of worksheets.""" nb = NotebookNode() nb.nbformat = nbformat nb.nbformat_minor = nbformat_minor if worksheets is None: nb.worksheets = [] else: nb.worksheets = list(worksheets...
Create a new metadata node.
def new_metadata(name=None, authors=None, license=None, created=None, modified=None, gistid=None): """Create a new metadata node.""" metadata = NotebookNode() if name is not None: metadata.name = unicode(name) if authors is not None: metadata.authors = list(authors) if created is...
Create a new author.
def new_author(name=None, email=None, affiliation=None, url=None): """Create a new author.""" author = NotebookNode() if name is not None: author.name = unicode(name) if email is not None: author.email = unicode(email) if affiliation is not None: author.affiliation = unicode(...
Embed and start an IPython kernel in a given scope. Parameters ---------- module: ModuleType optional The module to load into IPython globals ( default: caller ) local_ns: dict optional The namespace to load into IPython user namespace ( default: caller ) kwargs: various optional Further keyword args are relayed to the...
def embed_kernel(module=None, local_ns=None, **kwargs): """Embed and start an IPython kernel in a given scope. Parameters ---------- module : ModuleType, optional The module to load into IPython globals (default: caller) local_ns : dict, optional The namespace to load into IPyth...
Whether path is a directory to which the user has write access.
def _writable_dir(path): """Whether `path` is a directory, to which the user has write access.""" return os.path.isdir(path) and os.access(path, os.W_OK)
On Windows remove leading and trailing quotes from filenames.
def unquote_filename(name, win32=(sys.platform=='win32')): """ On Windows, remove leading and trailing quotes from filenames. """ if win32: if name.startswith(("'", '"')) and name.endswith(("'", '"')): name = name[1:-1] return name