Load history from a text file in user home directory
424001
def load_wdhistory(self, workdir=None):
        """"""
        if osp.isfile(self.LOG_PATH):
            wdhistory, _ = encoding.readlines(self.LOG_PATH)
            wdhistory = [name for name in wdhistory if os.path.isdir(name)]
        else:
            if workdir is None:
                workdir = get_home_dir()
            wdhistory = [ workdir ]
        return wdhistory
1210974
protected History prepareHistory() throws IOException {
        File file = new File(System.getProperty("user.home"), HISTORYFILE);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException ignored) {
                // can't create the file, so no history for you
            }
        }
        return file.canWrite() ? new FileHistory(file) : null;
    }
1082757
def _write_history(self, pfx, hdu, linechar=60, indentchar=2):
        
        channel = self.fv.get_channel(self.chname)
        if channel is None:
            return

        history_plgname = 'ChangeHistory'
        try:
            history_obj = self.fv.gpmon.getPlugin(history_plgname)
        except Exception:
            self.logger.error(
                '{0} plugin is not loaded. No HISTORY will be written to '
                '{1}.'.format(history_plgname, pfx))
            return

        if channel.name not in history_obj.name_dict:
            self.logger.error(
                '{0} channel not found in {1}. No HISTORY will be written to '
                '{2}.'.format(channel.name, history_plgname, pfx))
            return

        file_dict = history_obj.name_dict[channel.name]
        chistory = []
        ind = ' ' * indentchar

        # NOTE: List comprehension too slow!
        for key in file_dict:
            if not key.startswith(pfx):
                continue
            for bnch in file_dict[key].values():
                chistory.append('{0} {1}'.format(bnch.MODIFIED, bnch.DESCRIP))

        # Add each HISTORY prettily into header, sorted by timestamp
        for s in sorted(chistory):
            for i in range(0, len(s), linechar):
                subs = s[i:i + linechar]
                if i > 0:
                    subs = ind + subs.lstrip()
                hdu.header.add_history(subs)
1095295
def load_manuf(filename):
    """"""
    manufdb = ManufDA(_name=filename)
    with open(filename, "rb") as fdesc:
        for line in fdesc:
            try:
                line = line.strip()
                if not line or line.startswith(b"#"):
                    continue
                parts = line.split(None, 2)
                oui, shrt = parts[:2]
                lng = parts[2].lstrip(b"#").strip() if len(parts) > 2 else ""
                lng = lng or shrt
                manufdb[oui] = plain_str(shrt), plain_str(lng)
            except Exception:
                log_loading.warning("Couldn't parse one line from [%s] [%r]",
                                    filename, line, exc_info=True)
    return manufdb
392420
def add_history(self, filename):
        
        filename = encoding.to_unicode_from_fs(filename)
        if filename in self.filenames:
            return
        editor = codeeditor.CodeEditor(self)
        if osp.splitext(filename)[1] == '.py':
            language = 'py'
        else:
            language = 'bat'
        editor.setup_editor(linenumbers=self.get_option('line_numbers'),
                            language=language,
                            scrollflagarea=False)
        editor.focus_changed.connect(lambda: self.focus_changed.emit())
        editor.setReadOnly(True)
        color_scheme = self.get_color_scheme()
        editor.set_font( self.get_plugin_font(), color_scheme )
        editor.toggle_wrap_mode( self.get_option('wrap') )

        # Avoid a possible error when reading the history file
        try:
            text, _ = encoding.read(filename)
        except (IOError, OSError):
            text = "# Previous history could not be read from disk, sorry\n\n"
        text = normalize_eols(text)
        linebreaks = [m.start() for m in re.finditer('\n', text)]
        maxNline = self.get_option('max_entries')
        if len(linebreaks) > maxNline:
            text = text[linebreaks[-maxNline - 1] + 1:]
            # Avoid an error when trying to write the trimmed text to
            # disk.
            # See issue 9093
            try:
                encoding.write(text, filename)
            except (IOError, OSError):
                pass
        editor.set_text(text)
        editor.set_cursor_position('eof')

        self.editors.append(editor)
        self.filenames.append(filename)
        index = self.tabwidget.addTab(editor, osp.basename(filename))
        self.find_widget.set_editor(editor)
        self.tabwidget.setTabToolTip(index, filename)
        self.tabwidget.setCurrentIndex(index)
