Exemplo n.º 1
0
  @Override
  public byte getLeafSidesInNetwork(NetworkNode networkNode) {
    if (!hasLeafNode(networkNode))
      throw new IllegalArgumentException("Cannot test nodes not in network");

    if (networkingNodes.size() == 0) {
      // Degenerated network
      for (Side connectingOnSide : SideBitFlag.getSides(networkNode.connectionSides)) {
        Vector3i possibleLocation = networkNode.location.toVector3i();
        possibleLocation.add(connectingOnSide.getVector3i());
        for (NetworkNode node : leafNodes.get(new ImmutableBlockLocation(possibleLocation))) {
          if (SideBitFlag.hasSide(node.connectionSides, connectingOnSide.reverse())) {
            return SideBitFlag.getSide(connectingOnSide);
          }
        }
      }

      return 0;
    } else {
      byte result = 0;
      for (Side connectingOnSide : SideBitFlag.getSides(networkNode.connectionSides)) {
        Vector3i possibleLocation = networkNode.location.toVector3i();
        possibleLocation.add(connectingOnSide.getVector3i());
        for (NetworkNode node : networkingNodes.get(new ImmutableBlockLocation(possibleLocation))) {
          if (SideBitFlag.hasSide(node.connectionSides, connectingOnSide.reverse())) {
            result += SideBitFlag.getSide(connectingOnSide);
          }
        }
      }

      return result;
    }
  }
Exemplo n.º 2
0
  int invalidatePath(Path path) {
    try (AutoCloseableLock writeLock = rawAndComputedNodesLock.writeLock()) {
      int invalidatedRawNodes = 0;
      ImmutableSet<Map<String, Object>> rawNodes = allRawNodes.getIfPresent(path);
      if (rawNodes != null) {
        // Increment the counter
        invalidatedRawNodes = rawNodes.size();
        for (Map<String, Object> rawNode : rawNodes) {
          UnflavoredBuildTarget target =
              RawNodeParsePipeline.parseBuildTargetFromRawRule(cell.getRoot(), rawNode, path);
          LOG.debug("Invalidating target for path %s: %s", path, target);
          for (CacheImpl<?> cache : typedNodeCaches.values()) {
            cache.allComputedNodes.invalidateAll(targetsCornucopia.get(target));
          }
          targetsCornucopia.removeAll(target);
        }
        allRawNodes.invalidate(path);
      }

      // We may have been given a file that other build files depend on. Iteratively remove those.
      Iterable<Path> dependents = buildFileDependents.get(path);
      LOG.debug("Invalidating dependents for path %s: %s", path, dependents);
      for (Path dependent : dependents) {
        if (dependent.equals(path)) {
          continue;
        }
        invalidatedRawNodes += invalidatePath(dependent);
      }
      buildFileDependents.removeAll(path);
      buildFileConfigs.remove(path);

      return invalidatedRawNodes;
    }
  }
 public SetMultimap<AbstractModule, FeatureProject> resolveResolutionContext(
     AbstractModule module, boolean scopeTest) {
   final SetMultimap<AbstractModule, FeatureProject> result = LinkedHashMultimap.create();
   for (FeatureProject featureProject : requiredFeatures) {
     result.get(featureProject.getParent().getParent()).add(featureProject);
   }
   if (scopeTest) {
     for (FeatureProject featureProject : requiredTestFeatures) {
       result.get(featureProject.getParent().getParent()).add(featureProject);
     }
   }
   return result;
 }
