/**
   * Refresh the local cache of Flags by loading all enabled Flags from the database Also refresh
   * the privilege cache Note that flags and tags must be eagerly loaded for this to work
   */
  private void refreshCache() {
    // get the enabled flags and all tags for the flag and tag caches
    flagCache = dao.getAllEnabledFlags();
    tagCache = getAllTags();

    // alphabetize the flags, and sort by by priority ranking so that result sets are returned that
    // way
    Collections.sort(flagCache, new FlagAlphaComparator());
    Collections.sort(flagCache, new FlagPriorityComparator());

    // get the privileges associate with the patient flags default user for the privileges cache
    try {
      Context.addProxyPrivilege("View Users");
      String username =
          Context.getAdministrationService().getGlobalProperty("patientflags.username");
      User user = Context.getUserService().getUserByUsername(username);

      if (user != null) {
        if (user.isSuperUser()) { // need to explicitly get all privileges if user is a super user
          privilegeCache = Context.getUserService().getAllPrivileges();
        } else {
          privilegeCache = user.getPrivileges();
        }
      } else {
        privilegeCache = null;
      }
    } finally {
      Context.removeProxyPrivilege("View Users");
    }

    // set the initialized flag to true
    isInitialized = true;
  }
 private List<SchemaTransaction> generateTableTransactions(
     Database sourceDatabase, Database shadowDatabase) {
   List<SchemaTransaction> schemaTransactionList = new ArrayList<SchemaTransaction>();
   if (shadowDatabase == null) {
     for (Table table : sourceDatabase.getTableList()) {
       schemaTransactionList.add(new SchemaTransaction(table, TransactionType.INSERT));
       schemaTransactionList.addAll(generateColumnTransactions(table, null));
     }
   } else {
     Collections.sort(sourceDatabase.getTableList());
     Collections.sort(shadowDatabase.getTableList());
     for (Table table : sourceDatabase.getTableList()) {
       if (!shadowDatabase.getTableList().contains(table)) {
         table.setDatabase(shadowDatabase);
         schemaTransactionList.add(new SchemaTransaction(table, TransactionType.INSERT));
         schemaTransactionList.addAll(generateColumnTransactions(table, null));
       } else {
         Table shadowTable =
             shadowDatabase.getTableList().get(shadowDatabase.getTableList().indexOf(table));
         if (!table.getPk().equals(shadowTable.getPk())) {
           table.setId(shadowTable.getId());
           schemaTransactionList.add(new SchemaTransaction(table, TransactionType.UPDATE));
         }
         schemaTransactionList.addAll(generateColumnTransactions(table, shadowTable));
       }
     }
     for (Table table : shadowDatabase.getTableList()) {
       if (!sourceDatabase.getTableList().contains(table)) {
         schemaTransactionList.add(new SchemaTransaction(table, TransactionType.DELETE));
       }
     }
   }
   return schemaTransactionList;
 }
Esempio n. 3
0
  /**
   * Given a new LimitOrder, it will replace and old matching limit order in the orderbook or simply
   * get added. Finally, it is sorted.
   *
   * @param limitOrder
   */
  public void update(LimitOrder limitOrder) {

    if (limitOrder.getType().equals(OrderType.ASK)) {

      Iterator<LimitOrder> it = asks.iterator();
      while (it.hasNext()) {
        LimitOrder order = it.next();
        if (order.getLimitPrice().compareTo(limitOrder.getLimitPrice())
            == 0) { // they are equal. found it!
          it.remove();
          break;
        }
      }
      asks.add(limitOrder); // just add it
      Collections.sort(asks); // finally sort

    } else {

      Iterator<LimitOrder> it = bids.iterator();
      while (it.hasNext()) {
        LimitOrder order = it.next();
        if (order.getLimitPrice().compareTo(limitOrder.getLimitPrice())
            == 0) { // they are equal. found it!
          it.remove();
          break;
        }
      }
      bids.add(limitOrder); // just add it
      Collections.sort(bids); // finally sort
    }
  }
  private static void checkResult(
      String[] fileNames,
      final ArrayList<PsiFile> filesList,
      int[] starts,
      final IntArrayList startsList,
      int[] ends,
      final IntArrayList endsList) {
    List<SearchResult> expected = new ArrayList<SearchResult>();
    for (int i = 0; i < fileNames.length; i++) {
      String fileName = fileNames[i];
      expected.add(
          new SearchResult(
              fileName, i < starts.length ? starts[i] : -1, i < ends.length ? ends[i] : -1));
    }

    List<SearchResult> actual = new ArrayList<SearchResult>();
    for (int i = 0; i < filesList.size(); i++) {
      PsiFile psiFile = filesList.get(i);
      actual.add(
          new SearchResult(
              psiFile.getName(),
              i < starts.length ? startsList.get(i) : -1,
              i < ends.length ? endsList.get(i) : -1));
    }

    Collections.sort(expected);
    Collections.sort(actual);

    assertEquals("Usages don't match", expected, actual);
  }
