protected Set<ToutElement> listeAny(final String namespace, final String targetNamespace) {
   final LinkedHashSet<ToutElement> liste = new LinkedHashSet<ToutElement>();
   if (namespace == null || "".equals(namespace) || "##any".equals(namespace)) {
     for (final WXSElement el : lTousElements)
       if (el.getName() != null && el.getRef() == null && !el.getAbstract()) liste.add(el);
   } else if ("##local".equals(namespace)) {
     for (final WXSElement el : lTousElements) {
       if (el.getName() != null && el.getRef() == null && !el.getAbstract()) {
         final String tns = el.getNamespace();
         if (tns == null || tns.equals(targetNamespace)) liste.add(el);
       }
     }
   } else if ("##other".equals(namespace)) {
     final ArrayList<Element> references = cfg.listeElementsHorsEspace(targetNamespace);
     for (Element ref : references) liste.add(new ElementExterne(ref, cfg));
   } else {
     // liste d'espaces de noms s?par?s par des espaces
     final HashSet<String> espaces = new HashSet<String>(Arrays.asList(namespace.split("\\s")));
     if (espaces.contains("##targetNamespace")) {
       espaces.remove("##targetNamespace");
       espaces.add(targetNamespace);
     }
     if (espaces.contains("##local")) {
       espaces.remove("##local");
       espaces.add("");
     }
     final ArrayList<Element> references = cfg.listeElementsDansEspaces(espaces);
     for (Element ref : references) liste.add(new ElementExterne(ref, cfg));
   }
   return (liste);
 }
 public int longestConsecutive(int[] num) {
   // Start typing your Java solution below
   // DO NOT write main() function
   HashSet<Integer> set = new HashSet<Integer>();
   int max = 0;
   for (int i = 0; i < num.length; i++) {
     set.add(num[i]);
   }
   for (int i = 0; i < num.length; i++) {
     if (set.contains(num[i])) {
       int count1 = 0, count2 = 0;
       while (set.contains(num[i] + 1 + count1)) {
         set.remove(num[i] + 1 + count1);
         count1++;
       }
       while (set.contains(num[i] - 1 - count2)) {
         set.remove(num[i] - 1 - count2);
         count2++;
       }
       max = Math.max(max, count1 + count2 + 1);
       set.remove(num[i]);
     }
   }
   return max;
 }
    /** {@inheritDoc} */
    @Override
    public void rewriteAST(CompilationUnitRewrite cuRewrite) throws CoreException {
      ASTRewrite rewrite = cuRewrite.getASTRewrite();

      TextEditGroup group =
          createTextEditGroup(
              FixMessages.INSTANCE.UnusedCodeFix_RemoveCast_description(), cuRewrite);

      while (fUnnecessaryCasts.size() > 0) {
        CastExpression castExpression = fUnnecessaryCasts.iterator().next();
        fUnnecessaryCasts.remove(castExpression);
        CastExpression down = castExpression;
        while (fUnnecessaryCasts.contains(down.getExpression())) {
          down = (CastExpression) down.getExpression();
          fUnnecessaryCasts.remove(down);
        }

        Expression expression = down.getExpression();
        ASTNode move = rewrite.createMoveTarget(expression);

        CastExpression top = castExpression;
        while (fUnnecessaryCasts.contains(top.getParent())) {
          top = (CastExpression) top.getParent();
          fUnnecessaryCasts.remove(top);
        }

        ASTNode toReplace = top;
        if (top.getParent() instanceof ParenthesizedExpression
            && !NecessaryParenthesesChecker.needsParentheses(
                expression, top.getParent(), top.getLocationInParent())) {
          toReplace = top.getParent();
        }
        rewrite.replace(toReplace, move, group);
      }
    }
    /** {@inheritDoc} */
    public void rewriteAST(CompilationUnitRewrite cuRewrite, List textEditGroups)
        throws CoreException {
      TextEditGroup group =
          createTextEditGroup(FixMessages.ExpressionsFix_removeUnnecessaryParenthesis_description);
      textEditGroups.add(group);

      ASTRewrite rewrite = cuRewrite.getASTRewrite();

      while (fExpressions.size() > 0) {
        ParenthesizedExpression parenthesizedExpression =
            (ParenthesizedExpression) fExpressions.iterator().next();
        fExpressions.remove(parenthesizedExpression);
        ParenthesizedExpression down = parenthesizedExpression;
        while (fExpressions.contains(down.getExpression())) {
          down = (ParenthesizedExpression) down.getExpression();
          fExpressions.remove(down);
        }

        ASTNode move = rewrite.createMoveTarget(down.getExpression());

        ParenthesizedExpression top = parenthesizedExpression;
        while (fExpressions.contains(top.getParent())) {
          top = (ParenthesizedExpression) top.getParent();
          fExpressions.remove(top);
        }

        rewrite.replace(top, move, group);
      }
    }
