Executes a string of python code in cell input.
        We do not allow the kernel to make requests to the stdin
             this is the norm for notebooks

        Function returns a unique message id of the reply from
        the kernel.
181547
def execute_cell_input(self, cell_input, allow_stdin=None):
        
        if cell_input:
            logger.debug('Executing cell: "%s"...', cell_input.splitlines()[0][:40])
        else:
            logger.debug('Executing empty cell')
        return self.kc.execute(cell_input, allow_stdin=allow_stdin, stop_on_error=False)
530342
def input(self):
        
        def decorator(inputMethod):
            return MethodicalInput(automaton=self._automaton,
                                   method=inputMethod,
                                   symbol=self._symbol)
        return decorator
172887
def read_reply(self) -> Reply:
        '''
        '''
        _logger.debug('Read reply')
        reply = Reply()

        while True:
            line = yield from self._connection.readline()

            if line[-1:] != b'\n':
                raise NetworkError('Connection closed.')

            self._data_event_dispatcher.notify_read(line)
            reply.parse(line)

            if reply.code is not None:
                break

        return reply
632347
def exec_notebook_daemon_command(self, name, cmd, port=0):
        """"""
        cmd = self.get_notebook_daemon_command(name, cmd, port)

        # Make all arguments explicit strings
        cmd = [str(arg) for arg in cmd]

        logger.info("Running notebook command: %s", " ".join(cmd))
        # print("XXX - DEBUG - Running notebook command:", " ".join(cmd))

        # Add support for traceback dump on stuck
        env = os.environ.copy()
        env["PYTHONFAULTHANDLER"] = "true"

        p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, env=env)
        time.sleep(0.2)
        stdout, stderr = p.communicate()

        if b"already running" in stderr:
            raise RuntimeError("Looks like notebook_daemon is already running. Please kill it manually pkill -f notebook_daemon. Was: {}".format(stderr.decode("utf-8")))

        if p.returncode != 0:
            logger.error("STDOUT: %s", stdout)
            logger.error("STDERR: %s", stderr)

            raise RuntimeError("Could not execute notebook command. Exit code: {} cmd: {}".format(p.returncode, " ".join(cmd)))

        return stdout
73392
def _execute_cell_code(self, row, col, grid):
        """"""

        key = row, col, grid.current_table
        grid.code_array[key]

        grid.ForceRefresh()
672186
def load_ipython_extension(ip):
    
    decor = InteractiveDecorator(ip)
    ip.events.register('post_run_cell', decor.post_run_cell)

    #Unfortunately, the built-in "pre-execute" and "pre-run" methods are
    #triggered *before* the input from the cell has been stored to
    #history. Thus, we don't have access to the actual code that is about to be
    #executed. Instead, we use our own :class:`HistoryManager` that overrides
    #the :meth:`store_inputs` so we can handle the loop detection.
    newhist = AcornHistoryManager(ip.history_manager, decor)
    ip.history_manager = newhist
1195105
def make_notebook(cell_list):
    
    import utool as ut
    header = ut.codeblock(
        '''
        {
         "cells": [
        '''
    )

    footer = ut.codeblock(
        '''
         ],
         "metadata": {
          "kernelspec": {
           "display_name": "Python 2",
           "language": "python",
           "name": "python2"
          },
          "language_info": {
           "codemirror_mode": {
            "name": "ipython",
            "version": 2
           },
           "file_extension": ".py",
           "mimetype": "text/x-python",
           "name": "python",
           "nbconvert_exporter": "python",
           "pygments_lexer": "ipython2",
           "version": "2.7.6"
          }
         },
         "nbformat": 4,
         "nbformat_minor": 0
        }
        ''')

    cell_body = ut.indent(',\n'.join(cell_list), '  ')
    notebook_str = header + '\n' + cell_body +  '\n' +  footer
    try:
        import json
        json.loads(notebook_str)
    except ValueError as ex:
        ut.printex(ex, 'Invalid notebook JSON')
        raise
    return notebook_str
