text:
using Aardvark.Base.Sorting;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Aardvark.Base
{
    /// <summary>
    /// This interface enforces a common API for random number generators.
    /// </summary>
    public interface IRandomUniform
    {
        #region Info and Seeding

        /// <summary>
        /// Returns the number of random bits that the generator
        /// delivers. This many bits are actually random in the
        /// doubles returned by <see cref="UniformDouble()"/>.
        /// </summary>
        int RandomBits { get; }

        /// <summary>
        /// Returns true if the doubles generated by this random
        /// generator contain 52 random mantissa bits.
        /// </summary>
        bool GeneratesFullDoubles { get; }

        /// <summary>
        /// Reinitializes the random generator with the specified seed.
        /// </summary>
        void ReSeed(int seed);

        #endregion

        #region Random Integers

        /// <summary>
        /// Returns a uniformly distributed integer in the interval
        /// [0, 2^31-1].
        /// </summary>
        int UniformInt();

        /// <summary>
        /// Returns a uniformly distributed integer in the interval
        /// [0, 2^32-1].
        /// </summary>
        uint UniformUInt();

        /// <summary>
        /// Returns a uniformly distributed integer in the interval
        /// [0, 2^63-1].
        /// </summary>
        long UniformLong();

        /// <summary>
        /// Returns a uniformly distributed integer in the interval
        /// [0, 2^64-1].
        /// </summary>
        ulong UniformULong();

        #endregion

        #region Random Floating Point Values

        /// <summary>
        /// Returns a uniformly distributed float in the half-open interval
        /// [0.0f, 1.0f).
        /// </summary>
        float UniformFloat();

        /// <summary>
        /// Returns a uniformly distributed float in the closed interval
        /// [0.0f, 1.0f].
        /// </summary>
        float UniformFloatClosed();

        /// <summary>
        /// Returns a uniformly distributed float in the open interval
        /// (0.0f, 1.0f).
        /// </summary>
        float UniformFloatOpen();

        /// <summary>
        /// Returns a uniformly distributed double in the half-open interval
        /// [0.0, 1.0). Note, that only RandomBits bits are guaranteed to be
        /// random.
        /// </summary>
        double UniformDouble();

        /// <summary>
        /// Returns a uniformly distributed double in the closed interval
        /// [0.0, 1.0]. Note, that only RandomBits bits are guaranteed to be
        /// random.
        /// </summary>
        double UniformDoubleClosed();

        /// <summary>
        /// Returns a uniformly distributed double in the open interval
        /// (0.0, 1.0). Note, that only RandomBits bits are guaranteed to be
        /// random.
        /// </summary>
        double UniformDoubleOpen();

        #endregion
    }

    public static class IRandomUniformExtensions
    {
        #region Random Bits

        /// <summary>
        /// Supply random bits one at a time. The currently unused bits are
        /// maintained in the supplied reference parameter. Before the first
        /// call randomBits must be 0.
        /// </summary>
        public static bool RandomBit(
               this IRandomUniform rnd, ref int randomBits)
        {
            if (randomBits <= 1)
            {
                randomBits = rnd.UniformInt();
                bool bit = (randomBits & 1) != 0;
                randomBits = 0x40000000 | (randomBits >> 1);
                return bit;
            }
            else
            {
                bool bit = (randomBits & 1) != 0;
                randomBits >>= 1;
                return bit;
            }
        }

        #endregion

        #region Random Integers

        /// <summary>
        /// Returns a uniformly distributed int in the interval [0, count-1].
        /// In order to avoid excessive aliasing, two random numbers are used
        /// when count is greater or equal 2^24 and the random generator
        /// delivers 32 random bits or less. The method thus works fairly
        /// decently for all integers.
        /// </summary>
        public static int UniformInt(this IRandomUniform rnd, int size)
        {
            if (rnd.GeneratesFullDoubles || size < 16777216)
                return (int)(rnd.UniformDouble() * size);
            else
                return (int)(rnd.UniformDoubleFull() * size);
        }

        /// <summary>
        /// Returns a uniformly distributed long in the interval [0, size-1].
        /// NOTE: If count has more than about 48 bits, aliasing leads to
        /// noticeable (greater 5%) shifts in the probabilities (i.e. one
        /// long has a probability of x and the other a probability of
        /// x * (2^(52-b)-1)/(2^(52-b)), where b is log(size)/log(2)).
        /// </summary>
        public static long UniformLong(this IRandomUniform rnd, long size)
        {
            if (rnd.GeneratesFullDoubles || size < 16777216)
                return (long)(rnd.UniformDouble() * size);
            else
                return (long)(rnd.UniformDoubleFull() * size);
        }

        /// <summary>
        /// Returns a uniform int which is guaranteed not to be zero.
        /// </summary>
        public static int UniformIntNonZero(this IRandomUniform rnd)
        {
            int r;
            do { r = rnd.UniformInt(); } while (r == 0);
            return r;
        }

        /// <summary>
        /// Returns a uniform long which is guaranteed not to be zero.
        /// </summary>
        public static long UniformLongNonZero(this IRandomUniform rnd)
        {
            long r;
            do { r = rnd.UniformLong(); } while (r == 0);
            return r;
        }

        #endregion

        #region Random Floating Point Values

        /// <summary>
        /// Returns a uniformly distributed double in the half-open interval
        /// [0.0, 1.0). Note, that two random values are used to make all 53
        /// bits random. If you use this repeatedly, consider using a 64-bit
        /// random generator, which can  provide such doubles directly using
        /// UniformDouble().
        /// </summary>
        public static double UniformDoubleFull(this IRandomUniform rnd)
        {
            if (rnd.GeneratesFullDoubles) return rnd.UniformDouble();
            long r = ((~0xfL & (long)rnd.UniformInt()) << 22)
                      | ((long)rnd.UniformInt() >> 5);
            return r * (1.0 / 9007199254740992.0);
        }

        /// <summary>
        /// Returns a uniformly distributed double in the closed interval
        /// [0.0, 1.0]. Note, that two random values are used to make all 53
        /// bits random.
        /// </summary>
        public static double UniformDoubleFullClosed(this IRandomUniform rnd)
        {
            if (rnd.GeneratesFullDoubles) return rnd.UniformDoubleClosed();
            long r = ((~0xfL & (long)rnd.UniformInt()) << 22)
                      | ((long)rnd.UniformInt() >> 5);
            return r * (1.0 / 9007199254740991.0);
        }

        /// <summary>
        /// Returns a uniformly distributed double in the open interval
        /// (0.0, 1.0). Note, that two random values are used to make all 53
        /// bits random.
        /// </summary>
        public static double UniformDoubleFullOpen(this IRandomUniform rnd)
        {
            if (rnd.GeneratesFullDoubles) return rnd.UniformDoubleOpen();
            long r;
            do
            {
                r = ((~0xfL & (long)rnd.UniformInt()) << 22)
                    | ((long)rnd.UniformInt() >> 5);
            }
            while (r == 0);
            return r * (1.0 / 9007199254740992.0);
        }

        #endregion

        #region Creating Randomly Filled Arrays

        /// <summary>
        /// Create a random array of floats in the half-open interval
        /// [0.0, 1.0) of the specified length.
        /// </summary>
        public static float[] CreateUniformFloatArray(
                this IRandomUniform rnd, long length)
        {
            var array = new float[length];
            rnd.FillUniform(array);
            return array;
        }

        /// <summary>
        /// Create a random array of doubles in the half-open interval
        /// [0.0, 1.0) of the specified length.
        /// </summary>
        public static double[] CreateUniformDoubleArray(
                this IRandomUniform rnd, long length)
        {
            var array = new double[length];
            rnd.FillUniform(array);
            return array;
        }

        /// <summary>
        /// Create a random array of full doubles in the half-open interval
        /// [0.0, 1.0) of the specified length.
        /// </summary>
        public static double[] CreateUniformDoubleFullArray(
            this IRandomUniform rnd, long length)
        {
            var array = new double[length];
            rnd.FillUniformFull(array);
            return array;
        }

        /// <summary>
        /// Fills the specified array with random ints in the interval
        /// [0, 2^31-1].
        /// </summary>
        public static void FillUniform(this IRandomUniform rnd, int[] array)
        {
            long count = array.LongLength;
            for (long i = 0; i < count; i++)
                array[i] = rnd.UniformInt();
        }

        /// <summary>
        /// Fills the specified array with random floats in the half-open
        /// interval [0.0f, 1.0f).
        /// </summary>
        public static void FillUniform(this IRandomUniform rnd, float[] array)
        {
            long count = array.LongLength;
            for (long i = 0; i < count; i++)
                array[i] = rnd.UniformFloat();
        }

        /// <summary>
        /// Fills the specified array with random doubles in the half-open
        /// interval [0.0, 1.0).
        /// </summary>
        public static void FillUniform(
                this IRandomUniform rnd, double[] array)
        {
            long count = array.LongLength;
            for (long i = 0; i < count; i++)
                array[i] = rnd.UniformDouble();
        }

        /// <summary>
        /// Fills the specified array with fully random doubles (53 random
        /// bits) in the half-open interval [0.0, 1.0).
        /// </summary>
        public static void FillUniformFull(
                this IRandomUniform rnd, double[] array)
        {
            long count = array.LongLength;
            if (rnd.GeneratesFullDoubles)
            {
                for (long i = 0; i < count; i++)
                    array[i] = rnd.UniformDoubleFull();
            }
            else
            {
                for (long i = 0; i < count; i++)
                    array[i] = rnd.UniformDouble();
            }
        }

        /// <summary>
        /// Creates an array that contains a random permutation of the
        /// ints in the interval [0, count-1].
        /// </summary>
        public static int[] CreatePermutationArray(
                this IRandomUniform rnd, int count)
        {
            var p = new int[count].SetByIndex(i => i);
            rnd.Randomize(p);
            return p;
        }

        /// <summary>
        /// Creates an array that contains a random permutation of the
        /// numbers in the interval [0, count-1].
        /// </summary>
        public static long[] CreatePermutationArrayLong(
                this IRandomUniform rnd, long count)
        {
            var p = new long[count].SetByIndexLong(i => i);
            rnd.Randomize(p);
            return p;
        }

        #endregion

        #region Creationg a Random Subset (while maintaing order)

        /// <summary>
        /// Returns a random subset of an array with a supplied number of
        /// elements (subsetCount). The elements in the subset are in the
        /// same order as in the original array. O(count).
        /// NOTE: this method needs to generate one random number for each
        /// element of the original array. If subsetCount is significantly
        /// smaller than count, it is more efficient to use
        /// <see cref="CreateSmallRandomSubsetIndexArray"/> or
        /// <see cref="CreateSmallRandomSubsetIndexArrayLong"/> or
        /// <see cref="CreateSmallRandomOrderedSubsetIndexArray"/> or
        /// <see cref="CreateSmallRandomOrderedSubsetIndexArrayLong"/>.
        /// </summary>
        public static T[] CreateRandomSubsetOfSize<T>(
                this T[] array, long subsetCount, IRandomUniform rnd = null)
        {
            if (rnd == null) rnd = new RandomSystem();
            long count = array.LongLength;
            if (!(subsetCount >= 0 && subsetCount <= count)) throw new ArgumentOutOfRangeException(nameof(subsetCount));
            var subset = new T[subsetCount];
            long si = 0;
            for (int ai = 0; ai < count && si < subsetCount; ai++)
            {
                var p = (double)(subsetCount - si) / (double)(count - ai);
                if (rnd.UniformDouble() <= p) subset[si++] = array[ai];
            }
            return subset;
        }

        /// <summary>
        /// Returns a random subset of the enumeration with a supplied number of
        /// elements (subsetCount). The elements in the subset are in the
        /// same order as in the input. O(count).
        /// NOTE: The number of elements of the Enumerable need to be calculated, in case of true enumerations
        ///       the implementation of .Count() results in a second evaluation of the enumerable.
        /// </summary>
        public static T[] CreateRandomSubsetOfSize<T>(
                this IEnumerable<T> input, long subsetCount, IRandomUniform rnd = null)
        {
            if (rnd == null) rnd = new RandomSystem();
            long count = input.Count();
            if (!(subsetCount >= 0 && subsetCount <= count)) throw new ArgumentOutOfRangeException(nameof(subsetCount));
            var subset = new T[subsetCount];
            long si = 0, ai = 0;
            foreach (var a in input)
            {
                if (ai < count && si < subsetCount)
                {
                    var p = (double)(subsetCount - si) / (double)(count - ai++);
                    if (rnd.UniformDouble() <= p) subset[si++] = a;
                }
                else
                    break;
            }
            return subset;
        }

        /// <summary>
        /// Creates an unordered array of subsetCount long indices that
        /// constitute a subset of all longs in the range  [0, count-1].
        /// O(subsetCount) for subsetCount << count.
        /// NOTE: It is assumed that subsetCount is significantly smaller
        /// than count. If this is not the case, use
        /// CreateRandomSubsetOfSize instead.
        /// WARNING: As subsetCount approaches count execution time
        /// increases significantly.
        /// </summary>
        public static long[] CreateSmallRandomSubsetIndexArrayLong(
                this IRandomUniform rnd, long subsetCount, long count)
        {
            if (!(subsetCount >= 0 && subsetCount <= count)) throw new ArgumentOutOfRangeException(nameof(subsetCount));
            var subsetIndices = new LongSet(subsetCount);
            for (int i = 0; i < subsetCount; i++)
            {
                long index;
                do { index = rnd.UniformLong(count); }
                while (!subsetIndices.TryAdd(index));
            }
            return subsetIndices.ToArray();
        }

        /// <summary>
        /// Creates an ordered array of subsetCount long indices that
        /// constitute a subset of all longs in the range [0, count-1].
        /// O(subsetCount * log(subsetCount)) for subsetCount << count.
        /// NOTE: It is assumed that subsetCount is significantly smaller
        /// than count. If this is not the case, use
        /// CreateRandomSubsetOfSize instead.
        /// WARNING: As subsetCount approaches count execution time
        /// increases significantly.
        /// </summary>
        public static long[] CreateSmallRandomOrderedSubsetIndexArrayLong(
                this IRandomUniform rnd, long subsetCount, long count)
        {
            var subsetIndexArray = rnd.CreateSmallRandomSubsetIndexArrayLong(subsetCount, count);
            subsetIndexArray.QuickSortAscending();
            return subsetIndexArray;
        }

        /// <summary>
        /// Creates an unordered array of subsetCount int indices that
        /// constitute a subset of all ints in the range [0, count-1].
        /// O(subsetCount) for subsetCount << count.
        /// NOTE: It is assumed that subsetCount is significantly smaller
        /// than count. If this is not the case, use
        /// CreateRandomSubsetOfSize instead.
        /// WARNING: As subsetCount approaches count execution time
        /// increases significantly.
        /// </summary>
        public static int[] CreateSmallRandomSubsetIndexArray(
                this IRandomUniform rnd, int subsetCount, int count)
        {
            if (!(subsetCount >= 0 && subsetCount <= count)) throw new ArgumentOutOfRangeException(nameof(subsetCount));
            var subsetIndices = new IntSet(subsetCount);
            for (int i = 0; i < subsetCount; i++)
            {
                int index;
                do { index = rnd.UniformInt(count); }
                while (!subsetIndices.TryAdd(index));
            }
            return subsetIndices.ToArray();
        }

        /// <summary>
        /// Creates an ordered array of subsetCount int indices that
        /// constitute a subset of all ints in the range [0, count-1].
        /// O(subsetCount * log(subsetCount)) for subsetCount << count.
        /// NOTE: It is assumed that subsetCount is significantly smaller
        /// than count. If this is not the case, use
        /// CreateRandomSubsetOfSize instead.
        /// WARNING: As subsetCount approaches count execution time
        /// increases significantly.
        /// </summary>
        public static int[] CreateSmallRandomOrderedSubsetIndexArray(
                this IRandomUniform rnd, int subsetCount, int count)
        {
            var subsetIndexArray = rnd.CreateSmallRandomSubsetIndexArray(subsetCount, count);
            subsetIndexArray.QuickSortAscending();
            return subsetIndexArray;
        }

        #endregion

        #region Randomizing Existing Arrays

        /// <summary>
        /// Randomly permute the first count elements of the
        /// supplied array. This does work with counts of up
        /// to about 2^50.
        /// </summary>
        public static void Randomize<T>(
                this IRandomUniform rnd, T[] array, long count)
        {
            if (count <= (long)int.MaxValue)
            {
                int intCount = (int)count;
                for (int i = 0; i < intCount; i++)
                    array.Swap(i, rnd.UniformInt(intCount));
            }
            else
            {
                for (long i = 0; i < count; i++)
                    array.Swap(i, rnd.UniformLong(count));
            }
        }

        /// <summary>
        /// Randomly permute the elements of the supplied array. This does
        /// work with arrays up to a length of about 2^50.
        /// </summary>
        public static void Randomize<T>(
            this IRandomUniform rnd, T[] array)
        {
            rnd.Randomize(array, array.LongLength);
        }

        /// <summary>
        /// Randomly permute the elements of the supplied list.
        /// </summary>
        public static void Randomize<T>(
            this IRandomUniform rnd, List<T> list)
        {
            int count = list.Count;
            for (int i = 0; i < count; i++)
                list.Swap(i, rnd.UniformInt(count));
        }

        /// <summary>
        /// Randomly permute the specified number of elements in the supplied
        /// array starting at the specified index.
        /// </summary>
        public static void Randomize<T>(
            this IRandomUniform rnd, T[] array, int start, int count)
        {
            for (int i = start, e = start + count; i < e; i++)
                array.Swap(i, start + rnd.UniformInt(count));
        }

        /// <summary>
        /// Randomly permute the specified number of elements in the supplied
        /// array starting at the specified index.
        /// </summary>
        public static void Randomize<T>(
            this IRandomUniform rnd, T[] array, long start, long count)
        {
            for (long i = start, e = start + count; i < e; i++)
                array.Swap(i, start + rnd.UniformLong(count));
        }

        /// <summary>
        /// Randomly permute the specified number of elements in the supplied
        /// list starting at the specified index.
        /// </summary>
        public static void Randomize<T>(
            this IRandomUniform rnd, List<T> list, int start, int count)
        {
            for (int i = start; i < start + count; i++)
                list.Swap(i, start + rnd.UniformInt(count));
        }

        #endregion

        #region Random Distributions

        /// <summary>
        /// Generates normal distributed random variable with given mean and standard deviation.
        /// Uses the Box-Muller Transformation to transform two uniform distributed random variables to one normal distributed value.
        /// NOTE: If multiple normal distributed random values are required, consider using <see cref="RandomGaussian"/>.
        /// </summary>
        public static double Gaussian(this IRandomUniform rnd, double mean = 0.0, double stdDev = 1.0)
        {
            // Box-Muller Transformation
            var u1 = 1.0 - rnd.UniformDouble();   // uniform (0,1] -> log requires > 0
            var u2 = rnd.UniformDouble();         // uniform [0,1)
            var randStdNormal = Fun.Sqrt(-2.0 * Fun.Log(u1)) *
                                Fun.Sin(Constant.PiTimesTwo * u2);
            return mean + stdDev * randStdNormal;
        }

        #endregion
    }

    public static class IRandomEnumerableExtensions
    {
        #region Random Order

        /// <summary>
        /// Enumerates elements in random order.
        /// </summary>
        public static IEnumerable<T> RandomOrder<T>(this IEnumerable<T> self, IRandomUniform rnd = null)
        {
            var tmp = self.ToArray();
            if (rnd == null) rnd = new RandomSystem();
            var perm = rnd.CreatePermutationArray(tmp.Length);
            return perm.Select(index => tmp[index]);
        }

        #endregion
    }
}


