////////////////////////////////////// old metrics
174918
private static void pushOp(String operation, Stack<MetricExpression> expressions, Stack<String> operations) {
        if (operation.equals("(")) {
            operations.push(operation);
            return;
        }

        if (operation.equals(")")) {
            while (!operations.isEmpty()) {
                String op = operations.pop();
                if (op.equals("("))
                    return;
                doOperation(op, expressions, operations);
            }
        }


        if (operation.equals("*") || operation.equals("/")) {
            if (operations.isEmpty())
                operations.push(operation);
            else {
                String op1 = operations.peek();
                if (!op1.equals("(")) {
                    if (op1.equals("+") || op1.equals("-")) {
                        operations.push(operation);
                    } else {
                        doOperation(operations.pop(), expressions, operations);
                        operations.push(operation);
                    }
                } else {
                    operations.push(operation);
                }

            }
        }
        if (operation.equals("+") || operation.equals("-")) {
            if (operations.isEmpty())
                operations.push(operation);
            else {
                String op1 = operations.peek();
                if (!op1.equals("(")) {
                    doOperation(operations.pop(), expressions, operations);
                }
                operations.push(operation);
            }
        }
    }
792495
function (horiz, pos, tickmarkOffset, old) {
		var axis = this.axis,
			chart = axis.chart,
			cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
		
		return {
			x: horiz ?
				axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
				axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),

			y: horiz ?
				cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
				cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
		};
		
	}
1287972
def merge_metrics(self):
        

        self.metrics.extend(self._metrics.values())
        del self._metrics
620588
function (metric) {
      var now = (new Date().getTime()).toFixed(0)
      var line = null
      if (metric.sct === 'OS' && /collectd/.test(metric.name)) {
        line = this.collectdFormatLine(metric)
      } else {
        if (metric.sct === 'OS') {
          // new OS metric format
          if (metric.filters instanceof Array) {
            line = util.format('%d\t%s\t%d\t%s\t%s', now, metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value))
          } else {
            line = util.format('%d\t%s\t%d\t%s', now, metric.name, metric.ts, formatArray(metric.value))
          }
          logger.log(line)
        } else {
          line = util.format('%d\t%s\t%d\t%s\t%s', now, (metric.type || this.defaultType) + '-' + metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value))
          logger.log(line)
        }
      }
      return line
    }
722586
public void populateSaving(RaidNodeMetrics metrics) {
    if (lastRaidStatistics == null) {
      return;
    }
    long saving = 0;
    for (Codec codec : Codec.getCodecs()) {
      String code = codec.id;
      long s = lastRaidStatistics.get(code).getSaving(conf);
      if (s > 0) {
        metrics.savingForCode.get(code).set(s);
        saving += s;
      }
    }
    if (saving > 0) {
      metrics.saving.set(saving);
    }
  }
1074686
public void setMetrics(java.util.Collection<MetricDataQuery> metrics) {
        if (metrics == null) {
            this.metrics = null;
            return;
        }

        this.metrics = new com.amazonaws.internal.SdkInternalList<MetricDataQuery>(metrics);
    }
1331135
def stats_for_version(version):
    
    metrics = dict(STATS_METRICS)

    # JVM additional metrics
    if version >= [0, 90, 10]:
        metrics.update(JVM_METRICS_POST_0_90_10)
    else:
        metrics.update(JVM_METRICS_PRE_0_90_10)

    # Additional Stats metrics
    if version >= [0, 90, 5]:
        metrics.update(ADDITIONAL_METRICS_POST_0_90_5)
    else:
        metrics.update(ADDITIONAL_METRICS_PRE_0_90_5)

    if version >= [1, 0, 0]:
        metrics.update(ADDITIONAL_METRICS_POST_1_0_0)

    if version < [2, 0, 0]:
        metrics.update(ADDITIONAL_METRICS_PRE_2_0)
        if version >= [0, 90, 5]:
            metrics.update(ADDITIONAL_METRICS_POST_0_90_5_PRE_2_0)
        if version >= [1, 0, 0]:
            metrics.update(ADDITIONAL_METRICS_1_x)

    if version >= [1, 3, 0]:
        metrics.update(ADDITIONAL_METRICS_POST_1_3_0)

    if version >= [1, 4, 0]:
        metrics.update(ADDITIONAL_METRICS_POST_1_4_0)

    if version >= [1, 5, 0]:
        metrics.update(ADDITIONAL_METRICS_POST_1_5_0)

    if version >= [1, 6, 0]:
        metrics.update(ADDITIONAL_METRICS_POST_1_6_0)

    if version >= [2, 0, 0]:
        metrics.update(ADDITIONAL_METRICS_POST_2_0)

    if version >= [2, 1, 0]:
        metrics.update(ADDITIONAL_METRICS_POST_2_1)

    if version >= [5, 0, 0]:
        metrics.update(ADDITIONAL_METRICS_5_x)

    if version < [5, 0, 0]:
        metrics.update(ADDITIONAL_METRICS_PRE_5_0_0)

    if version >= [6, 3, 0]:
        metrics.update(ADDITIONAL_METRICS_POST_6_3)
    else:
        metrics.update(ADDITIONAL_METRICS_PRE_6_3)

    return metrics