Exemplo n.º 4
0
 private void parseSimpleFieldAnnotation(
     SetMultimap<String, ASMData> annotations,
     String annotationClassName,
     Function<ModContainer, Object> retreiver)
     throws IllegalAccessException {
   String[] annName = annotationClassName.split("\\.");
   String annotationName = annName[annName.length - 1];
   for (ASMData targets : annotations.get(annotationClassName)) {
     String targetMod = (String) targets.getAnnotationInfo().get("value");
     Field f = null;
     Object injectedMod = null;
     ModContainer mc = this;
     boolean isStatic = false;
     Class<?> clz = modInstance.getClass();
     if (!Strings.isNullOrEmpty(targetMod)) {
       if (Loader.isModLoaded(targetMod)) {
         mc = Loader.instance().getIndexedModList().get(targetMod);
       } else {
         mc = null;
       }
     }
     if (mc != null) {
       try {
         clz = Class.forName(targets.getClassName(), true, Loader.instance().getModClassLoader());
         f = clz.getDeclaredField(targets.getObjectName());
         f.setAccessible(true);
         isStatic = Modifier.isStatic(f.getModifiers());
         injectedMod = retreiver.apply(mc);
       } catch (Exception e) {
         Throwables.propagateIfPossible(e);
         FMLLog.log(
             getModId(),
             Level.WARNING,
             e,
             "Attempting to load @%s in class %s for %s and failing",
             annotationName,
             targets.getClassName(),
             mc.getModId());
       }
     }
     if (f != null) {
       Object target = null;
       if (!isStatic) {
         target = modInstance;
         if (!modInstance.getClass().equals(clz)) {
           FMLLog.log(
               getModId(),
               Level.WARNING,
               "Unable to inject @%s in non-static field %s.%s for %s as it is NOT the primary mod instance",
               annotationName,
               targets.getClassName(),
               targets.getObjectName(),
               mc.getModId());
           continue;
         }
       }
       f.set(target, injectedMod);
     }
   }
 }
 private void collectTransitiveClosure(ClassName className, Set<ClassName> transitiveClosure) {
   if (transitiveClosure.add(className)) {
     for (ClassName referencedClass : _classToReferencedClassesMap.get(className)) {
       collectTransitiveClosure(referencedClass, transitiveClosure);
     }
   }
 }
Exemplo n.º 6
0
  public void testFetch(final SetMultimap<Integer, Integer> nodePartitions) {
    for (final Integer node : nodePartitions.keySet()) {
      System.out.println(
          "Testing fetch of node " + node + " partitions " + nodePartitions.get(node) + ": \n");
      measureFunction(
          new Measurable() {

            @Override
            public long apply() {
              long i = 0;
              Iterator<Pair<ByteArray, Versioned<byte[]>>> result =
                  adminClient.bulkFetchOps.fetchEntries(
                      node,
                      storeName,
                      new ArrayList<Integer>(nodePartitions.get(node)),
                      null,
                      false);
              while (result.hasNext()) {
                i++;
                result.next();
              }
              return i;
            }
          },
          1);
    }
  }
  @Nonnull
  @Override
  public Map<Object, Map<Class, Set<Method>>> findSubscribers() {
    SetMultimap<String, ASMData> allAnnotationsInContainer =
        asmTable.getAnnotationsFor(Loader.instance().activeModContainer());
    if (!allAnnotationsInContainer.containsKey(ForgepathHandler.class.getCanonicalName()))
      return NO_SUBSCRIBERS;
    Set<ASMData> asmDataSet = allAnnotationsInContainer.get(ForgepathHandler.class.getName());

    // Goddamnit Java and your stupidly long types
    ImmutableMap.Builder<Object, Map<Class, Set<Method>>> mapBuilder =
        new ImmutableMap.Builder<Object, Map<Class, Set<Method>>>();

    for (ASMData asmData : asmDataSet) {
      String cname = asmData.getClassName();
      Object obj;
      try {
        obj = Class.forName(cname).newInstance();
      } catch (Exception ex) {
        continue; // SKIP!
      }
      Map<Class, Set<Method>> subscribers = innerLocator.findSubscribers(obj);
      mapBuilder.put(obj, subscribers);
    }

    return mapBuilder.build();
  }
  /**
   * Remove the targets and rules defined by {@code path} from the cache and recursively remove the
   * targets and rules defined by files that transitively include {@code path} from the cache.
   *
   * @param path The File that has changed.
   */
  private synchronized void invalidatePath(Cell cell, Path path) {
    // Paths from Watchman are not absolute.
    path = cell.getFilesystem().resolve(path);

    // If the path is a build file for the cell, nuke the targets that it owns first. We don't need
    // to check whether or not the path ends in the build file name, since we know that these are
    // the only things that get added. Which makes for an easy life.
    List<Map<String, Object>> rawNodes = allRawNodes.getIfPresent(path);
    if (rawNodes != null) {
      // Invalidate the target nodes first
      for (Map<String, Object> rawNode : rawNodes) {
        UnflavoredBuildTarget target = parseBuildTargetFromRawRule(cell.getRoot(), rawNode);
        allTargetNodes.invalidateAll(targetsCornucopia.get(target));
        targetsCornucopia.removeAll(target);
      }

      // And then the raw node itself.
      allRawNodes.invalidate(path);
    }

    // We may have been given a file that other build files depend on. Iteratively remove those.
    Iterable<Path> dependents = buildFileDependents.get(path);
    for (Path dependent : dependents) {
      if (dependent.equals(path)) {
        continue;
      }
      invalidatePath(cell, dependent);
    }
    buildFileDependents.removeAll(path);
  }