text:
module Fundry
  class Comment
    include DataMapper::Resource
    property   :id,         Serial
    property   :feature_id, Integer, required: true
    property   :user_id,    Integer, required: true
    property   :detail,     Text,    required: true, lazy: false
    timestamps :at

    belongs_to :feature
    belongs_to :user
  end
end

redpajama_set_name: RedPajamaGithub


text:
def split_string(string, chunk_size):
    """
    Generator function that splits string into chunks.

    :param string: string to be split.
    :param chunk_size: size of a single chunk.
    :return: yields individual chunks.
    """
    if not isinstance(string, str):
        raise TypeError("string parameter must be an instance of str")
    if not isinstance(chunk_size, int):
        raise TypeError("chunk_size parameter must be an instance of int")

    for index in range(0, len(string), chunk_size):
        yield string[index:index + chunk_size]

def hex_string(string, byte_separator, chunk_separator, chunk_size):
    """
    Returns HEXized string.

    :param string: string to be converted to hex representation.
    :param byte_separator: string to be inserted in-between bytes.
    :param chunk_separator: string to be inserted in-between chunks.
    :param chunk_size: integer specifying the size of a single chunk (in bytes).
    :return: hexadecimal representation of the string.
    """
    if not isinstance(string, str):
        raise TypeError("string parameter must be an instance of str")
    if not isinstance(byte_separator, str):
        raise TypeError("byte_separator parameter must be an instance of str")
    if not isinstance(chunk_separator, str):
        raise TypeError("chunk_separator parameter must be an instance of str")
    if not isinstance(chunk_size, int):
        raise TypeError("chunk_size parameter must be an instance of int")
    if chunk_size < 2:
        raise ValueError("chunk_size must be greater than 1")

    return chunk_separator.join(
        [byte_separator.join(
            ["{0:02x}".format(ord(byte)) for byte in x]
        ) for x in split_string(string, chunk_size)]
    )