1341563
function(input) {
  var code = '';

  var unparsedInput = input;
  var unparsedInputLength;
  var output;

  do {
    var section = toplevel(unparsedInput);
    unparsedInputLength = unparsedInput.length;
    if (section.zone === null) {
      output = unparsedInput;
      code += '$_write('
        + JSON.stringify(escapeCurly(output, section.escapes))
        + ');\n';
      break;
    }
    var span = unparsedInput.slice(section.zone.from + 2, section.zone.to - 2);
    var params = zoneParser(span);    // Fragment the parameters.
    var macro = params[0];

    output = unparsedInput.slice(0, section.zone.from);
    code += '$_write('
      + JSON.stringify(escapeCurly(output, section.escapes))
      + ');\n';

    // If the macro is not present, print the zone directly.
    if (macros[macro] === undefined) {
      output = unparsedInput.slice(section.zone.from, section.zone.to);
      code += '$_write('
        + JSON.stringify(escapeCurly(output, section.escapes))
        + ');\n';
      unparsedInput = unparsedInput.slice(section.zone.to);
      continue;
    }
    // If the macro is empty, this is code.
    if (macro === "") {
      code += params.slice(1).join('') + '\n';
      unparsedInput = unparsedInput.slice(section.zone.to);
      continue;
    }

    // Call the macro.
    var errmsg = JSON.stringify([
      'Template error: macro "MACRO" didn\'t work.',
      'Parameters: PARAMS',
      'Literal: LITERAL',
      'Message: MESSAGE'
    ].join('\n'))
     .replace('MACRO', '" + ' + JSON.stringify(macro) + ' + "')
     .replace('MESSAGE', '" + e.message + "')
     .replace('PARAMS', '" + ' + JSON.stringify(params.slice(1)) + ' + "')
     .replace('LITERAL', '" + $_scopestr + "');
    var macrocode = macros[macro](params.slice(1));
    code += [
      'try {',
      '  ' + macrocode,
      '} catch(e) {',
      '  try {',
      '    var $_scopestr = JSON.stringify($_scope);',
      '  } catch(e) { var $_scopestr = Object.keys($_scope).join(" "); }',
      '  throw Error (' + errmsg + ');',
      '}'
    ].join('\n');

    unparsedInput = unparsedInput.slice(section.zone.to);
  } while (section.zone.to < unparsedInputLength);

  return code;
}
675350
def execute(self, js_str, timeout=0, max_memory=0):
        

        wrapped = "(function(){return (%s)})()" % js_str
        return self.eval(wrapped, timeout, max_memory)
1350169
def process_input(self):
        
        try:
            character = self.window.getch()
        except Exception as e:
            character = -1
            if self.debug:
                self.addstr(self.height-1, self.width - len(e.message) + 1, e.message)

        # Check for any keys we've been told to exit on
        if character in self.exit_keys:
            self.stop()

        # Force redraw the screen on ^L
        if character == 12:
            self.window.clear()
            return

        # Send input to active panes (hidden panes can still receive input)
        if character != -1:
            [pane.process_input(character) for pane in self if pane.active ]

            # Print character codes to the bottom center if debugging.
            if self.debug:
                self.addstr(self.height-1, self.width/2, " "*4)
                self.addstr(self.height-1, self.width/2 - len(str(character)) / 2, str(character))
632726
def exit(code=0, text=''):
    
    if not isinstance(text, basestring_type):
        text = unicode_type(text)
    if code > 0:
        if text:
            if not isinstance(text, basestring_type):
                text = unicode_type(text)
            sys.stderr.write(text)
        sys.exit(code)
    else:
        if text:
            print(text)
        sys.exit(0)
