Merges the provided vector clock into this one by taking the maximum of
the logical timestamps for each replica.
This method is not thread safe and concurrent access must be synchronized
externally.
970240
public void merge(VectorClock other) {
        for (Entry<String, Long> entry : other.replicaTimestamps.entrySet()) {
            final String replicaId = entry.getKey();
            final long mergingTimestamp = entry.getValue();
            final long localTimestamp = replicaTimestamps.containsKey(replicaId)
                    ? replicaTimestamps.get(replicaId)
                    : Long.MIN_VALUE;
            replicaTimestamps.put(replicaId, Math.max(localTimestamp, mergingTimestamp));
        }
    }
996355
private int merge(String[] dst, String[] srcA, int lengthA, Tag[] srcB, int lengthB) {
    int i = 0;
    int ai = 0;
    int bi = 0;

    while (ai < lengthA && bi < lengthB) {
      final String ak = srcA[ai];
      final String av = srcA[ai + 1];
      Tag b = srcB[bi];
      int cmp = ak.compareTo(b.key());
      if (cmp < 0) {
        dst[i++] = ak;
        dst[i++] = av;
        ai += 2;
      } else if (cmp > 0) {
        dst[i++] = b.key();
        dst[i++] = b.value();
        ++bi;
      } else {
        // Newer tags should override, use source B if there are duplicate keys.
        // If source B has duplicates, then use the last value for the given key.
        int j = bi + 1;
        for (; j < lengthB && ak.equals(srcB[j].key()); ++j) {
          b = srcB[j];
        }
        dst[i++] = b.key();
        dst[i++] = b.value();
        bi = j;
        ai += 2; // Ignore
      }
    }

    if (ai < lengthA) {
      System.arraycopy(srcA, ai, dst, i, lengthA - ai);
      i += lengthA - ai;
    } else if (bi < lengthB) {
      i = dedup(srcB, bi, dst, i, lengthB - bi);
    }

    return i;
  }
229090
private void mergeSameDay(LinkedList<TimephasedCost> list)
   {
      LinkedList<TimephasedCost> result = new LinkedList<TimephasedCost>();

      TimephasedCost previousAssignment = null;
      for (TimephasedCost assignment : list)
      {
         if (previousAssignment == null)
         {
            assignment.setAmountPerDay(assignment.getTotalAmount());
            result.add(assignment);
         }
         else
         {
            Date previousAssignmentStart = previousAssignment.getStart();
            Date previousAssignmentStartDay = DateHelper.getDayStartDate(previousAssignmentStart);
            Date assignmentStart = assignment.getStart();
            Date assignmentStartDay = DateHelper.getDayStartDate(assignmentStart);

            if (previousAssignmentStartDay.getTime() == assignmentStartDay.getTime())
            {
               result.removeLast();

               double cost = previousAssignment.getTotalAmount().doubleValue();
               cost += assignment.getTotalAmount().doubleValue();

               TimephasedCost merged = new TimephasedCost();
               merged.setStart(previousAssignment.getStart());
               merged.setFinish(assignment.getFinish());
               merged.setTotalAmount(Double.valueOf(cost));
               assignment = merged;
            }

            assignment.setAmountPerDay(assignment.getTotalAmount());
            result.add(assignment);
         }

         previousAssignment = assignment;
      }

      list.clear();
      list.addAll(result);
   }
821201
def merge(intervals):
        
        out = []
        for i in sorted(intervals, key=lambda i: i.start):
            if out and i.start <= out[-1].end:
                out[-1].end = max(out[-1].end, i.end)
            else:
                out += i,
        return out
119805
public static double[] timesPlusTimes(final double[] v1, final double s1, final double[] v2, final double s2) {
    assert v1.length == v2.length : ERR_VEC_DIMENSIONS;
    final double[] result = new double[v1.length];
    for(int i = 0; i < result.length; i++) {
      result[i] = v1[i] * s1 + v2[i] * s2;
    }
    return result;
  }
