Ensure that returned metrics are properly exposed
493620
def _check_metrics(cls, schema, metrics):
        
        for name, value in metrics.items():
            metric = schema.get(name)
            if not metric:
                message = "Unexpected metric '{}' returned".format(name)
                raise Exception(message)
            cls._check_metric(schema, metric, name, value)
1128531
def collect(self):
        
        stats_config = self.config['stats']
        if USE_PYTHON_BINDING:
            collect_metrics = self.collect_via_pynvml
        else:
            collect_metrics = self.collect_via_nvidia_smi

        collect_metrics(stats_config)
871398
def validate_and_clean(args)
      
      raise GatticaError::MissingStartDate, ':start_date is required' if args[:start_date].nil? || args[:start_date].empty?
      raise GatticaError::MissingEndDate, ':end_date is required' if args[:end_date].nil? || args[:end_date].empty?
      raise GatticaError::TooManyDimensions, 'You can only have a maximum of 7 dimensions' if args[:dimensions] && (args[:dimensions].is_a?(Array) && args[:dimensions].length > 7)
      raise GatticaError::TooManyMetrics, 'You can only have a maximum of 10 metrics' if args[:metrics] && (args[:metrics].is_a?(Array) && args[:metrics].length > 10)
      
      possible = args[:dimensions] + args[:metrics]
      
      # make sure that the user is only trying to sort fields that they've previously included with dimensions and metrics
      if args[:sort]
        missing = args[:sort].find_all do |arg|
          !possible.include? arg.gsub(/^-/,'')    # remove possible minuses from any sort params
        end
        unless missing.empty?
          raise GatticaError::InvalidSort, "You are trying to sort by fields that are not in the available dimensions or metrics: #{missing.join(', ')}"
        end
      end
      
      # make sure that the user is only trying to filter fields that are in dimensions or metrics
      if args[:filters]
        missing = args[:filters].find_all do |arg|
          !possible.include? arg.match(/^\w*/).to_s    # get the name of the filter and compare
        end
        unless missing.empty?
          raise GatticaError::InvalidSort, "You are trying to filter by fields that are not in the available dimensions or metrics: #{missing.join(', ')}"
        end
      end
      
      return args
    end
1027242
def _publish_metrics(self, name, prev_keys, key, data):
        """"""
        value = data[key]
        keys = prev_keys + [key]
        if isinstance(value, dict):
            for new_key in value:
                self._publish_metrics(name, keys, new_key, value)
        elif isinstance(value, (float, int, long)):
            joined_keys = '.'.join(keys)
            if name:
                publish_key = '{}.{}'.format(name, joined_keys)
            else:
                publish_key = joined_keys
            if isinstance(value, bool):
                value = int(value)

            self.publish(publish_key, value)
333428
protected void handleStatsResetIfNeeded(StatusData<ApacheMetrics> status) {
        StatValue uptime = getStatValue(ApacheMetrics.SERVER_UPTIME);
        Long currUptime = Long.class.cast(status.get(ApacheMetrics.SERVER_UPTIME));
        if (uptime != null && currUptime != null && uptime.getValueAsLong() > currUptime) {
            for (ApacheMetrics metric : getAvailableMetrics()) {
                if (metric.getType() == StatValueTypes.DIFFLONG) {
                    StatValue stat = getStatValue(metric);
                    if (stat != null)
                        stat.reset();
                }
            }
        }
    }
294572
def _process_metric(self, data, metric, xtype, path, xform=None, tags=None, hostname=None):
        
        value = data

        # Traverse the nested dictionaries
        for key in path.split('.'):
            if value is not None:
                value = value.get(key)
            else:
                break

        if value is not None:
            if xform:
                value = xform(value)
            if xtype == "gauge":
                self.gauge(metric, value, tags=tags, hostname=hostname)
            else:
                self.rate(metric, value, tags=tags, hostname=hostname)
        else:
            self.log.debug("Metric not found: %s -> %s", path, metric)
911563
def get(method, hmc, uri, uri_parms, logon_required):
        """"""
        try:
            metrics_context = hmc.lookup_by_uri(uri)
        except KeyError:
            raise InvalidResourceError(method, uri)
        result = metrics_context.get_metric_values_response()
        return result
1058271
def process_metrics(self, snmp_data):
        ""
        self.metrics = {}
        for i in range(0, len(snmp_data)):
            mib_name = self.models[self.modem_type]['metrics'][i]
            conv = metric_mib[mib_name]['conv']
            self.metrics[mib_name] = conv(snmp_data[i])
