private void updateExistingProfilesForSegment(Segment segment) {
    long t = System.currentTimeMillis();
    Condition segmentCondition = new Condition();

    segmentCondition.setConditionType(
        definitionsService.getConditionType("profilePropertyCondition"));
    segmentCondition.setParameter("propertyName", "segments");
    segmentCondition.setParameter("comparisonOperator", "equals");
    segmentCondition.setParameter("propertyValue", segment.getItemId());

    if (segment.getMetadata().isEnabled()) {
      List<Profile> previousProfiles =
          persistenceService.query(segmentCondition, null, Profile.class);
      List<Profile> newProfiles =
          persistenceService.query(segment.getCondition(), null, Profile.class);

      List<Profile> add = new ArrayList<>(newProfiles);
      add.removeAll(previousProfiles);
      previousProfiles.removeAll(newProfiles);

      for (Profile profileToAdd : add) {
        profileToAdd.getSegments().add(segment.getItemId());
        persistenceService.update(
            profileToAdd.getItemId(), null, Profile.class, "segments", profileToAdd.getSegments());
        Event profileUpdated =
            new Event("profileUpdated", null, profileToAdd, null, null, profileToAdd, new Date());
        profileUpdated.setPersistent(false);
        eventService.send(profileUpdated);
      }
      for (Profile profileToRemove : previousProfiles) {
        profileToRemove.getSegments().remove(segment.getItemId());
        persistenceService.update(
            profileToRemove.getItemId(),
            null,
            Profile.class,
            "segments",
            profileToRemove.getSegments());
        Event profileUpdated =
            new Event(
                "profileUpdated", null, profileToRemove, null, null, profileToRemove, new Date());
        profileUpdated.setPersistent(false);
        eventService.send(profileUpdated);
      }

    } else {
      List<Profile> previousProfiles =
          persistenceService.query(segmentCondition, null, Profile.class);
      for (Profile profileToRemove : previousProfiles) {
        profileToRemove.getSegments().remove(segment.getItemId());
        persistenceService.update(
            profileToRemove.getItemId(),
            null,
            Profile.class,
            "segments",
            profileToRemove.getSegments());
      }
    }
    logger.info("Profiles updated in {}", System.currentTimeMillis() - t);
  }
 @NotNull
 public ApplyPatchStatus nonWriteActionPreCheck() {
   final List<FilePatch> failedPreCheck = myVerifier.nonWriteActionPreCheck();
   myFailedPatches.addAll(failedPreCheck);
   myPatches.removeAll(failedPreCheck);
   final List<FilePatch> skipped = myVerifier.getSkipped();
   final boolean applyAll = skipped.isEmpty();
   myPatches.removeAll(skipped);
   if (!failedPreCheck.isEmpty()) return ApplyPatchStatus.FAILURE;
   return applyAll
       ? ApplyPatchStatus.SUCCESS
       : ((skipped.size() == myPatches.size())
           ? ApplyPatchStatus.ALREADY_APPLIED
           : ApplyPatchStatus.PARTIAL);
 }
Beispiel #3
0
  @Override
  public Agent vote() {

    List<Agent> whiteAgent = new ArrayList<>();
    List<Agent> blackAgent = new ArrayList<>();

    for (Judge j : getMyJudgeList()) {
      if (getLatestDayGameInfo().getAliveAgentList().contains(judge.getTarget())) {
        switch (j.getResult()) {
          case HUMAN:
            whiteAgent.add(judge.getTarget());
            break;
          case WEREWOLF:
            blackAgent.add(judge.getTarget());
            break;
        }
      }
    }

    if (blackAgent.size() > 0) {
      return randomSelect(blackAgent);
    } else {
      List<Agent> voteCandidates = new ArrayList<Agent>();
      voteCandidates.addAll(getLatestDayGameInfo().getAliveAgentList());
      voteCandidates.remove(getMe());
      voteCandidates.removeAll(whiteAgent);

      return randomSelect(voteCandidates);
    }
  }