Exemple #5
0
 public void excludeMessagesFrom(JoinGraph.Node n) {
   JoinGraph.Arc arc = node.arcs.get(n);
   for (MessageFunction mf : arc.getInMessage(node)) {
     if (functions.contains(mf)) functions.remove(mf);
   }
   for (BeliefNode bn : arc.getCPTInMessage(node)) {
     if (cpts.contains(bn)) functions.remove(bn);
   }
 }
  /*
     Students: Uncomment this test once you've written the code to create the Location
     table.  Note that you will have to have chosen the same column names that I did in
     my solution for this test to compile, so if you haven't yet done that, this is
     a good time to change your column names to match mine.

     Note that this only tests that the Location table has the correct columns, since we
     give you the code for the weather table.  This test does not look at the
  */
  public void testCreateDb() throws Throwable {
    // build a HashSet of all of the table names we wish to look for
    // Note that there will be another table in the DB that stores the
    // Android metadata (db version information)
    final HashSet<String> tableNameHashSet = new HashSet<String>();
    tableNameHashSet.add(WeatherContract.LocationEntry.TABLE_NAME);
    tableNameHashSet.add(WeatherContract.WeatherEntry.TABLE_NAME);

    mContext.deleteDatabase(WeatherDbHelper.DATABASE_NAME);
    SQLiteDatabase db = new WeatherDbHelper(this.mContext).getWritableDatabase();
    assertEquals(true, db.isOpen());

    // have we created the tables we want?
    Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);

    assertTrue(
        "Error: This means that the database has not been created correctly", c.moveToFirst());

    // verify that the tables have been created
    do {
      tableNameHashSet.remove(c.getString(0));
    } while (c.moveToNext());

    // if this fails, it means that your database doesn't contain both the location entry
    // and weather entry tables
    assertTrue(
        "Error: Your database was created without both the location entry and weather entry tables",
        tableNameHashSet.isEmpty());

    // now, do our tables contain the correct columns?
    c = db.rawQuery("PRAGMA table_info(" + WeatherContract.LocationEntry.TABLE_NAME + ")", null);

    assertTrue(
        "Error: This means that we were unable to query the database for table information.",
        c.moveToFirst());

    // Build a HashSet of all of the column names we want to look for
    final HashSet<String> locationColumnHashSet = new HashSet<String>();
    locationColumnHashSet.add(WeatherContract.LocationEntry._ID);
    locationColumnHashSet.add(WeatherContract.LocationEntry.COLUMN_CITY_NAME);
    locationColumnHashSet.add(WeatherContract.LocationEntry.COLUMN_COORD_LAT);
    locationColumnHashSet.add(WeatherContract.LocationEntry.COLUMN_COORD_LONG);
    locationColumnHashSet.add(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING);

    int columnNameIndex = c.getColumnIndex("name");
    do {
      String columnName = c.getString(columnNameIndex);
      locationColumnHashSet.remove(columnName);
    } while (c.moveToNext());

    // if this fails, it means that your database doesn't contain all of the required location
    // entry columns
    assertTrue(
        "Error: The database doesn't contain all of the required location entry columns",
        locationColumnHashSet.isEmpty());
    db.close();
  }
Exemple #7
0
 public void subtractCluster(Cluster c2) {
   // deletes all functions and arcs of the cluster that are also in
   // cluster c2
   for (BeliefNode n : ((HashSet<BeliefNode>) c2.cpts.clone())) { // TODO
     // nonsense
     cpts.remove(n);
   }
   for (MessageFunction m : ((HashSet<MessageFunction>) c2.functions.clone())) {
     functions.remove(m);
   }
 }