943280
def _publish_metrics(self, prev_keys, key, data, publishfn=None):
        """"""
        if key not in data:
            return
        value = data[key]
        keys = prev_keys + [key]
        if not publishfn:
            publishfn = self.publish
        if isinstance(value, dict):
            for new_key in value:
                self._publish_metrics(keys, new_key, value)
        elif isinstance(value, int) or isinstance(value, float):
            publishfn('.'.join(keys), value)
        elif isinstance(value, long):
            publishfn('.'.join(keys), float(value))
340266
def prepare(metric, replacement = Separator)
      escaped = Regexp.escape(replacement)
      replace_begin_end_regex = /\A#{escaped}|#{escaped}\Z/

      metric = metric.to_s.gsub(ReplaceRegex, replacement)
      metric.squeeze!(replacement)
      metric.gsub!(replace_begin_end_regex, Nothing)
      metric
    end
119
def validate(self):
    """"""
    # PASS if all our validators return True, otherwise FAIL.
    try:
      if all(v(self.measured_value.value) for v in self.validators):
        self.outcome = Outcome.PASS
      else:
        self.outcome = Outcome.FAIL
      return self
    except Exception as e:  # pylint: disable=bare-except
      _LOG.error('Validation for measurement %s raised an exception %s.',
                 self.name, e)
      self.outcome = Outcome.FAIL
      raise
    finally:
      if self._cached:
        self._cached['outcome'] = self.outcome.name
504327
def _handle_final_metric_data(self, data):
        
        id_ = data['parameter_id']
        value = data['value']
        if id_ in _customized_parameter_ids:
            self.tuner.receive_customized_trial_result(id_, _trial_params[id_], value)
        else:
            self.tuner.receive_trial_result(id_, _trial_params[id_], value)
1110338
def _format_disk_metrics(self, metrics):
        """"""
        for name, raw_val in metrics.iteritems():
            if raw_val:
                match = DISK_STATS_RE.search(raw_val)
                if match is None or len(match.groups()) != 2:
                    self.log.warning('Can\'t parse value %s for disk metric %s. Dropping it.' % (raw_val, name))
                    metrics[name] = None
                val, unit = match.groups()
                # by default some are uppercased others lowercased. That's error prone.
                unit = unit.lower()
                try:
                    val = int(float(val) * UNIT_MAP[unit])
                    metrics[name] = val
                except KeyError:
                    self.log.error('Unrecognized unit %s for disk metric %s. Dropping it.' % (unit, name))
                    metrics[name] = None
        return metrics
950073
def _monitoring_metrics_list(args, _):
  """"""
  project_id = args['project']
  pattern = args['type'] or '*'
  descriptors = gcm.MetricDescriptors(context=_make_context(project_id))
  dataframe = descriptors.as_dataframe(pattern=pattern)
  return _render_dataframe(dataframe)
1329903
function shouldMetric(ctx) {
	if (ctx.broker.options.metrics) {
		sampleCounter++;
		if (sampleCounter * ctx.broker.options.metricsRate >= 1.0) {
			sampleCounter = 0;
			return true;
		}
	}

	return false;
}
666418
def get_metrics_from_perfdata(self, service, perf_data):
        """"""
        result = []
        metrics = PerfDatas(perf_data)

        for metric in metrics:
            logger.debug("service: %s, metric: %s (%s)", service, metric, metric.__dict__)

            if metric.name in ['time']:
                metric.name = "duration"
            name = sanitize_name(metric.name)
            name = self.multiple_values.sub(r'.\1', name)
            if not name:
                continue

            # get metric value and its thresholds values if they exist
            name_value = {
                name: metric.value,
                'uom_' + name: metric.uom
            }

            # Get or ignore extra values depending upon module configuration
            if metric.warning and self.send_warning:
                name_value[name + '_warn'] = metric.warning

            if metric.critical and self.send_critical:
                name_value[name + '_crit'] = metric.critical

            if metric.min and self.send_min:
                name_value[name + '_min'] = metric.min

            if metric.max and self.send_max:
                name_value[name + '_max'] = metric.max

            for key, value in name_value.items():
                result.append((key, value, metric.uom))

        logger.debug("Metrics: %s - %s", service, result)
        return result
245025
def _check_metrics_file(self, bam_name, metrics_ext):
        
        base, _ = os.path.splitext(bam_name)
        try:
            int(base[-1])
            can_glob = False
        except ValueError:
            can_glob = True
        check_fname = "{base}{maybe_glob}.{ext}".format(
            base=base, maybe_glob="*" if can_glob else "", ext=metrics_ext)
        glob_fnames = glob.glob(check_fname)
        if len(glob_fnames) > 0:
            return glob_fnames[0]
        else:
            return "{base}.{ext}".format(base=base, ext=metrics_ext)