77778
func (met *Metrics) InitSystemMetrics() {
	met.New(MetricProcessStart)
	met.New(MetricGoRoutines)
	met.New(MetricGoVersion)
	met.New(MetricMemoryAllocated)
	met.New(MetricMemoryNumObjects)
	met.New(MetricMemoryGCEnabled)
	met.Set(MetricProcessStart, ProcessStartTime.Unix())

	version := runtime.Version()
	if version[0] == 'g' && version[1] == 'o' {
		parts := strings.Split(version[2:], ".")
		numericVersion := make([]uint64, tmath.MaxI(3, len(parts)))
		for i, p := range parts {
			numericVersion[i], _ = strconv.ParseUint(p, 10, 64)
		}

		met.SetI(MetricGoVersion, int(numericVersion[0]*10000+numericVersion[1]*100+numericVersion[2]))
	}

	met.UpdateSystemMetrics()
}
70353
@Override
  public void doUpdates(MetricsContext unused) {
    synchronized (this) {
      for (MetricsBase metricsBase : registry.getMetricsList()) {
        metricsBase.pushMetric(metricsRecord);
      }

      metricsRecord.setMetric("aveMapSlotRefillMsecs",
        tt.getAveMapSlotRefillMsecs());
      metricsRecord.setMetric("aveReduceSlotRefillMsecs",
        tt.getAveReduceSlotRefillMsecs());
      if (checkJvms) {
        checkAndSetJvms();
      }

      metricsRecord.setMetric("cgroup_memory_oom", tt.getCGroupOOM());
      metricsRecord.setMetric("maps_running", tt.getRunningMaps());
      metricsRecord.setMetric("reduces_running", tt.getRunningReduces());
      metricsRecord.setMetric("mapTaskSlots", (short)tt.getMaxActualMapTasks());
      metricsRecord.setMetric("reduceTaskSlots",
                                   (short)tt.getMaxActualReduceTasks());
      metricsRecord.incrMetric("map_tasks_completed",
          numCompletedMapTasks);
      metricsRecord.incrMetric("reduce_tasks_completed",
          numCompletedReduceTasks);
      metricsRecord.incrMetric("tasks_completed", numCompletedTasks);
      metricsRecord.incrMetric("tasks_failed_timeout", timedoutTasks);
      metricsRecord.incrMetric("tasks_failed_ping", tasksFailedPing);
      metricsRecord.incrMetric("tasks_disk_out_of_space", 
          numDiskOutOfSpaceTasks);
      metricsRecord.setMetric("unaccounted_memory", unaccountedMemory);
      metricsRecord.incrMetric("tasks_failed_to_add_cgroup", tt.getAndResetNumFailedToAddTaskToCGroup());
      metricsRecord.incrMetric("tasks_saved_by_cgroup", tt.getAndResetAliveTaskNumInCGroup());
      metricsRecord.setMetric("rss_memory_usage", tt.getTaskTrackerRSSMem());
      metricsRecord.incrMetric("tasks_cpu_saved_by_cgroup", tt.getAndResetAliveTasksCPUMSecs());
      
      for (int index = 0; index <tt.getKilledTaskRssBucketsNum(); ++ index) {
        String metricKey = "tasks_killed_group_by_rss_" + index;
        metricsRecord.incrMetric(metricKey, tt.getAndRestNumOfKilledTasksByRssBucket(index));
      }

      numCompletedMapTasks = 0;
      numCompletedReduceTasks = 0;
      numCompletedTasks = 0;
      timedoutTasks = 0;
      tasksFailedPing = 0;
      numDiskOutOfSpaceTasks = 0;
    }
    
    metricsRecord.update();
  }