Exemplo n.º 9
0
 private TaskSource getSource(PlanNodeId planNodeId) {
   Set<ScheduledSplit> splits = pendingSplits.get(planNodeId);
   boolean noMoreSplits = this.noMoreSplits.contains(planNodeId);
   TaskSource element = null;
   if (!splits.isEmpty() || noMoreSplits) {
     element = new TaskSource(planNodeId, splits, noMoreSplits);
   }
   return element;
 }
Exemplo n.º 10
0
  /**
   * Creates a representation of the profile based on the assigned item for the specified
   * {@linkTaskContext}.
   *
   * @param context
   * @return
   */
  private ProfileData createProfileData(TaskContext context) {
    ProfileData profileData = new ProfileData();
    Set<WorkItem> workItems = assignedWorkItems.get(context);
    if (workItems.isEmpty()) {
      return profileData;
    }

    Container current = fabricService.get().getCurrentContainer();
    Version version = current.getVersion();
    String templateProfileName =
        String.valueOf(context.getConfiguration().get(TEMPLATE_PROFILE_PROPERTY_NAME));
    Profile templateProfile = version.getProfile(templateProfileName);
    Set<String> allFiles = templateProfile.getFileConfigurations().keySet();
    Iterable<String> mvelFiles = Iterables.filter(allFiles, MvelPredicate.INSTANCE);
    Iterable<String> plainFiles =
        Iterables.filter(allFiles, Predicates.not(MvelPredicate.INSTANCE));

    for (String mvelFile : mvelFiles) {
      Key key = new Key(templateProfile.getId(), mvelFile);
      synchronized (templates) {
        CompiledTemplate template = templates.get(key);
        if (template == null) {
          template =
              TemplateCompiler.compileTemplate(
                  new String(templateProfile.getFileConfigurations().get(mvelFile)), parserContext);
          templates.put(key, template);
        }
      }
    }

    for (WorkItem workItem : workItems) {
      Map<String, WorkItem> data = new HashMap<String, WorkItem>();
      data.put(WorkItem.ITEM, workItem);

      // Render templates
      for (String fileTemplate : mvelFiles) {
        String file = renderTemplateName(fileTemplate, workItem);
        Key key = new Key(templateProfile.getId(), fileTemplate);
        try {
          String renderedTemplate =
              TemplateRuntime.execute(templates.get(key), parserContext, data).toString();
          updateProfileData(file, renderedTemplate, profileData);
        } catch (Exception ex) {
          LOGGER.warn("Failed to render {}. Ignoring.", fileTemplate);
        }
      }

      // Copy plain files.
      for (String file : plainFiles) {
        String content = new String(templateProfile.getFileConfigurations().get(file));
        updateProfileData(file, content, profileData);
      }
    }
    return profileData;
  }