Esempio n. 5
0
  /**
   * Prints the genetics of this Brain to a String.
   *
   * @return a String representation of the underlying neural network
   */
  public String toString() {
    // TODO: Make this and DNA use Braincraft.listToString()
    // First line
    String output = "genomestart " + ID + "\n";

    // Node list
    ArrayList<NNode> nodes = new ArrayList<NNode>();
    nodes.addAll(nodemap.values());
    Collections.sort(nodes);
    output += Braincraft.listToString(nodes);

    // Gene list
    Set<Gene> genes = new HashSet<Gene>();
    for (ArrayList<Gene> arl : connections.values()) {
      for (Gene g : arl) {
        genes.add(g);
      }
    }
    ArrayList<Gene> allgenes = new ArrayList<Gene>();
    allgenes.addAll(genes);
    Collections.sort(allgenes);
    output += Braincraft.listToString(allgenes);

    // Last line
    output += "genomeend" + "\n";

    return output;
  }
  private void initParams() {
    WebElement dateSlot = getDriver().findElement(By.className("v-datecellslot"));
    int dateSlotWidth = dateSlot.getSize().getWidth();
    noOverlapWidth = dateSlotWidth;
    oneOverlapWidth = dateSlotWidth / 2;
    twoOverlapsWidth = dateSlotWidth / 3;

    Comparator<WebElement> startTimeComparator =
        new Comparator<WebElement>() {
          @Override
          public int compare(WebElement e1, WebElement e2) {
            int e1Top = e1.getLocation().getY();
            int e2Top = e2.getLocation().getY();
            return e1Top - e2Top;
          }
        };

    List<WebElement> eventElements =
        getDriver().findElements(By.className("v-calendar-event-content"));
    Collections.sort(eventElements, startTimeComparator);
    firstEvent = eventElements.get(0);
    secondEvent = eventElements.get(1);
    thirdEvent = eventElements.get(2);

    List<WebElement> resizeBottomElements =
        getDriver().findElements(By.className("v-calendar-event-resizebottom"));
    Collections.sort(resizeBottomElements, startTimeComparator);
    firstEventBottomResize = resizeBottomElements.get(0);
    secondEventBottomResize = resizeBottomElements.get(1);
    thirdEventBottomResize = resizeBottomElements.get(2);
  }
Esempio n. 7
0
  /**
   * Get the atoms in the target molecule that match the query pattern.
   *
   * <p>Since there may be multiple matches, the return value is a List of List objects. Each List
   * object contains the unique set of indices of the atoms in the target molecule, that match the
   * query pattern
   *
   * @return A List of List of atom indices in the target molecule
   */
  @TestMethod("testUniqueQueries")
  public List<List<Integer>> getUniqueMatchingAtoms() {
    List<List<Integer>> ret = new ArrayList<List<Integer>>();
    for (List<Integer> atomMapping : matchingAtoms) {
      Collections.sort(atomMapping);

      // see if this sequence of atom indices is present
      // in the return container
      boolean present = false;
      for (List<Integer> r : ret) {
        if (r.size() != atomMapping.size()) continue;
        Collections.sort(r);
        boolean matches = true;
        for (int i = 0; i < atomMapping.size(); i++) {
          int index1 = atomMapping.get(i);
          int index2 = r.get(i);
          if (index1 != index2) {
            matches = false;
            break;
          }
        }
        if (matches) {
          present = true;
          break;
        }
      }
      if (!present) ret.add(atomMapping);
    }
    return ret;
  }
Esempio n. 8
0
  private static void testComp() {

    // ラムダ
    Collections.sort(strList, (first, second) -> Integer.compare(first.length(), second.length()));

    // 関数型インターフェース
    BiFunction<String, String, Integer> comp =
        (first, second) -> Integer.compare(first.length(), second.length());

    Comparator<String> lengthComparator =
        (first, second) -> Integer.compare(first.length(), second.length());
    Collections.sort(strList, lengthComparator);

    // 有名クラスの無名インスタンス
    Collections.sort(strList, new LengthComparator());

    // 無名クラスの無名インスタンス
    Collections.sort(
        strList,
        new Comparator<String>() {
          public int compare(String first, String second) {
            return Integer.compare(first.length(), second.length());
          }
        });
  }