125283
def _main():
    
    if argv[1:]:
        stdout.write(_CLI_HELP)
        raise SystemExit()
    for line in stdin:
        try:
            message = loads(line)
        except ValueError:
            stdout.write("Not JSON: {}\n\n".format(line.rstrip(b"\n")))
            continue
        if REQUIRED_FIELDS - set(message.keys()):
            stdout.write(
                "Not an Eliot message: {}\n\n".format(line.rstrip(b"\n")))
            continue
        result = pretty_format(message) + "\n"
        if PY2:
            result = result.encode("utf-8")
        stdout.write(result)
119209
def process_mock_rpc(input_string):
    

    spec, equals, value = input_string.partition(u'=')

    if len(equals) == 0:
        print("Could not parse mock RPC argument: {}".format(input_string))
        sys.exit(1)

    try:
        value = int(value.strip(), 0)
    except ValueError as exc:
        print("Could not parse mock RPC value: {}".format(str(exc)))
        sys.exit(1)

    slot, part, rpc_id = spec.partition(u":")
    if len(part) == 0:
        print("Could not parse mock RPC slot/rpc definition: {}".format(spec))
        sys.exit(1)

    try:
        slot = SlotIdentifier.FromString(slot)
    except ArgumentError as exc:
        print("Could not parse slot id in mock RPC definition: {}".format(exc.msg))
        sys.exit(1)

    try:
        rpc_id = int(rpc_id, 0)
    except ValueError as exc:
        print("Could not parse mock RPC number: {}".format(str(exc)))
        sys.exit(1)

    return slot, rpc_id, value
612610
function (rawEmail, callback) {
        if (!isPythonAvailable) {
            return callback(null, false);
        }

        var verifyDkimPath = path.join(__dirname, '../python/verifydkim.py');
        var verifyDkim = child_process.spawn('python', [verifyDkimPath]);

        verifyDkim.stdout.on('data', function (data) {
            logger.verbose(data.toString());
        });

        verifyDkim.on('close', function (code) {
            logger.verbose('closed with return code ' + code);
            /* Convert return code to appropriate boolean. */
            return callback(null, !!!code);
        });

        verifyDkim.stdin.write(rawEmail);
        verifyDkim.stdin.end();
    }
1017351
def combine_inputs_with_outputs(nb_source, nb_outputs, fmt=None):
    """"""

    output_code_cells = [cell for cell in nb_outputs.cells if cell.cell_type == 'code']
    output_other_cells = [cell for cell in nb_outputs.cells if cell.cell_type != 'code']

    fmt = long_form_one_format(fmt)
    text_repr = nb_source.metadata.get('jupytext', {}).get('text_representation', {})
    ext = fmt.get('extension') or text_repr.get('extension')
    format_name = fmt.get('format_name') or text_repr.get('format_name')

    nb_outputs_filtered_metadata = copy(nb_outputs.metadata)
    filter_metadata(nb_outputs_filtered_metadata,
                    nb_source.metadata.get('jupytext', {}).get('notebook_metadata_filter'),
                    _DEFAULT_NOTEBOOK_METADATA)

    for key in nb_outputs.metadata:
        if key not in nb_outputs_filtered_metadata:
            nb_source.metadata[key] = nb_outputs.metadata[key]

    source_is_md_version_one = ext in ['.md', '.Rmd'] and text_repr.get('format_version') == '1.0'
    if nb_source.metadata.get('jupytext', {}).get('formats') or ext in ['.md', '.Rmd']:
        nb_source.metadata.get('jupytext', {}).pop('text_representation', None)

    if not nb_source.metadata.get('jupytext', {}):
        nb_source.metadata.pop('jupytext', {})

    for cell in nb_source.cells:
        # Remove outputs to warranty that trust of returned notebook is that of second notebook
        if cell.cell_type == 'code':
            cell.execution_count = None
            cell.outputs = []

            for i, ocell in enumerate(output_code_cells):
                if same_content(cell.source, ocell.source):
                    # Fill outputs with that of second notebook
                    cell.execution_count = ocell.execution_count
                    cell.outputs = ocell.outputs

                    # Append cell metadata that was filtered
                    if format_name in ['bare', 'sphinx'] or source_is_md_version_one:
                        ocell_filtered_metadata = {}
                    else:
                        ocell_filtered_metadata = copy(ocell.metadata)
                        filter_metadata(ocell_filtered_metadata,
                                        nb_source.metadata.get('jupytext', {}).get('cell_metadata_filter'),
                                        _IGNORE_CELL_METADATA)

                    for key in ocell.metadata:
                        if key not in ocell_filtered_metadata and key not in _JUPYTEXT_CELL_METADATA:
                            cell.metadata[key] = ocell.metadata[key]

                    output_code_cells = output_code_cells[(i + 1):]
                    break
        else:
            for i, ocell in enumerate(output_other_cells):
                if cell.cell_type == ocell.cell_type and same_content(cell.source, ocell.source):
                    if format_name in ['spin', 'bare', 'sphinx'] or source_is_md_version_one:
                        ocell_filtered_metadata = {}
                    else:
                        ocell_filtered_metadata = copy(ocell.metadata)
                        filter_metadata(ocell_filtered_metadata,
                                        nb_source.metadata.get('jupytext', {}).get('cell_metadata_filter'),
                                        _IGNORE_CELL_METADATA)

                    for key in ocell.metadata:
                        if key not in ocell_filtered_metadata:
                            cell.metadata[key] = ocell.metadata[key]

                    output_other_cells = output_other_cells[(i + 1):]
                    break

    return nb_source
