_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q280100
FrontendWidget._prompt_finished_hook
test
def _prompt_finished_hook(self): """ Called immediately after a prompt is finished, i.e. when some input will be processed and a new prompt displayed. """ # Flush all state from the input splitter so the next round of
python
{ "resource": "" }
q280101
FrontendWidget._tab_pressed
test
def _tab_pressed(self): """ Called when the tab key is pressed. Returns whether to continue processing the event. """ # Perform tab completion if: # 1) The cursor is in the input buffer. # 2) There is a non-whitespace character before the cursor. text = self._get_input_buffer_cursor_line()
python
{ "resource": "" }
q280102
FrontendWidget._context_menu_make
test
def _context_menu_make(self, pos): """ Reimplemented to add an action for raw copy. """ menu = super(FrontendWidget, self)._context_menu_make(pos) for before_action in menu.actions(): if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \
python
{ "resource": "" }
q280103
FrontendWidget._event_filter_console_keypress
test
def _event_filter_console_keypress(self, event): """ Reimplemented for execution interruption and smart backspace. """ key = event.key() if self._control_key_down(event.modifiers(), include_command=False): if key == QtCore.Qt.Key_C and self._executing: self.request_interrupt_kernel() return True elif key == QtCore.Qt.Key_Period: self.request_restart_kernel() return True elif not event.modifiers() & QtCore.Qt.AltModifier: # Smart backspace: remove four characters in one backspace if: # 1) everything left of the cursor is whitespace # 2) the four characters immediately left of the cursor are spaces if key == QtCore.Qt.Key_Backspace: col = self._get_input_buffer_cursor_column() cursor = self._control.textCursor() if col > 3 and not cursor.hasSelection():
python
{ "resource": "" }
q280104
FrontendWidget._insert_continuation_prompt
test
def _insert_continuation_prompt(self, cursor): """ Reimplemented for auto-indentation. """
python
{ "resource": "" }
q280105
FrontendWidget._handle_complete_reply
test
def _handle_complete_reply(self, rep): """ Handle replies for tab completion. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position():
python
{ "resource": "" }
q280106
FrontendWidget._silent_exec_callback
test
def _silent_exec_callback(self, expr, callback): """Silently execute `expr` in the kernel and call `callback` with reply the `expr` is evaluated silently in the kernel (without) output in the frontend. Call `callback` with the `repr <http://docs.python.org/library/functions.html#repr> `_ as first argument Parameters ---------- expr : string valid string to be executed by the kernel. callback : function function accepting one argument, as a string. The string will be
python
{ "resource": "" }
q280107
FrontendWidget._handle_exec_callback
test
def _handle_exec_callback(self, msg): """Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback`` Parameters ---------- msg : raw message send by the kernel containing an `user_expressions` and having a 'silent_exec_callback' kind. Notes ----- This function will look for a `callback` associated with the corresponding message id. Association has been made by `_silent_exec_callback`. `callback` is then called with the `repr()` of the value of corresponding `user_expressions` as argument. `callback` is then removed from the known list so that any message coming again
python
{ "resource": "" }
q280108
FrontendWidget._handle_execute_reply
test
def _handle_execute_reply(self, msg): """ Handles replies for code execution. """ self.log.debug("execute: %s", msg.get('content', '')) msg_id = msg['parent_header']['msg_id'] info = self._request_info['execute'].get(msg_id) # unset reading flag, because if execute finished, raw_input can't # still be pending. self._reading = False if info and info.kind == 'user' and not self._hidden: # Make sure that all output from the SUB channel has been processed # before writing a new prompt. self.kernel_manager.sub_channel.flush() # Reset the ANSI style information to prevent bad text in stdout # from messing up our colors. We're not a true terminal so we're # allowed to do this. if self.ansi_codes: self._ansi_processor.reset_sgr() content = msg['content'] status = content['status'] if status == 'ok':
python
{ "resource": "" }
q280109
FrontendWidget._handle_input_request
test
def _handle_input_request(self, msg): """ Handle requests for raw_input. """ self.log.debug("input: %s", msg.get('content', '')) if self._hidden: raise RuntimeError('Request for raw input during hidden execution.') # Make sure that all output from the SUB channel has been processed # before entering readline mode. self.kernel_manager.sub_channel.flush()
python
{ "resource": "" }
q280110
FrontendWidget._handle_kernel_died
test
def _handle_kernel_died(self, since_last_heartbeat): """ Handle the kernel's death by asking if the user wants to restart. """ self.log.debug("kernel died: %s", since_last_heartbeat) if self.custom_restart: self.custom_restart_kernel_died.emit(since_last_heartbeat) else: message = 'The kernel heartbeat has been inactive for %.2f ' \
python
{ "resource": "" }
q280111
FrontendWidget._handle_object_info_reply
test
def _handle_object_info_reply(self, rep): """ Handle replies for call tips. """ self.log.debug("oinfo: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('call_tip') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): # Get the information for a call tip. For now we format the call # line as string, later we can pass False to format_call and # syntax-highlight it ourselves for nicer formatting in the # calltip. content = rep['content'] # if this is
python
{ "resource": "" }
q280112
FrontendWidget._handle_pyout
test
def _handle_pyout(self, msg): """ Handle display hook output. """ self.log.debug("pyout: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg):
python
{ "resource": "" }
q280113
FrontendWidget._handle_stream
test
def _handle_stream(self, msg): """ Handle stdout, stderr, and stdin. """ self.log.debug("stream: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): # Most consoles treat tabs as being 8 space characters. Convert tabs # to spaces so that output looks as expected regardless of this
python
{ "resource": "" }
q280114
FrontendWidget._handle_shutdown_reply
test
def _handle_shutdown_reply(self, msg): """ Handle shutdown signal, only if from other console. """ self.log.debug("shutdown: %s", msg.get('content', '')) if not self._hidden and not self._is_from_this_session(msg): if self._local_kernel: if not msg['content']['restart']: self.exit_requested.emit(self) else: # we just got notified of a restart! time.sleep(0.25) # wait 1/4 sec to reset # lest the request for a new prompt # goes to the old kernel self.reset() else: # remote kernel, prompt on Kernel shutdown/reset title = self.window().windowTitle() if not msg['content']['restart']: reply = QtGui.QMessageBox.question(self, title, "Kernel has been shutdown permanently. " "Close the Console?", QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
python
{ "resource": "" }
q280115
FrontendWidget.execute_file
test
def execute_file(self, path, hidden=False): """ Attempts to execute file with 'path'. If 'hidden', no output is
python
{ "resource": "" }
q280116
FrontendWidget.interrupt_kernel
test
def interrupt_kernel(self): """ Attempts to interrupt the running kernel. Also unsets _reading flag, to avoid runtime errors if raw_input is called again. """ if self.custom_interrupt: self._reading = False self.custom_interrupt_requested.emit() elif self.kernel_manager.has_kernel:
python
{ "resource": "" }
q280117
FrontendWidget.reset
test
def reset(self, clear=False): """ Resets the widget to its initial state if ``clear`` parameter or ``clear_on_kernel_restart`` configuration setting is True, otherwise prints a visual indication of the fact that the kernel restarted, but does not clear the traces from previous usage of the kernel before it was restarted. With ``clear=True``, it is similar to ``%clear``, but also re-writes the banner and aborts execution if necessary. """ if self._executing: self._executing = False self._request_info['execute'] = {} self._reading = False self._highlighter.highlighting_on = False if self.clear_on_kernel_restart or clear: self._control.clear()
python
{ "resource": "" }
q280118
FrontendWidget.restart_kernel
test
def restart_kernel(self, message, now=False): """ Attempts to restart the running kernel. """ # FIXME: now should be configurable via a checkbox in the dialog. Right # now at least the heartbeat path sets it to True and the manual restart # to False. But those should just be the pre-selected states of a # checkbox that the user could override if so desired. But I don't know # enough Qt to go implementing the checkbox now. if self.custom_restart: self.custom_restart_requested.emit() elif self.kernel_manager.has_kernel: # Pause the heart beat channel to prevent further warnings. self.kernel_manager.hb_channel.pause() # Prompt the user to restart the kernel. Un-pause the heartbeat if # they decline. (If they accept, the heartbeat will be un-paused # automatically when the
python
{ "resource": "" }
q280119
FrontendWidget._call_tip
test
def _call_tip(self): """ Shows a call tip, if appropriate, at the current cursor location. """ # Decide if it makes sense to show a call tip if not self.enable_calltips: return False cursor = self._get_cursor() cursor.movePosition(QtGui.QTextCursor.Left) if cursor.document().characterAt(cursor.position()) != '(': return False context = self._get_context(cursor) if not context: return False # Send the metadata
python
{ "resource": "" }
q280120
FrontendWidget._complete
test
def _complete(self): """ Performs completion at the current cursor location. """ context = self._get_context() if context: # Send the completion request to the kernel msg_id = self.kernel_manager.shell_channel.complete( '.'.join(context), # text self._get_input_buffer_cursor_line(), # line
python
{ "resource": "" }
q280121
FrontendWidget._process_execute_error
test
def _process_execute_error(self, msg): """ Process a reply for an execution request that resulted in an error. """ content = msg['content'] # If a SystemExit is passed along, this means exit() was called - also # all the ipython %exit magic syntax of '-k' to be used to keep # the kernel running if content['ename']=='SystemExit':
python
{ "resource": "" }
q280122
FrontendWidget._process_execute_ok
test
def _process_execute_ok(self, msg): """ Process a reply for a successful execution request. """ payload = msg['content']['payload'] for item in payload: if not self._process_execute_payload(item):
python
{ "resource": "" }
q280123
FrontendWidget._document_contents_change
test
def _document_contents_change(self, position, removed, added): """ Called whenever the document's content changes. Display a call tip if appropriate. """ # Calculate where the cursor should be *after* the change: position
python
{ "resource": "" }
q280124
PluginProxy.addPlugin
test
def addPlugin(self, plugin, call): """Add plugin to my list of plugins to call, if it has the attribute I'm bound to. """ meth = getattr(plugin, call, None) if meth is not None: if call == 'loadTestsFromModule' and \
python
{ "resource": "" }
q280125
PluginProxy.chain
test
def chain(self, *arg, **kw): """Call plugins in a chain, where the result of each plugin call is sent to the next plugin as input. The final output result is returned. """ result = None # extract the static arguments (if any) from arg so they can # be passed to each plugin call in the chain static = [a
python
{ "resource": "" }
q280126
PluginProxy.generate
test
def generate(self, *arg, **kw): """Call all plugins, yielding each item in each non-None result. """ for p, meth in self.plugins: result = None try: result = meth(*arg, **kw) if result is not None: for r in result: yield
python
{ "resource": "" }
q280127
PluginProxy.simple
test
def simple(self, *arg, **kw): """Call all plugins, returning the first non-None result.
python
{ "resource": "" }
q280128
PluginManager.configure
test
def configure(self, options, config): """Configure the set of plugins with the given options and config instance. After configuration, disabled plugins are removed from the plugins list. """ log.debug("Configuring plugins") self.config = config cfg = PluginProxy('configure', self._plugins)
python
{ "resource": "" }
q280129
EntryPointPluginManager.loadPlugins
test
def loadPlugins(self): """Load plugins by iterating the `nose.plugins` entry point. """ from pkg_resources import iter_entry_points loaded = {} for entry_point, adapt in self.entry_points: for ep in iter_entry_points(entry_point): if ep.name in loaded: continue loaded[ep.name] = True log.debug('%s load plugin %s', self.__class__.__name__, ep) try: plugcls = ep.load() except KeyboardInterrupt: raise except Exception, e: # never want a plugin load to kill the test run
python
{ "resource": "" }
q280130
BuiltinPluginManager.loadPlugins
test
def loadPlugins(self): """Load plugins in nose.plugins.builtin """ from nose.plugins import builtin for plug in builtin.plugins:
python
{ "resource": "" }
q280131
latex_to_png
test
def latex_to_png(s, encode=False, backend='mpl'): """Render a LaTeX string to PNG. Parameters ---------- s : str The raw string containing valid inline LaTeX. encode : bool, optional Should the PNG data bebase64 encoded to make it JSON'able. backend : {mpl, dvipng}
python
{ "resource": "" }
q280132
latex_to_html
test
def latex_to_html(s, alt='image'): """Render LaTeX to HTML with embedded PNG data using data URIs. Parameters ---------- s : str The raw string containing valid inline LateX. alt : str The alt text to use for the HTML. """
python
{ "resource": "" }
q280133
math_to_image
test
def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None): """ Given a math expression, renders it in a closely-clipped bounding box to an image file. *s* A math expression. The math portion should be enclosed in dollar signs. *filename_or_obj* A filepath or writable file-like object to write the image data to. *prop* If provided, a FontProperties() object describing the size and style of the text. *dpi* Override the output dpi, otherwise use the default associated with the output format. *format* The output format, eg. 'svg', 'pdf', 'ps' or 'png'. If not provided, will be deduced from the filename. """ from matplotlib import figure # backend_agg supports all of
python
{ "resource": "" }
q280134
InstallRequirement.check_if_exists
test
def check_if_exists(self): """Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.conflicts_with appropriately.""" if self.req is None: return False try: self.satisfied_by = pkg_resources.get_distribution(self.req) except pkg_resources.DistributionNotFound: return False except pkg_resources.VersionConflict: existing_dist = pkg_resources.get_distribution(self.req.project_name) if self.use_user_site: if dist_in_usersite(existing_dist): self.conflicts_with = existing_dist
python
{ "resource": "" }
q280135
process_iter
test
def process_iter(): """Return a generator yielding a Process class instance for all running processes on the local machine. Every new Process instance is only created once and then cached into an internal table which is updated every time this is used. The sorting order in which processes are yielded is based on their PIDs. """ def add(pid): proc = Process(pid) _pmap[proc.pid] = proc return proc def remove(pid): _pmap.pop(pid, None) a = set(get_pid_list()) b = set(_pmap.keys()) new_pids = a - b gone_pids = b - a for pid in gone_pids: remove(pid) for pid, proc in sorted(list(_pmap.items()) + \ list(dict.fromkeys(new_pids).items())): try: if proc is None: # new process yield add(pid) else: # use is_running() to
python
{ "resource": "" }
q280136
cpu_percent
test
def cpu_percent(interval=0.1, percpu=False): """Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls. """ global _last_cpu_times global _last_per_cpu_times blocking = interval is not None and interval > 0.0 def calculate(t1, t2): t1_all = sum(t1) t1_busy = t1_all - t1.idle t2_all = sum(t2) t2_busy = t2_all - t2.idle # this usually indicates a float precision issue if t2_busy <= t1_busy: return 0.0 busy_delta = t2_busy - t1_busy all_delta
python
{ "resource": "" }
q280137
Process.as_dict
test
def as_dict(self, attrs=[], ad_value=None): """Utility method returning process information as a hashable dictionary. If 'attrs' is specified it must be a list of strings reflecting available Process class's attribute names (e.g. ['get_cpu_times', 'name']) else all public (read only) attributes are assumed. 'ad_value' is the value which gets assigned to a dict key in case AccessDenied exception is raised when retrieving that particular process information. """ excluded_names = set(['send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait', 'is_running', 'as_dict', 'parent', 'get_children', 'nice']) retdict = dict() for name in set(attrs or dir(self)): if name.startswith('_'): continue if name.startswith('set_'): continue if name in excluded_names: continue try: attr = getattr(self, name) if callable(attr): if name == 'get_cpu_percent': ret = attr(interval=0) else: ret = attr() else:
python
{ "resource": "" }
q280138
Process.name
test
def name(self): """The process name.""" name = self._platform_impl.get_process_name() if os.name == 'posix': # On UNIX the name gets truncated to the first 15 characters. # If it matches the first part of the cmdline we return that # one instead because it's usually more explicative.
python
{ "resource": "" }
q280139
Process.exe
test
def exe(self): """The process executable path. May also be an empty string.""" def guess_it(fallback): # try to guess exe from cmdline[0] in absence of a native # exe representation cmdline = self.cmdline if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'): exe = cmdline[0] # the possible exe rexe = os.path.realpath(exe) # ...in case it's a symlink if os.path.isabs(rexe) and os.path.isfile(rexe) \ and os.access(rexe, os.X_OK): return exe if isinstance(fallback, AccessDenied): raise fallback return fallback try: exe = self._platform_impl.get_process_exe() except AccessDenied: err = sys.exc_info()[1]
python
{ "resource": "" }
q280140
Process.get_children
test
def get_children(self, recursive=False): """Return the children of this process as a list of Process objects. If recursive is True return all the parent descendants. Example (A == this process): A ─┐ β”‚ β”œβ”€ B (child) ─┐ β”‚ └─ X (grandchild) ─┐ β”‚ └─ Y (great grandchild) β”œβ”€ C (child) └─ D (child) >>> p.get_children() B, C, D >>> p.get_children(recursive=True) B, X, Y, C, D Note that in the example above if process X disappears process Y won't be returned either as the reference to process A is lost. """ if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) ret = [] if not recursive: for p in process_iter(): try: if p.ppid == self.pid: # if child happens to be older than its parent # (self) it means child's PID has been reused if self.create_time <= p.create_time: ret.append(p) except NoSuchProcess: pass else: # construct a dict where 'values' are all the processes # having 'key' as their parent table = defaultdict(list) for p in process_iter(): try: table[p.ppid].append(p) except NoSuchProcess:
python
{ "resource": "" }
q280141
Process.get_cpu_percent
test
def get_cpu_percent(self, interval=0.1): """Return a float representing the current process CPU utilization as a percentage. When interval is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. """ blocking = interval is not None and interval > 0.0 if blocking: st1 = sum(cpu_times()) pt1 = self._platform_impl.get_cpu_times() time.sleep(interval) st2 = sum(cpu_times()) pt2 = self._platform_impl.get_cpu_times() else: st1 = self._last_sys_cpu_times pt1 = self._last_proc_cpu_times st2 = sum(cpu_times()) pt2 = self._platform_impl.get_cpu_times() if st1 is None or pt1 is None: self._last_sys_cpu_times = st2 self._last_proc_cpu_times = pt2 return 0.0 delta_proc = (pt2.user
python
{ "resource": "" }
q280142
Process.get_memory_percent
test
def get_memory_percent(self): """Compare physical system memory to process resident memory and calculate process memory utilization as a
python
{ "resource": "" }
q280143
Process.get_memory_maps
test
def get_memory_maps(self, grouped=True): """Return process's mapped memory regions as a list of nameduples whose fields are variable depending on the platform. If 'grouped' is True the mapped regions with the same 'path' are grouped together and the different memory fields are summed. If 'grouped' is False every mapped region is shown as a single entity and the namedtuple will also include the mapped region's address space ('addr') and permission set ('perms'). """ it = self._platform_impl.get_memory_maps() if grouped: d = {} for tupl in it: path = tupl[2] nums = tupl[3:] try:
python
{ "resource": "" }
q280144
Process.is_running
test
def is_running(self): """Return whether this process is running.""" if self._gone: return False try: # Checking if pid is alive is not enough as the pid might # have been reused by another process. # pid + creation time, on the other hand, is supposed to
python
{ "resource": "" }
q280145
Process.suspend
test
def suspend(self): """Suspend process execution.""" # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name)
python
{ "resource": "" }
q280146
Process.resume
test
def resume(self): """Resume process execution.""" # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name)
python
{ "resource": "" }
q280147
Process.kill
test
def kill(self): """Kill the current process.""" # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise
python
{ "resource": "" }
q280148
Process.wait
test
def wait(self, timeout=None): """Wait for process to terminate and, if process is a children of the current one also return its exit code, else None. """ if timeout is not None and not timeout >= 0:
python
{ "resource": "" }
q280149
GTKEmbed._wire_kernel
test
def _wire_kernel(self): """Initializes the kernel inside GTK. This is meant to run only once at startup, so it does its job and returns False to ensure it doesn't get run again by GTK. """ self.gtk_main, self.gtk_main_quit = self._hijack_gtk()
python
{ "resource": "" }
q280150
GTKEmbed._hijack_gtk
test
def _hijack_gtk(self): """Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt to start or stop Returns ------- The original functions that have been hijacked: - gtk.main - gtk.main_quit
python
{ "resource": "" }
q280151
is_shadowed
test
def is_shadowed(identifier, ip): """Is the given identifier defined in one of the namespaces which shadow the alias and magic namespaces? Note that an identifier is different
python
{ "resource": "" }
q280152
PrefilterManager.init_transformers
test
def init_transformers(self): """Create the default transformers.""" self._transformers = [] for transformer_cls in _default_transformers:
python
{ "resource": "" }
q280153
PrefilterManager.register_transformer
test
def register_transformer(self, transformer): """Register a transformer instance.""" if transformer not in self._transformers:
python
{ "resource": "" }
q280154
PrefilterManager.unregister_transformer
test
def unregister_transformer(self, transformer): """Unregister a transformer instance."""
python
{ "resource": "" }
q280155
PrefilterManager.init_checkers
test
def init_checkers(self): """Create the default checkers.""" self._checkers = [] for checker in _default_checkers: checker(
python
{ "resource": "" }
q280156
PrefilterManager.register_checker
test
def register_checker(self, checker): """Register a checker instance.""" if checker not in self._checkers:
python
{ "resource": "" }
q280157
PrefilterManager.unregister_checker
test
def unregister_checker(self, checker): """Unregister a checker instance."""
python
{ "resource": "" }
q280158
PrefilterManager.init_handlers
test
def init_handlers(self): """Create the default handlers.""" self._handlers = {} self._esc_handlers = {}
python
{ "resource": "" }
q280159
PrefilterManager.register_handler
test
def register_handler(self, name, handler, esc_strings): """Register a handler instance by name with esc_strings.""" self._handlers[name] = handler
python
{ "resource": "" }
q280160
PrefilterManager.unregister_handler
test
def unregister_handler(self, name, handler, esc_strings): """Unregister a handler instance by name with esc_strings.""" try: del self._handlers[name] except KeyError: pass for esc_str in
python
{ "resource": "" }
q280161
PrefilterManager.prefilter_line_info
test
def prefilter_line_info(self, line_info): """Prefilter a line that has been converted to a LineInfo object. This implements the checker/handler part of the prefilter pipe. """
python
{ "resource": "" }
q280162
PrefilterManager.find_handler
test
def find_handler(self, line_info): """Find a handler for the line_info by trying checkers.""" for checker in self.checkers: if checker.enabled: handler = checker.check(line_info)
python
{ "resource": "" }
q280163
PrefilterManager.transform_line
test
def transform_line(self, line, continue_prompt): """Calls the enabled transformers in order of increasing priority.""" for transformer in self.transformers:
python
{ "resource": "" }
q280164
PrefilterManager.prefilter_line
test
def prefilter_line(self, line, continue_prompt=False): """Prefilter a single input line as text. This method prefilters a single line of text by calling the transformers and then the checkers/handlers. """ # print "prefilter_line: ", line, continue_prompt # All handlers *must* return a value, even if it's blank (''). # save the line away in case we crash, so the post-mortem handler can # record it self.shell._last_input_line = line if not line: # Return immediately on purely empty lines, so that if the user # previously typed some whitespace that started a continuation # prompt, he can break out of that loop with just an empty line. # This is how the default python prompt works. return '' # At this point, we invoke our transformers. if not continue_prompt or (continue_prompt and self.multi_line_specials): line = self.transform_line(line, continue_prompt) # Now we compute line_info for the checkers and handlers line_info = LineInfo(line, continue_prompt) # the input history needs to track even empty lines
python
{ "resource": "" }
q280165
PrefilterManager.prefilter_lines
test
def prefilter_lines(self, lines, continue_prompt=False): """Prefilter multiple input lines of text. This is the main entry point for prefiltering multiple lines of input. This simply calls :meth:`prefilter_line` for each line of input. This covers cases where there are multiple lines in the user entry, which is the case when the user goes back to a multiline history entry and presses enter. """ llines = lines.rstrip('\n').split('\n') # We can get multiple lines in one shot, where multiline input 'blends' # into one line, in cases like recalling from the readline history # buffer.
python
{ "resource": "" }
q280166
IPyAutocallChecker.check
test
def check(self, line_info): "Instances of IPyAutocall in user_ns get autocalled immediately" obj = self.shell.user_ns.get(line_info.ifun, None) if isinstance(obj, IPyAutocall):
python
{ "resource": "" }
q280167
MultiLineMagicChecker.check
test
def check(self, line_info): "Allow ! and !! in multi-line statements if multi_line_specials is on" # Note that this one of the only places we check the first character of # ifun and *not* the pre_char. Also note that the below test matches # both ! and !!. if line_info.continue_prompt \
python
{ "resource": "" }
q280168
EscCharsChecker.check
test
def check(self, line_info): """Check for escape character and return either a handler to handle it, or None if there is no escape char.""" if line_info.line[-1] == ESC_HELP \ and line_info.esc != ESC_SHELL \ and line_info.esc != ESC_SH_CAP:
python
{ "resource": "" }
q280169
AliasChecker.check
test
def check(self, line_info): "Check if the initital identifier on the line is an alias." # Note: aliases can not contain '.' head = line_info.ifun.split('.',1)[0] if line_info.ifun not in self.shell.alias_manager \ or head not in self.shell.alias_manager \
python
{ "resource": "" }
q280170
PrefilterHandler.handle
test
def handle(self, line_info): # print "normal: ", line_info """Handle normal input lines. Use as a template for handlers.""" # With autoindent on, we need some way to exit the input loop, and I # don't want to force the user to have to backspace all the way to # clear the line. The rule will be in this
python
{ "resource": "" }
q280171
AliasHandler.handle
test
def handle(self, line_info): """Handle alias input lines. """ transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
python
{ "resource": "" }
q280172
ShellEscapeHandler.handle
test
def handle(self, line_info): """Execute the line in a shell, empty return value""" magic_handler = self.prefilter_manager.get_handler_by_name('magic') line = line_info.line if line.lstrip().startswith(ESC_SH_CAP): # rewrite LineInfo's line, ifun and the_rest to properly hold the # call to %sx and the actual command to be executed, so # handle_magic can work correctly. Note that this works even if # the line is indented, so it handles multi_line_specials # properly. new_rest
python
{ "resource": "" }
q280173
MagicHandler.handle
test
def handle(self, line_info): """Execute magic functions.""" ifun = line_info.ifun the_rest = line_info.the_rest
python
{ "resource": "" }
q280174
AutoHandler.handle
test
def handle(self, line_info): """Handle lines which can be auto-executed, quoting if requested.""" line = line_info.line ifun = line_info.ifun the_rest = line_info.the_rest pre = line_info.pre esc = line_info.esc continue_prompt = line_info.continue_prompt obj = line_info.ofind(self.shell)['obj'] #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg # This should only be active for single-line input! if continue_prompt: return line force_auto = isinstance(obj, IPyAutocall) # User objects sometimes raise exceptions on attribute access other # than AttributeError (we've seen it in the past), so it's safest to be # ultra-conservative here and catch all. try: auto_rewrite = obj.rewrite except Exception: auto_rewrite = True if esc == ESC_QUOTE: # Auto-quote splitting on whitespace newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) elif esc == ESC_QUOTE2: # Auto-quote whole string newcmd = '%s("%s")' % (ifun,the_rest) elif esc == ESC_PAREN: newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) else: # Auto-paren. if force_auto: # Don't rewrite if it is already a call. do_rewrite = not the_rest.startswith('(') else: if not the_rest: # We only apply it to argument-less calls if the autocall # parameter is set to 2. do_rewrite = (self.shell.autocall >= 2)
python
{ "resource": "" }
q280175
HelpHandler.handle
test
def handle(self, line_info): """Try to get some help for the object. obj? or ?obj -> basic information. obj?? or ??obj -> more details. """ normal_handler = self.prefilter_manager.get_handler_by_name('normal') line = line_info.line # We need to make sure that we don't process lines which would be # otherwise valid python, such as "x=1 # what?" try: codeop.compile_command(line) except SyntaxError: # We should only handle as help stuff which is NOT valid syntax if line[0]==ESC_HELP: line = line[1:] elif line[-1]==ESC_HELP: line = line[:-1] if line: #print 'line:<%r>' % line # dbg self.shell.magic('pinfo %s' %
python
{ "resource": "" }
q280176
CallTipWidget.eventFilter
test
def eventFilter(self, obj, event): """ Reimplemented to hide on certain key presses and on text edit focus changes. """ if obj == self._text_edit: etype = event.type() if etype == QtCore.QEvent.KeyPress: key = event.key() if key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return): self.hide() elif key == QtCore.Qt.Key_Escape: self.hide()
python
{ "resource": "" }
q280177
CallTipWidget.enterEvent
test
def enterEvent(self, event): """ Reimplemented to cancel the hide timer. """
python
{ "resource": "" }
q280178
CallTipWidget.paintEvent
test
def paintEvent(self, event): """ Reimplemented to paint the background panel. """ painter = QtGui.QStylePainter(self) option = QtGui.QStyleOptionFrame() option.initFrom(self)
python
{ "resource": "" }
q280179
CallTipWidget.show_call_info
test
def show_call_info(self, call_line=None, doc=None, maxlines=20): """ Attempts to show the specified call line and docstring at the current cursor location. The docstring is possibly truncated for length. """ if doc: match = re.match("(?:[^\n]*\n){%i}" % maxlines, doc) if match: doc = doc[:match.end()] +
python
{ "resource": "" }
q280180
CallTipWidget.show_tip
test
def show_tip(self, tip): """ Attempts to show the specified tip at the current cursor location. """ # Attempt to find the cursor position at which to show the call tip. text_edit = self._text_edit document = text_edit.document() cursor = text_edit.textCursor() search_pos = cursor.position() - 1 self._start_position, _ = self._find_parenthesis(search_pos, forward=False) if self._start_position == -1: return False # Set the text and resize the widget accordingly. self.setText(tip) self.resize(self.sizeHint()) # Locate and show the widget. Place the tip below the current line # unless it would be off the screen. In that case, decide the best # location based trying to minimize the area that goes off-screen. padding = 3 # Distance in pixels between cursor bounds and tip box. cursor_rect = text_edit.cursorRect(cursor) screen_rect = QtGui.qApp.desktop().screenGeometry(text_edit) point = text_edit.mapToGlobal(cursor_rect.bottomRight()) point.setY(point.y() + padding) tip_height = self.size().height() tip_width = self.size().width() vertical = 'bottom' horizontal = 'Right' if point.y() + tip_height > screen_rect.height(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off screen, check if point is in top or bottom # half of screen. if point_.y() - tip_height < padding: # If point is in upper half of screen, show tip below it. # otherwise above it. if 2*point.y() < screen_rect.height(): vertical = 'bottom' else: vertical = 'top' else:
python
{ "resource": "" }
q280181
CallTipWidget._cursor_position_changed
test
def _cursor_position_changed(self): """ Updates the tip based on user cursor movement. """ cursor = self._text_edit.textCursor() if cursor.position() <= self._start_position: self.hide() else:
python
{ "resource": "" }
q280182
proxied_attribute
test
def proxied_attribute(local_attr, proxied_attr, doc): """Create a property that proxies attribute ``proxied_attr`` through the local attribute ``local_attr``. """ def fget(self): return getattr(getattr(self, local_attr), proxied_attr) def fset(self,
python
{ "resource": "" }
q280183
canonicalize_path
test
def canonicalize_path(cwd, path): """ Canonicalizes a path relative to a given working directory. That is, the path, if not absolute, is interpreted relative to the working directory, then
python
{ "resource": "" }
q280184
schema_validate
test
def schema_validate(instance, schema, exc_class, *prefix, **kwargs): """ Schema validation helper. Performs JSONSchema validation. If a schema validation error is encountered, an exception of the designated class is raised with the validation error message appropriately simplified and passed as the sole positional argument. :param instance: The object to schema validate. :param schema: The schema to use for validation. :param exc_class: The exception class to raise instead of the ``jsonschema.ValidationError``
python
{ "resource": "" }
q280185
SensitiveDict.masked
test
def masked(self): """ Retrieve a read-only subordinate mapping. All values are stringified, and sensitive values are masked. The
python
{ "resource": "" }
q280186
virtualenv_no_global
test
def virtualenv_no_global(): """ Return True if in a venv and no system site packages. """ #this mirrors the logic in virtualenv.py for locating the no-global-site-packages.txt file site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))
python
{ "resource": "" }
q280187
pwordfreq
test
def pwordfreq(view, fnames): """Parallel word frequency counter. view - An IPython DirectView fnames - The filenames containing the split data. """ assert len(fnames) == len(view.targets) view.scatter('fname', fnames, flatten=True) ar = view.apply(wordfreq, Reference('fname')) freqs_list = ar.get() word_set = set() for f in freqs_list:
python
{ "resource": "" }
q280188
view_decorator
test
def view_decorator(function_decorator): """Convert a function based decorator into a class based decorator usable on class based Views. Can't subclass the `View` as it breaks inheritance (super in particular), so we monkey-patch instead. Based on http://stackoverflow.com/a/8429311 """
python
{ "resource": "" }
q280189
default_aliases
test
def default_aliases(): """Return list of shell aliases to auto-define. """ # Note: the aliases defined here should be safe to use on a kernel # regardless of what frontend it is attached to. Frontends that use a # kernel in-process can define additional aliases that will only work in # their case. For example, things like 'less' or 'clear' that manipulate # the terminal should NOT be declared here, as they will only work if the # kernel is running inside a true terminal, and not over the network. if os.name == 'posix': default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'), ('mv', 'mv -i'), ('rm', 'rm -i'), ('cp', 'cp -i'), ('cat', 'cat'), ] # Useful set of ls aliases. The GNU and BSD options are a little # different, so we make aliases that provide as similar as possible # behavior in ipython, by passing the right flags for each platform if sys.platform.startswith('linux'): ls_aliases = [('ls', 'ls -F --color'), # long ls ('ll', 'ls -F -o --color'), # ls normal files only ('lf', 'ls -F -o --color %l | grep ^-'), # ls symbolic links ('lk', 'ls -F -o --color %l | grep ^l'), # directories or links to directories, ('ldir', 'ls -F -o --color %l | grep /$'), # things which are executable ('lx',
python
{ "resource": "" }
q280190
AliasManager.soft_define_alias
test
def soft_define_alias(self, name, cmd): """Define an alias, but don't raise on an AliasError.""" try:
python
{ "resource": "" }
q280191
AliasManager.define_alias
test
def define_alias(self, name, cmd): """Define a new alias after validating it. This will raise an :exc:`AliasError` if
python
{ "resource": "" }
q280192
AliasManager.validate_alias
test
def validate_alias(self, name, cmd): """Validate an alias and return the its number of arguments.""" if name in self.no_alias: raise InvalidAliasError("The name %s can't be aliased " "because it is a keyword or builtin." % name) if not (isinstance(cmd, basestring)): raise InvalidAliasError("An alias command must be a string, " "got: %r"
python
{ "resource": "" }
q280193
AliasManager.call_alias
test
def call_alias(self, alias, rest=''): """Call an alias given its name and the rest of the line."""
python
{ "resource": "" }
q280194
AliasManager.transform_alias
test
def transform_alias(self, alias,rest=''): """Transform alias to system command string.""" nargs, cmd = self.alias_table[alias] if ' ' in cmd and os.path.isfile(cmd): cmd = '"%s"' % cmd # Expand the %l special to be the user's input line if cmd.find('%l') >= 0: cmd = cmd.replace('%l', rest) rest = '' if nargs==0: # Simple, argument-less aliases cmd = '%s %s' % (cmd, rest) else:
python
{ "resource": "" }
q280195
AliasManager.expand_alias
test
def expand_alias(self, line): """ Expand an alias in the command line Returns the provided command line, possibly with the first word (command) translated according to alias
python
{ "resource": "" }
q280196
autohelp_directive
test
def autohelp_directive(dirname, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """produces rst from nose help""" config = Config(parserClass=OptBucket, plugins=BuiltinPluginManager()) parser = config.getParser(TestProgram.usage()) rst = ViewList() for line in parser.format_help().split('\n'): rst.append(line, '<autodoc>') rst.append('Options', '<autodoc>') rst.append('-------', '<autodoc>') rst.append('', '<autodoc>') for opt in parser: rst.append(opt.options(), '<autodoc>') rst.append(' \n', '<autodoc>') rst.append(' ' + opt.help + '\n', '<autodoc>') rst.append('\n', '<autodoc>')
python
{ "resource": "" }
q280197
AnsiCodeProcessor.reset_sgr
test
def reset_sgr(self): """ Reset graphics attributs to their default values. """ self.intensity = 0
python
{ "resource": "" }
q280198
AnsiCodeProcessor.split_string
test
def split_string(self, string): """ Yields substrings for which the same escape code applies. """ self.actions = [] start = 0 # strings ending with \r are assumed to be ending in \r\n since # \n is appended to output strings automatically. Accounting # for that, here. last_char = '\n' if len(string) > 0 and string[-1] == '\n' else None string = string[:-1] if last_char is not None else string for match in ANSI_OR_SPECIAL_PATTERN.finditer(string): raw = string[start:match.start()] substring = SPECIAL_PATTERN.sub(self._replace_special, raw) if substring or self.actions: yield substring self.actions = [] start = match.end() groups = filter(lambda x: x is not None, match.groups()) g0 = groups[0] if g0 == '\a': self.actions.append(BeepAction('beep')) yield None self.actions = [] elif g0 == '\r': self.actions.append(CarriageReturnAction('carriage-return')) yield None self.actions = [] elif g0 == '\b': self.actions.append(BackSpaceAction('backspace')) yield None self.actions = [] elif g0 == '\n' or g0 == '\r\n': self.actions.append(NewLineAction('newline')) yield g0 self.actions = [] else: params = [ param for param in groups[1].split(';') if param ]
python
{ "resource": "" }
q280199
QtAnsiCodeProcessor.get_color
test
def get_color(self, color, intensity=0): """ Returns a QColor for a given color code, or None if one cannot be constructed. """ if color is None: return None # Adjust for intensity, if possible. if color < 8 and intensity > 0: color += 8 constructor = self.color_map.get(color, None) if isinstance(constructor, basestring): # If this is an X11 color name, we just hope there is a close SVG # color name. We could use QColor's static method
python
{ "resource": "" }