Esempio n. 9
0
File: List.java Progetto: pybee/voc
  @org.python.Method(
      __doc__ = "L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*",
      args = {},
      default_args = {"key", "reverse"})
  public org.python.Object sort(final org.python.Object key, org.python.Object reverse) {
    if (key == null && reverse == null) {
      Collections.sort(this.value);
    } else {
      // needs to be final in order to use inside the comparator
      final boolean shouldReverse =
          reverse == null ? false : ((org.python.types.Bool) reverse.__bool__()).value;

      Collections.sort(
          this.value,
          new Comparator<org.python.Object>() {
            @Override
            public int compare(org.python.Object o1, org.python.Object o2) {
              org.python.Object val1 = o1;
              org.python.Object val2 = o2;
              if (key != null) {
                val1 = ((org.python.types.Function) key).invoke(o1, null, null);
                val2 = ((org.python.types.Function) key).invoke(o2, null, null);
              }
              return shouldReverse ? val2.compareTo(val1) : val1.compareTo(val2);
            }
          });
    }
    return org.python.types.NoneType.NONE;
  }
  @Nullable
  public ExcludesConfigurationState getActualState() {
    ensureOldSettingsLoaded();
    if (myExcludedFiles.isEmpty() && myExcludedFrameworks.isEmpty()) {
      return null;
    }

    final ExcludesConfigurationState state = new ExcludesConfigurationState();
    state.getFrameworkTypes().addAll(myExcludedFrameworks);
    Collections.sort(state.getFrameworkTypes(), String.CASE_INSENSITIVE_ORDER);

    for (String typeId : myExcludedFiles.keySet()) {
      final VirtualFilePointerContainer container = myExcludedFiles.get(typeId);
      for (String url : container.getUrls()) {
        state.getFiles().add(new ExcludedFileState(url, typeId));
      }
    }
    Collections.sort(
        state.getFiles(),
        new Comparator<ExcludedFileState>() {
          @Override
          public int compare(ExcludedFileState o1, ExcludedFileState o2) {
            return StringUtil.comparePairs(
                o1.getFrameworkType(), o1.getUrl(), o2.getFrameworkType(), o2.getUrl(), true);
          }
        });
    return state;
  }
  @SynchronizeByAllEntity(entityClass = Site.class)
  @RemoteMethod
  public String execute(final Integer targetSiteId) throws IOException, ServletException {
    userSitesUrl = configStorage.get().getUserSitesUrl();

    final UserManager userManager = new UsersManager().getLogined();

    if (targetSiteId != null) {
      targetSite = userManager.getRight().getSiteRight().getSiteForEdit(targetSiteId).getSite();
      targetSites = Arrays.asList(targetSite);
    } else {
      targetSites =
          persistance.getSites(userManager.getUserId(), SiteAccessLevel.getUserAccessLevels());
      Collections.sort(targetSites, new SiteByTitleComparator());
    }

    sites = new ArrayList<Site>();
    for (final Site site : persistance.getAllSites()) {
      if (site.getType() == SiteType.COMMON
          && site.getSitePaymentSettings().getSiteStatus() == SiteStatus.ACTIVE) {
        sites.add(site);
      }
    }
    Collections.sort(sites, new SiteByTitleComparator());
    return executePage("/site/showRequestContent.jsp");
  }