831095
def _generate_transcript(self, history: List[Union[HistoryItem, str]], transcript_file: str) -> None:
        """"""
        import io
        # Validate the transcript file path to make sure directory exists and write access is available
        transcript_path = os.path.abspath(os.path.expanduser(transcript_file))
        transcript_dir = os.path.dirname(transcript_path)
        if not os.path.isdir(transcript_dir) or not os.access(transcript_dir, os.W_OK):
            self.perror("{!r} is not a directory or you don't have write access".format(transcript_dir),
                        traceback_war=False)
            return

        try:
            with self.sigint_protection:
                # Disable echo while we manually redirect stdout to a StringIO buffer
                saved_echo = self.echo
                saved_stdout = self.stdout
                self.echo = False

            # The problem with supporting regular expressions in transcripts
            # is that they shouldn't be processed in the command, just the output.
            # In addition, when we generate a transcript, any slashes in the output
            # are not really intended to indicate regular expressions, so they should
            # be escaped.
            #
            # We have to jump through some hoops here in order to catch the commands
            # separately from the output and escape the slashes in the output.
            transcript = ''
            for history_item in history:
                # build the command, complete with prompts. When we replay
                # the transcript, we look for the prompts to separate
                # the command from the output
                first = True
                command = ''
                for line in history_item.splitlines():
                    if first:
                        command += '{}{}\n'.format(self.prompt, line)
                        first = False
                    else:
                        command += '{}{}\n'.format(self.continuation_prompt, line)
                transcript += command
                # create a new string buffer and set it to stdout to catch the output
                # of the command
                membuf = io.StringIO()
                self.stdout = membuf
                # then run the command and let the output go into our buffer
                self.onecmd_plus_hooks(history_item)
                # rewind the buffer to the beginning
                membuf.seek(0)
                # get the output out of the buffer
                output = membuf.read()
                # and add the regex-escaped output to the transcript
                transcript += output.replace('/', r'\/')
        finally:
            with self.sigint_protection:
                # Restore altered attributes to their original state
                self.echo = saved_echo
                self.stdout = saved_stdout

        # finally, we can write the transcript out to the file
        try:
            with open(transcript_file, 'w') as fout:
                fout.write(transcript)
        except OSError as ex:
            self.perror('Failed to save transcript: {}'.format(ex), traceback_war=False)
        else:
            # and let the user know what we did
            if len(history) > 1:
                plural = 'commands and their outputs'
            else:
                plural = 'command and its output'
            msg = '{} {} saved to transcript file {!r}'
            self.pfeedback(msg.format(len(history), plural, transcript_file))
92509
function addToHistory (state, type, value) {
  let dest

  if (type === 'file') {
    dest = utils.getRefFilePath(value)
  } else {
    if (value === '#') {
      return false
    }
    dest = state.current.concat(`:${value}`)
  }

  if (dest) {
    dest = dest.toLowerCase()
    if (state.history.indexOf(dest) >= 0) {
      return false
    }

    state.history.push(dest)
  }
  return true
}
1235087
def chdir(self, directory, browsing_history=False,
              refresh_explorer=True, refresh_console=True):
        """"""
        if directory:
            directory = osp.abspath(to_text_string(directory))

        # Working directory history management
        if browsing_history:
            directory = self.history[self.histindex]
        elif directory in self.history:
            self.histindex = self.history.index(directory)
        else:
            if self.histindex is None:
                self.history = []
            else:
                self.history = self.history[:self.histindex+1]
            self.history.append(directory)
            self.histindex = len(self.history)-1
        
        # Changing working directory
        try:
            os.chdir(directory)
            if refresh_explorer:
                self.set_explorer_cwd.emit(directory)
            if refresh_console:
                self.set_current_console_wd.emit(directory)
            self.refresh_findinfiles.emit()
        except OSError:
            self.history.pop(self.histindex)
        self.refresh_plugin()