Exemple #8
0
  /** java.util.HashSet#remove(java.lang.Object) */
  public void test_removeLjava_lang_Object() {
    // Test for method boolean java.util.HashSet.remove(java.lang.Object)
    int size = hs.size();
    hs.remove(new Integer(98));
    assertTrue("Failed to remove element", !hs.contains(new Integer(98)));
    assertTrue("Failed to decrement set size", hs.size() == size - 1);

    HashSet s = new HashSet();
    s.add(null);
    assertTrue("Cannot handle null", s.remove(null));
    assertFalse(hs.remove(new Integer(-98)));
  }
Exemple #9
0
  /**
   * performs an OR conjunction with the capabilities of the given Capabilities object and updates
   * itself
   *
   * @param c the capabilities to OR with
   */
  public void or(Capabilities c) {
    for (Capability cap : Capability.values()) {
      // capability
      if (handles(cap) || c.handles(cap)) m_Capabilities.add(cap);
      else m_Capabilities.remove(cap);
      // dependency
      if (hasDependency(cap) || c.hasDependency(cap)) m_Dependencies.add(cap);
      else m_Dependencies.remove(cap);
    }

    if (c.getMinimumNumberInstances() < getMinimumNumberInstances())
      setMinimumNumberInstances(c.getMinimumNumberInstances());
  }
  /**
   * Try to remove a thread from the executor. Perhaps counterintuitively, this method can add a new
   * thread if removing the specified thread leaves the Executor with no active threads and tasks
   * remaining in the scheduler. This condition should be rare--it can only happen if all active
   * threads are trying to end while new items are being added to the schedule.
   *
   * @param thread The thread to remove
   * @return true if it could be removed, false otherwise
   */
  private boolean removeThread(JobThread thread) {
    synchronized (poolLock) {
      if (activePool.remove(thread)) {
        // If all of our threads have ended at once, make sure something remains to handle any
        // existing jobs
        // DEV_LOG.debug("Removing thread " + thread + " down to " + activePool.size());
        checkActive();
        return true;
      }

      return inactivePool.remove(thread);
    }
  }
Exemple #11
0
  public Row join(Row pRow, String pField) {
    // dbgMsg("Join!");
    RowFormat newFormat = mFormat.join(pRow.mFormat, pField);
    Row newRow = (Row) newFormat.getRowFactory().makeRow();
    // String[] ourFieldNames = mFormat.getFieldNames();
    // String[] theirFieldNames =pRow.mFormat.getFieldNames();
    // dbgMsg("ourFieldNames="+StringUtils.arrayToString(ourFieldNames, ", "));
    // dbgMsg("theirFieldNames="+StringUtils.arrayToString(theirFieldNames, ", "));

    HashSet ourFields = new HashSet(Arrays.asList(mFormat.getFieldNames()));
    HashSet theirFields = new HashSet(Arrays.asList(pRow.mFormat.getFieldNames()));
    ourFields.remove(pField);
    theirFields.remove(pField);
    HashSet commonFields = new HashSet(ourFields);
    commonFields.retainAll(theirFields);
    ourFields.removeAll(commonFields);
    theirFields.removeAll(commonFields);

    // dbgMsg("join field "+pField);
    // dbgMsg("our fields: "+StringUtils.collectionToString(ourFields, " "));
    // dbgMsg("their fields: "+StringUtils.collectionToString(theirFields, " "));
    // dbgMsg("common fields: "+StringUtils.collectionToString(commonFields, " "));

    // copy join field
    newRow.set(pField, get(pField)); // (copied arbitrarily from...us, as should be same!)

    // copy our fields
    Iterator ourFieldsIter = ourFields.iterator();
    while (ourFieldsIter.hasNext()) {
      String field = (String) ourFieldsIter.next();
      newRow.set(field, (get(field)));
    }

    // copy their fields
    Iterator theirFieldsIter = theirFields.iterator();
    while (theirFieldsIter.hasNext()) {
      String field = (String) theirFieldsIter.next();
      newRow.set(field, (pRow.get(field)));
    }

    // copy common fields (renaming fields becomes necessary)
    Iterator commonFieldsIter = commonFields.iterator();
    while (commonFieldsIter.hasNext()) {
      String field = (String) commonFieldsIter.next();
      newRow.set(field + "1", (get(field)));
      newRow.set(field + "2", (pRow.get(field)));
    }

    return newRow;
  }
