public void addQuizAns(String key, String ans) {
   if (ans.equals("0")) {
     hist.addImageAnswer(key, ans, true);
   } else {
     hist.addImageAnswer(key, ans, false);
   }
 }
Exemple #2
0
  public List<History> getHistory() {
    ArrayList<History> historys = new ArrayList<History>();

    try {

      Cursor c =
          db.query(
              HISTORY_TABLE,
              new String[] {"history_id", "displaytext", "url"},
              null,
              null,
              null,
              null,
              null);

      int numRows = c.getCount();
      c.moveToFirst();

      for (int i = 0; i < numRows; ++i) {
        History history = new History();
        history.historyId = c.getLong(0);
        history.displayText = c.getString(1);
        history.url = c.getString(2);
        historys.add(history);
        c.moveToNext();
      }

      c.close();

    } catch (SQLException e) {
    }
    return historys;
  }
Exemple #3
0
  /**
   * Get the history after a specified revision.
   *
   * <p>The default implementation first fetches the full history and then throws away the oldest
   * revisions. This is not efficient, so subclasses should override it in order to get good
   * performance. Once every subclass has implemented a more efficient method, the default
   * implementation should be removed and made abstract.
   *
   * @param file the file to get the history for
   * @param sinceRevision the revision right before the first one to return, or {@code null} to
   *     return the full history
   * @return partial history for file
   * @throws HistoryException on error accessing the history
   */
  History getHistory(File file, String sinceRevision) throws HistoryException {

    // If we want an incremental history update and get here, warn that
    // it may be slow.
    if (sinceRevision != null) {
      Logger logger = OpenGrokLogger.getLogger();
      logger.log(
          Level.WARNING,
          "Incremental history retrieval is not implemented for {0}.",
          getClass().getSimpleName());
      logger.log(Level.WARNING, "Falling back to slower full history retrieval.");
    }

    History history = getHistory(file);

    if (sinceRevision == null) {
      return history;
    }

    List<HistoryEntry> partial = new ArrayList<>();
    for (HistoryEntry entry : history.getHistoryEntries()) {
      partial.add(entry);
      if (sinceRevision.equals(entry.getRevision())) {
        // Found revision right before the first one to return.
        break;
      }
    }

    removeAndVerifyOldestChangeset(partial, sinceRevision);
    history.setHistoryEntries(partial);
    return history;
  }
Exemple #4
0
  @Override
  public void keyTyped(final KeyEvent e) {
    if (!hist.active()
        || control(e)
        || DELNEXT.is(e)
        || DELPREV.is(e)
        || ESCAPE.is(e)
        || CUT2.is(e)) return;

    final int caret = editor.pos();

    // remember if marked text is to be deleted
    final StringBuilder sb = new StringBuilder(1).append(e.getKeyChar());
    final boolean indent = TAB.is(e) && editor.indent(sb, e.isShiftDown());

    // delete marked text
    final boolean selected = editor.selected() && !indent;
    if (selected) editor.delete();

    final int move = ENTER.is(e) ? editor.enter(sb) : editor.add(sb, selected);

    // refresh history and adjust cursor position
    hist.store(editor.text(), caret, editor.pos());
    if (move != 0) editor.pos(Math.min(editor.size(), caret + move));

    // adjust text height
    scrollCode.invokeLater(true);
    e.consume();
  }
  /** Helper for {@link #get(File, Repository)}. */
  private History getHistory(File file, Repository repository, boolean withFiles)
      throws HistoryException, SQLException {
    final String filePath = getSourceRootRelativePath(file);
    final String reposPath = toUnixPath(repository.getDirectoryName());
    final ArrayList<HistoryEntry> entries = new ArrayList<HistoryEntry>();
    final ConnectionResource conn = connectionManager.getConnectionResource();
    try {
      final PreparedStatement ps;
      if (file.isDirectory()) {
        // Fetch history for all files under this directory.
        ps = conn.getStatement(GET_DIR_HISTORY);
        ps.setString(2, filePath);
      } else {
        // Fetch history for a single file only.
        ps = conn.getStatement(GET_FILE_HISTORY);
        ps.setString(2, getParentPath(filePath));
        ps.setString(3, getBaseName(filePath));
      }
      ps.setString(1, reposPath);

      final PreparedStatement filePS = withFiles ? conn.getStatement(GET_CS_FILES) : null;

      try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
          // Get the information about a changeset
          String revision = rs.getString(1);
          String author = rs.getString(2);
          Timestamp time = rs.getTimestamp(3);
          String message = rs.getString(4);
          HistoryEntry entry = new HistoryEntry(revision, time, author, null, message, true);
          entries.add(entry);

          // Fill the list of files touched by the changeset, if
          // requested.
          if (withFiles) {
            int changeset = rs.getInt(5);
            filePS.setInt(1, changeset);
            try (ResultSet fileRS = filePS.executeQuery()) {
              while (fileRS.next()) {
                entry.addFile(fileRS.getString(1));
              }
            }
          }
        }
      }
    } finally {
      connectionManager.releaseConnection(conn);
    }

    History history = new History();
    history.setHistoryEntries(entries);

    RuntimeEnvironment env = RuntimeEnvironment.getInstance();
    if (env.isTagsEnabled() && repository.hasFileBasedTags()) {
      repository.assignTagsInHistory(history);
    }

    return history;
  }