Beispiel #4
0
  private Graph changeLatentNames(Graph full, Clusters measurements, List<String> latentVarList) {
    Graph g2 = null;

    try {
      g2 = (Graph) new MarshalledObject(full).get();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    for (int i = 0; i < measurements.getNumClusters(); i++) {
      List<String> d = measurements.getCluster(i);
      String latentName = latentVarList.get(i);

      for (Node node : full.getNodes()) {
        if (!(node.getNodeType() == NodeType.LATENT)) {
          continue;
        }

        List<Node> _children = full.getChildren(node);

        _children.removeAll(ReidentifyVariables.getLatents(full));

        List<String> childNames = getNames(_children);

        if (new HashSet<String>(childNames).equals(new HashSet<String>(d))) {
          g2.getNode(node.getName()).setName(latentName);
        }
      }
    }

    return g2;
  }
Beispiel #5
0
  /** @param aProperties the updated properties. */
  @SuppressWarnings("rawtypes")
  final void setProperties(final Dictionary aProperties) {
    final Map<String, String> newProps = new HashMap<String, String>();

    Enumeration keys = aProperties.keys();
    while (keys.hasMoreElements()) {
      final String key = (String) keys.nextElement();
      if (!KNOWN_KEYS.contains(key) && !IGNORED_KEYS.contains(key)) {
        LOG.log(Level.WARNING, "Unknown/unsupported profile key: " + key);
        continue;
      }

      final String value = aProperties.get(key).toString();
      newProps.put(key, value.trim());
    }

    // Verify whether all known keys are defined...
    final List<String> checkedKeys = new ArrayList<String>(KNOWN_KEYS);
    checkedKeys.removeAll(newProps.keySet());
    if (!checkedKeys.isEmpty()) {
      throw new IllegalArgumentException(
          "Profile settings not complete! Missing keys are: " + checkedKeys.toString());
    }

    this.properties.putAll(newProps);

    LOG.log(
        Level.INFO,
        "New device profile settings applied for {1} ({0}) ...", //
        new Object[] {getType(), getDescription()});
  }
Beispiel #6
0
  /**
   * If merge_id is not equal to this.merge_id then discard. Else cast the view/digest to all
   * members of this group.
   */
  public void handleMergeView(final MergeData data, final MergeId merge_id) {
    if (!matchMergeId(merge_id)) {
      if (log.isErrorEnabled())
        log.error("merge_ids don't match (or are null); merge view discarded");
      return;
    }

    // only send to our *current* members, if we have A and B being merged (we are B), then we would
    // *not*
    // receive a VIEW_ACK from A because A doesn't see us in the pre-merge view yet and discards the
    // view

    // [JGRP-700] - FLUSH: flushing should span merge

    // we have to send new view only to current members and we should not wait
    // for view acks from newly merged mebers
    List<Address> newViewMembers = new Vector<Address>(data.view.getMembers());
    newViewMembers.removeAll(gms.members.getMembers());

    gms.castViewChangeWithDest(data.view, data.digest, null, newViewMembers);
    // if we have flush in stack send ack back to merge coordinator
    if (gms.flushProtocolInStack) {
      Message ack = new Message(data.getSender(), null, null);
      ack.setFlag(Message.OOB);
      GMS.GmsHeader ack_hdr = new GMS.GmsHeader(GMS.GmsHeader.INSTALL_MERGE_VIEW_OK);
      ack.putHeader(gms.getId(), ack_hdr);
      gms.getDownProtocol().down(new Event(Event.MSG, ack));
    }
    cancelMerge(merge_id);
  }
  private Map<Integer, Double> computeOptimizationScores(
      int expMinCluster, int expMaxCluster, int hop, Optimizer optimizer) {

    List<Integer> searchSpace = computeSearchSpace(expMinCluster, expMaxCluster, hop);

    List<Integer> newSearchSpace = new ArrayList<>(searchSpace);
    newSearchSpace.removeAll(scores.keySet());

    OptimizationManager_old optimizationManager =
        new OptimizationManager_old(parallelWorkers, maxJobsPerWorker);
    Map<Integer, Double> scores = optimizationManager.process(optimizer, newSearchSpace);
    this.scores.putAll(scores);

    for (int s : searchSpace) scores.put(s, this.scores.get(s));

    System.out.println("[]Tried search space:" + scores);
    // are scores valid? if not, half the hop, recompute search space, re-optimize
    if (invalid(scores)) {
      if (hop != 1) {
        hop = reduceHop(hop);
        return computeOptimizationScores(expMinCluster, expMaxCluster, hop, optimizer);
      } else {
        return null;
      }
    }
    return scores;
  }
  @Nullable
  private ApplyPatchStatus actualApply(
      final List<Pair<VirtualFile, ApplyTextFilePatch>> textPatches,
      final List<Pair<VirtualFile, ApplyFilePatchBase<BinaryType>>> binaryPatches,
      final CommitContext commitContext) {
    final ApplyPatchContext context = new ApplyPatchContext(myBaseDirectory, 0, true, true);
    ApplyPatchStatus status;

    try {
      status = applyList(textPatches, context, null, commitContext);

      if (status == ApplyPatchStatus.ABORT) return status;

      if (myCustomForBinaries == null) {
        status = applyList(binaryPatches, context, status, commitContext);
      } else {
        ApplyPatchStatus patchStatus = myCustomForBinaries.apply(binaryPatches);
        final List<FilePatch> appliedPatches = myCustomForBinaries.getAppliedPatches();
        moveForCustomBinaries(binaryPatches, appliedPatches);

        status = ApplyPatchStatus.and(status, patchStatus);
        myRemainingPatches.removeAll(appliedPatches);
      }
    } catch (IOException e) {
      showError(myProject, e.getMessage(), true);
      return ApplyPatchStatus.ABORT;
    }
    return status;
  }
Beispiel #9
0
  /**
   * Disseminates cache information (UUID/IP adddress/port/name) to the given members
   *
   * @param current_mbrs The current members. Guaranteed to be non-null. This is a copy and can be
   *     modified.
   * @param left_mbrs The members which left. These are excluded from dissemination. Can be null if
   *     no members left
   * @param new_mbrs The new members that we need to disseminate the information to. Will be all
   *     members if null.
   */
  protected void disseminateDiscoveryInformation(
      List current_mbrs, List<Address> left_mbrs, List<Address> new_mbrs) {
    if (new_mbrs == null || new_mbrs.isEmpty()) return;

    if (local_addr != null) current_mbrs.remove(local_addr);
    if (left_mbrs != null) current_mbrs.removeAll(left_mbrs);

    // 1. Send information about <everyone - self - left_mbrs> to new_mbrs
    Set<Address> info = new HashSet<>(current_mbrs);
    for (Address addr : info) {
      PhysicalAddress phys_addr =
          (PhysicalAddress) down_prot.down(new Event(Event.GET_PHYSICAL_ADDRESS, addr));
      if (phys_addr == null) continue;
      boolean is_coordinator = isCoord(addr);
      for (Address target : new_mbrs)
        sendDiscoveryResponse(addr, phys_addr, UUID.get(addr), target, is_coordinator);
    }

    // 2. Send information about new_mbrs to <everyone - self - left_mbrs - new_mbrs>
    Set<Address> targets = new HashSet<>(current_mbrs);
    targets.removeAll(new_mbrs);

    if (!targets.isEmpty()) {
      for (Address addr : new_mbrs) {
        PhysicalAddress phys_addr =
            (PhysicalAddress) down_prot.down(new Event(Event.GET_PHYSICAL_ADDRESS, addr));
        if (phys_addr == null) continue;
        boolean is_coordinator = isCoord(addr);
        for (Address target : targets)
          sendDiscoveryResponse(addr, phys_addr, UUID.get(addr), target, is_coordinator);
      }
    }
  }
  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;
  }