def safe_string(string, safe_char):
    """
    Replaces all non-printable characters with safe_char.

    :param string: string to be scanned for unprintable characters.
    :param safe_char: a single character string to be used in place of unsafe characters.
    :return: safe to print string.
    """
    if not isinstance(string, str):
        raise TypeError("string parameter must be an instance of str")
    if not isinstance(safe_char, str):
        raise TypeError("safe_char parameter must be an instance of str")
    if len(safe_char) != 1:
        raise ValueError("safe_char length must be 1")

    unsafe_char_codes = range(0, 32) + [127]
    return "".join([char if ord(char) not in unsafe_char_codes else safe_char for char in string])


text:
from django.shortcuts import render
from django.views.generic import TemplateView

class ProfileView(TemplateView):
    template_name="profiles/profile.html"

class ProfileUpdateView(TemplateView):
    template_name="profiles/update_profile.html"


text:
//
//  AmResponsive.h
//  AmChartsLibrary
//
//  Created by Andrew on 2/6/15.
//  Copyright (c) 2015 Chimp Studios. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface AmResponsive : NSObject

/**
 Specifies whether the Responsibe Plugin should be used.
 http://www.amcharts.com/tutorials/making-charts-responsive/
 */
@property(strong) NSNumber * enabled;

- (NSDictionary *)dictionaryRepresentation;
- (NSString *)javascriptRepresentation;