Exemplo n.º 11
0
 private boolean canConnectToNetworkingNode(NetworkNode networkNode) {
   for (Side connectingOnSide : SideBitFlag.getSides(networkNode.connectionSides)) {
     final ImmutableBlockLocation possibleConnectionLocation =
         networkNode.location.move(connectingOnSide);
     for (NetworkNode possibleConnectedNode : networkingNodes.get(possibleConnectionLocation)) {
       if (SideBitFlag.hasSide(possibleConnectedNode.connectionSides, connectingOnSide.reverse()))
         return true;
     }
   }
   return false;
 }
Exemplo n.º 12
0
 private void listConnectedNotVisitedNetworkingNodes(
     Set<NetworkNode> visitedNodes, NetworkNode location, Collection<NetworkNode> result) {
   for (Side connectingOnSide : SideBitFlag.getSides(location.connectionSides)) {
     final ImmutableBlockLocation possibleConnectionLocation =
         location.location.move(connectingOnSide);
     for (NetworkNode possibleConnection : networkingNodes.get(possibleConnectionLocation)) {
       if (!visitedNodes.contains(possibleConnection)
           && SideBitFlag.hasSide(possibleConnection.connectionSides, connectingOnSide.reverse()))
         result.add(possibleConnection);
     }
   }
 }
Exemplo n.º 13
0
 @Override
 public void render(Screen screen, MapCanvas canvas) {
   if (canvas.getMapView() != this.map) map = canvas.getMapView();
   Arrays.fill(getBuffer(canvas), (byte) -1);
   for (RenderPriority priority : RenderPriority.values()) {
     if (!renderers.containsKey(priority)) continue;
     for (CanvasRenderer renderer : renderers.get(priority)) {
       if (!renderer.isRendering()) continue;
       directRender(screen, renderer, canvas);
     }
   }
   merge(buffer.buffer, getBuffer(canvas));
 }
Exemplo n.º 14
0
  private double rearrangeGeneTrees(
      List<SortedMap<Node, Node>> branchMovedNodes,
      SetMultimap<Integer, Node> branchGraftNodes,
      boolean forwardMove) {
    double logHastingsRatio = 0.0;

    for (int j = 0; j < nGeneTrees; j++) {
      final Set<Node> jForwardGraftNodes = branchGraftNodes.get(j);
      final SortedMap<Node, Node> jForwardMovedNodes = branchMovedNodes.get(j);
      for (final Entry<Node, Node> nodePair : jForwardMovedNodes.entrySet()) {
        final Node movedNode = nodePair.getKey();
        final Node disownedChild = nodePair.getValue();
        final double movedNodeHeight = movedNode.getHeight();

        final List<Node> validGraftBranches = new ArrayList<>();
        int forwardGraftCount = 0;
        for (Node potentialGraft : jForwardGraftNodes) {
          final double potentialGraftBottom = potentialGraft.getHeight();
          double potentialGraftTop;

          if (potentialGraft.isRoot()) {
            potentialGraftTop = Double.POSITIVE_INFINITY;
          } else {
            potentialGraftTop = potentialGraft.getParent().getHeight();
          }

          if (movedNodeHeight > potentialGraftBottom && movedNodeHeight < potentialGraftTop) {
            forwardGraftCount++;
            validGraftBranches.add(potentialGraft);
          }
        }

        // no compatible branches to graft this node on to
        // this only occurs when there is missing data and the gene tree root is in the "parent"
        // branch
        // or if two gene tree nodes which need moving are of equal height
        if (forwardGraftCount == 0) {
          return Double.NEGATIVE_INFINITY;
        } else {
          logHastingsRatio += Math.log(forwardGraftCount);
          if (forwardMove) { // only actually change gene trees if this is the forward move
            final Node chosenGraft = validGraftBranches.get(Randomizer.nextInt(forwardGraftCount));
            pruneAndRegraft(movedNode, chosenGraft, disownedChild);
          }
        }
      }
    }

    return logHastingsRatio;
  }