Beispiel #11
0
 /**
  * @param parentKey
  * @param childrenName
  * @param referenceMap
  * @param list
  * @return
  */
 private static void recursion(
     String parentKey,
     String childrenName,
     Map<Object, Map<String, Object>> referenceMap,
     List<Object> list,
     String selfKey) {
   List<Object> executedObjectList = new ArrayList<>();
   for (Object object : list) {
     Map<String, Object> map = (Map<String, Object>) object;
     Object pid = map.get(parentKey);
     Map<String, Object> parentMap = referenceMap.get(pid);
     if (parentMap != null) {
       List<Map<String, Object>> children;
       if (parentMap.containsKey(childrenName)) {
         children = (List<Map<String, Object>>) parentMap.get(childrenName);
       } else {
         children = new ArrayList<>();
         parentMap.put(childrenName, children);
       }
       children.add(map);
       referenceMap.put(map.get(selfKey), map);
       executedObjectList.add(map);
     }
   }
   list.removeAll(executedObjectList);
   if (list.size() > 0) {
     recursion(parentKey, childrenName, referenceMap, list, selfKey);
   }
 }
  /**
   * Permanently removes locally stored message history for the metacontact, remove any recent
   * contacts if any.
   */
  public void eraseLocallyStoredHistory(MetaContact contact) throws IOException {
    List<ComparableEvtObj> toRemove = null;
    synchronized (recentMessages) {
      toRemove = new ArrayList<ComparableEvtObj>();
      Iterator<Contact> iter = contact.getContacts();
      while (iter.hasNext()) {
        Contact item = iter.next();
        String id = item.getAddress();
        ProtocolProviderService provider = item.getProtocolProvider();

        for (ComparableEvtObj msc : recentMessages) {
          if (msc.getProtocolProviderService().equals(provider)
              && msc.getContactAddress().equals(id)) {
            toRemove.add(msc);
          }
        }
      }

      recentMessages.removeAll(toRemove);
    }
    if (recentQuery != null) {
      for (ComparableEvtObj msc : toRemove) {
        recentQuery.fireContactRemoved(msc);
      }
    }
  }