Exemple #12
0
  /**
   * performs an AND conjunction with the capabilities of the given Capabilities object and updates
   * itself
   *
   * @param c the capabilities to AND with
   */
  public void and(Capabilities c) {
    for (Capability cap : Capability.values()) {
      // capability
      if (handles(cap) && c.handles(cap)) m_Capabilities.add(cap);
      else m_Capabilities.remove(cap);
      // dependency
      if (hasDependency(cap) && c.hasDependency(cap)) m_Dependencies.add(cap);
      else m_Dependencies.remove(cap);
    }

    // minimum number of instances that both handlers need at least to work
    if (c.getMinimumNumberInstances() > getMinimumNumberInstances())
      setMinimumNumberInstances(c.getMinimumNumberInstances());
  }
  boolean _solveSudoku(char[][] board) {
    int mx = board.length;
    int my = board[0].length;

    int x, y;

    for (x = 0; x < mx; x++) {
      for (y = 0; y < my; y++) {

        if (board[x][y] == '.') {
          int _x, _y;
          HashSet<Character> val = new HashSet<Character>(VALID);

          for (_y = 0; _y < my; _y++) val.remove(board[x][_y]);

          for (_x = 0; _x < mx; _x++) val.remove(board[_x][y]);

          int sx = x / 3 * 3;
          int sy = y / 3 * 3;
          for (int offset = 0; offset < 9; offset++) {
            int ox = offset % 3;
            int oy = offset / 3;

            val.remove(board[sx + ox][sy + oy]);
          }

          for (char c : val) {
            board[x][y] = c;

            if (isValidSudoku(board)) {
              // try next '.'
              if (_solveSudoku(board)) {
                return true;
              }

              // try another number
            }

            board[x][y] = '.';
          }

          // board[x][y] is '.' return false to fail fast
          return false;
        }
      }
    }

    return true;
  }
Exemple #14
0
  private Authentication fresh(Authentication authentication, ServletRequest req) {
    HttpServletRequest request = (HttpServletRequest) req;

    HttpSession session = request.getSession(false);

    if (session != null) {
      SessionRegistry sessionRegistry =
          (SessionRegistry) SpringBeanUtil.getBeanByName("sessionRegistry");
      SessionInformation info = sessionRegistry.getSessionInformation(session.getId());

      if (info != null) {
        // Non-expired - update last request date/time
        Object principal = info.getPrincipal();
        if (principal instanceof org.springframework.security.core.userdetails.User) {
          org.springframework.security.core.userdetails.User userRefresh =
              (org.springframework.security.core.userdetails.User) principal;
          ServletContext sc = session.getServletContext();
          HashSet<String> unrgas = springSecurityService.getUsersNeedRefreshGrantedAuthorities();
          if (unrgas.size() > 0) {
            HashSet<String> loginedUsernames = new HashSet<String>();

            List<Object> loggedUsers = sessionRegistry.getAllPrincipals();
            for (Object lUser : loggedUsers) {
              if (lUser instanceof org.springframework.security.core.userdetails.User) {
                org.springframework.security.core.userdetails.User u =
                    (org.springframework.security.core.userdetails.User) lUser;
                loginedUsernames.add(u.getUsername());
              }
            }
            // 清除已经下线的但需要刷新的username
            for (Iterator iterator = unrgas.iterator(); iterator.hasNext(); ) {
              String unrgs = (String) iterator.next();
              if (!loginedUsernames.contains(unrgs)) {
                iterator.remove();
              }
            }
            if (unrgas.contains(userRefresh.getUsername())) {
              // 如果需要刷新权限的列表中有当前的用户,刷新登录用户权限
              // FIXME:与springSecurityServiceImpl中的功能,相重复,需重构此方法和springSecurityServiceImpl
              MyJdbcUserDetailsManager mdudm =
                  (MyJdbcUserDetailsManager)
                      SpringBeanUtil.getBeanByType(MyJdbcUserDetailsManager.class);
              SecurityContextHolder.getContext()
                  .setAuthentication(
                      new UsernamePasswordAuthenticationToken(
                          userRefresh,
                          userRefresh.getPassword(),
                          mdudm.getUserAuthorities(userRefresh.getUsername())));
              session.setAttribute(
                  HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                  SecurityContextHolder.getContext());
              unrgas.remove(userRefresh.getUsername());
              return SecurityContextHolder.getContext().getAuthentication();
            }
          }
        }
      }
    }
    return authentication;
  }