1188699
function (index, old) {
				var tick = this,
					major = !tick.minor,
					label = tick.label,
					pos = tick.pos,
					labelOptions = options.labels,
					gridLine = tick.gridLine,
					gridLineWidth = major ? options.gridLineWidth : options.minorGridLineWidth,
					gridLineColor = major ? options.gridLineColor : options.minorGridLineColor,
					dashStyle = major ?
						options.gridLineDashStyle :
						options.minorGridLineDashStyle,
					gridLinePath,
					mark = tick.mark,
					markPath,
					tickLength = major ? options.tickLength : options.minorTickLength,
					tickWidth = major ? options.tickWidth : (options.minorTickWidth || 0),
					tickColor = major ? options.tickColor : options.minorTickColor,
					tickPosition = major ? options.tickPosition : options.minorTickPosition,
					step = labelOptions.step,
					cHeight = (old && oldChartHeight) || chartHeight,
					attribs,
					x,
					y;

				// get x and y position for ticks and labels
				x = horiz ?
					translate(pos + tickmarkOffset, null, null, old) + transB :
					plotLeft + offset + (opposite ? ((old && oldChartWidth) || chartWidth) - marginRight - plotLeft : 0);

				y = horiz ?
					cHeight - marginBottom + offset - (opposite ? plotHeight : 0) :
					cHeight - translate(pos + tickmarkOffset, null, null, old) - transB;

				// create the grid line
				if (gridLineWidth) {
					gridLinePath = getPlotLinePath(pos + tickmarkOffset, gridLineWidth, old);

					if (gridLine === UNDEFINED) {
						attribs = {
							stroke: gridLineColor,
							'stroke-width': gridLineWidth
						};
						if (dashStyle) {
							attribs.dashstyle = dashStyle;
						}
						if (major) {
							attribs.zIndex = 1;
						}
						tick.gridLine = gridLine =
							gridLineWidth ?
								renderer.path(gridLinePath)
									.attr(attribs).add(gridGroup) :
								null;
					}

					// If the parameter 'old' is set, the current call will be followed
					// by another call, therefore do not do any animations this time
					if (!old && gridLine && gridLinePath) {
						gridLine.animate({
							d: gridLinePath
						});
					}
				}

				// create the tick mark
				if (tickWidth) {

					// negate the length
					if (tickPosition === 'inside') {
						tickLength = -tickLength;
					}
					if (opposite) {
						tickLength = -tickLength;
					}

					markPath = renderer.crispLine([
						M,
						x,
						y,
						L,
						x + (horiz ? 0 : -tickLength),
						y + (horiz ? tickLength : 0)
					], tickWidth);

					if (mark) { // updating
						mark.animate({
							d: markPath
						});
					} else { // first time
						tick.mark = renderer.path(
							markPath
						).attr({
							stroke: tickColor,
							'stroke-width': tickWidth
						}).add(axisGroup);
					}
				}

				// the label is created on init - now move it into place
				if (label && !isNaN(x)) {
					x = x + labelOptions.x - (tickmarkOffset && horiz ?
						tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
					y = y + labelOptions.y - (tickmarkOffset && !horiz ?
						tickmarkOffset * transA * (reversed ? 1 : -1) : 0);

					// vertically centered
					if (!defined(labelOptions.y)) {
						y += pInt(label.styles.lineHeight) * 0.9 - label.getBBox().height / 2;
					}


					// correct for staggered labels
					if (staggerLines) {
						y += (index / (step || 1) % staggerLines) * 16;
					}
					// apply step
					if (step) {
						// show those indices dividable by step
						label[index % step ? 'hide' : 'show']();
					}

					label[tick.isNew ? 'attr' : 'animate']({
						x: x,
						y: y
					});
				}

				tick.isNew = false;
			}
451080
function metrics(context) {
  //x-height
  context.fillStyle = 'blue'
  context.fillRect(0, -layout.height + layout.baseline, 15, -layout.xHeight)

  //ascender
  context.fillStyle = 'pink'
  context.fillRect(27, -layout.height, 36, layout.ascender)

  //cap height
  context.fillStyle = 'yellow'
  context.fillRect(110, -layout.height + layout.baseline , 18, -layout.capHeight)

  //baseline
  context.fillStyle = 'orange'
  context.fillRect(140, -layout.height, 36, layout.baseline)

  //descender
  context.fillStyle = 'green'
  context.fillRect(0, 0, 30, layout.descender)

  //line height
  context.fillStyle = 'red'
  context.fillRect(0, -layout.height + layout.baseline, 52, layout.lineHeight)
  
  //bounds
  context.strokeRect(0, 0, layout.width, -layout.height)
}
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}
78655
private void mergeCounters(Map<String, Map<Integer, MetricSnapshot>> newCounters,
                               Map<String, Map<Integer, MetricSnapshot>> oldCounters) {
        for (Map.Entry<String, Map<Integer, MetricSnapshot>> entry : newCounters.entrySet()) {
            String metricName = entry.getKey();
            Map<Integer, MetricSnapshot> snapshots = entry.getValue();
            Map<Integer, MetricSnapshot> oldSnapshots = oldCounters.get(metricName);
            if (oldSnapshots != null && oldSnapshots.size() > 0) {
                for (Map.Entry<Integer, MetricSnapshot> snapshotEntry : snapshots.entrySet()) {
                    Integer win = snapshotEntry.getKey();
                    MetricSnapshot snapshot = snapshotEntry.getValue();
                    MetricSnapshot oldSnapshot = oldSnapshots.get(win);
                    if (oldSnapshot != null) {
                        snapshot.set_longValue(snapshot.get_longValue() + oldSnapshot.get_longValue());
                    }
                }
            }
        }
    }