Beispiel #13
0
 private RNode[] linearSeeds(List<RNode> cc) {
   RNode[] seeds = new RNode[2];
   boolean done = false;
   RNode s1 = null;
   RNode s2 = null;
   double maxDis = -Double.MAX_VALUE;
   for (int i = 0; i < cc.size(); i++) {
     for (int k = i + 1; k < cc.size(); k++) {
       RNode e1 = cc.get(i);
       RNode e2 = cc.get(k);
       double d = getDistance(e1, e2);
       if (d > maxDis) {
         maxDis = d;
         s1 = e1;
         s2 = e2;
         done = true;
       }
     }
   }
   if (done) {
     seeds[0] = s1;
     seeds[1] = s2;
   } else {
     seeds = new RNode[] {cc.get(0), cc.get(1)};
   }
   cc.removeAll(Arrays.asList(seeds));
   return seeds;
 }
  // Quartets first , then triples.
  private Set<Set<Integer>> estimateClustersSAG() {
    Map<Node, Set<Node>> adjacencies;

    if (depth == -2) {
      adjacencies = new HashMap<Node, Set<Node>>();

      for (Node node : variables) {
        HashSet<Node> _nodes = new HashSet<Node>(variables);
        _nodes.remove(node);
        adjacencies.put(node, _nodes);
      }
    } else {
      System.out.println("Running PC adjacency search...");
      Graph graph = new EdgeListGraph(variables);
      Fas fas = new Fas(graph, indTest);
      fas.setDepth(depth); // 1?
      adjacencies = fas.searchMapOnly();
      System.out.println("...done.");
    }

    List<Integer> _variables = new ArrayList<Integer>();
    for (int i = 0; i < variables.size(); i++) _variables.add(i);

    Set<Set<Integer>> pureClusters = findPureClusters(_variables, adjacencies);
    for (Set<Integer> cluster : pureClusters) _variables.removeAll(cluster);
    Set<Set<Integer>> mixedClusters =
        findMixedClusters(_variables, unionPure(pureClusters), adjacencies);
    Set<Set<Integer>> allClusters = new HashSet<Set<Integer>>(pureClusters);
    allClusters.addAll(mixedClusters);
    return allClusters;
  }
  private SubscriberChangeEvent[] handleRemovedRoot(IResource removedRoot) {
    // Determine if any of the roots of the compare are affected
    List removals = new ArrayList(resources.length);
    for (int j = 0; j < resources.length; j++) {
      IResource root = resources[j];
      if (removedRoot.getFullPath().isPrefixOf(root.getFullPath())) {
        // The root is no longer managed by CVS
        removals.add(root);
        try {
          tree.flushVariants(root, IResource.DEPTH_INFINITE);
        } catch (TeamException e) {
          CVSProviderPlugin.log(e);
        }
      }
    }
    if (removals.isEmpty()) {
      return new SubscriberChangeEvent[0];
    }

    // Adjust the roots of the subscriber
    List newRoots = new ArrayList(resources.length);
    newRoots.addAll(Arrays.asList(resources));
    newRoots.removeAll(removals);
    resources = (IResource[]) newRoots.toArray(new IResource[newRoots.size()]);

    // Create the deltas for the removals
    SubscriberChangeEvent[] deltas = new SubscriberChangeEvent[removals.size()];
    for (int i = 0; i < deltas.length; i++) {
      deltas[i] =
          new SubscriberChangeEvent(
              this, ISubscriberChangeEvent.ROOT_REMOVED, (IResource) removals.get(i));
    }
    return deltas;
  }
 /** removeAll removes all elements from the given collection */
 public void testRemoveAll() {
   List full = populatedArray(3);
   Vector v = new Vector();
   v.add(one);
   v.add(two);
   full.removeAll(v);
   assertEquals(1, full.size());
 }