Esempio n. 12
0
  public static void main(String args[]) {
    int N;
    Scanner in = new Scanner(System.in);
    N = in.nextInt();
    int arr[] = new int[N];
    ArrayList even = new ArrayList();
    ArrayList odd = new ArrayList();
    ArrayList list = new ArrayList();

    for (int i = 0; i < N; i++) {
      arr[i] = in.nextInt();
    }
    int evenSum = 0;
    int oddSum = 0;
    for (int i = 0; i < N; i++) {
      if (arr[i] % 2 == 0) {
        even.add(arr[i]);
        evenSum = evenSum + arr[i];
      } else {
        odd.add(arr[i]);
        oddSum = oddSum + arr[i];
      }
    }
    even.add(evenSum);
    odd.add(oddSum);
    Collections.sort(even);
    Collections.sort(odd);
    list.addAll(even);
    list.addAll(odd);
    Iterator itr = list.iterator();
    while (itr.hasNext()) {
      System.out.println(itr.next());
    }
  }
 StoredWorkflowDefinition convert(AbstractWorkflowDefinition<? extends WorkflowState> definition) {
   StoredWorkflowDefinition resp = new StoredWorkflowDefinition();
   resp.type = definition.getType();
   resp.description = definition.getDescription();
   resp.onError = definition.getErrorState().name();
   Map<String, StoredWorkflowDefinition.State> states = new HashMap<>();
   for (WorkflowState state : definition.getStates()) {
     states.put(
         state.name(),
         new StoredWorkflowDefinition.State(
             state.name(), state.getType().name(), state.getDescription()));
   }
   for (Entry<String, List<String>> entry : definition.getAllowedTransitions().entrySet()) {
     StoredWorkflowDefinition.State state = states.get(entry.getKey());
     for (String targetState : entry.getValue()) {
       state.transitions.add(targetState);
     }
     sort(state.transitions);
   }
   for (Entry<String, WorkflowState> entry : definition.getFailureTransitions().entrySet()) {
     StoredWorkflowDefinition.State state = states.get(entry.getKey());
     state.onFailure = entry.getValue().name();
   }
   resp.states = new ArrayList<>(states.values());
   sort(resp.states);
   return resp;
 }
  /* Scan the files in the new directory, and store them in the filelist.
   * Update the UI by refreshing the list adapter.
   */
  private void loadDirectory(String newdirectory) {
    if (newdirectory.equals("../")) {
      try {
        directory = new File(directory).getParent();
      } catch (Exception e) {
      }
    } else {
      directory = newdirectory;
    }
    SharedPreferences.Editor editor = getPreferences(0).edit();
    editor.putString("lastBrowsedDirectory", directory);
    editor.commit();
    directoryView.setText(directory);

    filelist = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedDirs = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedFiles = new ArrayList<FileUri>();
    if (!newdirectory.equals(rootdir)) {
      String parentDirectory = new File(directory).getParent() + "/";
      Uri uri = Uri.parse("file://" + parentDirectory);
      sortedDirs.add(new FileUri(uri, parentDirectory));
    }
    try {
      File dir = new File(directory);
      File[] files = dir.listFiles();
      if (files != null) {
        for (File file : files) {
          if (file == null) {
            continue;
          }
          String filename = file.getName();
          if (file.isDirectory()) {
            Uri uri = Uri.parse("file://" + file.getAbsolutePath() + "/");
            FileUri fileuri = new FileUri(uri, uri.getPath());
            sortedDirs.add(fileuri);
          } else if (filename.endsWith(".mid")
              || filename.endsWith(".MID")
              || filename.endsWith(".midi")
              || filename.endsWith(".MIDI")) {

            Uri uri = Uri.parse("file://" + file.getAbsolutePath());
            FileUri fileuri = new FileUri(uri, uri.getLastPathSegment());
            sortedFiles.add(fileuri);
          }
        }
      }
    } catch (Exception e) {
    }

    if (sortedDirs.size() > 0) {
      Collections.sort(sortedDirs, sortedDirs.get(0));
    }
    if (sortedFiles.size() > 0) {
      Collections.sort(sortedFiles, sortedFiles.get(0));
    }
    filelist.addAll(sortedDirs);
    filelist.addAll(sortedFiles);
    adapter = new IconArrayAdapter<FileUri>(this, android.R.layout.simple_list_item_1, filelist);
    this.setListAdapter(adapter);
  }
  /**
   * Reconcile positions based on the AST subtrees
   *
   * @param subtrees the AST subtrees
   */
  private void reconcilePositions(DartNode[] subtrees) {
    // copy fRemovedPositions into removedPositions and removedPositionsDeleted
    removedPositions = fRemovedPositions.toArray(new Position[fRemovedPositions.size()]);
    Arrays.sort(removedPositions, positionsComparator);
    removedPositionsDeleted = new boolean[removedPositions.length];

    // FIXME: remove positions not covered by subtrees
    for (int i = 0, n = subtrees.length; i < n; i++) {
      // subtrees[i].accept(fCollector);
      subtrees[i].accept(fCollector);
    }

    // copy removedPositions and removedPositionsDeleted into fRemovedPositions
    fRemovedPositions = new ArrayList<Position>(removedPositions.length);
    for (int i = 0; i < removedPositions.length; i++) {
      if (!removedPositionsDeleted[i]) {
        fRemovedPositions.add(removedPositions[i]);
      }
    }

    List<Position> oldPositions = fRemovedPositions;
    List<Position> newPositions = new ArrayList<Position>(fNOfRemovedPositions);
    for (int i = 0, n = oldPositions.size(); i < n; i++) {
      Position current = oldPositions.get(i);
      if (current != null) {
        newPositions.add(current);
      }
    }
    fRemovedPositions = newPositions;

    Collections.sort(fRemovedPositions, positionsComparator);
    Collections.sort(fAddedPositions, positionsComparator);
  }
  private void doTestEARResourceRetrieval(boolean recursive, String rootDir) {
    ModuleClassLoader classLoader = (ModuleClassLoader) getClass().getClassLoader();
    List<String> foundResources =
        ResourceListingUtils.listResources(classLoader, rootDir, recursive);

    // only resources in EAR library should be listed
    List<String> resourcesInDeployment = new ArrayList<>();
    resourcesInDeployment.add(ResourceListingUtils.classToPath(EarResourceListingTestCase.class));
    resourcesInDeployment.add(ResourceListingUtils.classToPath(ResourceListingUtils.class));
    resourcesInDeployment.add("META-INF/emptyJarLibResource.properties");
    resourcesInDeployment.add("META-INF/properties/nestedJarLib.properties");

    ResourceListingUtils.filterResources(resourcesInDeployment, rootDir, !recursive);

    Collections.sort(foundResources);
    Collections.sort(resourcesInDeployment);

    log.info("List of expected resources:");
    for (String expectedResource : resourcesInDeployment) {
      log.info(expectedResource);
    }
    log.info("List of found resources: ");
    for (String foundResource : foundResources) {
      log.info(foundResource);
    }

    Assert.assertArrayEquals(
        "Not all resources from EAR archive are correctly listed",
        resourcesInDeployment.toArray(),
        foundResources.toArray());
  }
  @Override
  public void afterCheckProject(@NonNull Context context) {
    if (mNames != null && mNames.size() > 0 && mHaveBytecode) {
      List<String> names = new ArrayList<String>(mNames.keySet());
      Collections.sort(names);
      LintDriver driver = context.getDriver();
      for (String name : names) {
        Handle handle = mNames.get(name);

        Object clientData = handle.getClientData();
        if (clientData instanceof Node) {
          if (driver.isSuppressed(ISSUE, (Node) clientData)) {
            continue;
          }
        }

        Location location = handle.resolve();
        String message =
            String.format(
                "Corresponding method handler 'public void %1$s(android.view.View)' not found",
                name);
        List<String> similar = mSimilar != null ? mSimilar.get(name) : null;
        if (similar != null) {
          Collections.sort(similar);
          message =
              message + String.format(" (did you mean %1$s ?)", Joiner.on(", ").join(similar));
        }
        context.report(ISSUE, location, message, null);
      }
    }
  }
  protected Result describeMbean(
      @Nonnull MBeanServerConnection mbeanServer, @Nonnull ObjectName objectName)
      throws IntrospectionException, ReflectionException, InstanceNotFoundException, IOException {
    MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(objectName);
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    out.println("# MBEAN");
    out.println(objectName.toString());
    out.println();
    out.println("## OPERATIONS");
    List<MBeanOperationInfo> operations = Arrays.asList(mbeanInfo.getOperations());
    Collections.sort(
        operations,
        new Comparator<MBeanOperationInfo>() {
          @Override
          public int compare(MBeanOperationInfo o1, MBeanOperationInfo o2) {
            return o1.getName().compareTo(o1.getName());
          }
        });

    for (MBeanOperationInfo opInfo : operations) {
      out.print("* " + opInfo.getName() + "(");
      MBeanParameterInfo[] signature = opInfo.getSignature();
      for (int i = 0; i < signature.length; i++) {
        MBeanParameterInfo paramInfo = signature[i];
        out.print(paramInfo.getType() + " " + paramInfo.getName());
        if (i < signature.length - 1) {
          out.print(", ");
        }
      }

      out.print("):" + opInfo.getReturnType() /* + " - " + opInfo.getDescription() */);
      out.println();
    }
    out.println();
    out.println("## ATTRIBUTES");
    List<MBeanAttributeInfo> attributes = Arrays.asList(mbeanInfo.getAttributes());
    Collections.sort(
        attributes,
        new Comparator<MBeanAttributeInfo>() {
          @Override
          public int compare(MBeanAttributeInfo o1, MBeanAttributeInfo o2) {
            return o1.getName().compareTo(o2.getName());
          }
        });
    for (MBeanAttributeInfo attrInfo : attributes) {
      out.println(
          "* "
              + attrInfo.getName()
              + ": "
              + attrInfo.getType()
              + " - "
              + (attrInfo.isReadable() ? "r" : "")
              + (attrInfo.isWritable() ? "w" : "") /* + " - " +
                    attrInfo.getDescription() */);
    }

    String description = sw.getBuffer().toString();
    return new Result(objectName, description, description);
  }
