Construct avg transaction graph.

@param scenarioResults   the scenario results
@param scenarioGraphData the scenario graph data
336380
static void constructAvgTransactionGraph(Map.Entry<String, LrProjectScenarioResults> scenarioResults,
                                             JSONObject scenarioGraphData) {
        Map<Integer, TreeMap<String, AvgTransactionResponseTime>> avgTransactionResponseTimeResults =
                scenarioResults.getValue().getAvgTransactionResponseTimeResults();
        JSONObject avgTransactionResponseTimeGraphSet =
                extractAvgTrtData(avgTransactionResponseTimeResults, scenarioResults.getValue().getTransactions());
        if (!avgTransactionResponseTimeGraphSet.getJSONArray(LABELS).isEmpty()) {
            avgTransactionResponseTimeGraphSet.put(TITLE, "Average Transaction Response TIme");
            avgTransactionResponseTimeGraphSet.put(X_AXIS_TITLE, "Build number");
            avgTransactionResponseTimeGraphSet
                    .put(Y_AXIS_TITLE, "Time (Sec.)");
            avgTransactionResponseTimeGraphSet.put(DESCRIPTION,
                    "Displays the average time taken to perform transactions during each second of the load test." +
                            " This graph helps you determine whether the performance of the server is within " +
                            "acceptable minimum and maximum transaction performance time ranges defined for your " +
                            "system.");
            scenarioGraphData.put("averageTransactionResponseTime", avgTransactionResponseTimeGraphSet);
        }
    }
432550
@Bean
    @ConditionalOnMissingBean
    RolloutApprovalStrategy rolloutApprovalStrategy(final UserDetailsService userDetailsService,
            final TenantConfigurationManagement tenantConfigurationManagement,
            final SystemSecurityContext systemSecurityContext) {
        return new DefaultRolloutApprovalStrategy(userDetailsService, tenantConfigurationManagement,
                systemSecurityContext);
    }
436490
public final void merge(TransactionStatistics transactionStatistics) {
      if (trace) {
         log.tracef("Merge transaction statistics %s to the node statistics", transactionStatistics);
      }
      ReservoirSampler reservoirSampler;
      ExtendedStatistic percentileSample;
      if (transactionStatistics.isLocalTransaction()) {
         if (transactionStatistics.isReadOnly()) {
            reservoirSampler = percentiles.get(RO_LOCAL_EXECUTION);
            percentileSample = transactionStatistics.isCommitted() ? RO_TX_SUCCESSFUL_EXECUTION_TIME :
                  RO_TX_ABORTED_EXECUTION_TIME;
         } else {
            reservoirSampler = percentiles.get(WR_LOCAL_EXECUTION);
            percentileSample = transactionStatistics.isCommitted() ? WR_TX_SUCCESSFUL_EXECUTION_TIME :
                  WR_TX_ABORTED_EXECUTION_TIME;
         }
      } else {
         if (transactionStatistics.isReadOnly()) {
            reservoirSampler = percentiles.get(RO_REMOTE_EXECUTION);
            percentileSample = transactionStatistics.isCommitted() ? RO_TX_SUCCESSFUL_EXECUTION_TIME :
                  RO_TX_ABORTED_EXECUTION_TIME;
         } else {
            reservoirSampler = percentiles.get(WR_REMOTE_EXECUTION);
            percentileSample = transactionStatistics.isCommitted() ? WR_TX_SUCCESSFUL_EXECUTION_TIME :
                  WR_TX_ABORTED_EXECUTION_TIME;
         }
      }
      doMerge(transactionStatistics, reservoirSampler, percentileSample);
   }
513642
public void attachToGraph(GraphContext graphContext)
    {
        for (IssueCategory issueCategory : this.issueCategories.values())
        {
            IssueCategoryModel model = graphContext.create(IssueCategoryModel.class);
            model.setCategoryID(issueCategory.getCategoryID());
            model.setName(issueCategory.getName());
            model.setDescription(issueCategory.getDescription());
            model.setOrigin(issueCategory.getOrigin());
            model.setPriority(issueCategory.getPriority());
        }
    }
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);
        }

    }
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;
    }