Beispiel #17
0
    boolean accepts(String pluginKey) {
      if (CORE_PLUGIN.equals(pluginKey) || ENGLISH_PACK_PLUGIN.equals(pluginKey)) {
        return true;
      }

      List<String> mergeList = newArrayList(blacks);
      mergeList.removeAll(whites);
      return mergeList.isEmpty() || !mergeList.contains(pluginKey);
    }
 /**
  * Checks that given element has any non-builtin decorators.
  *
  * @param element decoratable element to check
  * @param context type evaluation context. If it doesn't allow switch to AST, decorators will be
  *     compared by the text of the last component of theirs qualified names.
  * @see PyKnownDecoratorUtil.KnownDecorator
  */
 public static boolean hasNonBuiltinDecorator(
     @NotNull PyDecoratable element, @NotNull TypeEvalContext context) {
   final List<KnownDecorator> knownDecorators = getKnownDecorators(element, context);
   if (!allDecoratorsAreKnown(element, knownDecorators)) {
     return true;
   }
   knownDecorators.removeAll(BUILTIN_DECORATORS);
   return !knownDecorators.isEmpty();
 }
Beispiel #19
0
 public void removeHeader(String name) {
   List<Field> removeFields = new ArrayList<Field>();
   for (Field field : mFields) {
     if (field.name.equalsIgnoreCase(name)) {
       removeFields.add(field);
     }
   }
   mFields.removeAll(removeFields);
 }
Beispiel #20
0
 private boolean localMarkovIndep(Node x, Node y, Graph pattern, IndependenceTest test) {
   List<Node> future = pattern.getDescendants(Collections.singletonList(x));
   List<Node> boundary = pattern.getAdjacentNodes(x);
   boundary.removeAll(future);
   List<Node> closure = new ArrayList<>(boundary);
   closure.add(x);
   closure.remove(y);
   if (future.contains(y) || boundary.contains(y)) return false;
   return test.isIndependent(x, y, boundary);
 }
  private void processDeletedFiles(Project project) {
    final List<Pair<FilePath, WorkingCopyFormat>> deletedFiles =
        new ArrayList<Pair<FilePath, WorkingCopyFormat>>();
    final Collection<FilePath> filesToProcess = new ArrayList<FilePath>();
    List<VcsException> exceptions = new ArrayList<VcsException>();
    final AbstractVcsHelper vcsHelper = AbstractVcsHelper.getInstance(project);

    try {
      fillDeletedFiles(project, deletedFiles, filesToProcess);
      if (deletedFiles.isEmpty() && filesToProcess.isEmpty() || myUndoingMove) return;
      SvnVcs vcs = SvnVcs.getInstance(project);
      final VcsShowConfirmationOption.Value value = vcs.getDeleteConfirmation().getValue();
      if (value != VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY) {
        if (!deletedFiles.isEmpty()) {
          final Collection<FilePath> confirmed =
              promptAboutDeletion(deletedFiles, vcs, value, vcsHelper);
          if (confirmed != null) {
            filesToProcess.addAll(confirmed);
          }
        }
        if (filesToProcess != null && !filesToProcess.isEmpty()) {
          runInBackground(
              project,
              "Deleting files from Subversion",
              createDeleteRunnable(project, vcs, filesToProcess, exceptions));
        }
        final List<FilePath> deletedFilesFiles =
            ObjectsConvertor.convert(
                deletedFiles,
                new Convertor<Pair<FilePath, WorkingCopyFormat>, FilePath>() {
                  @Override
                  public FilePath convert(Pair<FilePath, WorkingCopyFormat> o) {
                    return o.getFirst();
                  }
                });
        for (FilePath file : deletedFilesFiles) {
          final FilePath parent = file.getParentPath();
          if (parent != null) {
            myFilesToRefresh.add(parent.getVirtualFile());
          }
        }
        if (filesToProcess != null) {
          deletedFilesFiles.removeAll(filesToProcess);
        }
        for (FilePath file : deletedFilesFiles) {
          FileUtil.delete(file.getIOFile());
        }
      }
    } catch (SVNException e) {
      exceptions.add(new VcsException(e));
    }
    if (!exceptions.isEmpty()) {
      vcsHelper.showErrors(exceptions, SvnBundle.message("delete.files.errors.title"));
    }
  }