Esempio n. 19
0
  /** Sort all the painters (according to priority and name) */
  protected void sortThem() {
    sortByPriority.clear();
    sortByName.clear();

    sortByName.addAll(paintersByName.keySet());
    Collections.sort(sortByName);

    Vector<String> painterNames = new Vector<String>();
    Vector<Integer> priorities = new Vector<Integer>();

    painterNames.addAll(sortByName);
    priorities.addAll(painterPriorities.values());
    Collections.sort(priorities);

    while (!priorities.isEmpty()) {
      int prio = priorities.get(0);
      priorities.remove(0);

      for (int i = 0; i < painterNames.size(); i++) {
        if (painterPriorities.get(painterNames.get(i)) == prio) {
          sortByPriority.add(painterNames.get(i));
          painterNames.remove(i);
          break;
        }
      }
    }
  }
 public static void main(String[] args) {
   Random r = new Random();
   for (int times = 0; times < 1000; ++times) {
     int m, n;
     if (args.length == 2) {
       m = Integer.parseInt(args[0]);
       n = Integer.parseInt(args[1]);
     } else {
       m = r.nextInt(10001);
       n = r.nextInt(10001);
     }
     List<Integer> A = new ArrayList<>(m + n);
     for (int i = 0; i < m; ++i) {
       A.add(r.nextInt((m + n) * 2 + 1) - (m + n));
     }
     List<Integer> B = new ArrayList<>(n);
     for (int i = 0; i < n; ++i) {
       B.add(r.nextInt((m + n) * 2 + 1) - (m + n));
     }
     Collections.sort(A);
     for (int i = m; i < m + n; ++i) {
       A.add(null);
     }
     Collections.sort(B);
     mergeTwoSortedArrays(A, m, B, n);
     checkAns(A);
   }
 }
  /**
   * Sorts the given rank by crowding distance (i.e. the &quot;neighborhoodship&quot; in the fitness
   * space).
   */
  private void sortByCrowdingDistance(List<AggregationIndividual> rank) {
    Iterator<AggregationIndividual> f = rank.iterator();
    int numberOfCriteria = 0;
    while (f.hasNext()) {
      AggregationIndividual current = f.next();
      current.setCrowdingDistance(0.0d);
      numberOfCriteria = Math.max(numberOfCriteria, current.getPerformance().getSize());
    }

    for (int m = 0; m < numberOfCriteria; m++) {
      Comparator<AggregationIndividual> comparator = new CriteriaComparator(m);
      Collections.sort(rank, comparator);
      rank.get(0).setCrowdingDistance(Double.POSITIVE_INFINITY);
      rank.get(rank.size() - 1).setCrowdingDistance(Double.POSITIVE_INFINITY);

      for (int i = 1; i < (rank.size() - 1); i++) {
        AggregationIndividual current = rank.get(i);
        double currentCrowdingDistance = current.getCrowdingDistance();
        AggregationIndividual afterI = rank.get(i + 1);
        AggregationIndividual beforeI = rank.get(i - 1);
        double afterPerformance = afterI.getPerformance().getCriterion(m).getFitness();
        double beforePerformance = beforeI.getPerformance().getCriterion(m).getFitness();
        current.setCrowdingDistance(
            currentCrowdingDistance + Math.abs(afterPerformance - beforePerformance));
      }
    }

    Collections.sort(rank, new CrowdingComparator());
  }
