Construct avg hits graph.

@param scenarioResults   the scenario results
@param scenarioGraphData the scenario graph data
435127
static void constructAvgHitsGraph(Map.Entry<String, LrProjectScenarioResults> scenarioResults,
                                      JSONObject scenarioGraphData) {
        Map<Integer, WholeRunResult> avgHitsPerSec = scenarioResults.getValue().getAverageHitsPerSecondResults();
        JSONObject avgHitsPerSecGraphSet = extractWholeRunSlaResult(avgHitsPerSec, "Hits/Sec");
        if (!avgHitsPerSecGraphSet.getJSONArray(LABELS).isEmpty()) {
            avgHitsPerSecGraphSet.put(TITLE, "Average Hits per Second");
            avgHitsPerSecGraphSet.put(X_AXIS_TITLE, "Build number");
            avgHitsPerSecGraphSet.put(Y_AXIS_TITLE, "Hits");
            avgHitsPerSecGraphSet.put(DESCRIPTION,
                    "Displays the number of hits made on the Web server by Vusers " +
                            "during each second of the load test. This graph helps you evaluate the amount of load " +
                            "Vusers" +
                            " " +
                            "generate, in terms of the number of hits.");
            scenarioGraphData.put("avgHitsPerSec", avgHitsPerSecGraphSet);
        }
    }
843903
public JavaDoubleRDD scoreExamples(RDD<DataSet> data, boolean includeRegularizationTerms, int batchSize) {
        return scoreExamples(data.toJavaRDD(), includeRegularizationTerms, batchSize);
    }
686055
public static EdgeScores insideOutsideO2AllGraSingleRoot(DependencyScorer scorer, Algebra s) {
        return insideOutside02AllGra(scorer, s, true);
    }
417631
protected void createRealmDataObject(Root inputRootObject, String inputRealm) {
        // use the root DataGraph to create a Context DataGraph
        List<Context> contexts = inputRootObject.getContexts();
        if (contexts != null) {
            Context ctx = new Context();
            // set "WIM.Realm" in the Context DataGraph to the realm
            ctx.setKey(Service.VALUE_CONTEXT_REALM_KEY);
            ctx.setValue(inputRealm);
            contexts.add(ctx);
        }

    }
207601
public static void marginals(final Hypergraph graph, final Hyperpotential w, final Algebra s,
            final Scores scores) {
        final int n = graph.getNodes().size();
        final double[] alpha = scores.alpha;
        final double[] beta = scores.beta;
        final double[] marginal = new double[n];
        int root = graph.getRoot().getId();
        
        // p(i) = \alpha_i * \beta_i / \beta_{root}
        for (Hypernode iNode : graph.getNodes()) {
            int i = iNode.getId();
            marginal[i] = s.divide(s.times(alpha[i], beta[i]), beta[root]); 
        }
        
        scores.marginal = marginal;
    }
545938
def add_scenario(network_id, scenario,**kwargs):
    
    user_id = int(kwargs.get('user_id'))
    log.info("Adding scenarios to network")

    _check_network_ownership(network_id, user_id)

    existing_scen = db.DBSession.query(Scenario).filter(Scenario.name==scenario.name, Scenario.network_id==network_id).first()
    if existing_scen is not None:
        raise HydraError("Scenario with name %s already exists in network %s"%(scenario.name, network_id))

    scen = Scenario()
    scen.name                 = scenario.name
    scen.description          = scenario.description
    scen.layout               = scenario.get_layout()
    scen.network_id           = network_id
    scen.created_by           = user_id
    scen.start_time           = str(timestamp_to_ordinal(scenario.start_time)) if scenario.start_time else None
    scen.end_time             = str(timestamp_to_ordinal(scenario.end_time)) if scenario.end_time else None
    scen.time_step            = scenario.time_step
    scen.resourcescenarios    = []
    scen.resourcegroupitems   = []

    #Just in case someone puts in a negative ID for the scenario.
    if scenario.id < 0:
        scenario.id = None

    if scenario.resourcescenarios is not None:
        #extract the data from each resourcescenario so it can all be
        #inserted in one go, rather than one at a time
        all_data = [r.dataset for r in scenario.resourcescenarios]

        datasets = data._bulk_insert_data(all_data, user_id=user_id)

        #record all the resource attribute ids
        resource_attr_ids = [r.resource_attr_id for r in scenario.resourcescenarios]

        #get all the resource scenarios into a list and bulk insert them
        for i, ra_id in enumerate(resource_attr_ids):
            rs_i = ResourceScenario()
            rs_i.resource_attr_id = ra_id
            rs_i.dataset_id       = datasets[i].id
            rs_i.scenario_id      = scen.id
            rs_i.dataset = datasets[i]
            scen.resourcescenarios.append(rs_i)

    if scenario.resourcegroupitems is not None:
        #Again doing bulk insert.
        for group_item in scenario.resourcegroupitems:
            group_item_i = ResourceGroupItem()
            group_item_i.scenario_id = scen.id
            group_item_i.group_id    = group_item.group_id
            group_item_i.ref_key     = group_item.ref_key
            if group_item.ref_key == 'NODE':
                group_item_i.node_id      = group_item.ref_id
            elif group_item.ref_key == 'LINK':
                group_item_i.link_id      = group_item.ref_id
            elif group_item.ref_key == 'GROUP':
                group_item_i.subgroup_id  = group_item.ref_id
            scen.resourcegroupitems.append(group_item_i)
    db.DBSession.add(scen)
    db.DBSession.flush()
    return scen