Exemple #15
0
    @Override
    public void layerRemoved(LayerCollectionEvent e) {
      HashSet<ILayer> newSelection = new HashSet<ILayer>();
      newSelection.addAll(Arrays.asList(selectedLayers));
      ILayer[] affected = e.getAffected();
      for (final ILayer layer : affected) {
        // Check active
        if (activeLayer == layer) {
          setActiveLayer(null);
        }

        // Check selection
        newSelection.remove(layer);
        layer.removeLayerListenerRecursively(openerListener);
        if (isOpen()) {
          try {
            layer.close();
          } catch (LayerException e1) {
            LOGGER.warn(I18N.tr("Cannot close layer {0}", layer.getName()), e1);
          }
        }
      }

      setSelectedLayers(newSelection.toArray(new ILayer[newSelection.size()]));
      // checkIfHasToResetSRID();
    }
  private void removeSelections(boolean all) {
    List<Object[]> toUnselect = new ArrayList<Object[]>();
    int[] rows;

    if (all) {
      int rowCount = individualsSTP.getTable().getModel().getRowCount();
      rows = new int[rowCount];
      for (int i = 0; i < rowCount; i++) {
        rows[i] = i;
      }
    } else {
      rows = individualsSTP.getTable().getSelectedRows();
    }

    for (int r : rows) {
      int realRow = individualsSTP.getActualRowAt(r);
      Object[] o = individualsRetriever.getIndividuals().get(realRow);
      toUnselect.add(o);
    }

    for (int i : rows) {
      selectedRows.remove(individualsSTP.getActualRowAt(i));
    }

    for (Object[] s : toUnselect) {
      selectedHospitalIDs.remove(s[INDEX_OF_HOSPITAL_ID].toString());
    }

    refreshSelectionIndicator();
  }
  public static boolean removeFixedNPCSpawn(Player p, String npcName, NPCHandler handle) {
    if (!FileLocator.doesNPCNameExist(npcName)) {
      if (p != null) {
        QuestX.logChat(p, ChatColor.RED + LocaleBundle.getString("no_npc_name"));
      }
      return false;
    } else {
      if (!fixedSpawns.containsKey(npcName)) {
        if (p != null) {
          QuestX.logChat(p, LocaleBundle.getString("no_fixed_spawn"));
        }
        return false;
      } else {
        SimpleNPC rem = handle.getSimpleNPCByName(npcName);
        if (rem != null) {
          rem.destroyNPCObject();
        }

        loader.read();
        loader.clearWriteArray();
        for (SyncWrapper wrap : loader.getReadableData()) {
          // copy all the data read, except the npc to remove
          if (!wrap.getTag().equalsIgnoreCase(npcName)) {
            loader.add(wrap);
          }
        }
        loader.write();
        loader.clearReadArray();
        loader.clearWriteArray();

        fixedSpawns.remove(npcName);

        io.read();
        io.clearWriteArray();
        io.clearReadArray();
        for (SyncWrapper wrap : loader.getReadableData()) {
          // copy all the data read, except the npc to remove
          if (!wrap.getTag().equalsIgnoreCase(npcName)) {
            io.add(wrap);
          }
        }
        io.write();

        if (p != null) {
          QuestX.logChat(
              p, LocaleBundle.getString("t_fs") + npcName + LocaleBundle.getString("was_rem"));
          if (presetNPCs.contains(npcName)) {
            QuestX.logChat(
                p, LocaleBundle.getString("t_pp") + npcName + LocaleBundle.getString("was_rem"));
            presetNPCs.remove(npcName);
          }
        }

        FixedSpawnsDisplay.updateSoftReference();
        PresetPathsDisplay.updateSoftReference();

        return true;
      }
    }
  }
 private HashSet<Integer> getAAStoreNewIds(OperandStack stack) {
   int currentSizeOfStack = stack.getCurrentSize();
   GCType type = (GCType) stack.get(currentSizeOfStack - 3);
   HashSet<Integer> toRet = type.getAllNewIds();
   toRet.remove(-1);
   return toRet;
 }