@end


text:
int CCval; // Constrained Midi Value
String ScrennedVal; // Stringed midi val for screen
String ScrennedCC; // Stringed midi CC for screen

void controlChange(byte channel, byte control, byte value) {
#if ENABLE_DEBUG
  Serial.print("CC: ");
  Serial.print(channel + 1);
  Serial.print("| ");
  Serial.print(control);
  Serial.print("| ");
  Serial.println(value);
#endif
  midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
  MidiUSB.sendMIDI(event);
#if USE_SCREEN
  clearscreen();
  String ScrennedVal = String(value, DEC);
  String ScrennedCC = String(control, DEC);
  printscreen(0, 25, 1, "CC: 3 | ");
  printscreen(45, 25, 1, ScrennedCC);
  printscreen(55, 25, 1, " | ");
  printscreen(72, 25, 1, ScrennedVal);
#endif
  // return;
}


text:
package org.apache.flink.runtime.operators.testutils.types;

import java.io.IOException;

import org.apache.flink.api.common.typeutils.CompatibilityResult;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerConfigSnapshot;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.types.StringValue;

public class StringPairSerializer extends TypeSerializer<StringPair> {

	private static final long serialVersionUID = 1L;

	@Override
	public boolean isImmutableType() {
		return false;
	}

	@Override
	public StringPairSerializer duplicate() {
		return this;
	}