129950
function getInitializedAverage(data) {
    return _.reduce(data, function (prev, a, dataKey) {
      // create a first-level object of the key
      prev[dataKey] = {};

      _.each(data[dataKey], function (b, dataMetricKey) {
        // the metrics are properties inside this object
        prev[dataKey][dataMetricKey] = 0;
      });

      return prev;
    }, {});
  }
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;
    }
205290
private static Map<Long, Double> _fillMetricTransform(QueryContext queryContext, Metric metric, long windowSizeInSeconds, long offsetInSeconds, double value) {
    	if(metric == null || metric.getDatapoints() == null || metric.getDatapoints().isEmpty()) {
    		return Collections.emptyMap();
    	}
    	
        Map<Long, Double> filledDatapoints = new TreeMap<>();
        Map<Long, Double> sortedDatapoints = new TreeMap<>(metric.getDatapoints());
        Long[] sortedTimestamps = new Long[sortedDatapoints.size()];

        sortedDatapoints.keySet().toArray(sortedTimestamps);

        Long[] startAndEndTimestamps = QueryUtils.getStartAndEndTimesWithMaxInterval(queryContext);
        
        Long startTimestamp = startAndEndTimestamps[0]>0 ? startAndEndTimestamps[0] : sortedTimestamps[0];
        Long endTimestamp = startAndEndTimestamps[1]>0 ? startAndEndTimestamps[1] : sortedTimestamps[sortedTimestamps.length - 1];

        // create a new datapoints map propagateDatpoints, which have all the
        // expected timestamps, then fill the missing value
        int index = 1;
        int numDatapoints = 0;
        while (startTimestamp <= endTimestamp && numDatapoints++ < MAX_DATAPOINTS_FOR_FILL) {
            filledDatapoints.put(startTimestamp, sortedDatapoints.containsKey(startTimestamp) ? sortedDatapoints.get(startTimestamp) : null);
            if (index >= sortedDatapoints.size()) {
              	startTimestamp = startTimestamp + windowSizeInSeconds * 1000;
                continue;
            }
            if ((startTimestamp + windowSizeInSeconds * 1000) < sortedTimestamps[index]) {
                startTimestamp = startTimestamp + windowSizeInSeconds * 1000;
            } else {
                startTimestamp = sortedTimestamps[index];
                index++;
            }
        }

        int newLength = filledDatapoints.size();
        List<Long> newTimestamps = new ArrayList<Long>();
        List<Double> newValues = new ArrayList<>();
        
        for (Map.Entry<Long, Double> entry : filledDatapoints.entrySet()) {
            newTimestamps.add(entry.getKey());
            newValues.add(entry.getValue());
        }
        for (int i = 0; i < newLength; i++) {
            if (newValues.get(i) != null) {
                continue;
            } else {
                filledDatapoints.put(newTimestamps.get(i) + offsetInSeconds * 1000, value);
            }
        }

        Map<Long, Double> cleanFilledDatapoints = new TreeMap<>();

        for (Map.Entry<Long, Double> entry : filledDatapoints.entrySet()) {
            if (entry.getValue() != null) {
                cleanFilledDatapoints.put(entry.getKey(), entry.getValue());
            }
        }
        return cleanFilledDatapoints;
    }
372291
def search_metrics(self, query, fromTime=None, toTime=None, requestedDataPoints=600, maxDataPoints=800):
        ''''''
        def millisectimestamp(ts):
            '''Convert UNIX timestamp to milliseconds'''
            if ts > 10**12:
                ts = ts/(10**(len(str(ts))-13))
            else:
                ts = ts*10**(12-len(str(ts)))
            return int(ts)

        params = {'query': [{"query":query, "rowId":"A"}],
                  'startTime': millisectimestamp(fromTime),
                  'endTime': millisectimestamp(toTime),
                  'requestedDataPoints': requestedDataPoints,
                  'maxDataPoints': maxDataPoints}
        r = self.post('/metrics/results', params)
        return json.loads(r.text)