277094
@Override
  public MarginalSet computeMarginals(FactorGraph factorGraph) {
    VariableNumMap variables = factorGraph.getVariables();
    Preconditions.checkArgument(variables.getDiscreteVariables().size() == variables.size());

    // Initialize the mean field distribution to the uniform distribution over
    // all variables.
    long curTime = System.currentTimeMillis();
    System.out.println("init: " + (System.currentTimeMillis() - curTime)); 
    int numVars = variables.size();
    IndexedList<Integer> variableNums = new IndexedList<Integer>(variables.getVariableNums());
    List<DiscreteVariable> variableTypes = variables.getDiscreteVariables();
    List<Tensor> variableMarginals = Lists.newArrayListWithCapacity(numVars);
    for (int i = 0; i < numVars; i++) {
      int[] dimensions = new int[] { variableNums.get(i) };
      int[] sizes = new int[] { variableTypes.get(i).numValues() };
      variableMarginals.add(DenseTensor.constant(dimensions, sizes, 1.0 / sizes[0]));
    }
    System.out.println("logweights: "  + (System.currentTimeMillis() - curTime));
    // Get the log weights for each factor in the original factor graph.
    List<Tensor> logWeights = Lists.newArrayList();
    for (Factor factor : factorGraph.getFactors()) {
      logWeights.add(factor.coerceToDiscrete().getWeights().elementwiseLog());
    }
    System.out.println("done: " +  + (System.currentTimeMillis() - curTime)); 

    double updateL2 = Double.POSITIVE_INFINITY;
    int numIterations = 0;
    while (updateL2 > CONVERGENCE_DELTA) {
      updateL2 = 0.0;
      for (int i = 0; i < numVars; i++) {
        int curVarNum = variableNums.get(i);
        // Accumulate the messages from each factor containing this variable.
        DenseTensorBuilder messageAccumulator = new DenseTensorBuilder(
            variableMarginals.get(i).getDimensionNumbers(), variableMarginals.get(i).getDimensionSizes());
        Set<Integer> factorIndexes = factorGraph.getFactorsWithVariable(curVarNum);
        // System.out.println(i + " " + curVarNum + ": " + factorIndexes);
        for (int factorIndex : factorIndexes) {
          Tensor factorMessage = getFactorMessage(curVarNum, logWeights.get(factorIndex),
              variableMarginals, variableNums);
          // System.out.println("factorMessage: " +
          // Arrays.toString(factorMessage.getDimensionNumbers()));
          // System.out.println("messageAccumulator: " +
          // Arrays.toString(messageAccumulator.getDimensionNumbers()));
          messageAccumulator.increment(factorMessage);
        }

        // Update the marginal based on the inbound messages, setting
        // marginal equal to the logistic function of the accumulated messages.
        messageAccumulator.exp();
        double normalizingConstant = messageAccumulator.getTrace();
        messageAccumulator.multiply(1.0 / normalizingConstant);
        Tensor newMarginal = messageAccumulator.buildNoCopy();

        // Compute the convergence criteria
        Tensor delta = newMarginal.elementwiseAddition(
            variableMarginals.get(i).elementwiseProduct(SparseTensor.getScalarConstant(-1.0)));
        updateL2 += delta.getL2Norm();

        variableMarginals.set(i, newMarginal);
      }
      numIterations++;
      System.out.println("update L2: " + updateL2);
    }
    
    System.out.println("iterations:" + numIterations);
    // Format output as factors.
    List<Factor> marginals = Lists.newArrayList();
    for (int i = 0; i < numVars; i++) {
      marginals.add(new TableFactor(variables.intersection(variableNums.get(i)),
          variableMarginals.get(i)));
    }

    System.out.println("really done: " +  + (System.currentTimeMillis() - curTime));
    return new FactorMarginalSet(marginals, 1.0, factorGraph.getConditionedVariables(),
        factorGraph.getConditionedValues());
  }