	@Override
	public StringPair createInstance() {
		return new StringPair();
	}

	@Override
	public StringPair copy(StringPair from) {
		return new StringPair(from.getKey(), from.getValue());
	}
	@Override
	public StringPair copy(StringPair from, StringPair reuse) {
		reuse.setKey(from.getKey());
		reuse.setValue(from.getValue());
		return reuse;
	}

	@Override
	public int getLength() {
		return -1;
	}

	@Override
	public void serialize(StringPair record, DataOutputView target) throws IOException {
		StringValue.writeString(record.getKey(), target);
		StringValue.writeString(record.getValue(), target);
	}

	@Override
	public StringPair deserialize(DataInputView source) throws IOException {
		return new StringPair(StringValue.readString(source), StringValue.readString(source));
	}

	@Override
	public StringPair deserialize(StringPair record, DataInputView source) throws IOException {
		record.setKey(StringValue.readString(source));
		record.setValue(StringValue.readString(source));
		return record;
	}

	@Override
	public void copy(DataInputView source, DataOutputView target) throws IOException {
		StringValue.writeString(StringValue.readString(source), target);
		StringValue.writeString(StringValue.readString(source), target);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof StringPairSerializer) {
			StringPairSerializer other = (StringPairSerializer) obj;

			return other.canEqual(this);
		} else {
			return false;
		}
	}

	@Override
	public boolean canEqual(Object obj) {
		return obj instanceof StringPairSerializer;
	}

	@Override
	public int hashCode() {
		return StringPairSerializer.class.hashCode();
	}

	@Override
	public TypeSerializerConfigSnapshot snapshotConfiguration() {
		throw new UnsupportedOperationException();
	}

	@Override
	public CompatibilityResult<StringPair> ensureCompatibility(TypeSerializerConfigSnapshot configSnapshot) {
		throw new UnsupportedOperationException();
	}
}


text:
using namespace clang::ast_matchers;
using clang::tooling::Replacement;
using clang::tooling::Replacements;
using llvm::StringRef;