Exemple #6
0
 @Test
 public void constructor() {
   History another = new History(INSERT_VERSION, UPDATE_VERSION);
   assertEquals("insert version not set.", INSERT_VERSION, another.getInsertVersion());
   assertEquals("update version not set.", UPDATE_VERSION, another.getUpdateVersion());
   assertNotNull("created on is null.", another.getCreatedOn());
   assertNull("deleted on is set.", another.getDeletedOn());
 }
Exemple #7
0
  public static void main(String[] args) {
    History history = new History("start_url_here");

    try {
      history.add("start_url_here");
    } catch (HistoryAddingException e) {
      e.printStackTrace();
    }

    try {
      history.add("second_url_here");
    } catch (HistoryAddingException e) {
      e.printStackTrace();
    }

    try {
      history.add("third_url_here");
    } catch (HistoryAddingException e) {
      e.printStackTrace();
    }

    try {
      history.add("fourth_url_here");
    } catch (HistoryAddingException e) {
      e.printStackTrace();
    }

    try {
      history.add("start_url_here");
    } catch (HistoryAddingException e) {
      e.printStackTrace();
    }

    try {
      history.goBack();
    } catch (HistoryGoBackException e) {
      e.printStackTrace();
    }

    try {
      history.goForward();
    } catch (HistoryGoForwardException e) {
      e.printStackTrace();
    }

    try {
      history.goBack();
    } catch (HistoryGoBackException e) {
      e.printStackTrace();
    }

    try {
      history.add("random_url_here");
    } catch (HistoryAddingException e) {
      e.printStackTrace();
    }
  }
 public void solvePuzzle() {
   startmills = System.currentTimeMillis();
   List<String> candidateList = null;
   while (true) {
     long time = System.currentTimeMillis();
     long duration = time - startmills;
     long secs = (duration / 1000);
     if (secs > MAXTIME) {
       break;
     }
     candidateList = answerBoard.getListFromCandidate(MAXSIZE);
     //			Util.writeLog(candidateList.get(0));
     answerBoard = new AnswerBoard();
     for (String oldPazzle : candidateList) {
       String operationHistory = history.getOperationHistory(oldPazzle);
       int currentDistance = history.getDistanceHistory(oldPazzle);
       int currentMaxDistance = history.getMaxDistanceHistory(oldPazzle);
       for (int op = 0; op < 4; op++) {
         switch (op) {
           case UP_OP:
             board = new Board(width, height, oldPazzle);
             if (board.up()) {
               MovedPosition position = board.getPosition();
               move(operationHistory + "U", position, currentDistance, currentMaxDistance);
             }
             break;
           case LEFT_OP:
             board = new Board(width, height, oldPazzle);
             if (board.left()) {
               MovedPosition position = board.getPosition();
               move(operationHistory + "L", position, currentDistance, currentMaxDistance);
             }
             break;
           case RIGHT_OP:
             board = new Board(width, height, oldPazzle);
             if (board.right()) {
               MovedPosition position = board.getPosition();
               move(operationHistory + "R", position, currentDistance, currentMaxDistance);
             }
             break;
           case DOWN_OP:
             board = new Board(width, height, oldPazzle);
             if (board.down()) {
               MovedPosition position = board.getPosition();
               move(operationHistory + "D", position, currentDistance, currentMaxDistance);
             }
             break;
         }
         // 解答があったら終了。
         if (answerBoard.contains(correctPuzzle)) {
           return;
         }
       }
     }
   }
 }
 /**
  * Check that the diagnosis is correct //TODO: Make this general for randomly ordered diags
  *
  * @param key the key to the diagnosis
  * @return
  */
 public boolean checkDiag(String key) {
   if (key.equals("0")) {
     hist.addAnswer(key, true);
     hist.save();
     return true;
   } else {
     hist.addAnswer(key, false);
     return false;
   }
 }
  /**
   * Move up or down the history tree.
   *
   * @param direction less than 0 to move up the tree, down otherwise
   */
  private final boolean moveHistory(final boolean next) throws IOException {
    if (next && !history.next()) {
      return false;
    } else if (!next && !history.previous()) {
      return false;
    }

    setBuffer(history.current());

    return true;
  }