1374344
@Override
	public DataSet<Result<K>> runInternal(Graph<K, VV, EV> input)
			throws Exception {
		// s, t, d(t)
		DataSet<Edge<K, Tuple2<EV, LongValue>>> neighborDegree = input
			.run(new EdgeTargetDegree<K, VV, EV>()
				.setParallelism(parallelism));

		// group span, s, t, d(t)
		DataSet<Tuple4<IntValue, K, K, IntValue>> groupSpans = neighborDegree
			.groupBy(0)
			.sortGroup(1, Order.ASCENDING)
			.reduceGroup(new GenerateGroupSpans<>(groupSize))
				.setParallelism(parallelism)
				.name("Generate group spans");

		// group, s, t, d(t)
		DataSet<Tuple4<IntValue, K, K, IntValue>> groups = groupSpans
			.rebalance()
				.setParallelism(parallelism)
				.name("Rebalance")
			.flatMap(new GenerateGroups<>())
				.setParallelism(parallelism)
				.name("Generate groups");

		// t, u, d(t)+d(u)
		DataSet<Tuple3<K, K, IntValue>> twoPaths = groups
			.groupBy(0, 1)
			.sortGroup(2, Order.ASCENDING)
			.reduceGroup(new GenerateGroupPairs<>(groupSize))
				.name("Generate group pairs");

		// t, u, intersection, union
		DataSet<Result<K>> scores = twoPaths
			.groupBy(0, 1)
			.reduceGroup(new ComputeScores<>(unboundedScores,
					minimumScoreNumerator, minimumScoreDenominator,
					maximumScoreNumerator, maximumScoreDenominator))
				.name("Compute scores");

		if (mirrorResults) {
			scores = scores
				.flatMap(new MirrorResult<>())
					.name("Mirror results");
		}

		return scores;
	}
744873
@SuppressWarnings("unchecked")
    public GraphTraversal<Vertex, Map<String, Element>> getGraphTraversal(TransactionOLTP tx, Set<Variable> vars) {

        if (fragments().size() == 1) {
            // If there are no disjunctions, we don't need to union them and get a performance boost
            ImmutableList<Fragment> list = Iterables.getOnlyElement(fragments());
            return getConjunctionTraversal(tx, tx.getTinkerTraversal().V(), vars, list);
        } else {
            Traversal[] traversals = fragments().stream()
                    .map(list -> getConjunctionTraversal(tx, __.V(), vars, list))
                    .toArray(Traversal[]::new);

            // This is a sneaky trick - we want to do a union but tinkerpop requires all traversals to start from
            // somewhere, so we start from a single arbitrary vertex.
            GraphTraversal traversal = tx.getTinkerTraversal().V().limit(1).union(traversals);

            return selectVars(traversal, vars);
        }
    }
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
691845
public function afterScenario(ScenarioEvent $event)
    {
        $scenario = $event->getScenario();
        $feature = $scenario->getFeature();
        $url = $feature->getFile();
        $issue = $this->jiraService->getIssue($url);

        if ($issue) {
            $this->postComment($issue, $event->getResult(), $scenario->getTitle());
            $this->updateIssue($issue, $event->getResult());
        }
    }
872101
@Override
    public void evaluate(RDFHandler resultHandler) throws QueryEvaluationException, RDFHandlerException {
        GraphQueryResult queryResult = evaluate();
        if(queryResult.hasNext())
        {
            QueryResults.report(queryResult, resultHandler);
        }
    }
199794
public static double score(ComputationGraph model, MultiDataSetIterator testData, boolean average) {
        //TODO: do this properly taking into account division by N, L1/L2 etc
        double sumScore = 0.0;
        int totalExamples = 0;
        while (testData.hasNext()) {
            MultiDataSet ds = testData.next();
            long numExamples = ds.getFeatures(0).size(0);
            sumScore += numExamples * model.score(ds);
            totalExamples += numExamples;
        }

        if (!average)
            return sumScore;
        return sumScore / totalExamples;
    }