namespace {

// Helper class for AppendRawCallback to visit each DeclRefExpr for a given
// VarDecl. If it finds a DeclRefExpr it can't figure out how to rewrite, the
// traversal will be terminated early.
class CollectDeclRefExprVisitor
    : public clang::RecursiveASTVisitor<CollectDeclRefExprVisitor> {
 public:
  CollectDeclRefExprVisitor(clang::SourceManager* source_manager,
                            clang::ASTContext* ast_context,
                            const clang::VarDecl* decl,
                            const clang::FunctionDecl* containing_function)
      : source_manager_(source_manager),
        ast_context_(ast_context),
        decl_(decl),
        is_valid_(decl->hasInit()),
        map_(containing_function->getBody()) {}

  // RecursiveASTVisitor:
  bool VisitDeclRefExpr(const clang::DeclRefExpr* expr) {
    if (expr->getDecl() != decl_)
      return true;

    const clang::Stmt* stmt = expr;
    while (stmt) {
      // TODO(dcheng): Add a const version of getParentIgnoreParenImpCasts.
      stmt = map_.getParentIgnoreParenImpCasts(const_cast<clang::Stmt*>(stmt));

      if (clang::isa<clang::MemberExpr>(stmt)) {
        // Member expressions need no special rewriting since std::unique_ptr
        // overloads `.' and `->'.
        return is_valid_;
      } else if (auto* member_call_expr =
                     clang::dyn_cast<clang::CXXMemberCallExpr>(stmt)) {
        return HandleMemberCallExpr(member_call_expr, expr);
      } else if (auto* binary_op =
                     clang::dyn_cast<clang::BinaryOperator>(stmt)) {
        return HandleBinaryOp(binary_op);
      } else {
        // Can't handle this so cancel the rewrite.
        stmt->dump();
        return false;
      }
    }

    assert(false);
    return false;
  }

  const Replacements& replacements() const { return replacements_; }

 private:
  bool HandleMemberCallExpr(const clang::CXXMemberCallExpr* member_call_expr,
                            const clang::DeclRefExpr* decl_ref_expr) {
    // If this isn't a ListValue::Append() call, cancel the rewrite: it
    // will require manual inspection to determine if it's an ownership
    // transferring call or not.
    auto* method_decl = member_call_expr->getMethodDecl();
    if (method_decl->getQualifiedNameAsString() != "base::ListValue::Append")
      return false;
    // Use-after-move is also a fatal error.
    if (!is_valid_)
      return false;

    is_valid_ = false;

    // Surround the DeclRefExpr with std::move().
    replacements_.emplace(*source_manager_, decl_ref_expr->getLocStart(), 0,
                          "std::move(");

    clang::SourceLocation end = clang::Lexer::getLocForEndOfToken(
        decl_ref_expr->getLocEnd(), 0, *source_manager_,
        ast_context_->getLangOpts());
    replacements_.emplace(*source_manager_, end, 0, ")");
    return true;
  }

  bool HandleBinaryOp(const clang::BinaryOperator* op) {
    if (op->isRelationalOp() || op->isEqualityOp() || op->isLogicalOp()) {
      // Supported binary operations for which no rewrites need to be done.
      return is_valid_;
    }
    if (!op->isAssignmentOp()) {
      // Pointer arithmetic or something else clever. Just cancel the rewrite.
      return false;
    }
    if (op->isCompoundAssignmentOp()) {
      // +=, -=, etc. Give up and cancel the rewrite.
      return false;
    }

    const clang::Expr* rhs = op->getRHS()->IgnoreParenImpCasts();
    const clang::CXXNewExpr* new_expr = clang::dyn_cast<clang::CXXNewExpr>(rhs);
    if (!new_expr) {
      // The variable isn't being assigned the result of a new operation. Just
      // cancel the rewrite.
      return false;
    }

    is_valid_ = true;

    // Rewrite the assignment operation to use std::unique_ptr::reset().
    clang::CharSourceRange range = clang::CharSourceRange::getCharRange(
        op->getOperatorLoc(), op->getRHS()->getLocStart());
    replacements_.emplace(*source_manager_, range, ".reset(");

    clang::SourceLocation expr_end = clang::Lexer::getLocForEndOfToken(
        op->getLocEnd(), 0, *source_manager_, ast_context_->getLangOpts());
    replacements_.emplace(*source_manager_, expr_end, 0, ")");
    return true;
  }

  clang::SourceManager* const source_manager_;
  clang::ASTContext* const ast_context_;
  const clang::VarDecl* const decl_;
  // Tracks the state of |decl_| during the traversal. |decl_| becomes valid
  // upon initialization/assignment and becomes invalid when passed as an
  // argument to base::ListValue::Append(base::Value*).
  bool is_valid_;
  clang::ParentMap map_;
  Replacements replacements_;
};

}  // namespace

ListValueRewriter::AppendCallback::AppendCallback(Replacements* replacements)
    : replacements_(replacements) {}

void ListValueRewriter::AppendCallback::run(
    const MatchFinder::MatchResult& result) {
  // Delete `new base::*Value(' and `)'.
  auto* newExpr = result.Nodes.getNodeAs<clang::CXXNewExpr>("newExpr");
  auto* argExpr = result.Nodes.getNodeAs<clang::Expr>("argExpr");

  // Note that for the end loc, we use the expansion loc: the argument might be
  // a macro like true and false.
  clang::CharSourceRange pre_arg_range = clang::CharSourceRange::getCharRange(
      newExpr->getLocStart(),
      result.SourceManager->getExpansionLoc(argExpr->getLocStart()));
  replacements_->emplace(*result.SourceManager, pre_arg_range, "");

  clang::CharSourceRange post_arg_range =
      clang::CharSourceRange::getTokenRange(newExpr->getLocEnd());
  replacements_->emplace(*result.SourceManager, post_arg_range, "");
}

ListValueRewriter::AppendBooleanCallback::AppendBooleanCallback(
    Replacements* replacements)
    : AppendCallback(replacements) {}

void ListValueRewriter::AppendBooleanCallback::run(
    const MatchFinder::MatchResult& result) {
  // Replace 'Append' with 'AppendBoolean'.
  auto* callExpr = result.Nodes.getNodeAs<clang::CXXMemberCallExpr>("callExpr");

  clang::CharSourceRange call_range =
      clang::CharSourceRange::getTokenRange(callExpr->getExprLoc());
  replacements_->emplace(*result.SourceManager, call_range, "AppendBoolean");

  AppendCallback::run(result);
}

ListValueRewriter::AppendIntegerCallback::AppendIntegerCallback(
    Replacements* replacements)
    : AppendCallback(replacements) {}

void ListValueRewriter::AppendIntegerCallback::run(
    const MatchFinder::MatchResult& result) {
  // Replace 'Append' with 'AppendInteger'.
  auto* callExpr = result.Nodes.getNodeAs<clang::CXXMemberCallExpr>("callExpr");

  clang::CharSourceRange call_range =
      clang::CharSourceRange::getTokenRange(callExpr->getExprLoc());
  replacements_->emplace(*result.SourceManager, call_range, "AppendInteger");

  AppendCallback::run(result);
}

