Sets the metrics of the group based on aggregation_type.
974338
def _aggregate_metrics(self, session_group):
    """"""

    if (self._request.aggregation_type == api_pb2.AGGREGATION_AVG or
        self._request.aggregation_type == api_pb2.AGGREGATION_UNSET):
      _set_avg_session_metrics(session_group)
    elif self._request.aggregation_type == api_pb2.AGGREGATION_MEDIAN:
      _set_median_session_metrics(session_group,
                                  self._request.aggregation_metric)
    elif self._request.aggregation_type == api_pb2.AGGREGATION_MIN:
      _set_extremum_session_metrics(session_group,
                                    self._request.aggregation_metric,
                                    min)
    elif self._request.aggregation_type == api_pb2.AGGREGATION_MAX:
      _set_extremum_session_metrics(session_group,
                                    self._request.aggregation_metric,
                                    max)
    else:
      raise error.HParamsError('Unknown aggregation_type in request: %s' %
                               self._request.aggregation_type)
287593
def _use_aggregation(self, agg, columns=None):
        """"""
        if not columns:
            columns = self._columns
        from pyspark.sql import functions as F
        aggs = map(lambda column: agg(column).alias(column), self._columns)
        aggRdd = self._grouped_spark_sql.agg(*aggs)
        df = DataFrame.from_schema_rdd(aggRdd, self._by)
        return df
324307
def new_tank_metric(self, _type, name, hostname=None, group=None, source=None, *kw):
        
        if not _type:
            raise ValueError('Metric type should be defined.')

        if _type in available_metrics:
            metric_obj = available_metrics[_type](None, self.routing_queue)  # create metric object
            metric_info = {'type': _type,
                           'source': source,
                           'name': name,
                           'hostname': hostname,
                           'group': group}
            if kw is not None:
                metric_info.update(kw)
            metric_meta = pd.DataFrame({metric_obj.local_id: metric_info}).T  # create metric meta
            self.metrics_meta = self.metrics_meta.append(metric_meta)  # register metric meta
            self.metrics[metric_obj.local_id] = metric_obj  # register metric object

            # find subscribers for this metric
            this_metric_subscribers = self.__reversed_filter(self.subscribers, metric_info)
            if this_metric_subscribers.empty:
                logger.debug('subscriber for metric %s not found', metric_obj.local_id)
            else:
                logger.debug('Found subscribers for this metric, subscribing...: %s', this_metric_subscribers)
                # attach this metric id to discovered subscribers and select id <-> callbacks
                this_metric_subscribers['id'] = metric_obj.local_id
                found_callbacks = this_metric_subscribers[['id', 'callback']].set_index('id')
                # add this metric callbacks to DataManager's callbacks
                self.callbacks = self.callbacks.append(found_callbacks)
            return metric_obj
        else:
            raise NotImplementedError('Unknown metric type: %s' % _type)
1305283
def Set(self, value, fields=None):
    """"""
    self._metric_values[_FieldsToKey(fields)] = self._value_type(value)
940761
def categorize_metrics(self):
        """"""
        category = self.cleaned_data['category_name']
        metrics = self.cleaned_data['metrics']
        self.r.reset_category(category, metrics)