Exemple #19
0
  /**
   * Remove a mouse listener that will no longer be notified
   *
   * @param listener The listen to be removed
   */
  public void removeMouseListener(MouseListener listener) {
    mouseListeners.remove(listener);

    if (!controllerListeners.contains(listener) && !keyListeners.contains(listener)) {
      allListeners.remove(listener);
    }
  }
  /**
   * The given name has been modified or removed in this context. Invalidate all local value
   * computations and listeners that depend on this name.
   */
  public void invalidate(String name, int eventType, Object oldValue, Set<Scheduled> scheduled) {
    ContextChangeEvent event = new ContextChangeEvent(this, eventType, null, name, oldValue);
    ValueComputation computation = localValueComputations.get(name);
    if (computation != null) {
      if (computation.shouldRemove(event)) {
        localValueComputations.remove(name);
        Collection<HashSet<Computation>> allListeners = listeners.values();
        for (HashSet<Computation> group : allListeners) {
          group.remove(computation);
        }
      }
      computation.handleInvalid(event, scheduled);
    }
    HashSet<Computation> namedComputations = listeners.get(name);
    if (namedComputations != null) {
      for (Computation listener : namedComputations) {
        listener.handleInvalid(event, scheduled);
      }
    }

    // invalidate this name in child contexts
    for (EclipseContext childContext : getChildren()) {
      childContext.invalidate(name, eventType, oldValue, scheduled);
    }
  }
Exemple #21
0
  public ArrayList<SchedulePiece> toSchedulePieces() {

    if (isScheduleUpdated) {
      // schedulePieces = null;
      schedulePieces = new ArrayList<SchedulePiece>();
      isScheduleUpdated = false;

      // generate initial or additional schedule pieces
      Collections.sort(scheduleRecords);
      int previousTime = scheduleRecords.get(0).time;
      HashSet<Integer> hset = new HashSet<Integer>();
      hset.add(scheduleRecords.get(0).scIndex);

      for (int index = 1; index < scheduleRecords.size(); index++) {
        ScheduleRecord r = scheduleRecords.get(index);

        // found the new piece?
        if (r.time != previousTime) {

          // finish and save the old piece
          // schedulePieces.add(new SchedulePiece(r.time, (Integer[]) hset.toArray()));
          schedulePieces.add(new SchedulePiece(previousTime, hset.toArray()));
          previousTime = r.time;
        }

        if (r.isStart) hset.add(r.scIndex);
        else hset.remove(r.scIndex);
      }

      // last piece
      schedulePieces.add(new SchedulePiece(previousTime, hset.toArray()));
    }

    return schedulePieces;
  }
  /** Tests all columns in {@code Videos} table were created */
  @Test
  public void videosTableShouldBeCreated_ReturnsTrue() {
    // Holds column names of tables
    final HashSet<String> tableColumnSet = new HashSet<>();

    // Test all columns of Videos table was created
    tableColumnSet.add(ArticleContract.Videos._ID);
    tableColumnSet.add(ArticleContract.VideosColumns.VIDEO_ID);
    tableColumnSet.add(ArticleContract.VideosColumns.ARTICLE_ID);
    tableColumnSet.add(ArticleContract.VideosColumns.URL);
    tableColumnSet.add(ArticleContract.VideosColumns.CAPTION);
    tableColumnSet.add(ArticleContract.VideosColumns.DESCRIPTION);
    tableColumnSet.add(ArticleContract.VideosColumns.THUMBNAIL_URL);
    tableColumnSet.add(ArticleContract.VideosColumns.SIZE_FORMAT);

    // Gets info of Videos table
    cursor = db.rawQuery("PRAGMA table_info(" + ArticleDatabase.Tables.VIDEOS + ")", null);
    assertTrue("Error: Can not query Videos table info.", cursor.moveToFirst());

    int columnNameIndex = cursor.getColumnIndex("name");
    do {
      String columnName = cursor.getString(columnNameIndex);
      tableColumnSet.remove(columnName);
    } while (cursor.moveToNext());
    assertTrue(
        "Error: The database doesn't contain all of the required Videos " + "table columns.",
        tableColumnSet.isEmpty());
  }
  @Override
  public BooleanMatrix combineRow(
      BooleanMatrix row, BooleanMatrix bm, BooleanMatrix basis, double onesWeight) {

    int dim = basis.getHeight();
    BooleanMatrix combination = new BooleanMatrix(1, dim);
    HashSet<Integer> remainingIndices = new HashSet<Integer>();
    for (int i = 0; i < dim; i++) {
      remainingIndices.add(i);
    }
    Cover cover = new Cover(row.getWidth(), onesWeight);

    while (true) {
      double maxUsefulness = Double.NEGATIVE_INFINITY;
      int bestIndex = -1;
      for (int i : remainingIndices) {
        BooleanMatrix basisRow = basis.getRow(i);
        double usefulness = usefulness(cover, row, basisRow);
        if (usefulness > maxUsefulness) {
          maxUsefulness = usefulness;
          bestIndex = i;
        }
      }
      if (maxUsefulness > 0) {
        remainingIndices.remove(bestIndex);
        cover.include(basis.getRow(bestIndex));
        combination.update(bestIndex, TRUE);
      } else {
        break;
      }
    }

    return combination;
  }
