Takes one metric or a wildcard seriesList.

    Sorts the list of metrics by the sum of values across the time period
    specified.
195450
def sortByTotal(requestContext, seriesList):
    
    return list(sorted(seriesList, key=safeSum, reverse=True))
1343148
@POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/metrics")
    @Description("Submits externally collected metric data.")
    public Map<String, Object> submitMetrics(@Context HttpServletRequest req, final List<MetricDto> metricDtos) {
        PrincipalUser remoteUser = getRemoteUser(req);

        SystemAssert.requireArgument(metricDtos != null, "Cannot submit null timeseries metrics list.");

        List<Metric> legalMetrics = new ArrayList<>();
        List<MetricDto> illegalMetrics = new ArrayList<>();
        List<String> errorMessages = new ArrayList<>();

        for (MetricDto metricDto : metricDtos) {
            try {
                Metric metric = new Metric(metricDto.getScope(), metricDto.getMetric());
                metric.setTags(metricDto.getTags());
                if (metricDto.getMetatags() != null) {
                    metric.setMetatagsRecord(new MetatagsRecord(metricDto.getMetatags(), metricDto.getMetatagsKey()));
                }

                copyProperties(metric, metricDto);
                legalMetrics.add(metric);
            } catch (Exception e) {
                illegalMetrics.add(metricDto);
                errorMessages.add(e.getMessage());
            }
        }
        _collectionService.submitMetrics(remoteUser, legalMetrics);

        Map<String, Object> result = new HashMap<>();

        result.put("Success", legalMetrics.size() + " metrics");
        result.put("Error", illegalMetrics.size() + " metrics");
        result.put("Error Messages", errorMessages);
        return result;
    }
643005
private void summarize(MetricDatum datum, Map<String, MetricDatum> uniqueMetrics) {
        Double value = datum.getValue();
        if (value == null) {
            return;
        }
        List<Dimension> dims = datum.getDimensions();
        Collections.sort(dims, DimensionComparator.INSTANCE);
        String metricName = datum.getMetricName();
        String key = metricName + Jackson.toJsonString(dims);
        MetricDatum statDatum = uniqueMetrics.get(key);
        if (statDatum == null) {
            statDatum = new MetricDatum()
                .withDimensions(datum.getDimensions())
                .withMetricName(metricName)
                .withUnit(datum.getUnit())
                .withStatisticValues(new StatisticSet()
                    .withMaximum(value)
                    .withMinimum(value)
                    .withSampleCount(0.0)
                    .withSum(0.0))
                ;
            uniqueMetrics.put(key, statDatum);
        }
        StatisticSet stat = statDatum.getStatisticValues();
        stat.setSampleCount(stat.getSampleCount() + 1.0);
        stat.setSum(stat.getSum() + value);
        if (value > stat.getMaximum()) {
            stat.setMaximum(value);
        } else if (value < stat.getMinimum()) {
            stat.setMinimum(value);
        }
    }
752451
def time_segments_aggregate(X, interval, time_column, method=['mean']):
    """"""
    if isinstance(X, np.ndarray):
        X = pd.DataFrame(X)

    X = X.sort_values(time_column).set_index(time_column)

    if isinstance(method, str):
        method = [method]

    start_ts = X.index.values[0]
    max_ts = X.index.values[-1]

    values = list()
    index = list()
    while start_ts <= max_ts:
        end_ts = start_ts + interval
        subset = X.loc[start_ts:end_ts - 1]
        aggregated = [
            getattr(subset, agg)(skipna=True).values
            for agg in method
        ]
        values.append(np.concatenate(aggregated))
        index.append(start_ts)
        start_ts = end_ts

    return np.asarray(values), np.asarray(index)
1193188
def linear_weighted_moving_average(data, period):
    
    catch_errors.check_for_period_error(data, period)

    idx_period = list(range(1, period+1))
    lwma = [(sum([i * idx_period[data[idx-(period-1):idx+1].index(i)]
              for i in data[idx-(period-1):idx+1]])) /
            sum(range(1, len(data[idx+1-period:idx+1])+1)) for idx in range(period-1, len(data))]
    lwma = fill_for_noncomputable_vals(data, lwma)
    return lwma
990846
function() {
      this.totals = [];
      this.maxTotal = 0;
      this.bounds.reset();

      if (this.series_.length === 0)
        return;

      var firstSeries = this.series_[0];
      var lastSeries = this.series_[this.series_.length - 1];

      this.bounds.addValue(firstSeries.getTimestamp(0));
      this.bounds.addValue(lastSeries.getTimestamp(lastSeries.length - 1));

      var numSeries = this.numSeries;
      this.maxTotal = -Infinity;

      // Sum the samples at each timestamp.
      // Note, this assumes that all series have all timestamps.
      for (var i = 0; i < firstSeries.length; ++i) {
        var total = 0;
        this.series_.forEach(function(series) {
          total += series.getSample(i).value;
          this.totals.push(total);
        }.bind(this));

        this.maxTotal = Math.max(total, this.maxTotal);
      }
    }