Beispiel #22
0
 public static List<Integer> minus(List<Integer> arr1, List<Integer> arr2) {
   List<Integer> lists = new ArrayList<Integer>();
   if (arr1.size() == 0) {
     lists = arr2;
   }
   if (arr1.size() != 0) {
     arr2.removeAll(arr1);
     lists = arr2;
   }
   return lists;
 }
  /**
   * If {@link #generateFields} is <code>true</code>, then this method will return an array of cmp +
   * cmr + pseudo cmr fields, otherwise the method will return an array of cmp + cmr fields.
   *
   * @param ejbName The ejb-name element for the bean
   * @param fieldName The name of a container managed field in the named bean
   * @return an array of fields in the ejb bean
   */
  public Object[] getFields(String ejbName) {
    List fields = (List) cmpFieldMap.get(ejbName);

    if (fields != null) {
      if (!generateFields()) fields.removeAll(getGeneratedRelationships(ejbName));

      return fields.toArray();
    }

    return null;
  }
Beispiel #24
0
 public static void main(String[] args) {
   Random rand = new Random(47);
   List<Pet> pets = Pets.arrayList(7);
   print("1: " + pets);
   Hamster h = new Hamster();
   pets.add(h); // Automatically resizes
   print("2: " + pets);
   print("3: " + pets.contains(h));
   pets.remove(h); // Remove by object
   Pet p = pets.get(2);
   print("4: " + p + " " + pets.indexOf(p));
   Pet cymric = new Cymric();
   print("5: " + pets.indexOf(cymric));
   print("6: " + pets.remove(cymric));
   // Must be the exact object:
   print("7: " + pets.remove(p));
   print("8: " + pets);
   pets.add(3, new Mouse()); // Insert at an index
   print("9: " + pets);
   List<Pet> sub = pets.subList(1, 4);
   print("subList: " + sub);
   print("10: " + pets.containsAll(sub));
   Collections.sort(sub); // In-place sort
   print("sorted subList: " + sub);
   // Order is not important in containsAll():
   print("11: " + pets.containsAll(sub));
   Collections.shuffle(sub, rand); // Mix it up
   print("shuffled subList: " + sub);
   print("12: " + pets.containsAll(sub));
   List<Pet> copy = new ArrayList<Pet>(pets);
   sub = Arrays.asList(pets.get(1), pets.get(4));
   print("sub: " + sub);
   copy.retainAll(sub);
   print("13: " + copy);
   copy = new ArrayList<Pet>(pets); // Get a fresh copy
   copy.remove(2); // Remove by index
   print("14: " + copy);
   copy.removeAll(sub); // Only removes exact objects
   print("15: " + copy);
   copy.set(1, new Mouse()); // Replace an element
   print("16: " + copy);
   copy.addAll(2, sub); // Insert a list in the middle
   print("17: " + copy);
   print("18: " + pets.isEmpty());
   pets.clear(); // Remove all elements
   print("19: " + pets);
   print("20: " + pets.isEmpty());
   pets.addAll(Pets.arrayList(4));
   print("21: " + pets);
   Object[] o = pets.toArray();
   print("22: " + o[3]);
   Pet[] pa = pets.toArray(new Pet[0]);
   print("23: " + pa[3].id());
 }