Esempio n. 22
0
  public int complete(String buffer, int cursor, List<String> candidates) {
    if (session == null) {
      session = CommandSessionHolder.getSession();
    }

    List<String> scopes = getCurrentScopes();
    Map<String, Completer>[] allCompleters = checkData();
    sort(allCompleters, scopes);

    String subShell = getCurrentSubShell();
    String completion = getCompletionType();

    // SUBSHELL mode
    if ("SUBSHELL".equalsIgnoreCase(completion)) {
      if (subShell.isEmpty()) {
        subShell = "*";
      }
      List<Completer> completers = new ArrayList<Completer>();
      for (String name : allCompleters[1].keySet()) {
        if (name.startsWith(subShell)) {
          completers.add(allCompleters[1].get(name));
        }
      }
      if (!subShell.equals("*")) {
        completers.add(new StringsCompleter(new String[] {"exit"}));
      }
      int res = new AggregateCompleter(completers).complete(buffer, cursor, candidates);
      Collections.sort(candidates);
      return res;
    }

    if ("FIRST".equalsIgnoreCase(completion)) {
      if (!subShell.isEmpty()) {
        List<Completer> completers = new ArrayList<Completer>();
        for (String name : allCompleters[1].keySet()) {
          if (name.startsWith(subShell)) {
            completers.add(allCompleters[1].get(name));
          }
        }
        int res = new AggregateCompleter(completers).complete(buffer, cursor, candidates);
        if (!candidates.isEmpty()) {
          Collections.sort(candidates);
          return res;
        }
      }
      List<Completer> compl = new ArrayList<Completer>();
      compl.add(new StringsCompleter(getAliases()));
      compl.addAll(allCompleters[0].values());
      int res = new AggregateCompleter(compl).complete(buffer, cursor, candidates);
      Collections.sort(candidates);
      return res;
    }

    List<Completer> compl = new ArrayList<Completer>();
    compl.add(new StringsCompleter(getAliases()));
    compl.addAll(allCompleters[0].values());
    int res = new AggregateCompleter(compl).complete(buffer, cursor, candidates);
    Collections.sort(candidates);
    return res;
  }
  static void logPlugins() {
    List<String> loadedBundled = new ArrayList<String>();
    List<String> disabled = new ArrayList<String>();
    List<String> loadedCustom = new ArrayList<String>();

    for (IdeaPluginDescriptor descriptor : ourPlugins) {
      final String version = descriptor.getVersion();
      String s = descriptor.getName() + (version != null ? " (" + version + ")" : "");
      if (descriptor.isEnabled()) {
        if (descriptor.isBundled() || SPECIAL_IDEA_PLUGIN.equals(descriptor.getName()))
          loadedBundled.add(s);
        else loadedCustom.add(s);
      } else {
        disabled.add(s);
      }
    }

    Collections.sort(loadedBundled);
    Collections.sort(loadedCustom);
    Collections.sort(disabled);

    getLogger().info("Loaded bundled plugins: " + StringUtil.join(loadedBundled, ", "));
    if (!loadedCustom.isEmpty()) {
      getLogger().info("Loaded custom plugins: " + StringUtil.join(loadedCustom, ", "));
    }
    if (!disabled.isEmpty()) {
      getLogger().info("Disabled plugins: " + StringUtil.join(disabled, ", "));
    }
  }
  @Override
  public boolean process() {
    uniqueRows = new ArrayList<K>(new HashSet<K>(rows));
    Collections.sort(uniqueRows);
    uniqueCols = new ArrayList<J>(new HashSet<J>(cols));
    Collections.sort(uniqueCols);

    final List<Assignment> assignments = new ArrayList<Assignment>(costs.length);
    for (int i = 0; i < costs.length; i++) {
      final K rowObj = rows.get(i);
      final J colObj = cols.get(i);
      final int r = Collections.binarySearch(uniqueRows, rowObj);
      final int c = Collections.binarySearch(uniqueCols, colObj);
      assignments.add(new Assignment(r, c, costs[i]));
    }
    Collections.sort(assignments);

    // Test we do not have duplicates.
    Assignment previousAssgn = assignments.get(0);
    for (int i = 1; i < assignments.size(); i++) {
      final Assignment assgn = assignments.get(i);
      if (assgn.equals(previousAssgn)) {
        errorMessage = BASE_ERROR_MESSAGE + "Found duplicate assignment at index: " + assgn + ".";
        return false;
      }
      previousAssgn = assgn;
    }

    final int nRows = uniqueRows.size();
    final int nCols = uniqueCols.size();
    final int[] kk = new int[costs.length];
    final int[] number = new int[nRows];
    final double[] cc = new double[costs.length];

    Assignment a = assignments.get(0);
    kk[0] = a.c;
    cc[0] = a.cost;
    int currentRow = a.r;
    int nOfEl = 0;
    for (int i = 1; i < assignments.size(); i++) {
      a = assignments.get(i);

      kk[i] = a.c;
      cc[i] = a.cost;
      nOfEl++;

      if (a.r != currentRow) {
        number[currentRow] = nOfEl;
        nOfEl = 0;
        currentRow = a.r;
      }
    }
    number[currentRow] = nOfEl + 1;

    scm = new SparseCostMatrix(cc, kk, number, nCols);

    alternativeCost = computeAlternativeCosts();

    return true;
  }
 private List<SchemaTransaction> generateColumnTransactions(Table sourceTable, Table shadowTable) {
   List<SchemaTransaction> shemaTransactionList = new ArrayList<SchemaTransaction>();
   if (shadowTable == null) {
     for (Column column : sourceTable.getColumnList()) {
       shemaTransactionList.add(new SchemaTransaction(column, TransactionType.INSERT));
     }
   } else {
     Collections.sort(sourceTable.getColumnList());
     Collections.sort(shadowTable.getColumnList());
     for (Column column : sourceTable.getColumnList()) {
       if (!shadowTable.getColumnList().contains(column)) {
         column.setTable(shadowTable);
         shemaTransactionList.add(new SchemaTransaction(column, TransactionType.INSERT));
       } else {
         Column shadowColumn =
             shadowTable.getColumnList().get(shadowTable.getColumnList().indexOf(column));
         if (column.getOrdinalPosition() != (shadowColumn.getOrdinalPosition())
             || !column.getDataType().equals(shadowColumn.getDataType())
             || column.getSize() != shadowColumn.getSize()) {
           column.setId(shadowColumn.getId());
           shemaTransactionList.add(new SchemaTransaction(column, TransactionType.UPDATE));
         }
       }
     }
     for (Column column : shadowTable.getColumnList()) {
       if (!sourceTable.getColumnList().contains(column)) {
         shemaTransactionList.add(new SchemaTransaction(column, TransactionType.DELETE));
       }
     }
   }
   return shemaTransactionList;
 }