Exemple #24
0
  /**
   * Get all vertical and horizontal moves
   *
   * @param starting - starting coordinate
   * @return all valid vertical and horizontal moves
   */
  public HashSet<Coordinate> VHMoves(Coordinate start) {
    HashSet<Coordinate> moves = new HashSet<Coordinate>();
    int x = start.getXCoordinate();
    int y = start.getYCoordinate();
    // get north
    while (y >= 0) {
      moves.add(new Coordinate(start.getXCoordinate(), y));
      y--;
    }
    x = start.getXCoordinate();
    y = start.getYCoordinate();
    // get south
    while (y < this.y) {
      moves.add(new Coordinate(start.getXCoordinate(), y));
      y++;
    }
    x = start.getXCoordinate();
    y = start.getYCoordinate();
    // get east
    while (x < this.x) {
      moves.add(new Coordinate(x, start.getYCoordinate()));
      x++;
    }
    x = start.getXCoordinate();
    y = start.getYCoordinate();
    // get west
    while (x >= 0) {
      moves.add(new Coordinate(x, start.getYCoordinate()));
      x--;
    }
    moves.remove(start); // remove current location

    return moves;
  }
 public String[] getjavaVMs() {
   // get the internal VM name
   // App Clients never run on the internal VM
   Set res = new HashSet();
   if (!(this instanceof AppClientModuleMdl)) {
     // res.addAll(findNames("j2eeType=JVM,name=" + MOAgentFactory.getAgent().getJVMId()));
   }
   // get the external VM names
   Iterator vmNames = externalVMs.iterator();
   while (vmNames.hasNext()) {
     String vmName = (String) vmNames.next();
     Set x = findNames("j2eeType=JVM,name=" + vmName);
     if (x.size() > 0) {
       res.addAll(x);
     } else {
       // no longer an active VM
       externalVMs.remove(vmName);
       vmNames = externalVMs.iterator();
     }
   }
   Iterator it = res.iterator();
   String[] vms = new String[res.size()];
   int i = 0;
   while (it.hasNext()) {
     vms[i++] = ((ObjectName) it.next()).toString();
   }
   return vms;
 }
  /** Tests all expected tables were created. */
  @Test
  public void expectedTablesShouldBeCreated_ReturnsTrue() {
    final HashSet<String> tableNameHashSet = new HashSet<>();
    tableNameHashSet.add(ArticleDatabase.Tables.ARTICLES);
    tableNameHashSet.add(ArticleDatabase.Tables.LINKED_ARTICLES);
    tableNameHashSet.add(ArticleDatabase.Tables.REFERENCE_ARTICLES);
    tableNameHashSet.add(ArticleDatabase.Tables.CATEGORIES);
    tableNameHashSet.add(ArticleDatabase.Tables.PHOTOS);
    tableNameHashSet.add(ArticleDatabase.Tables.VIDEOS);

    cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);

    assertTrue("Error: The database has not been created correctly", cursor.moveToFirst());

    // Verify that the tables have been created
    do {
      tableNameHashSet.remove(cursor.getString(0));
    } while (cursor.moveToNext());

    assertTrue(
        "Error: The database was created but it did not create all expected tables",
        tableNameHashSet.isEmpty());

    cursor.close();
  }
  private void handleReparent(EclipseContext newParent, Set<Scheduled> scheduled) {
    // TBD should we lock waiting list while doing reparent?
    // Add "boolean inReparent" on the root context and process right away?
    processWaiting();
    // 1) everybody who depends on me: I need to collect combined list of names injected
    Set<String> usedNames = new HashSet<String>();
    collectDependentNames(usedNames);

    // 2) for each used name:
    for (Iterator<String> i = usedNames.iterator(); i.hasNext(); ) {
      String name = i.next();
      if (localValues.containsKey(name)) continue; // it is a local value
      Object oldValue = get(name);
      Object newValue = (newParent != null) ? newParent.get(name) : null;
      if (oldValue != newValue) invalidate(name, ContextChangeEvent.ADDED, oldValue, scheduled);
    }

    ContextChangeEvent event =
        new ContextChangeEvent(this, ContextChangeEvent.ADDED, null, null, null);
    for (Computation computation : localValueComputations.values()) {
      Collection<HashSet<Computation>> allListeners = listeners.values();
      for (HashSet<Computation> group : allListeners) {
        group.remove(computation);
      }
      computation.handleInvalid(event, scheduled);
    }
    localValueComputations.clear();
  }
  /**
   * Run some random insertions/ deletions and compare the results against <code>java.util.HashSet
   * </code>.
   */
  @Test
  public void testAgainstHashMap() {
    final java.util.Random rnd = new Random(0xBADCAFE);
    final java.util.HashSet<KType> other = new java.util.HashSet<KType>();

    for (int size = 1000; size < 20000; size += 4000) {
      other.clear();
      this.set.clear();

      for (int round = 0; round < size * 20; round++) {
        final KType key = cast(rnd.nextInt(size));

        if (rnd.nextBoolean()) {
          other.add(key);
          this.set.add(key);

          Assert.assertTrue(this.set.contains(key));
        } else {
          Assert.assertTrue(
              "size= " + size + ", round = " + round, other.remove(key) == this.set.remove(key));
        }

        Assert.assertEquals(other.size(), this.set.size());
      }
    }
  }