1193045
def write_to_history(**kwargs):
        
        from hyperstream import HyperStream
        hs = HyperStream(loglevel=logging.CRITICAL, file_logger=False, console_logger=False, mqtt_logger=None)
        if hs.current_session:
            hs.current_session.write_to_history(**kwargs)
1223277
def run(self):
        """"""
        if self._skip_delims:
            delims = readline.get_completer_delims()
            for delim in self._skip_delims:
                delims = delims.replace(delim, '')
            readline.set_completer_delims(delims)

        readline.parse_and_bind("tab: complete")
        readline.set_completer(self._completer.complete)

        if self._history_file:
            # Ensure history file exists
            if not os.path.isfile(self._history_file):
                open(self._history_file, 'w').close()

            readline.read_history_file(self._history_file)

        self._running = True
        try:
            while self._running:
                try:
                    command = input(self._format_prompt())
                    if command:
                        result = self.execute(*shlex.split(command))
                        if result:
                            print(result)
                except CLIException as exc:
                    print(exc)
                except (KeyboardInterrupt, EOFError):
                    self._running = False
                    print()
                except Exception as exc:
                    if self._verbose:
                        traceback.print_exc()
                    else:
                        print(exc)
        finally:
            if self._history_file:
                readline.write_history_file(self._history_file)
1084321
def load_history(self):
        """"""
        if osp.isfile(self.history_filename):
            rawhistory, _ = encoding.readlines(self.history_filename)
            rawhistory = [line.replace('\n', '') for line in rawhistory]
            if rawhistory[1] != self.INITHISTORY[1]:
                rawhistory[1] = self.INITHISTORY[1]
        else:
            rawhistory = self.INITHISTORY
        history = [line for line in rawhistory \
                   if line and not line.startswith('#')]

        # Truncating history to X entries:
        while len(history) >= CONF.get('historylog', 'max_entries'):
            del history[0]
            while rawhistory[0].startswith('#'):
                del rawhistory[0]
            del rawhistory[0]

        # Saving truncated history:
        try:
            encoding.writelines(rawhistory, self.history_filename)
        except EnvironmentError:
            pass

        return history
689911
def history(self):
        ''''''
        r = self.obj.api.getDatastreamHistory(self.obj.pid, self.id, format='xml')
        return parse_xml_object(DatastreamHistory, r.content, r.url)
306030
def history(self):
        
        res = self._api_request('hist')
        if res[0][0] == '-1':
            raise PuushError("History retrieval failed.")
        
        files = []
        for line in res[1:]:
            id, upload_time, url, filename, views, _ = line
            files.append(self._File(id, url, filename, upload_time, views))
        return files
1267684
def write_history_file(self, filename = None): 
        '''
        if filename is None:
            filename = self.history_filename
        fp = open(filename, u'wb')
        for line in self.history[-self.history_length:]:
            fp.write(ensure_str(line.get_line_text()))
            fp.write(u'\n')
        fp.close()
151474
def load_history(self, f):
        
        # TODO: Remove warning in a future release
        warnings.warn(
            "load_history is deprecated and will be removed in the next "
            "release, please use load_params with the f_history keyword",
            DeprecationWarning)

        self.history = History.from_file(f)
1333791
def add_history(self, line):
        '''
        if not hasattr(line, "get_line_text"):
            line = lineobj.ReadLineTextBuffer(line)
        if not line.get_line_text():
            pass
        elif len(self.history) > 0 and self.history[-1].get_line_text() == line.get_line_text():
            pass
        else:
            self.history.append(line)
        self.history_cursor = len(self.history)
904243
def results_history(history_log, no_color):
    """"""
    try:
        with open(history_log, 'r') as f:
            lines = f.readlines()
    except Exception as error:
        echo_style(
            'Unable to process results history log: %s' % error,
            no_color,
            fg='red'
        )
        sys.exit(1)

    index = len(lines)
    for item in lines:
        click.echo('{} {}'.format(index, item), nl=False)
        index -= 1