608418
public static <I, O> SequenceTaggerError evaluateTagger(SequenceTagger<I, O> tagger,
      Collection<? extends TaggedSequence<I, O>> evaluationData) {
    MapReduceExecutor executor = MapReduceConfiguration.getMapReduceExecutor();
    return executor.mapReduce(evaluationData, new SequenceTaggerEvaluationMapper<I, O>(tagger, -1),
        new SequenceTaggerEvaluationReducer());
  }
1312690
public static Map<IssueCategoryModel, List<ProblemSummary>> getProblemSummaries(GraphContext graphContext, Set<ProjectModel> projectModels, Set<String> includeTags,
                                                                                    Set<String> excludeTags,
                                                                                    boolean strictComparison,
                                                                                    boolean strictExclude)
    {
        // The key is the severity as a String
        Map<IssueCategoryModel, List<ProblemSummary>> results = new TreeMap<>(new IssueCategoryModel.IssueSummaryPriorityComparator());
        Map<RuleSummaryKey, ProblemSummary> ruleToSummary = new HashMap<>();

        InlineHintService hintService = new InlineHintService(graphContext);
        final Iterable<InlineHintModel> hints = projectModels == null ? hintService.findAll() : hintService.getHintsForProjects(new ArrayList<>(projectModels));
        for (InlineHintModel hint : hints)
        {
            if (hint.getIssueDisplayMode() == IssueDisplayMode.DETAIL_ONLY)
                continue;

            Set<String> tags = hint.getTags();

            boolean hasTagMatch;

            if (strictComparison)
            {
                hasTagMatch = TagUtil.strictCheckMatchingTags(tags, includeTags, excludeTags);
            }
            else
            {
                hasTagMatch = TagUtil.checkMatchingTags(tags, includeTags, excludeTags, strictExclude);
            }

            if (!hasTagMatch)
            {
                continue;
            }

            RuleSummaryKey key = new RuleSummaryKey(hint.getEffort(), hint.getRuleID(), hint.getTitle());

            ProblemSummary summary = ruleToSummary.get(key);
            if (summary == null)
            {
                summary = new ProblemSummary(UUID.randomUUID().toString(), hint.getIssueCategory(), hint.getRuleID(), hint.getTitle(), 1, hint.getEffort());
                for (LinkModel link : hint.getLinks())
                {
                    summary.addLink(link.getDescription(), link.getLink());
                }
                ruleToSummary.put(key, summary);
                addToResults(results, summary);
            }
            else
            {
                summary.setNumberFound(summary.getNumberFound() + 1);
            }
            summary.addFile(hint.getHint(), hint.getFile());
        }

        ClassificationService classificationService = new ClassificationService(graphContext);
        for (ClassificationModel classification : classificationService.findAll())
        {
            if (classification.getIssueDisplayMode() == IssueDisplayMode.DETAIL_ONLY)
                continue;

            Set<String> tags = classification.getTags();
            if (!TagUtil.checkMatchingTags(tags, includeTags, excludeTags, false))
                continue;

            List<FileModel> newFileModels = new ArrayList<>();
            for (FileModel file : classification.getFileModels())
            {
                if (projectModels != null)
                {
                    // make sure this one is in the project
                    if (!projectModels.contains(file.getProjectModel()))
                        continue;
                }
                newFileModels.add(file);
            }

            if (newFileModels.isEmpty())
                continue;

            RuleSummaryKey key = new RuleSummaryKey(classification.getEffort(), classification.getRuleID(), classification.getClassification());
            ProblemSummary summary = ruleToSummary.get(key);
            if (summary == null)
            {
                summary = new ProblemSummary(UUID.randomUUID().toString(), classification.getIssueCategory(), classification.getRuleID(),
                            classification.getClassification(),
                            0, classification.getEffort());
                for (LinkModel link : classification.getLinks())
                {
                    summary.addLink(link.getDescription(), link.getLink());
                }
                ruleToSummary.put(key, summary);
                addToResults(results, summary);
            }

            for (FileModel file : newFileModels)
                summary.addFile(classification.getDescription(), file);

            summary.setNumberFound(summary.getNumberFound() + newFileModels.size());
        }

        return results;
    }