Exemple #29
0
  public String echo() {
    if (null == connectedVertexSets) {
      return "Uninitialized.\n";
    }

    final StringBuilder str = new StringBuilder();
    final Set<Integer> vid = connectedVertexSets.keySet();
    final HashSet<Integer> eid = new HashSet<Integer>(connectedEdgeSets.keySet());

    for (final Integer id : vid) {
      str.append(id + ":\n");
      str.append(" - " + connectedVertexSets.get(id) + "\n");
      final Set<DefaultWeightedEdge> es = connectedEdgeSets.get(id);
      if (es == null) {
        str.append(" - no matching edges!\n");
      } else {
        str.append(" - " + es + "\n");
      }
      eid.remove(id);
    }

    if (eid.isEmpty()) {
      str.append("No remaining edges ID.\n");
    } else {
      str.append("Found non-matching edge IDs!\n");
      for (final Integer id : eid) {
        str.append(id + ":\n");
        str.append(" - " + connectedEdgeSets.get(id) + "\n");
      }
    }

    return str.toString();
  }
Exemple #30
0
  /**
   * Remove a key listener that will no longer be notified
   *
   * @param listener The listen to be removed
   */
  public void removeKeyListener(KeyListener listener) {
    keyListeners.remove(listener);

    if (!mouseListeners.contains(listener) && !controllerListeners.contains(listener)) {
      allListeners.remove(listener);
    }
  }