100698
def _execute(self, line):
        
        output = self.app.output

        # WORKAROUND: Due to a bug in Jedi, the current directory is removed
        # from sys.path. See: https://github.com/davidhalter/jedi/issues/1148
        if '' not in sys.path:
            sys.path.insert(0, '')

        def compile_with_flags(code, mode):
            " Compile code with the right compiler flags. "
            return compile(code, '<stdin>', mode,
                           flags=self.get_compiler_flags(),
                           dont_inherit=True)

        if line.lstrip().startswith('\x1a'):
            # When the input starts with Ctrl-Z, quit the REPL.
            self.app.exit()

        elif line.lstrip().startswith('!'):
            # Run as shell command
            os.system(line[1:])
        else:
            # Try eval first
            try:
                code = compile_with_flags(line, 'eval')
                result = eval(code, self.get_globals(), self.get_locals())

                locals = self.get_locals()
                locals['_'] = locals['_%i' % self.current_statement_index] = result

                if result is not None:
                    out_prompt = self.get_output_prompt()

                    try:
                        result_str = '%r\n' % (result, )
                    except UnicodeDecodeError:
                        # In Python 2: `__repr__` should return a bytestring,
                        # so to put it in a unicode context could raise an
                        # exception that the 'ascii' codec can't decode certain
                        # characters. Decode as utf-8 in that case.
                        result_str = '%s\n' % repr(result).decode('utf-8')

                    # Align every line to the first one.
                    line_sep = '\n' + ' ' * fragment_list_width(out_prompt)
                    result_str = line_sep.join(result_str.splitlines()) + '\n'

                    # Write output tokens.
                    if self.enable_syntax_highlighting:
                        formatted_output = merge_formatted_text([
                            out_prompt,
                            PygmentsTokens(list(_lex_python_result(result_str))),
                        ])
                    else:
                        formatted_output = FormattedText(
                                out_prompt + [('', result_str)])

                    print_formatted_text(
                        formatted_output, style=self._current_style,
                        style_transformation=self.style_transformation,
                        include_default_pygments_style=False)

            # If not a valid `eval` expression, run using `exec` instead.
            except SyntaxError:
                code = compile_with_flags(line, 'exec')
                six.exec_(code, self.get_globals(), self.get_locals())

            output.flush()
556369
async def get_reply(self, message=None, *, timeout=None):
        
        return await self._get_message(
            message, self._reply_indices, self._pending_replies, timeout,
            lambda x, y: x.reply_to_msg_id == y
        )