Read specified history file to history buffer
435009
private void readFile() {
        if(historyFile.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(historyFile))) {
                String line;
                while((line = reader.readLine()) != null)
                    push(Parser.toCodePoints(line));
            } catch(FileNotFoundException ignored) {
                //AESH-205
            } catch (IOException e) {
                if(logging)
                    LOGGER.log(Level.WARNING, "Failed to read from history file, ", e);
            }
        }
    }
1131448
def read_file_to_buffer(filename):
    
    f = open(filename, "r")
    buf = BytesIO(f.read())
    f.close()
    return buf
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)
1231342
def history_search_backward(self, e): # ()
        '''
        self.l_buffer=self._history.history_search_backward(self.l_buffer)
1316097
public synchronized void setHistory(CollectHistory history) {
        history_ = Optional.of(history);
        history_.ifPresent(getApi()::setHistory);
        data_.initWithHistoricalData(history, getDecoratorLookBack());
    }
705414
def _get_next(self, history):
        """"""
        orig_history = history
        if not history:
            return helper.START
        history = history[-(self._n-1):]
        while history and not self._T.get(history):
            history = history[1:]
        kv = [(k, v) for k, v in self._T.items(history)
              if not (k in reserved_words or k == history)]
        total = sum(v for k, v in kv)
        while total == 0 and len(history) > 0:
            history = history[1:]
            kv = [(k, v) for k, v in self._T.items(history)
                  if not (k in reserved_words or k == history)]
            total = sum(v for k, v in kv)
        assert total > 0, "Sorry there is no n-gram with {!r}".format(orig_history)
        d = defaultdict(float)
        total = self._T.get(history)
        for k, v in kv:
            k = k[len(history):]
            d[k] += (v+1)/(total + N_VALID_CHARS-1)
        return d
511398
def archive(context, clear_log, items, path, name):
    
    history_log = context.obj['history_log']
    no_color = context.obj['no_color']

    with open(history_log, 'r') as f:
        # Get history items
        history_items = f.readlines()

    if items:
        # Split comma separated list and cast indices to integer.
        items = [int(item) for item in items.split(',')]

        lines = []
        for index in items:
            lines.append(history_items[len(history_items) - index])
        history_items = lines

    with tempfile.TemporaryDirectory() as temp_dir:
        for item in history_items:
            # Copy log and results file,
            # update results file with relative path.
            archive_history_item(item, temp_dir, no_color)

        file_name = ''.join([name, '.tar.gz'])
        archive_path = os.path.join(path, file_name)

        with tarfile.open(archive_path, "w:gz") as tar:
            # Create tar archive
            tar.add(temp_dir, arcname='results')

    if clear_log:
        if items:
            # Remove duplicates to prevent unwanted deletion.
            items = list(set(items))

            # Must delete items from bottom to top of history file
            # to preserve indices. (Index 0 is last item in file)
            items.sort()
            for index in items:
                context.invoke(delete, item=index)
        else:
            context.invoke(clear)

    click.echo(
        'Exported results history to archive: {0}'.format(archive_path)
    )
1166934
def namedb_get_history_rows( cur, history_id, offset=None, count=None, reverse=False ):
    
    ret = []
    if not reverse:
        select_query = "SELECT * FROM history WHERE history_id = ? ORDER BY block_id ASC, vtxindex ASC"
    else:
        select_query = "SELECT * FROM history WHERE history_id = ? ORDER BY block_id DESC, vtxindex DESC"

    args = (history_id,)

    if count is not None:
        select_query += " LIMIT ?"
        args += (count,)

        if offset is not None:
            select_query += " OFFSET ?"
            args += (offset,)

    select_query += ";"

    history_rows = namedb_query_execute( cur, select_query, args)
    for r in history_rows:
        rd = dict(r)
        ret.append(rd)

    return ret
1047403
def RecordHistory(self):
        """"""
        if not self.restoringHistory:
            record = self.activated_node
            if self.historyIndex < -1:
                try:
                    del self.history[self.historyIndex+1:]
                except AttributeError, err:
                    pass
            if (not self.history) or record != self.history[-1]:
                self.history.append(record)
            del self.history[:-200]
            self.historyIndex = -1
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
706073
def _grab_history(self):
        
        default_location = None
        config = self.setup_cfg.config
        if config and config.has_option('zest.releaser', 'history_file'):
            default_location = config.get('zest.releaser', 'history_file')
        history_file = self.vcs.history_file(location=default_location)
        if not history_file:
            logger.warn("No history file found")
            self.data['history_lines'] = None
            self.data['history_file'] = None
            return
        logger.debug("Checking %s", history_file)
        history_lines = open(history_file).read().split('\n')
        # ^^^ TODO: .readlines()?
        headings = utils.extract_headings_from_history(history_lines)
        if not len(headings):
            logger.error("No detectable version heading in the history "
                         "file %s", history_file)
            sys.exit()
        good_heading = self.data['history_header'] % self.data
        # ^^^ history_header is a string with %(abc)s replacements.
        line = headings[0]['line']
        previous = history_lines[line]
        history_lines[line] = good_heading
        logger.debug("Set heading from %r to %r.", previous, good_heading)
        history_lines[line + 1] = utils.fix_rst_heading(
            heading=good_heading,
            below=history_lines[line + 1])
        logger.debug("Set line below heading to %r",
                     history_lines[line + 1])
        self.data['history_lines'] = history_lines
        self.data['history_file'] = history_file
1168778
def split_history_item(history):
    
    try:
        log_file, description = shlex.split(history)
    except ValueError:
        log_file = history.strip()
        description = None

    return log_file, description
1345153
def preloop(self):
        '''  '''
        if not self.already_prelooped:
            self.already_prelooped = True
            open('.psiturk_history', 'a').close()  # create file if it doesn't exist
            readline.read_history_file('.psiturk_history')
            for i in range(readline.get_current_history_length()):
                if readline.get_history_item(i) is not None:
                    self.history.append(readline.get_history_item(i))
781957
def end_of_history(event):
    
    event.current_buffer.history_forward(count=10**100)
    buff = event.current_buffer
    buff.go_to_history(len(buff._working_lines) - 1)
161018
def _update_history(self):
        """"""
        version = self.data['new_version']
        history = self.vcs.history_file()
        if not history:
            logger.warn("No history file found")
            return
        history_lines = open(history).read().split('\n')
        headings = utils.extract_headings_from_history(history_lines)
        if not len(headings):
            logger.warn("No detectable existing version headings in the "
                        "history file.")
            inject_location = 0
            underline_char = '-'
        else:
            first = headings[0]
            inject_location = first['line']
            underline_line = first['line'] + 1
            try:
                underline_char = history_lines[underline_line][0]
            except IndexError:
                logger.debug("No character on line below header.")
                underline_char = '-'
        header = '%s (unreleased)' % version
        inject = [header,
                  underline_char * len(header),
                  '',
                  self.data['nothing_changed_yet'],
                  '',
                  '']
        history_lines[inject_location:inject_location] = inject
        contents = '\n'.join(history_lines)
        open(history, 'w').write(contents)
        logger.info("Injected new section into the history: %r", header)
965039
def update_history(self) -> None:
        
        self.log.debug(f"Saving history. History is: \n{self.history}")

        jsons = []
        for item in self.history:
            json_item = item.__dict__

            # Convert sub-entries into JSON as well.
            json_item["output_records"] = self._parse_output_records(item)

            jsons.append(json_item)

        if not path.isfile(self.history_filename):
            open(self.history_filename, "a+").close()

        with open(self.history_filename, "w") as f:
            json.dump(jsons, f, default=lambda x: x.__dict__.copy(), sort_keys=True, indent=4)
            f.write("\n")
873082
private static String getHistoryFileUrl(RetireJobInfo info) {
    String historyFile = info.getHistoryFile();
    String historyFileUrl = null;
    if (historyFile != null && !historyFile.equals("")) {
      try {
        historyFileUrl = URLEncoder.encode(info.getHistoryFile(), "UTF-8");
      } catch (UnsupportedEncodingException e) {
        LOG.warn("Can't create history url ", e);
      }
    }
    return historyFileUrl;
  }