346580
public static void main(String... args) throws Exception {
		
		if(!parseParameters(args)) {
			return;
		}
		
		// set up execution environment
		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
		
		// read vertex and edge data
		DataSet<Long> vertices = getVertexDataSet(env);
		DataSet<Tuple2<Long, Long>> edges = getEdgeDataSet(env).flatMap(new UndirectEdge());
		
		// assign the initial components (equal to the vertex id)
		DataSet<Tuple2<Long, Long>> verticesWithInitialId = vertices.map(new DuplicateValue<Long>());
				
		// open a delta iteration
		DeltaIteration<Tuple2<Long, Long>, Tuple2<Long, Long>> iteration =
				verticesWithInitialId.iterateDelta(verticesWithInitialId, maxIterations, 0);
		
		// apply the step logic: join with the edges, select the minimum neighbor, update if the component of the candidate is smaller
		DataSet<Tuple2<Long, Long>> changes = iteration.getWorkset().join(edges).where(0).equalTo(0).with(new NeighborWithComponentIDJoin())
				.groupBy(0).aggregate(Aggregations.MIN, 1)
				.join(iteration.getSolutionSet()).where(0).equalTo(0)
				.with(new ComponentIdFilter());

		// close the delta iteration (delta and new workset are identical)
		DataSet<Tuple2<Long, Long>> result = iteration.closeWith(changes, changes);
		
		// emit result
		if(fileOutput) {
			result.writeAsCsv(outputPath, "\n", " ");
		} else {
			result.print();
		}
				
		// execute program
		env.execute("Connected Components Example");
				
	}
64280
public function registerScenarioStat(ScenarioStat $stat)
    {
        if (TestResults::NO_TESTS === $stat->getResultCode()) {
            return;
        }

        $this->scenarioCounters[$stat->getResultCode()]++;

        if (TestResult::FAILED === $stat->getResultCode()) {
            $this->failedScenarioStats[] = $stat;
        }

        if (TestResult::SKIPPED === $stat->getResultCode()) {
            $this->skippedScenarioStats[] = $stat;
        }
    }
319372
public void addScenario(Class<? extends Scenario> scenarioClass,
            String scenarioID, String initialState, Properties properties,
            String gatewayDeviceID, String externalLinkID)
            throws ShanksException {
        // throws NonGatewayDeviceException, TooManyConnectionException,
        // DuplicatedIDException, AlreadyConnectedScenarioException,
        // SecurityException, NoSuchMethodException, IllegalArgumentException,
        // InstantiationException, IllegalAccessException,
        // InvocationTargetException {
        Constructor<? extends Scenario> c;
        Scenario scenario;
        try {
            c = scenarioClass.getConstructor(new Class[] { String.class,
                    String.class, Properties.class, Logger.class });
            scenario = c.newInstance(scenarioID, initialState, properties, this.getLogger());
        } catch (SecurityException e) {
            throw new ShanksException(e);
        } catch (NoSuchMethodException e) {
            throw new ShanksException(e);
        } catch (IllegalArgumentException e) {
            throw new ShanksException(e);
        } catch (InstantiationException e) {
            throw new ShanksException(e);
        } catch (IllegalAccessException e) {
            throw new ShanksException(e);
        } catch (InvocationTargetException e) {
            throw new ShanksException(e);
        }

        Device gateway = (Device) scenario.getNetworkElement(gatewayDeviceID);
        Link externalLink = (Link) this.getNetworkElement(externalLinkID);
        if (!scenario.getCurrentElements().containsKey(gatewayDeviceID)) {
            throw new NonGatewayDeviceException(scenario, gateway, externalLink);
        } else {
            gateway.connectToLink(externalLink);
            if (!this.getCurrentElements().containsKey(externalLink.getID())) {
                this.addNetworkElement(externalLink);
            }
            if (!this.scenarios.containsKey(scenario)) {
                this.scenarios.put(scenario, new ArrayList<Link>());
            } else {
                List<Link> externalLinks = this.scenarios.get(scenario);
                if (!externalLinks.contains(externalLink)) {
                    externalLinks.add(externalLink);
                } else if (externalLink.getLinkedDevices().contains(gateway)) {
                    throw new AlreadyConnectedScenarioException(scenario,
                            gateway, externalLink);
                }
            }
        }
    }
