Basic query to get the metric values

        :param evolutionary: if True the metric values time series is returned. If False the aggregated metric value.
        :return: the DSL query to be sent to Elasticsearch
163361
def get_query(self, evolutionary=False):
        

        if not evolutionary:
            interval = None
            offset = None
        else:
            interval = self.interval
            offset = self.offset
            if not interval:
                raise RuntimeError("Evolutionary query without an interval.")

        query = ElasticQuery.get_agg(field=self.FIELD_COUNT,
                                     date_field=self.FIELD_DATE,
                                     start=self.start, end=self.end,
                                     filters=self.esfilters,
                                     agg_type=self.AGG_TYPE,
                                     interval=interval,
                                     offset=offset)

        logger.debug("Metric: '%s' (%s); Query: %s",
                     self.name, self.id, query)
        return query
5890
def on_epoch_end(self, last_metrics, **kwargs):
        ""
        if not self.nums: return
        metrics = [self.metrics[name]/self.nums for name in self.names]
        return {'last_metrics': last_metrics+metrics}
143686
def __get_metrics(self):
        
        esfilters_merge = None
        esfilters_abandon = None
        if self.esfilters:
            esfilters_merge = self.esfilters.copy()
            esfilters_abandon = self.esfilters.copy()

        merged = Merged(self.es_url, self.es_index,
                        start=self.start, end=self.end,
                        esfilters=esfilters_merge, interval=self.interval)

        abandoned = Abandoned(self.es_url, self.es_index,
                              start=self.start, end=self.end,
                              esfilters=esfilters_abandon, interval=self.interval)
        return (merged, abandoned)
826098
def _get_metrics_record(xapi, rectype, record):
    '''
    
    '''
    metrics_id = record['metrics']
    return getattr(xapi, '{0}_metrics'.format(rectype)).get_record(metrics_id)
110591
def MetricValueTypeFromPythonType(python_type):
  """"""
  if python_type in (int, long):
    return rdf_stats.MetricMetadata.ValueType.INT
  elif python_type == float:
    return rdf_stats.MetricMetadata.ValueType.FLOAT
  else:
    raise ValueError("Invalid value type: %s" % python_type)
1343173
def est_cluster_metric(self, cluster_opts=None):
        
        wcv, bcv, tv = self.est_cluster_covs(cluster_opts)
        return np.diag(bcv) / np.diag(tv)
1116510
def get(self):
        
        if self.num_inst == 0:
            return (self.name, float('nan'))
        else:
            return (self.name, self.sum_metric / self.num_inst)
119557
def Get(self, fields=None):
    """"""
    if not self._field_defs and fields:
      raise ValueError("Metric was registered without fields, "
                       "but following fields were provided: %s." % (fields,))

    if self._field_defs and not fields:
      raise ValueError("Metric was registered with fields (%s), "
                       "but no fields were provided." % self._field_defs)

    if self._field_defs and fields and len(self._field_defs) != len(fields):
      raise ValueError(
          "Metric was registered with %d fields (%s), but "
          "%d fields were provided (%s)." % (len(
              self._field_defs), self._field_defs, len(fields), fields))

    metric_value = self._metric_values.get(_FieldsToKey(fields))
    return self._DefaultValue() if metric_value is None else metric_value
1299803
def get_metrics(tag):
    
    if tag is None:
        return metrics.metrics_by_name_list(metrics.metrics())
    else:
        return metrics.metrics_by_tag(tag)
640250
def get_aggs(self):
        

        res = self.fetch_aggregation_results()
        if 'aggregations' in res and 'values' in res['aggregations'][str(self.parent_agg_counter - 1)]:
            try:
                agg = res['aggregations'][str(self.parent_agg_counter - 1)]['values']["50.0"]
                if agg == 'NaN':
                    # ES returns NaN. Convert to None for matplotlib graph
                    agg = None
            except Exception as e:
                raise RuntimeError("Multivalue aggregation result not supported")

        elif 'aggregations' in res and 'value' in res['aggregations'][str(self.parent_agg_counter - 1)]:
            agg = res['aggregations'][str(self.parent_agg_counter - 1)]['value']

        else:
            agg = res['hits']['total']

        return agg
695385
def __get_metrics(self):
        
        esfilters_close = None
        esfilters_submit = None
        if self.esfilters:
            esfilters_close = self.esfilters.copy()
            esfilters_submit = self.esfilters.copy()

        closed = ClosedPR(self.es_url, self.es_index,
                          start=self.start, end=self.end,
                          esfilters=esfilters_close, interval=self.interval)
        # For BMI we need when the ticket was closed
        closed.FIELD_DATE = 'closed_at'
        submitted = SubmittedPR(self.es_url, self.es_index,
                                start=self.start, end=self.end,
                                esfilters=esfilters_submit,
                                interval=self.interval)

        return (closed, submitted)
1266955
def _fetch_atari_metrics(base_env):
    
    unwrapped = base_env.get_unwrapped()
    if not unwrapped:
        return None
    atari_out = []
    for u in unwrapped:
        monitor = get_wrapper_by_cls(u, MonitorEnv)
        if not monitor:
            return None
        for eps_rew, eps_len in monitor.next_episode_results():
            atari_out.append(RolloutMetrics(eps_len, eps_rew, {}, {}, {}))
    return atari_out
152417
def get_evolution_stone(self, slug):
        
        endpoint = '/evolution-stone/' + slug
        return self.make_request(self.BASE_URL + endpoint)
42485
private List<Long> collectLongMetric(String metricGetterName) {
        List<Long> vals = new ArrayList<Long>();
        for(BdbEnvironmentStats envStats: environmentStatsTracked) {
            vals.add((Long) ReflectUtils.callMethod(envStats,
                                                    BdbEnvironmentStats.class,
                                                    metricGetterName,
                                                    new Class<?>[0],
                                                    new Object[0]));
        }
        return vals;
    }
111333
def _collect_dict(self, metric_type, field_metric_map, query, db, tags):
        
        try:
            with closing(db.cursor()) as cursor:
                cursor.execute(query)
                result = cursor.fetchone()
                if result is not None:
                    for field, metric in list(iteritems(field_metric_map)):
                        # Find the column name in the cursor description to identify the column index
                        # http://www.python.org/dev/peps/pep-0249/
                        # cursor.description is a tuple of (column_name, ..., ...)
                        try:
                            col_idx = [d[0].lower() for d in cursor.description].index(field.lower())
                            self.log.debug("Collecting metric: %s" % metric)
                            if result[col_idx] is not None:
                                self.log.debug("Collecting done, value %s" % result[col_idx])
                                if metric_type == GAUGE:
                                    self.gauge(metric, float(result[col_idx]), tags=tags)
                                elif metric_type == RATE:
                                    self.rate(metric, float(result[col_idx]), tags=tags)
                                else:
                                    self.gauge(metric, float(result[col_idx]), tags=tags)
                            else:
                                self.log.debug("Received value is None for index %d" % col_idx)
                        except ValueError:
                            self.log.exception("Cannot find %s in the columns %s" % (field, cursor.description))
        except Exception:
            self.warning("Error while running %s\n%s" % (query, traceback.format_exc()))
            self.log.exception("Error while running %s" % query)
1285207
def _get_xml(self, metric):
        """"""
        self._opener = urllib2.build_opener()
        self._opener.addheaders = [('User-agent', self.user_agent)]

        if metric:
            url = self.base_url + '?w={0}&u=c'.format(self.woeid)
        else:
            url = self.base_url + '?w={0}'.format(self.woeid)

        return etree.parse(
            self._opener.open(url)
        ).getroot()[0]
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)