Exemplo n.º 15
0
  public TaskSelection getSelection(String path) {
    SetMultimap<String, Task> tasksByName;
    String baseName;
    String prefix;

    ProjectInternal project = gradle.getDefaultProject();

    if (path.contains(Project.PATH_SEPARATOR)) {
      project = projectFinder.findProject(path, project);
      baseName = StringUtils.substringAfterLast(path, Project.PATH_SEPARATOR);
      prefix = project.getPath() + Project.PATH_SEPARATOR;

      tasksByName = taskNameResolver.select(baseName, project);
    } else {
      baseName = path;
      prefix = "";

      tasksByName = taskNameResolver.selectAll(path, project);
    }

    Set<Task> tasks = tasksByName.get(baseName);
    if (!tasks.isEmpty()) {
      // An exact match
      return new TaskSelection(path, tasks);
    }

    NameMatcher matcher = new NameMatcher();
    String actualName = matcher.find(baseName, tasksByName.keySet());

    if (actualName != null) {
      // A partial match
      return new TaskSelection(prefix + actualName, tasksByName.get(actualName));
    }

    throw new TaskSelectionException(matcher.formatErrorMessage("task", project));
  }
Exemplo n.º 16
0
 @Override
 public BindsConfig deserialize(
     JsonElement json, Type typeOfT, JsonDeserializationContext context)
     throws JsonParseException {
   BindsConfig result = new BindsConfig();
   JsonObject inputObj = json.getAsJsonObject();
   for (Map.Entry<String, JsonElement> entry : inputObj.entrySet()) {
     SetMultimap<String, Input> map = context.deserialize(entry.getValue(), SetMultimap.class);
     for (String id : map.keySet()) {
       SimpleUri uri = new SimpleUri(new Name(entry.getKey()), id);
       result.data.putAll(uri, map.get(id));
     }
   }
   return result;
 }
Exemplo n.º 17
0
  /**
   * Returns all elements of the dependency graph that match the given predicate, and any elements
   * upstream of those matching elements.
   *
   * <p>The graph may contain cycles.
   *
   * <p>Each key in the dependency graph depends on/is downstream of its associated values.
   */
  public static <T> ImmutableSet<T> getMatchingAndUpstream(
      Set<T> allNodes, SetMultimap<T, T> dependencyGraph, Predicate<T> matcher) {
    Set<T> results = Sets.newHashSet();

    Deque<T> toTry = Queues.newArrayDeque();
    toTry.addAll(Collections2.filter(allNodes, matcher));

    while (!toTry.isEmpty()) {
      T curElem = toTry.remove();
      if (!results.contains(curElem)) {
        results.add(curElem);
        toTry.addAll(dependencyGraph.get(curElem));
      }
    }
    return ImmutableSet.copyOf(results);
  }