616324
def do_metric_list(mc, args):
    ''''''
    fields = {}
    if args.name:
        fields['name'] = args.name
    if args.dimensions:
        fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
    if args.limit:
        fields['limit'] = args.limit
    if args.offset:
        fields['offset'] = args.offset
    if args.starttime:
        _translate_starttime(args)
        fields['start_time'] = args.starttime
    if args.endtime:
        fields['end_time'] = args.endtime
    if args.tenant_id:
        fields['tenant_id'] = args.tenant_id

    try:
        metric = mc.metrics.list(**fields)
    except (osc_exc.ClientException, k_exc.HttpError) as he:
        raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
    else:
        if args.json:
            print(utils.json_formatter(metric))
            return
        cols = ['name', 'dimensions']
        formatters = {
            'name': lambda x: x['name'],
            'dimensions': lambda x: utils.format_dict(x['dimensions']),
        }
        if isinstance(metric, list):
            # print the list
            utils.print_list(metric, cols, formatters=formatters)
        else:
            # add the dictionary to a list, so print_list works
            metric_list = list()
            metric_list.append(metric)
            utils.print_list(
                metric_list,
                cols,
                formatters=formatters)
633775
def sort_values(self, return_indexer=False, ascending=True):
        
        if return_indexer:
            _as = self.argsort()
            if not ascending:
                _as = _as[::-1]
            sorted_index = self.take(_as)
            return sorted_index, _as
        else:
            sorted_values = np.sort(self._ndarray_values)
            attribs = self._get_attributes_dict()
            freq = attribs['freq']

            if freq is not None and not is_period_dtype(self):
                if freq.n > 0 and not ascending:
                    freq = freq * -1
                elif freq.n < 0 and ascending:
                    freq = freq * -1
            attribs['freq'] = freq

            if not ascending:
                sorted_values = sorted_values[::-1]

            return self._simple_new(sorted_values, **attribs)
183400
public TimeSeriesMetricDeltaSet map(Function<? super MetricValue, ? extends MetricValue> fn) {
        return values_
                .map(
                        fn,
                        (x) -> x.entrySet().stream().map((entry) -> apply_fn_(entry, fn))
                )
                .mapCombine(TimeSeriesMetricDeltaSet::new, TimeSeriesMetricDeltaSet::new);
    }
178792
@Override
  public SortedMap<String, Timer> getTimers(MetricFilter filter) {
    return this.innerMetricContext.getTimers(filter);
  }
717798
public Group withMetrics(java.util.Map<String, MetricValue> metrics) {
        setMetrics(metrics);
        return this;
    }
1230049
private List<Metric> mapping(List<Metric> metrics) {
        SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");
        if (metrics.isEmpty()) {
            return metrics;
        }

        List<Metric> newMetricsList = new ArrayList<Metric>();

        for (Metric metric : metrics) {
            Map<Long, Double> cleanDatapoints = cleanDPs(metric.getDatapoints());

            metric.setDatapoints(this.valueMapping.mapping(cleanDatapoints));
            newMetricsList.add(metric);
        }
        return newMetricsList;
    }
748241
def get_metrics(self, start, end, period):
        """"""
        values = {}
        default_dimensions = {
            'Policy': self.policy.name, 'ResType': self.policy.resource_type,
            'Scope': 'Policy'}

        metrics = list(self.POLICY_METRICS)

        # Support action, and filter custom metrics
        for el in itertools.chain(
                self.policy.resource_manager.actions,
                self.policy.resource_manager.filters):
            if el.metrics:
                metrics.extend(el.metrics)

        session = utils.local_session(self.policy.session_factory)
        client = session.client('cloudwatch')

        for m in metrics:
            if isinstance(m, six.string_types):
                dimensions = default_dimensions
            else:
                m, m_dimensions = m
                dimensions = dict(default_dimensions)
                dimensions.update(m_dimensions)
            results = client.get_metric_statistics(
                Namespace=DEFAULT_NAMESPACE,
                Dimensions=[
                    {'Name': k, 'Value': v} for k, v
                    in dimensions.items()],
                Statistics=['Sum', 'Average'],
                StartTime=start,
                EndTime=end,
                Period=period,
                MetricName=m)
            values[m] = results['Datapoints']
        return values
517139
public Stream<Entry<MatchedName, MetricValue>> filter(Context t) {
        return t.getTSData().getCurrentCollection().get(this::match, x -> true).stream()
                .flatMap(this::filterMetricsInTsv);
    }
190827
public List<Series> retrieveMetricSeries(String metricName, String entityName) {
        return retrieveMetricSeries(metricName, Collections.singletonMap("entity", entityName));
    }
271189
def averageOutsidePercentile(requestContext, seriesList, n):
    
    averages = [safeAvg(s) for s in seriesList]

    if n < 50:
        n = 100 - n

    lowPercentile = _getPercentile(averages, 100 - n)
    highPercentile = _getPercentile(averages, n)

    return [s for s in seriesList
            if not lowPercentile < safeAvg(s) < highPercentile]
131839
static Map<String, Double> processMetrics(String prefix, Iterable<MetricsInfo> metrics) {
    Map<String, Double> map = new HashMap<>();
    for (MetricsInfo r : metrics) {
      try {
        map.put(prefix + r.getName(), Double.valueOf(r.getValue()));
      } catch (NumberFormatException ne) {
        LOG.log(Level.SEVERE, "Could not parse metric, Name: "
            + r.getName() + " Value: " + r.getValue(), ne);
      }
    }
    return map;
  }