918807
@SuppressWarnings("fallthrough")
  private void getAggregatedMetrics(List<MetricTimeRangeValue> metricValue,
                                    long startTime, long endTime, long bucketId,
                                    MetricsFilter.MetricAggregationType type,
                                    MetricGranularity granularity) {
    LOG.fine("getAggregatedMetrics " + startTime + " " + endTime);
    // per request
    long outterCountAvg = 0;

    // prepare range value
    long outterStartTime = Long.MAX_VALUE;
    long outterEndTime = 0;
    String outterValue = null;

    double outterResult = 0;
    Long startKey = cacheMetric.floorKey(startTime);
    for (Long key = startKey != null ? startKey : cacheMetric.firstKey();
         key != null && key <= endTime;
         key = cacheMetric.higherKey(key)) {
      LinkedList<MetricDatapoint> bucket = cacheMetric.get(key).get(bucketId);

      if (bucket != null) {
        // per bucket
        long innerCountAvg = 0;

        // prepare range value
        long innerStartTime = Long.MAX_VALUE;
        long innerEndTime = 0;
        String innerValue = null;

        double innerResult = 0;
        for (MetricDatapoint datapoint : bucket) {
          if (datapoint.inRange(startTime, endTime)) {
            switch (type) {
              case AVG:
                outterCountAvg++;
                innerCountAvg++;
              case SUM:
                outterResult += Double.parseDouble(datapoint.getValue());
                innerResult += Double.parseDouble(datapoint.getValue());
                break;
              case LAST:
                if (outterEndTime < datapoint.getTimestamp()) {
                  outterValue = datapoint.getValue();
                }
                if (innerEndTime < datapoint.getTimestamp()) {
                  innerValue = datapoint.getValue();
                }
                break;
              case UNKNOWN:
              default:
                LOG.warning(
                    "Unknown metric type, CacheCore does not know how to aggregate " + type);
                return;
            }
            outterStartTime = Math.min(outterStartTime, datapoint.getTimestamp());
            outterEndTime = Math.max(outterEndTime, datapoint.getTimestamp());
            innerStartTime = Math.min(innerStartTime, datapoint.getTimestamp());
            innerEndTime = Math.max(innerEndTime, datapoint.getTimestamp());
          }
        } // end bucket

        if (type.equals(MetricsFilter.MetricAggregationType.AVG) && innerCountAvg > 0) {
          innerValue = String.valueOf(innerResult / innerCountAvg);
        } else if (type.equals(MetricsFilter.MetricAggregationType.SUM)) {
          innerValue = String.valueOf(innerResult);
        }
        if (innerValue != null && granularity.equals(MetricGranularity.AGGREGATE_BY_BUCKET)) {
          metricValue.add(new MetricTimeRangeValue(innerStartTime, innerEndTime, innerValue));
        }
      }

    } // end tree

    if (type.equals(MetricsFilter.MetricAggregationType.AVG) && outterCountAvg > 0) {
      outterValue = String.valueOf(outterResult / outterCountAvg);
    } else if (type.equals(MetricsFilter.MetricAggregationType.SUM)) {
      outterValue = String.valueOf(outterResult);
    }
    if (outterValue != null && granularity.equals(MetricGranularity.AGGREGATE_ALL_METRICS)) {
      metricValue.add(new MetricTimeRangeValue(outterStartTime, outterEndTime, outterValue));
    }
  }
525088
def _set_attributes(self, **kwargs):
        '''
        '''

        try:
            self.devices = kwargs['devices'][:]
            self.name = kwargs['device_group_name']
            self.type = kwargs['device_group_type']
            self.partition = kwargs['device_group_partition']
        except KeyError as ex:
            raise MissingRequiredDeviceGroupParameter(ex)
758217
public void setBandwidthGroups(com.google.api.ads.admanager.axis.v201808.Technology[] bandwidthGroups) {
        this.bandwidthGroups = bandwidthGroups;
    }
1170443
public void ensure_metric_groups() {
        HttpURLConnection urlConnection = null;
        OutputStreamWriter wr = null;
        URL myurl = null;

        try {
           myurl = new URL(url_str + "/metric_groups.json?show_hidden=1");
           urlConnection = (HttpURLConnection) myurl.openConnection();
           urlConnection.setRequestMethod("GET");
           urlConnection.setDoInput(true);
           urlConnection.setDoOutput(true);
           urlConnection.setReadTimeout(coppereggApiTimeoutInMillis);
           urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
           urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication);

           int responseCode = urlConnection.getResponseCode();
           if (responseCode != 200) {
               logger.warn("Bad responsecode " + String.valueOf(responseCode)+ " from metric_groups Index: " +  myurl);
           }
        } catch (Exception e) {
              exceptionCounter.incrementAndGet();
              logger.warn("Failure to execute metric_groups index request "+ myurl + "  "+ e);
        } finally {
            if (urlConnection != null) {
                try {
                    InputStream in = urlConnection.getInputStream();
                    String theString = convertStreamToString(in);
                    for (Map.Entry<String, String> entry : metricgroupMap.entrySet()) {
                        String checkName =  entry.getKey();
                        try {
                            String Rslt = groupFind(checkName, theString, 0);
                            if(Rslt != null){
                                // Update it
                                Rslt = Send_Commmand("/metric_groups/" + Rslt + ".json?show_hidden=1", "PUT", entry.getValue(),0);
                            } else {
                                // create it
                                Rslt = Send_Commmand("/metric_groups.json", "POST", entry.getValue(),0);
                            }
                            if(Rslt != null) {
                                if (Rslt.toLowerCase().contains("tomcat")) {
                                    if (Rslt.toLowerCase().contains("thread_pool")) {
                                       tomcat_thread_pool_groupID = Rslt;
                                    } else if(Rslt.toLowerCase().contains("grp")) { 
                                        tomcat_grp_groupID = Rslt;
                                    } else if(Rslt.toLowerCase().contains("servlet")) { 
                                        tomcat_servlet_groupID = Rslt;
                                    } else if(Rslt.toLowerCase().contains("manager")) { 
                                        tomcat_manager_groupID = Rslt;
                                    } else if(Rslt.toLowerCase().contains("db")) { 
                                        tomcat_db_groupID = Rslt;
                                    }
                                } else if (Rslt.toLowerCase().contains("jmxtrans")){
                                    jmxtrans_metric_groupID = Rslt;
                                } else if (Rslt.toLowerCase().contains("sales")){
                                    app_sales_groupID = Rslt;
                                } else if (Rslt.toLowerCase().contains("cocktail")){
                                    app_groupID = Rslt;
                                } else if (Rslt.toLowerCase().contains("jvm")){
                                    if (Rslt.toLowerCase().contains("os")) {
                                        jvm_os_groupID = Rslt;
                                    } else if (Rslt.toLowerCase().contains("gc")) {
                                        jvm_gc_groupID = Rslt;
                                    } else if (Rslt.toLowerCase().contains("runtime")) {
                                        jvm_runtime_groupID = Rslt;
                                    } else if (Rslt.toLowerCase().contains("class")) {
                                        jvm_class_groupID = Rslt;
                                    } else if (Rslt.toLowerCase().contains("thread")) {
                                        jvm_thread_groupID = Rslt;
                                    }
                                } else if (Rslt.toLowerCase().contains("nonheap")) {
                                    nonheap_metric_groupID = Rslt;
                                } else if (Rslt.toLowerCase().contains("heap")) {
                                    heap_metric_groupID = Rslt;
                                } 
                            }
                        } catch (Exception e) {
                            exceptionCounter.incrementAndGet();
                            logger.warn("Exception in metric_group update or create: "+ myurl + "  "+ e);
                        }
                    }
                } catch (IOException e) {
                    exceptionCounter.incrementAndGet();
                    logger.warn("Exception flushing http connection"+ e);
                }
            }
        }
    }