1325237
static TimingInterval merge(Iterable<TimingInterval> intervals, int maxSamples, long start)
    {
        ThreadLocalRandom rnd = ThreadLocalRandom.current();
        long operationCount = 0, partitionCount = 0, rowCount = 0, errorCount = 0;
        long maxLatency = 0, totalLatency = 0;
        List<SampleOfLongs> latencies = new ArrayList<>();
        long end = 0;
        long pauseStart = 0, pauseEnd = Long.MAX_VALUE;
        for (TimingInterval interval : intervals)
        {
            if (interval != null)
            {
                end = Math.max(end, interval.end);
                operationCount += interval.operationCount;
                maxLatency = Math.max(interval.maxLatency, maxLatency);
                totalLatency += interval.totalLatency;
                partitionCount += interval.partitionCount;
                rowCount += interval.rowCount;
                errorCount += interval.errorCount;
                latencies.addAll(Arrays.asList(interval.sample));
                if (interval.pauseLength > 0)
                {
                    pauseStart = Math.max(pauseStart, interval.pauseStart);
                    pauseEnd = Math.min(pauseEnd, interval.pauseStart + interval.pauseLength);
                }
            }
        }

        if (pauseEnd < pauseStart || pauseStart <= 0)
        {
            pauseEnd = pauseStart = 0;
        }

        return new TimingInterval(start, end, maxLatency, pauseStart, pauseEnd - pauseStart, partitionCount, rowCount,
                                  totalLatency, operationCount, errorCount, SampleOfLongs.merge(rnd, latencies, maxSamples));

    }
440178
function mergeData(timeserieses, range) {
  const reference = {revisions: {}};
  let cell;
  for (const timeseries of timeserieses) {
    for (const datum of timeseries) {
      if (datum.revision < range.min) {
        if (!reference.revision ||
            datum.revision < reference.revision) {
          reference.revision = datum.revision;
          // This might overwrite some or all of reference.revisions.
          Object.assign(reference.revisions, datum.revisions);
        }
        continue;
      }

      if (!cell) {
        cell = {...datum};
        cell.timestampRange = new tr.b.math.Range();
        if (cell.timestamp) {
          cell.timestampRange.addValue(cell.timestamp.getTime());
        }
        if (!cell.revisions) cell.revisions = {};
        continue;
      }

      TimeseriesMerger.mergeStatistics(cell, datum);
      if (datum.timestamp) {
        cell.timestampRange.addValue(datum.timestamp.getTime());
      }

      // TODO Uncomment when Histograms are displayed.
      // mergeHistograms(cell, datum);

      if (datum.revision > cell.revision) {
        cell.revision = datum.revision;
        Object.assign(cell.revisions, datum.revisions);
      }

      // TODO merge annotations
    }
  }
  return {reference, cell};
}
16262
private Deferred<Object> addPointInternal(final long timestamp,
      final byte[] value, final short flags) throws IllegalDataException {
    final boolean ms_timestamp = (timestamp & Const.SECOND_MASK) != 0;

    // we only accept unix epoch timestamps in seconds or milliseconds
    if (timestamp < 0 || (ms_timestamp && timestamp > 9999999999999L)) {
      throw new IllegalArgumentException((timestamp < 0 ? "negative " : "bad")
          + " timestamp=" + timestamp
          + " when trying to add value=" + Arrays.toString(value) + " to " + this);
    }

    // always maintain lastTimestamp in milliseconds
    if ((ms_timestamp ? timestamp : timestamp * 1000) <= last_timestamp) {
      throw new IllegalArgumentException("New timestamp=" + timestamp
          + " is less than or equal to previous=" + last_timestamp
          + " when trying to add value=" + Arrays.toString(value)
          + " to " + this);
    }
    last_timestamp = (ms_timestamp ? timestamp : timestamp * 1000);

    long incomingBaseTime;
    if (ms_timestamp) {
      // drop the ms timestamp to seconds to calculate the base timestamp
      incomingBaseTime = 
          ((timestamp / 1000) - ((timestamp / 1000) % Const.MAX_TIMESPAN));
    }
    else {
      incomingBaseTime = (timestamp - (timestamp % Const.MAX_TIMESPAN));
    }

    /**
     * First time we add a point initialize the rows timestamp.
     */
    if (base_time == Long.MIN_VALUE) {
      base_time = incomingBaseTime;
      Bytes.setInt(row_key, (int) base_time, 
          tsdb.metrics.width() + Const.SALT_WIDTH());
    }

    if (incomingBaseTime - base_time >= Const.MAX_TIMESPAN) {
      throw new IllegalDataException(
          "The timestamp is beyond the boundary of this batch of data points");
    }
    if (incomingBaseTime < base_time) {
      throw new IllegalDataException(
          "The timestamp is prior to the boundary of this batch of data points");
    }

    // Java is so stupid with its auto-promotion of int to float.
    final byte[] new_qualifier = Internal.buildQualifier(timestamp, flags);

    // compact this data point with the previously compacted data points.
    append(new_qualifier, value);
    size++;

    /**
     * Satisfies the interface.
     */
    return Deferred.fromResult((Object) null);
  }