Exemple #11
0
 @Test
 public void copyConstructor() {
   History another = new History(entity);
   assertEquals("insert version not same.", entity.getInsertVersion(), another.getInsertVersion());
   assertEquals("update version not same.", entity.getUpdateVersion(), another.getUpdateVersion());
   assertEquals("created on not same.", entity.getCreatedOn(), another.getCreatedOn());
   assertEquals("deleted on not same.", entity.getDeletedOn(), another.getDeletedOn());
 }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {

    // start
    super.onCreate(savedInstanceState);
    setContentView(R.layout.browserhook);
    mDbHelperConverter = new Converter(this);
    mDbHelperConverter.open();
    mDBHelperHistory = new History(this);
    mDBHelperHistory.open();
    mSharedPrefs = getSharedPreferences(PREFS_NAME, 0);

    // bind
    mWdgDirectBtn = (Button) findViewById(R.id.ButtonDirect);
    mWdgDirectBtn.setOnClickListener(this);
    mWdgConvertBtn = (Button) findViewById(R.id.ButtonConvert);
    mWdgConvertBtn.setOnClickListener(this);
    mWdgHistoryBtn = (Button) findViewById(R.id.ButtonHistory);
    mWdgHistoryBtn.setOnClickListener(this);
    mWdgSettingBtn = (Button) findViewById(R.id.ButtonSetting);
    mWdgSettingBtn.setOnClickListener(this);

    // インテントが渡されたか単体起動かを判別
    if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
      URI = getIntent().getData();
      setTitle(getText(R.string.apptitle_main).toString() + ": " + URI.toString()); // タイトルを設定
      IS_STANDALONE = false;
      // Log.d(TAG, "oc:i:got");

      // 履歴が許可されているなら記録
      final Boolean historyAvailable = mSharedPrefs.getBoolean(sPrefKeyDisableHistory, false);
      if (!historyAvailable) {
        Date currentTime_1 = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String dateString = formatter.format(currentTime_1);
        // Log.d(TAG, "sba:cv:" + dateString);
        mDBHelperHistory.createItem(URI.toString(), dateString);
      }

      // load shared prefs
      mLastBrowser = mSharedPrefs.getString("lastBrowser", "");

      // build spinner
      buildBrowserSpinner();
      buildConvertSpinner();

    } else {
      IS_STANDALONE = true;
      startConverterlistActivity();
      finish();
    }
    return;
  }
  private void processMessage(Message message) throws IOException {
    if (message.getType().equals("SimpleMessage")) {
      MessageType messageType = (MessageType) message.getValue();
      String receiver = messageType.getToUser();
      history.get(receiver).add(messageType);
    }

    if (message.getType().equals("ConnectUserMessage")) {
      String user = (String) message.getValue();
      Messages messages = history.get(user);
      Operations.sendHistory(messages.getLastFiveWith(user), out);
    }
  }