Exemplo n.º 18
0
  /**
   * For each node in the graph, we want to find the longest path from the node to the root. The
   * length of the longest path is the depth at which the node should be drawn in the visualization
   * of the graph.
   */
  @VisibleForTesting
  static SetMultimap<Integer, String> calculateModuleDepths(
      String root, Map<String, List<String>> graph) {

    // To determine the longest path for each node, progressively descend
    // down the inverted dependency tree. Keep track of each module found at
    // that depth and record the deepest point at which the module was seen.
    SetMultimap<Integer, String> modulesAtDepth = HashMultimap.create();
    modulesAtDepth.put(0, root);
    Map<String, Integer> moduleToDepth = Maps.newHashMap();
    moduleToDepth.put(root, 0);

    int depth = 0;
    while (true) {
      Set<String> modules = modulesAtDepth.get(depth);
      if (modules.isEmpty()) {
        break;
      }
      int newDepth = ++depth;

      // For each module at the current depth, collect of its descendants so
      // they can be inserted in modulesAtDepth at their new depth.
      Set<String> atNewDepth = Sets.newHashSet();
      for (String module : modules) {
        List<String> descendants = graph.get(module);
        for (String descendant : descendants) {
          atNewDepth.add(descendant);
        }
      }

      // A module in atNewDepth may already be in the modulesAtDepth multimap.
      // If so, then the key with which it is associated in the multimap must
      // be changed. The moduleToDepth map is used to keep track of where each
      // module is in the multimap for quick lookup, so moduleToDepth must be
      // kept up to date, as well.
      for (String module : atNewDepth) {
        if (moduleToDepth.containsKey(module)) {
          int oldDepth = moduleToDepth.remove(module);
          modulesAtDepth.remove(oldDepth, module);
        }
        moduleToDepth.put(module, newDepth);
        modulesAtDepth.put(newDepth, module);
      }
    }

    return modulesAtDepth;
  }
Exemplo n.º 19
0
  /**
   * Returns new or cached instances of PBXBuildFiles corresponding to files that may or may not
   * belong to an aggregate reference (see {@link AggregateReferenceType}). Files specified by the
   * {@code paths} argument are grouped into individual PBXBuildFiles using the given {@link
   * AggregateReferenceType}. Files that are standalone are not put in an aggregate reference, but
   * are put in a standalone PBXBuildFile in the returned sequence.
   */
  public Iterable<PBXBuildFile> get(AggregateReferenceType type, Iterable<Path> paths) {
    ImmutableList.Builder<PBXBuildFile> result = new ImmutableList.Builder<>();
    SetMultimap<AggregateKey, Path> keyedPaths = type.aggregates(paths);
    for (Map.Entry<AggregateKey, Collection<Path>> aggregation : keyedPaths.asMap().entrySet()) {
      if (!aggregation.getKey().isStandalone()) {
        ImmutableSet<Path> itemPaths = ImmutableSet.copyOf(aggregation.getValue());
        result.add(
            aggregateBuildFile(
                itemPaths, type.create(aggregation.getKey(), fileReferences(itemPaths))));
      }
    }
    for (Path generalResource : keyedPaths.get(AggregateKey.standalone())) {
      result.add(getStandalone(FileReference.of(generalResource.toString(), SourceTree.GROUP)));
    }

    return result.build();
  }
Exemplo n.º 20
0
 @Override
 public JsonElement serialize(
     BindsConfig src, Type typeOfSrc, JsonSerializationContext context) {
   JsonObject result = new JsonObject();
   SetMultimap<Name, SimpleUri> bindByModule = HashMultimap.create();
   for (SimpleUri key : src.data.keySet()) {
     bindByModule.put(key.getModuleName(), key);
   }
   List<Name> sortedModules = Lists.newArrayList(bindByModule.keySet());
   Collections.sort(sortedModules);
   for (Name moduleId : sortedModules) {
     SetMultimap<String, Input> moduleBinds = HashMultimap.create();
     for (SimpleUri bindUri : bindByModule.get(moduleId)) {
       moduleBinds.putAll(bindUri.getObjectName().toString(), src.data.get(bindUri));
     }
     JsonElement map = context.serialize(moduleBinds, SetMultimap.class);
     result.add(moduleId.toString(), map);
   }
   return result;
 }
  // batch job (possibly real-time using streaming APIs)
  public static void createProductAssociativityGraphPerCategory() {
    Set<String> customers = purchasesCache.keySet();
    customers.forEach(
        customer -> {
          List<String> customerPurchases = Lists.newArrayList(purchasesCache.get(customer));
          for (int i = 0; i < customerPurchases.size(); i++) {
            for (int j = i + 1; j < customerPurchases.size(); j++) {
              Product product1 = productCache.get(customerPurchases.get(i));
              Product product2 = productCache.get(customerPurchases.get(j));

              if (product1.category.equals(product2.category)) {
                ProductAssociativityGraph graph =
                    productAssociativityGraphMap.getOrDefault(
                        product1.category, ProductAssociativityGraph.create());

                graph.addAssociation(Vertex.create(product1.id), Vertex.create(product2.id), 1);
                productAssociativityGraphMap.putIfAbsent(product1.category, graph);
              }
            }
          }
        });
  }