493884
def merge(self, other):
        ''''''
        our_element_frequencies = self.items
        their_element_frequencies = other.items
        for element_name, freq in sorted(our_element_frequencies.iteritems()):
            our_element_frequencies[element_name] = max(our_element_frequencies.get(element_name, 0), their_element_frequencies.get(element_name, 0))
        for element_name, freq in sorted(their_element_frequencies.iteritems()):
            if element_name not in our_element_frequencies:
                our_element_frequencies[element_name] = their_element_frequencies[element_name]
436669
protected synchronized void merge(DoubleMinMax minmax) {
    this.minmax.put(minmax.getMin());
    this.minmax.put(minmax.getMax());
  }
771385
private void mergeInstantFields() {
        if (fieldValues.containsKey(INSTANT_SECONDS)) {
            if (zone != null) {
                mergeInstantFields0(zone);
            } else {
                Long offsetSecs = fieldValues.get(OFFSET_SECONDS);
                if (offsetSecs != null) {
                    ZoneOffset offset = ZoneOffset.ofTotalSeconds(offsetSecs.intValue());
                    mergeInstantFields0(offset);
                }
            }
        }
    }
884382
public void mergeNE(double x, double y) {
		if (xmin > x)
			xmin = x;
		else if (xmax < x)
			xmax = x;

		if (ymin > y)
			ymin = y;
		else if (ymax < y)
			ymax = y;
	}
281585
private CompletableFuture<SegmentProperties> mergeInStorage(SegmentMetadata transactionMetadata, MergeSegmentOperation mergeOp, TimeoutTimer timer) {
        return this.storage
                .getStreamSegmentInfo(transactionMetadata.getName(), timer.getRemaining())
                .thenAcceptAsync(transProperties -> {
                    // One last verification before the actual merger:
                    // Check that the Storage agrees with our metadata (if not, we have a problem ...)
                    if (transProperties.getLength() != transactionMetadata.getStorageLength()) {
                        throw new CompletionException(new DataCorruptionException(String.format(
                                "Transaction Segment '%s' cannot be merged into parent '%s' because its metadata disagrees with the Storage. Metadata.StorageLength=%d, Storage.StorageLength=%d",
                                transactionMetadata.getName(),
                                this.metadata.getName(),
                                transactionMetadata.getStorageLength(),
                                transProperties.getLength())));
                    }

                    if (transProperties.getLength() != mergeOp.getLength()) {
                        throw new CompletionException(new DataCorruptionException(String.format(
                                "Transaction Segment '%s' cannot be merged into parent '%s' because the declared length in the operation disagrees with the Storage. Operation.Length=%d, Storage.StorageLength=%d",
                                transactionMetadata.getName(),
                                this.metadata.getName(),
                                mergeOp.getLength(),
                                transProperties.getLength())));
                    }
                }, this.executor)
                .thenComposeAsync(v -> createSegmentIfNecessary(
                        () -> storage.concat(this.handle.get(), mergeOp.getStreamSegmentOffset(), transactionMetadata.getName(), timer.getRemaining()),
                        timer.getRemaining()), this.executor)
                .exceptionally(ex -> {
                    ex = Exceptions.unwrap(ex);
                    if (transactionMetadata.getLength() == 0
                            && ex instanceof StreamSegmentNotExistsException
                            && ((StreamSegmentNotExistsException) ex).getStreamSegmentName().equals(transactionMetadata.getName())) {
                        log.warn("{}: Not applying '{}' because source segment is missing (storage) and had no data.", this.traceObjectId, mergeOp);
                        return null;
                    } else {
                        throw new CompletionException(ex);
                    }
                })
                .thenComposeAsync(v -> storage.getStreamSegmentInfo(this.metadata.getName(), timer.getRemaining()), this.executor);
    }