Exemple #14
0
  @Test
  public void hashCodeAndEquals() {
    basicEqualsTest(entity);

    History another = new History(entity);
    assertEqualsAndHashCode(entity, another);

    another.setInsertVersion(INSERT_VERSION_2);
    assertNotEqualsAndHashCode(entity, another);

    another = new History(entity);
    another.setUpdateVersion(UPDATE_VERSION_2);
    assertNotEqualsAndHashCode(entity, another);
  }
  public boolean back(Object withResult) {
    check();
    if (!history.canKill()) {
      return false;
    }

    History.Entry entry = history.kill();
    if (withResult != null) {
      entry.returnsResult = withResult;
    }

    dispatcher.dispatch(entry);

    return true;
  }
  /** Returns a recursively created XML representation of this <code>Meta</code>. */
  public String toString() {

    StringBuilder buffer = new StringBuilder();
    buffer.append("<" + xmltag + ">" + newline);

    if (null != corpus_id) {
      buffer.append("\t\t\t" + corpus_id.toString());
    }
    if (null != history) {
      buffer.append("\t\t\t" + history.toString());
    }
    if (null != format) {
      buffer.append("\t\t\t" + format.toString());
    }
    if (null != name) {
      buffer.append("\t\t\t" + name.toString());
    }
    if (null != author) {
      buffer.append("\t\t\t" + author.toString());
    }
    if (null != date) {
      buffer.append("\t\t\t" + date.toString());
    }
    if (null != description) {
      buffer.append("\t\t\t" + description.toString());
    }

    buffer.append("\t\t</" + xmltag + ">" + newline);

    return buffer.toString();
  }
 @UiHandler({"dayButton", "weekButton", "monthButton", "yearButton", "allButton"})
 public void onButtonSelected(SelectEvent event) {
   TextButton sourceButton = (TextButton) event.getSource();
   int index = window.getButtonBar().getWidgetIndex(sourceButton);
   history = History.fromInteger(index);
   window.hide();
 }
  public boolean backToRoot(Object result) {
    check();
    if (!history.canKill()) {
      return false;
    }

    List<History.Entry> entries = history.killAll(false);

    if (result != null) {
      entries.get(0).returnsResult = result;
    }
    //        entries.get(entries.size() - 1).transitionDirection = TransitionDirection.BACKWARD;

    dispatcher.dispatch(entries);
    return true;
  }
  /**
   * Returns the cached recent messages history.
   *
   * @return
   * @throws IOException
   */
  private History getHistory() throws IOException {
    synchronized (historyID) {
      HistoryService historyService =
          MessageHistoryActivator.getMessageHistoryService().getHistoryService();

      if (history == null) {
        history = historyService.createHistory(historyID, recordStructure);

        // lets check the version if not our version, re-create
        // history (delete it)
        HistoryReader reader = history.getReader();
        boolean delete = false;
        QueryResultSet<HistoryRecord> res = reader.findLast(1);
        if (res != null && res.hasNext()) {
          HistoryRecord hr = res.next();
          if (hr.getPropertyValues().length >= 4) {
            if (!hr.getPropertyValues()[3].equals(RECENT_MSGS_VER)) delete = true;
          } else delete = true;
        }

        if (delete) {
          // delete it
          try {
            historyService.purgeLocallyStoredHistory(historyID);

            history = historyService.createHistory(historyID, recordStructure);
          } catch (IOException ex) {
            logger.error("Cannot delete recent_messages history", ex);
          }
        }
      }

      return history;
    }
  }
  /**
   * Get a map from author names to their ids in the database. The authors that are not in the
   * database are added to it.
   *
   * @param conn the connection to the database
   * @param history the history to get the author names from
   * @param reposId the id of the repository
   * @return a map from author names to author ids
   */
  private Map<String, Integer> getAuthors(ConnectionResource conn, History history, int reposId)
      throws SQLException {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    PreparedStatement ps = conn.getStatement(GET_AUTHORS);
    ps.setInt(1, reposId);
    try (ResultSet rs = ps.executeQuery()) {
      while (rs.next()) {
        map.put(rs.getString(1), rs.getInt(2));
      }
    }

    PreparedStatement insert = conn.getStatement(ADD_AUTHOR);
    insert.setInt(1, reposId);
    for (HistoryEntry entry : history.getHistoryEntries()) {
      String author = entry.getAuthor();
      if (!map.containsKey(author)) {
        int id = nextAuthorId.getAndIncrement();
        insert.setString(2, author);
        insert.setInt(3, id);
        insert.executeUpdate();
        map.put(author, id);
        conn.commit();
      }
    }

    return map;
  }