Exemplo n.º 22
0
  /** @see eu.esdihumboldt.hale.ui.cst.debug.metadata.internal.TreeGraphProvider#generateGraph() */
  @Override
  public Graph generateGraph() {

    tree.accept(graphVisitor);

    SetMultimap<String, String> connections = graphVisitor.getAllConnections();
    Set<String> ids = graphVisitor.getAllIds();

    TinkerGraph graph = new TinkerGraph();

    // add nodes to the graph
    for (String key : ids) {
      TransformationNode node = graphVisitor.getNode(key);
      Vertex vertex = graph.addVertex(key);
      setVertexProperty(node, vertex);
    }

    for (String key : connections.keySet()) {
      for (String value : connections.get(key)) {
        graph.addEdge(null, graph.getVertex(key), graph.getVertex(value), " ");
      }
    }
    return graph;
  }
 public Set<ClassName> getReferencedClasses(ClassName className) {
   return Collections.unmodifiableSet(_classToReferencedClassesMap.get(className));
 }
Exemplo n.º 24
0
  private List<SetMultimap<AbstractDirection, Point>> run(String folder, String branchName) {
    List<SetMultimap<AbstractDirection, Point>> res =
        new ArrayList<SetMultimap<AbstractDirection, Point>>();

    File[] files = new File(folder).listFiles();

    /*
     * Holds the number of the parse mapped to the station name mapped to the file for
     * that station
     */
    Map<Integer, List<String>> biDirectionalParseFolders = new HashMap<Integer, List<String>>();
    for (File f : files) {
      int individualParseId = new Integer(f.getName().split("-")[0]);
      String stationNameWithDotTxt = (f.getName().split("-")[2]);
      String stationName = stationNameWithDotTxt.substring(0, (stationNameWithDotTxt.length() - 4));

      if (!biDirectionalParseFolders.containsKey(individualParseId)) {
        biDirectionalParseFolders.put(individualParseId, new ArrayList<String>());
      }
      List<String> stationNames = biDirectionalParseFolders.get(individualParseId);
      stationNames.add(stationName);
    }

    List<List<String>> parseFiles = new ArrayList<List<String>>();
    for (int i = 0; i < biDirectionalParseFolders.size(); i++) {
      parseFiles.add(biDirectionalParseFolders.get(i));
    }

    for (int i = 0; i < parseFiles.size(); i++) {
      System.out.println("LongevityRecordedTests.run parsing id: " + i);
      TflSiteScraperFromSavedFilesForTesting scraper =
          new TflSiteScraperFromSavedFilesForTesting(new File(folder), "" + i);
      BranchIterator branchIterator =
          new BranchIteratorImpl(fixture.getSerializedFileDaoFactory(), scraper);
      SetMultimap<AbstractDirection, Point> map = branchIterator.run(branchName);
      res.add(branchIterator.run(branchName));

      int count = 0;
      for (AbstractDirection dir : map.keySet()) {
        List<Point> pointList = Lists.newArrayList(map.get(dir));
        count += pointList.size();
        System.out.println(dir + " total: " + pointList.size());
        for (Point point : pointList) {
          System.out.println(
              dir
                  + ": "
                  + ((DiscoveredTrain) point).getDescription()
                  + "   ('"
                  + ((DiscoveredTrain) point).getFurthestStation().getStationName()
                  + "')");
        }
      }
      // int totalMeasuredTrains =
      // SingletonStatsCollector.getInstance().allStats().get(branchName).iterator().next().getNumberOfTrainsFound();
      // System.out.println("total trains: "+count+ " total measured trains in stats:
      // "+totalMeasuredTrains);

    }

    return res;
  }