Esempio n. 26
0
  @Test
  public void testCommandSorting() {
    // @formatter:off
    CliBuilder<Runnable> builder =
        Cli.<Runnable>builder("git")
            .withDescription("the stupid content tracker")
            .withDefaultCommand(Help.class)
            .withCommand(Help.class)
            .withCommand(Add.class);

    builder
        .withGroup("remote")
        .withDescription("Manage set of tracked repositories")
        .withDefaultCommand(RemoteShow.class)
        .withCommand(RemoteShow.class)
        .withCommand(RemoteAdd.class);

    Cli<Runnable> gitParser = builder.build();

    List<CommandMetadata> defCommands =
        new ArrayList<>(gitParser.getMetadata().getDefaultGroupCommands());
    Collections.sort(defCommands, UsageHelper.DEFAULT_COMMAND_COMPARATOR);

    Assert.assertEquals(defCommands.get(0).getName(), "add");
    Assert.assertEquals(defCommands.get(1).getName(), "help");

    // Check sort is stable
    Collections.sort(defCommands, UsageHelper.DEFAULT_COMMAND_COMPARATOR);

    Assert.assertEquals(defCommands.get(0).getName(), "add");
    Assert.assertEquals(defCommands.get(1).getName(), "help");

    // @formatter:on
  }
  protected Collection getKeysOfType(int elementType) {

    LinkedList keys = (LinkedList) super.getKeysOfType(elementType);
    LinkedList temp = null;

    if ((elementType & PatternFilter.PROPERTY) != 0) {
      temp = new LinkedList();
      temp.addAll(patternAnalyser.getPropertyPatterns());
      Collections.sort(temp, new PatternComparator());
      keys.addAll(temp);
      // keys.addAll( patternAnalyser.getPropertyPatterns() );
    }
    if ((elementType & PatternFilter.IDXPROPERTY) != 0) {
      temp = new LinkedList();
      temp.addAll(patternAnalyser.getIdxPropertyPatterns());
      Collections.sort(temp, new PatternComparator());
      keys.addAll(temp);
      // keys.addAll( patternAnalyser.getIdxPropertyPatterns() );
    }
    if ((elementType & PatternFilter.EVENT_SET) != 0) {
      temp = new LinkedList();
      temp.addAll(patternAnalyser.getEventSetPatterns());
      Collections.sort(temp, new PatternComparator());
      keys.addAll(temp);
      // keys.addAll( patternAnalyser.getEventSetPatterns() );
    }

    //    if ((filter == null) || filter.isSorted ())
    //      Collections.sort (keys, comparator);
    return keys;
  }
 @Override
 public List<File> loadInBackground() {
   if (path == null || !path.isDirectory()) return Collections.emptyList();
   final File[] listed_files = path.listFiles();
   if (listed_files == null) return Collections.emptyList();
   final List<File> dirs = new ArrayList<File>();
   final List<File> files = new ArrayList<File>();
   for (final File file : listed_files) {
     if (!file.canRead() || file.isHidden()) {
       continue;
     }
     if (file.isDirectory()) {
       dirs.add(file);
     } else if (file.isFile()) {
       final String name = file.getName();
       final int idx = name.lastIndexOf(".");
       if (extensions == null
           || extensions.length == 0
           || idx == -1
           || idx > -1 && extensions_regex.matcher(name.substring(idx + 1)).matches()) {
         files.add(file);
       }
     }
   }
   Collections.sort(dirs, NAME_COMPARATOR);
   Collections.sort(files, NAME_COMPARATOR);
   final List<File> list = new ArrayList<File>();
   final File parent = path.getParentFile();
   if (path.getParentFile() != null) {
     list.add(parent);
   }
   list.addAll(dirs);
   list.addAll(files);
   return list;
 }
  private List<InvoiceConfiguration> sort(List<InvoiceConfiguration> entries, boolean asc) {

    if (asc) {

      Collections.sort(
          entries,
          new Comparator<InvoiceConfiguration>() {

            @Override
            public int compare(InvoiceConfiguration arg0, InvoiceConfiguration arg1) {
              if (arg0.getAlias() == null) return -1;
              if (arg1.getAlias() == null) return 1;
              return (arg0).getAlias().compareTo((arg1).getAlias());
            }
          });

    } else {

      Collections.sort(
          entries,
          new Comparator<InvoiceConfiguration>() {

            @Override
            public int compare(InvoiceConfiguration arg0, InvoiceConfiguration arg1) {
              if (arg0.getAlias() == null) return 1;
              if (arg1.getAlias() == null) return -1;
              return (arg1).getAlias().compareTo((arg0).getAlias());
            }
          });
    }
    return entries;
  }