Exemple #21
0
 /**
  * Play a single game to the end.
  *
  * @param simulatedWorld simulator used by agents to determine move.
  */
 private void runSimulation(
     Simulator<S, A> simulatedWorld, List<Agent> agents, int[] agentMoveOrder) {
   long[] totalMoveTime = new long[agents.size()];
   double[] totalRewards = new double[agents.size()];
   int[] actionCounts = new int[agents.size()];
   world_.setInitialState();
   history_ = new History<S, A>(world_.getState());
   for (int i = 0; i < totalRewards.length; i++) totalRewards[i] = world_.getRewards()[i];
   while (!world_.isTerminalState()) {
     int agentTurn = world_.getState().getAgentTurn();
     long startTime = System.currentTimeMillis();
     A action = agents.get(agentTurn).selectAction(world_.getState(), simulatedWorld.copy());
     totalMoveTime[agentTurn] += System.currentTimeMillis() - startTime;
     world_.takeAction(action);
     for (int i = 0; i < totalRewards.length; i++) totalRewards[i] += world_.getRewards()[i];
     actionCounts[agentTurn]++;
     history_.add(world_.getState(), action);
   }
   long[] totalMoveTime2 = new long[agents.size()];
   double[] totalRewards2 = new double[agents.size()];
   int[] actionCounts2 = new int[agents.size()];
   for (int i = 0; i < agents_.size(); i++) {
     totalMoveTime2[i] = totalMoveTime[agentMoveOrder[i]];
     totalRewards2[i] = totalRewards[agentMoveOrder[i]];
     actionCounts2[i] = actionCounts[agentMoveOrder[i]];
   }
   totalMoveTimeData_.add(totalMoveTime2);
   totalRewardsData_.add(totalRewards2);
   actionCountsData_.add(actionCounts2);
 }
 @Test
 public void testTwoLikes() {
   SparseVector vec = sum.summarize(History.forUser(42, Like.create(42, 39), Like.create(42, 67)));
   assertThat(vec.size(), equalTo(2));
   assertThat(vec.get(39), equalTo(1.0));
   assertThat(vec.get(67), equalTo(1.0));
 }
Exemple #23
0
 public void add(History h) {
   if (this.history == null) {
     this.history = new LinkedHashSet<History>();
   }
   h.setParent(this);
   this.history.add(h);
 }
Exemple #24
0
  @Override
  public boolean onContextItemSelected(MenuItem item) {

    if (item.getItemId() == CONTEXTMENU_TRANSIT) {

      History it = ((History) adapter.getItems().get(selectedRowId));
      adapter.getFilter().filter("." + it.getOrdSerial() + ".");
    }

    if (item.getItemId() == CONTEXTMENU_DELETE) {

      History it = ((History) adapter.getItems().get(selectedRowId));
      Common.delOrder(this, it);
    }
    return true;
  }
 /**
  * 解答の操作文字列を得る。
  *
  * @return
  */
 public String getSolvedString() {
   String historyOperation = history.getOperationHistory(correctPuzzle);
   if (historyOperation != null && !historyOperation.isEmpty()) {
     return historyOperation;
   } else {
     return "";
   }
 }
 public synchronized void accessed(TypeNameMatch info) {
   // Fetching the timestamp might not be cheap (remote file system
   // external Jars. So check if we alreay have one.
   if (!fTimestampMapping.containsKey(info)) {
     fTimestampMapping.put(info, new Long(getContainerTimestamp(info)));
   }
   super.accessed(info);
 }
 private void updateGUI() {
   comp.imageChanged(FULL);
   layer.updateIconImage();
   if (imageEdit instanceof ImageAndMaskEdit) {
     layer.getMask().updateIconImage();
   }
   History.notifyMenus(this);
 }
  /**
   * * 移動とその距離をhistoryに加える処理。
   *
   * @param operation
   * @param position
   * @param currentDistance
   * @param currentMaxDistance
   */
  private void move(
      String operation, MovedPosition position, int currentDistance, int currentMaxDistance) {
    String boardStr = board.getBoardString();
    char changedChar = position.getC();
    int oldX = position.getOldX();
    int oldY = position.getOldY();
    int newX = position.getNewX();
    int newY = position.getNewY();
    if (history.getOperationHistory(boardStr) == null) {
      char[][] c = Util.createBoard(width, height, boardStr);
      int newDistance =
          distance.getNewDistance(changedChar, oldX, oldY, newX, newY, currentDistance);
      int newMaxDistance = distance.getMaxDistance(c);

      answerBoard.put(boardStr, newDistance, newMaxDistance);
      history.putHistory(boardStr, operation, newDistance, newMaxDistance);
    }
  }
Exemple #29
0
  @Override
  public void undo() throws CannotUndoException {
    super.undo();

    second.undo();
    first.undo();

    History.notifyMenus(this);
  }
Exemple #30
0
  @Override
  public void redo() throws CannotRedoException {
    super.redo();

    first.redo();
    second.redo();

    History.notifyMenus(this);
  }