Exemplo n.º 25
0
 public static void unregister(UUID id, World world) {
   synchronized (mutex) {
     worldMapping.get(world).remove(id);
     cs.remove(id);
   }
 }
 /**
  * Get the value of the program counter at the current state's successor state.
  *
  * @return an AbsoluteAddress corresponding to the next PC value for the analyzed module.
  */
 public Set<AbsoluteAddress> getNextPC() {
   return succ.get(cur);
 }
  private ARGState relocateRefinementRoot(
      final ARGState pRefinementRoot, final boolean predicatePrecisionIsAvailable)
      throws InterruptedException {

    // no relocation needed if only running value analysis,
    // because there, this does slightly degrade performance
    // when running VA+PA, merging/covering and refinements
    // of both CPAs could lead to the state, where in two
    // subsequent refinements, two identical error paths
    // were found, through different parts of the ARG
    // So now, when running VA+PA, the refinement root
    // is set to the lowest common ancestor of those states
    // that are covered by the states in the subtree of the
    // original refinement root
    if (!predicatePrecisionIsAvailable) {
      return pRefinementRoot;
    }

    // no relocation needed if restart at top
    if (restartStrategy == RestartStrategy.ROOT) {
      return pRefinementRoot;
    }

    Set<ARGState> descendants = pRefinementRoot.getSubgraph();
    Set<ARGState> coveredStates = new HashSet<>();
    shutdownNotifier.shutdownIfNecessary();
    for (ARGState descendant : descendants) {
      coveredStates.addAll(descendant.getCoveredByThis());
    }
    coveredStates.add(pRefinementRoot);

    // no relocation needed if set of descendants is closed under coverage
    if (descendants.containsAll(coveredStates)) {
      return pRefinementRoot;
    }

    Map<ARGState, ARGState> predecessorRelation = Maps.newHashMap();
    SetMultimap<ARGState, ARGState> successorRelation = LinkedHashMultimap.create();

    Deque<ARGState> todo = new ArrayDeque<>(coveredStates);
    ARGState coverageTreeRoot = null;

    // build the coverage tree, bottom-up, starting from the covered states
    while (!todo.isEmpty()) {
      shutdownNotifier.shutdownIfNecessary();
      final ARGState currentState = todo.removeFirst();

      if (currentState.getParents().iterator().hasNext()) {
        ARGState parentState = currentState.getParents().iterator().next();
        todo.add(parentState);
        predecessorRelation.put(currentState, parentState);
        successorRelation.put(parentState, currentState);

      } else if (coverageTreeRoot == null) {
        coverageTreeRoot = currentState;
      }
    }

    // starting from the root of the coverage tree,
    // the new refinement root is either the first node
    // having two or more children, or the original
    // refinement root, what ever comes first
    shutdownNotifier.shutdownIfNecessary();
    ARGState newRefinementRoot = coverageTreeRoot;
    while (successorRelation.get(newRefinementRoot).size() == 1
        && newRefinementRoot != pRefinementRoot) {
      newRefinementRoot = Iterables.getOnlyElement(successorRelation.get(newRefinementRoot));
    }

    rootRelocations.inc();
    return newRefinementRoot;
  }
Exemplo n.º 28
0
 @Override
 public Set<CFAEdge> getTransformers(AbstractState a) {
   return reverseCFA.get(a.getLocation());
 }
Exemplo n.º 29
0
 @Override
 public Iterable<BlockUri> getBlockFamiliesWithCategory(String category) {
   return categoryLookup.get(category.toLowerCase(Locale.ENGLISH));
 }