Esempio n. 30
0
  public Element getState() {
    final Element element = new Element(COMPONENT_NAME);

    JDOMExternalizerUtil.writeField(
        element, INSTRUMENTATION_TYPE_NAME, myInstrumentationType.toString());
    JDOMExternalizerUtil.writeField(element, LANGUAGE_ANNOTATION_NAME, myLanguageAnnotation);
    JDOMExternalizerUtil.writeField(element, PATTERN_ANNOTATION_NAME, myPatternAnnotation);
    JDOMExternalizerUtil.writeField(element, SUBST_ANNOTATION_NAME, mySubstAnnotation);
    JDOMExternalizerUtil.writeField(
        element, RESOLVE_REFERENCES, String.valueOf(myResolveReferences));

    final List<String> injectorIds = new ArrayList<String>(myInjections.keySet());
    Collections.sort(injectorIds);
    for (String key : injectorIds) {
      final List<BaseInjection> injections = new ArrayList<BaseInjection>(myInjections.get(key));
      if (myDefaultInjections != null) {
        injections.removeAll(myDefaultInjections);
      }
      Collections.sort(
          injections,
          new Comparator<BaseInjection>() {
            public int compare(final BaseInjection o1, final BaseInjection o2) {
              return Comparing.compare(o1.getDisplayName(), o2.getDisplayName());
            }
          });
      for (BaseInjection injection : injections) {
        element.addContent(injection.getState());
      }
    }
    return element;
  }