Beispiel #25
0
  /**
   * 把数据库中查出来的扁平数据转换成树
   *
   * @param list sql 数据集
   * @param selfKey id
   * @param parentKey pid
   * @param childrenName children
   * @return
   */
  @SuppressWarnings("unchecked")
  public static List<Map<String, Object>> generateTree(
      List<Object> list,
      String selfKey,
      String parentKey,
      String childrenName,
      Boolean hasAttributes) {
    if (CollectionUtils.isEmpty(list)) {
      return null;
    }
    List<Map<String, Object>> rootList = new ArrayList<>();

    // 引用指引Map
    Map<Object, Map<String, Object>> referenceMap = new HashMap<>();
    // 所有元素集合
    Set<Object> allObjectSet = new HashSet<>();
    // 孤儿节点
    List<Map<String, Object>> orphanList = new ArrayList<>();

    for (Object object : list) {
      Map<String, Object> map = (Map<String, Object>) object;
      allObjectSet.add(map.get(selfKey));
    }
    for (Object object : list) {
      Map<String, Object> map = (Map<String, Object>) object;
      Object pid = map.get(parentKey);
      if (pid == null || "0".equals(pid.toString())) {
        rootList.add(map);
        referenceMap.put(map.get(selfKey), map);
      } else if (!allObjectSet.contains(pid)) {
        orphanList.add(map);
      }
    }
    list.removeAll(rootList);
    list.removeAll(orphanList);
    // 递归出所有子节点
    recursion(parentKey, childrenName, referenceMap, list, selfKey);

    LG.info(JsonUtil.toJson(rootList));
    return rootList;
  }
Beispiel #26
0
 private boolean missingColliders(Graph graph) {
   List<Triple> colliders = getUnshieldedCollidersFromGraph(graph);
   Graph copy = new EdgeListGraphSingleConnections(graph);
   new MeekRules().orientImplied(copy);
   if (copy.existsDirectedCycle()) return true;
   List<Triple> newColliders = getUnshieldedCollidersFromGraph(copy);
   newColliders.removeAll(colliders);
   if (!newColliders.isEmpty()) {
     return true;
   }
   return false;
 }
 @Override
 public void transferListenersTo(
     IModelChangeProviderExtension target, IModelChangedListenerFilter filter) {
   ArrayList<IModelChangedListener> removed = new ArrayList<>();
   for (int i = 0; i < fListeners.size(); i++) {
     IModelChangedListener listener = fListeners.get(i);
     if (filter == null || filter.accept(listener)) {
       target.addModelChangedListener(listener);
       removed.add(listener);
     }
   }
   fListeners.removeAll(removed);
 }
  @Override
  public List<String> getAllIndexedSpaceKeys() throws Exception {
    if (allIndexedSpacesKeys == null
        || allIndexedSpacesKeysNextRefresh < System.currentTimeMillis()) {
      allIndexedSpacesKeys = remoteSystemClient.getAllSpaces();
      if (spaceKeysExcluded != null) {
        allIndexedSpacesKeys.removeAll(spaceKeysExcluded);
      }
      allIndexedSpacesKeysNextRefresh = System.currentTimeMillis() + SPACES_REFRESH_TIME;
    }

    return allIndexedSpacesKeys;
  }
Beispiel #29
0
 public static void main(String[] args) {
   Jug[] jugarray = new Jug[5];
   for (int i = 0; i < 5; i++) jugarray[i] = new Jug();
   List<Jug> juglist = Arrays.asList(jugarray);
   System.out.println("Full list: " + juglist);
   List<Jug> sub = juglist.subList(2, 5);
   System.out.println("Sublist: " + sub);
   // juglist.removeAll(sub);	//Throws exception
   List<Jug> copy = new ArrayList<Jug>(juglist);
   copy.removeAll(sub);
   juglist = copy;
   System.out.println("Result: " + juglist);
 }
Beispiel #30
0
  /** @return the list of edges not in any tier. */
  public final List<String> getVariablesNotInTiers() {
    List<MyNode> notInTier = new ArrayList<>(myNodes);

    for (Set<MyNode> tier : tierSpecs) {
      if (tier == null) tier = new HashSet<>();
      notInTier.removeAll(tier);
    }

    List<String> names = new ArrayList<>();
    for (MyNode MyNode : notInTier) names.add(MyNode.getName());

    return names;
  }