79441
def agg(self, aggregations):
        
        check_type(aggregations, list)

        new_index = Index(np.array(aggregations, dtype=np.bytes_), np.dtype(np.bytes_))

        return _series_agg(self, aggregations, new_index)
1303576
def set_metric_ids(self, key, metric_ids):
        
        with self._lock:
            self._metric_ids[key] = metric_ids
1031556
def set_metrics(self, key, name, metrics):
        
        with self._mor_lock:
            mor = self._mor[key].get(name)
            if mor is None:
                raise MorNotFoundError("Mor object '{}' is not in the cache.".format(name))
            mor['metrics'] = metrics
1216783
private void setAliveDeadMetrics() {
    clusterManager.getMetrics().setAliveNodes(nameToNode.size());
    int totalHosts = hostsReader.getHosts().size();
    if (totalHosts > 0) {
      clusterManager.getMetrics().setDeadNodes(
          totalHosts - nameToNode.size());
    }
  }
511623
public void setAggregateComplianceCounts(java.util.Collection<AggregateComplianceCount> aggregateComplianceCounts) {
        if (aggregateComplianceCounts == null) {
            this.aggregateComplianceCounts = null;
            return;
        }

        this.aggregateComplianceCounts = new com.amazonaws.internal.SdkInternalList<AggregateComplianceCount>(aggregateComplianceCounts);
    }
848317
public void add(final Metric metric) {
		Preconditions.checkNotNull(metric);
		
		// get the aggregate for this minute
		
		MetricAggregate aggregate = getAggregate(metric.getIdentity());
		
		// add the current metric into the aggregate
		
		switch (metric.getIdentity().getType()) {
			case COUNTER: 
			case TIMER: 
			case AVERAGE:
				aggregate.setCount(aggregate.getCount() + 1);
				aggregate.setValue(aggregate.getValue() + metric.getValue());
			    break;
			case GAUGE:
				aggregate.setCount(1);
				if (metric.isIncrement()) {
					aggregate.setValue(aggregate.getValue() + metric.getValue());
				} else {
					aggregate.setValue(metric.getValue());
				}
			    break;	
			default:
				LOGGER.info("Unable to aggregate {} metric type", metric.getIdentity().getType());
				break;
		}
	}
431752
def __set_type(self, stats, sensor_type):
        
        for i in stats:
            # Set the sensors type
            i.update({'type': sensor_type})
            # also add the key name
            i.update({'key': self.get_key()})

        return stats
340933
public void setGroups(java.util.Collection<GroupType> groups) {
        if (groups == null) {
            this.groups = null;
            return;
        }

        this.groups = new java.util.ArrayList<GroupType>(groups);
    }