14020
private List<StatValueAO> mergeStatValues(List<StatValueAO> firstStat, List<StatValueAO> secondStat) {
        // If stats are null or not of the same type return nothing
        if (firstStat == null || secondStat == null) {
            return new ArrayList<>();
        }

        List<StatValueAO> result = new ArrayList<>();
        for (StatValueAO firstStatValue : firstStat) {
            for (StatValueAO secondStatValue : secondStat) {
                // If it's one stat value type cumulate them
                if (firstStatValue.getName().equals(secondStatValue.getName())) {
                    try {
                        // Stat value equals NoR, just set it
                        if ("NoR".equals(firstStatValue.getValue()) || "NoR".equals(secondStatValue.getValue())) {
                            final StatValueAO norValue = new LongValueAO(firstStatValue.getName(), Long.MAX_VALUE);
                            result.add(norValue);
                        } else if (firstStatValue instanceof LongValueAO && secondStatValue instanceof LongValueAO) {
                            Number firstStatNumber = NumberFormat.getNumberInstance(Locale.US).parse(firstStatValue.getValue());
                            Number secondStatNumber = NumberFormat.getNumberInstance(Locale.US).parse(secondStatValue.getValue());
                            final StatValueAO sumValue = new LongValueAO(firstStatValue.getName(), firstStatNumber.longValue() + secondStatNumber.longValue());

                            result.add(sumValue);
                        } else if (firstStatValue instanceof DoubleValueAO && secondStatValue instanceof DoubleValueAO) {
                            Number firstStatNumber = NumberFormat.getNumberInstance(Locale.US).parse(firstStatValue.getValue());
                            Number secondStatNumber = NumberFormat.getNumberInstance(Locale.US).parse(secondStatValue.getValue());
                            final StatValueAO sumValue = new DoubleValueAO(firstStatValue.getName(), firstStatNumber.doubleValue() + secondStatNumber.doubleValue());

                            result.add(sumValue);
                        }
                    }
                    catch (ParseException ex) {
                        LOGGER.warn("Can't parse stat values: " + firstStatValue.getValue() + " and " + secondStatValue.getValue());
                    }
                }
            }
        }

        return result;
    }
1307409
public static VectorClock makeClock(Set<Integer> serverIds, long clockValue, long timestamp) {
        List<ClockEntry> clockEntries = new ArrayList<ClockEntry>(serverIds.size());
        for(Integer serverId: serverIds) {
            clockEntries.add(new ClockEntry(serverId.shortValue(), clockValue));
        }
        return new VectorClock(clockEntries, timestamp);
    }
828817
private static void distributeShareMax(
      Collection<? extends Schedulable> schedulableVector) {
    for (Schedulable schedulable : schedulableVector) {
      double minShare = Math.max(schedulable.getMinimum(),
                                 schedulable.getRequested());
      schedulable.share += Math.min(schedulable.getMaximum(),
                                    minShare);
    }
  }
474891
public static Timecode max(final Timecode... timecodes)
	{
		Timecode max = null;

		for (Timecode timecode : timecodes)
			if (max == null || lt(max, timecode))
				max = timecode;

		return max;
	}