ListValueRewriter::AppendDoubleCallback::AppendDoubleCallback(
    Replacements* replacements)
    : AppendCallback(replacements) {}

void ListValueRewriter::AppendDoubleCallback::run(
    const MatchFinder::MatchResult& result) {
  // Replace 'Append' with 'AppendDouble'.
  auto* callExpr = result.Nodes.getNodeAs<clang::CXXMemberCallExpr>("callExpr");

  clang::CharSourceRange call_range =
      clang::CharSourceRange::getTokenRange(callExpr->getExprLoc());
  replacements_->emplace(*result.SourceManager, call_range, "AppendDouble");

  AppendCallback::run(result);
}

ListValueRewriter::AppendStringCallback::AppendStringCallback(
    Replacements* replacements)
    : AppendCallback(replacements) {}

void ListValueRewriter::AppendStringCallback::run(
    const MatchFinder::MatchResult& result) {
  // Replace 'Append' with 'AppendString'.
  auto* callExpr = result.Nodes.getNodeAs<clang::CXXMemberCallExpr>("callExpr");

  clang::CharSourceRange call_range =
      clang::CharSourceRange::getTokenRange(callExpr->getExprLoc());
  replacements_->emplace(*result.SourceManager, call_range, "AppendString");

  AppendCallback::run(result);
}

ListValueRewriter::AppendReleasedUniquePtrCallback::
    AppendReleasedUniquePtrCallback(Replacements* replacements)
    : replacements_(replacements) {}

void ListValueRewriter::AppendReleasedUniquePtrCallback::run(
    const MatchFinder::MatchResult& result) {
  auto* object_expr = result.Nodes.getNodeAs<clang::Expr>("objectExpr");
  bool arg_is_rvalue = object_expr->Classify(*result.Context).isRValue();

  // Remove .release()
  auto* member_call =
      result.Nodes.getNodeAs<clang::CXXMemberCallExpr>("memberCall");
  auto* member_expr = result.Nodes.getNodeAs<clang::MemberExpr>("memberExpr");
  clang::CharSourceRange release_range = clang::CharSourceRange::getTokenRange(
      member_expr->getOperatorLoc(), member_call->getLocEnd());
  replacements_->emplace(*result.SourceManager, release_range,
                         arg_is_rvalue ? "" : ")");

  if (arg_is_rvalue)
    return;

  // Insert `std::move(' for non-rvalue expressions.
  clang::CharSourceRange insertion_range = clang::CharSourceRange::getCharRange(
      object_expr->getLocStart(), object_expr->getLocStart());
  replacements_->emplace(*result.SourceManager, insertion_range, "std::move(");
}

ListValueRewriter::AppendRawPtrCallback::AppendRawPtrCallback(
    Replacements* replacements)
    : replacements_(replacements) {}

void ListValueRewriter::AppendRawPtrCallback::run(
    const MatchFinder::MatchResult& result) {
  auto* var_decl = result.Nodes.getNodeAs<clang::VarDecl>("varDecl");
  // As an optimization, skip processing if it's already been visited, since
  // this match callback walks the entire function body.
  if (visited_.find(var_decl) != visited_.end())
    return;
  visited_.insert(var_decl);
  auto* function_context = var_decl->getParentFunctionOrMethod();
  assert(function_context && "local var not in function context?!");
  auto* function_decl = clang::cast<clang::FunctionDecl>(function_context);

  auto* type_source_info = var_decl->getTypeSourceInfo();
  assert(type_source_info && "no type source info for VarDecl?!");
  // Don't bother trying to handle qualifiers.
  clang::QualType qual_type = var_decl->getType();
  if (qual_type.hasQualifiers()) {
    return;
  }

  CollectDeclRefExprVisitor visitor(result.SourceManager, result.Context,
                                    var_decl, function_decl);
  if (!visitor.TraverseStmt(function_decl->getBody()))
    return;

  // Rewrite the variable type to use std::unique_ptr.
  clang::CharSourceRange type_range = clang::CharSourceRange::getTokenRange(
      type_source_info->getTypeLoc().getSourceRange());
  std::string replacement_type = "std::unique_ptr<";
  while (true) {
    const clang::Type* type = qual_type.getTypePtr();
    if (auto* auto_type = type->getAs<clang::AutoType>()) {
      if (!auto_type->isDeduced()) {
        // If an AutoType isn't deduced, the rewriter can't do anything.
        return;
      }
      qual_type = auto_type->getDeducedType();
    } else if (auto* pointer_type = type->getAs<clang::PointerType>()) {
      qual_type = pointer_type->getPointeeType();
    } else {
      break;
    }
  }
  replacement_type += qual_type.getAsString();
  replacement_type += ">";
  replacements_->emplace(*result.SourceManager, type_range, replacement_type);

  // Initialized with `='
  if (var_decl->hasInit() &&
      var_decl->getInitStyle() == clang::VarDecl::CInit) {
    clang::SourceLocation name_end = clang::Lexer::getLocForEndOfToken(
        var_decl->getLocation(), 0, *result.SourceManager,
        result.Context->getLangOpts());
    clang::CharSourceRange range = clang::CharSourceRange::getCharRange(
        name_end, var_decl->getInit()->getLocStart());
    replacements_->emplace(*result.SourceManager, range, "(");

    clang::SourceLocation init_end = clang::Lexer::getLocForEndOfToken(
        var_decl->getInit()->getLocEnd(), 0, *result.SourceManager,
        result.Context->getLangOpts());
    replacements_->emplace(*result.SourceManager, init_end, 0, ")");
  }

  // Also append the collected replacements from visiting the DeclRefExprs.
  replacements_->insert(visitor.replacements().begin(),
                        visitor.replacements().end());
}