627880
@Override
	public Graph<K, VV, EV> runInternal(Graph<K, VV, EV> input)
			throws Exception {
		// u, d(u)
		DataSet<Vertex<K, LongValue>> vertexDegree = input
			.run(new VertexDegree<K, VV, EV>()
				.setReduceOnTargetId(reduceOnTargetId.get())
				.setParallelism(parallelism));

		// u, d(u) if d(u) > maximumDegree
		DataSet<Tuple1<K>> highDegreeVertices = vertexDegree
			.flatMap(new DegreeFilter<>(maximumDegree))
				.setParallelism(parallelism)
				.name("Filter high-degree vertices");

		JoinHint joinHint = broadcastHighDegreeVertices.get() ? JoinHint.BROADCAST_HASH_SECOND : JoinHint.REPARTITION_HASH_SECOND;

		// Vertices
		DataSet<Vertex<K, VV>> vertices = input
			.getVertices()
			.leftOuterJoin(highDegreeVertices, joinHint)
			.where(0)
			.equalTo(0)
			.with(new ProjectVertex<>())
				.setParallelism(parallelism)
				.name("Project low-degree vertices");

		// Edges
		DataSet<Edge<K, EV>> edges = input
			.getEdges()
			.leftOuterJoin(highDegreeVertices, joinHint)
			.where(reduceOnTargetId.get() ? 1 : 0)
			.equalTo(0)
				.with(new ProjectEdge<>())
				.setParallelism(parallelism)
				.name("Project low-degree edges by " + (reduceOnTargetId.get() ? "target" : "source"))
			.leftOuterJoin(highDegreeVertices, joinHint)
			.where(reduceOnTargetId.get() ? 0 : 1)
			.equalTo(0)
			.with(new ProjectEdge<>())
				.setParallelism(parallelism)
				.name("Project low-degree edges by " + (reduceOnTargetId.get() ? "source" : "target"));

		// Graph
		return Graph.fromDataSet(vertices, edges, input.getContext());
	}
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;
    }
1357543
private static void initDataId(String scenarioName) throws TechnicalException {
        final List<DataIndex> indexData = new ArrayList<>();
        try {
            Context.getDataInputProvider().prepare(scenarioName);
            final Class<Model> model = Context.getDataInputProvider().getModel(Context.getModelPackages());
            if (model != null) {
                final String[] headers = Context.getDataInputProvider().readLine(0, false);
                if (headers != null) {
                    final Constructor<Model> modelConstructor = DataUtils.getModelConstructor(model, headers);
                    final Map<String, ModelList> fusionedData = DataUtils.fusionProcessor(model, modelConstructor);
                    int dataIndex = 0;
                    for (final Entry<String, ModelList> e : fusionedData.entrySet()) {
                        dataIndex++;
                        indexData.add(new DataIndex(dataIndex, e.getValue().getIds()));
                    }
                } else {
                    logger.error(Messages.getMessage(ScenarioInitiator.SCENARIO_INITIATOR_ERROR_EMPTY_FILE));
                }
            } else {
                for (int i = 1; i < Context.getDataInputProvider().getNbLines(); i++) {
                    final List<Integer> index = new ArrayList<>();
                    index.add(i);
                    indexData.add(new DataIndex(i, index));
                }
            }
            Context.getDataInputProvider().setIndexData(indexData);
        } catch (final Exception te) {
            throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE) + te.getMessage(), te);
        }
    }
293964
public void performAdd(File file, String baseURI, RDFFormat dataFormat, Transaction tx, Resource... contexts) throws RDFParseException {
        try {
            graphManager.setDefaultMimetype(dataFormat.getDefaultMIMEType());
            if (dataFormat.equals(RDFFormat.NQUADS) || dataFormat.equals(RDFFormat.TRIG)) {
                graphManager.mergeGraphs(new FileHandle(file),tx);
            } else {
                if (notNull(contexts) && contexts.length>0) {
                    for (int i = 0; i < contexts.length; i++) {
                        if(notNull(contexts[i])){
                            graphManager.mergeAs(contexts[i].toString(), new FileHandle(file), getGraphPerms(),tx);
                        }else{
                            graphManager.mergeAs(DEFAULT_GRAPH_URI, new FileHandle(file),getGraphPerms(), tx);
                        }
                    }
                } else {
                    graphManager.mergeAs(DEFAULT_GRAPH_URI, new FileHandle(file), getGraphPerms(),tx);
                }
            }
        } catch (FailedRequestException e) {
            logger.error(e.getLocalizedMessage());
            throw new RDFParseException("Request to MarkLogic server failed, check file and format.");
        }
    }
676913
public Object getResult(AverageData data) {
        return data.count == 0 ? BigDecimal.ZERO : data.total.divide(BigDecimal.valueOf( data.count ), RoundingMode.HALF_EVEN );
    }