1245715
public static Evaluation getEvaluation(ComputationGraph model, MultiDataSetIterator testData) {
        if (model.getNumOutputArrays() != 1)
            throw new IllegalStateException("GraphSetSetAccuracyScoreFunction cannot be "
                            + "applied to ComputationGraphs with more than one output. NumOutputs = "
                            + model.getNumOutputArrays());

        return model.evaluate(testData);
    }
402618
@Override
  public void outputText(SDocumentGraph graph, boolean alignmc, int matchNumber,
    Writer out) throws IOException, IllegalArgumentException
  {

    // first match
    if (matchNumber == 0)
    {
      // output header
      List<String> headerLine = new ArrayList<>();
      for(Map.Entry<Integer, TreeSet<String>> match: annotationsForMatchedNodes.entrySet())
      {
        int node_id = match.getKey();
        headerLine.add(String.valueOf(node_id) + "_id");
        headerLine.add(String.valueOf(node_id) + "_span");
        for (String annoName: match.getValue())
        {
          headerLine.add(String.valueOf(node_id) + "_anno_" + annoName);
        }
      }
      for (String key: metakeys) {
        headerLine.add("meta_" + key);
      }
      out.append(StringUtils.join(headerLine, "\t"));
      out.append("\n");
    }

    // output nodes in the order of the matches
    SortedMap<Integer, String> contentLine = new TreeMap<>();
    for (SNode node: this.getMatchedNodes(graph)) {
      List<String> nodeLine = new ArrayList<>();
      // export id
      RelannisNodeFeature feats = RelannisNodeFeature.extract(node);
      nodeLine.add(String.valueOf(feats.getInternalID()));
      // export spanned text
      String span = graph.getText(node);
      if (span != null)
        nodeLine.add(graph.getText(node));
      else
        nodeLine.add("");
      // export annotations
      int node_id = node
        .getFeature(AnnisConstants.ANNIS_NS, AnnisConstants.FEAT_MATCHEDNODE)
        .getValue_SNUMERIC().intValue();
      for (String annoName: annotationsForMatchedNodes.get(node_id))
      {
        SAnnotation anno = node.getAnnotation(annoName);
        if (anno != null)
        {
          nodeLine.add(anno.getValue_STEXT());
        }
        else
          nodeLine.add("'NULL'");
      }
      // add everything to line
      contentLine.put(node_id, StringUtils.join(nodeLine, "\t"));
    }

    out.append(StringUtils.join(contentLine.values(), "\t"));

    // export Metadata
    // TODO cache the metadata
    if(!metakeys.isEmpty()) {
      // TODO is this the best way to get the corpus name?
      String corpus_name = CommonHelper.getCorpusPath(java.net.URI.create(graph.getDocument().getId())).get(0);
      List<Annotation> asList = Helper.getMetaData(corpus_name, graph.getDocument().getName());
      for(Annotation anno : asList)
      {
        if (metakeys.contains(anno.getName()))
          out.append("\t" + anno.getValue());
      }
    }

    out.append("\n");
  }
984839
public OverviewStats valuate(CucumberScenarioResult scenario) {
        this.reset();
        scenario.valuate();
        this.addOverallDuration((float) scenario.getDuration());
        this.addStepsPassed(scenario.getPassed());
        this.addStepsFailed(scenario.getFailed());
        this.addStepsKnown(scenario.getKnown());
        this.addStepsUndefined(scenario.getUndefined() + scenario.getSkipped());
        return this;
    }
1310238
public static double score(ComputationGraph model, DataSetIterator testSet, RegressionValue regressionValue) {
        RegressionEvaluation evaluation = model.evaluateRegression(testSet);
        return getScoreFromRegressionEval(evaluation, regressionValue);
    }
1175732
public JavaDoubleRDD scoreExamples(JavaRDD<DataSet> data, boolean includeRegularizationTerms) {
        return scoreExamplesMultiDataSet(data.map(new DataSetToMultiDataSetFn()), includeRegularizationTerms);
    }