ListValueRewriter::ListValueRewriter(Replacements* replacements)
    : append_boolean_callback_(replacements),
      append_integer_callback_(replacements),
      append_double_callback_(replacements),
      append_string_callback_(replacements),
      append_released_unique_ptr_callback_(replacements),
      append_raw_ptr_callback_(replacements) {}

void ListValueRewriter::RegisterMatchers(MatchFinder* match_finder) {
  auto is_list_append = cxxMemberCallExpr(
      callee(cxxMethodDecl(hasName("::base::ListValue::Append"))),
      argumentCountIs(1));

  // base::ListValue::Append(new base::FundamentalValue(bool))
  //     => base::ListValue::AppendBoolean()
  match_finder->addMatcher(
      id("callExpr",
         cxxMemberCallExpr(
             is_list_append,
             hasArgument(
                 0, ignoringParenImpCasts(id(
                        "newExpr",
                        cxxNewExpr(has(cxxConstructExpr(
                            hasDeclaration(cxxMethodDecl(hasName(
                                "::base::FundamentalValue::FundamentalValue"))),
                            argumentCountIs(1),
                            hasArgument(
                                0, id("argExpr",
                                      expr(hasType(booleanType())))))))))))),
      &append_boolean_callback_);

  // base::ListValue::Append(new base::FundamentalValue(int))
  //     => base::ListValue::AppendInteger()
  match_finder->addMatcher(
      id("callExpr",
         cxxMemberCallExpr(
             is_list_append,
             hasArgument(
                 0,
                 ignoringParenImpCasts(id(
                     "newExpr",
                     cxxNewExpr(has(cxxConstructExpr(
                         hasDeclaration(cxxMethodDecl(hasName(
                             "::base::FundamentalValue::FundamentalValue"))),
                         argumentCountIs(1),
                         hasArgument(0, id("argExpr",
                                           expr(hasType(isInteger()),
                                                unless(hasType(
                                                    booleanType()))))))))))))),
      &append_integer_callback_);

  // base::ListValue::Append(new base::FundamentalValue(double))
  //     => base::ListValue::AppendDouble()
  match_finder->addMatcher(
      id("callExpr",
         cxxMemberCallExpr(
             is_list_append,
             hasArgument(
                 0, ignoringParenImpCasts(id(
                        "newExpr",
                        cxxNewExpr(has(cxxConstructExpr(
                            hasDeclaration(cxxMethodDecl(hasName(
                                "::base::FundamentalValue::FundamentalValue"))),
                            argumentCountIs(1),
                            hasArgument(
                                0, id("argExpr",
                                      expr(hasType(
                                          realFloatingPointType())))))))))))),
      &append_double_callback_);

  // base::ListValue::Append(new base::StringValue(...))
  //     => base::ListValue::AppendString()
  match_finder->addMatcher(
      id("callExpr",
         cxxMemberCallExpr(
             is_list_append,
             hasArgument(
                 0, ignoringParenImpCasts(id(
                        "newExpr",
                        cxxNewExpr(has(cxxConstructExpr(
                            hasDeclaration(cxxMethodDecl(
                                hasName("::base::StringValue::StringValue"))),
                            argumentCountIs(1),
                            hasArgument(0, id("argExpr", expr())))))))))),
      &append_string_callback_);

  auto is_unique_ptr_release =
      allOf(callee(cxxMethodDecl(
                hasName("release"),
                ofClass(cxxRecordDecl(hasName("::std::unique_ptr"))))),
            argumentCountIs(0));

  // base::ListValue::Append(ReturnsUniquePtr().release())
  //     => base::ListValue::Append(ReturnsUniquePtr())
  //   or
  // base::ListValue::Append(unique_ptr_var.release())
  //     => base::ListValue::Append(std::move(unique_ptr_var))
  match_finder->addMatcher(
      cxxMemberCallExpr(
          is_list_append,
          hasArgument(
              0, ignoringParenImpCasts(
                     id("memberCall",
                        cxxMemberCallExpr(has(id("memberExpr", memberExpr())),
                                          is_unique_ptr_release,
                                          on(id("objectExpr", expr()))))))),
      &append_released_unique_ptr_callback_);

  // Simple versions of the following pattern. Note the callback itself does
  // much of the filtering (to detect use-after-move, things that aren't
  // assigned the result of a new expression, etc).
  //
  // base::ListValue* this_list = new base::ListValue;
  // this_list->AppendInteger(1);
  // that_list->Append(this_list);
  //
  // will be rewritten to
  //
  // std::unique_ptr<base::ListValue> this_list(new base::ListValue);
  // this_list->AppendInteger(1);
  // that_list->Append(std::move(this_list);
  match_finder->addMatcher(
      cxxMemberCallExpr(
          is_list_append,
          hasArgument(
              0,
              ignoringParenImpCasts(id(
                  "declRefExpr",
                  declRefExpr(to(id(
                      "varDecl",
                      varDecl(
                          hasLocalStorage(),
                          anyOf(hasInitializer(
                                    // Note this won't match C++11 uniform
                                    // initialization syntax, since the
                                    // CXXNewExpr is wrapped in an
                                    // InitListExpr in that case.
                                    ignoringParenImpCasts(cxxNewExpr())),
                                unless(hasInitializer(expr()))),
                          unless(parmVarDecl()))))))))),
      &append_raw_ptr_callback_);
}