Convert buffer from format A to format B.
546438
function convert (buffer, from, to) {
	//ensure formats are full
	if (!isNormalized(from)) from = normalize(from)
	if (!isNormalized(to)) to = normalize(to)

	//convert buffer/alike to arrayBuffer
	var data
	if (buffer instanceof ArrayBuffer) {
		data = buffer
	}
	else if (ArrayBuffer.isView(buffer)) {
		if (buffer.byteOffset != null) data = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
		else data = buffer.buffer;
	}
	else {
		data = (new Uint8Array(buffer.length != null ? buffer : [buffer])).buffer
	}

	//ignore needless conversion
	if (equal(from ,to)) {
		return data
	}

	//create containers for conversion
	var fromArray = new (arrayClass(from))(data)

	//toArray is automatically filled with mapped values
	//but in some cases mapped badly, e. g. float → int(round + rotate)
	var toArray = new (arrayClass(to))(fromArray)

	//if range differ, we should apply more thoughtful mapping
	if (from.max !== to.max) {
		fromArray.forEach(function (value, idx) {
			//ignore not changed range
			//bring to 0..1
			var normalValue = (value - from.min) / (from.max - from.min)

			//bring to new format ranges
			value = normalValue * (to.max - to.min) + to.min

			//clamp (buffers does not like values outside of bounds)
			toArray[idx] = Math.max(to.min, Math.min(to.max, value))
		})
	}

	//reinterleave, if required
	if (from.interleaved != to.interleaved) {
		var channels = from.channels
		var len = Math.floor(fromArray.length / channels)

		//deinterleave
		if (from.interleaved && !to.interleaved) {
			toArray = toArray.map(function (value, idx, data) {
				var targetOffset = idx % len
				var targetChannel = ~~(idx / len)

				return data[targetOffset * channels + targetChannel]
			})
		}
		//interleave
		else if (!from.interleaved && to.interleaved) {
			toArray = toArray.map(function (value, idx, data) {
				var targetOffset = ~~(idx / channels)
				var targetChannel = idx % channels

				return data[targetChannel * len + targetOffset]
			})
		}
	}

	//ensure endianness
	if (!to.float && from.byteOrder !== to.byteOrder) {
		var le = to.byteOrder === 'LE'
		var view = new DataView(toArray.buffer)
		var step = to.bitDepth / 8
		var methodName = 'set' + getDataViewSuffix(to)
		for (var i = 0, l = toArray.length; i < l; i++) {
			view[methodName](i*step, toArray[i], le)
		}
	}

	return toArray.buffer
}
102535
public void serializeToBuffer(ByteBuffer b) {
        assert(getSerializedSize() <= b.remaining());
        b.putInt(getSerializedSize() - 4);
        b.put((byte)getExceptionType().ordinal());
        if (m_message != null) {
            final byte messageBytes[] = m_message.getBytes();
            b.putInt(messageBytes.length);
            b.put(messageBytes);
        } else {
            b.putInt(0);
        }
        p_serializeToBuffer(b);
    }
1176994
def FromTextFormat(cls, text):
    """"""
    tmp = cls.protobuf()  # pylint: disable=not-callable
    text_format.Merge(text, tmp)

    return cls.FromSerializedString(tmp.SerializeToString())
970640
def convert_to_mb(s):
    """"""
    s = s.upper()
    try:
        if s.endswith('G'):
            return float(s[:-1].strip()) * 1024
        elif s.endswith('T'):
            return float(s[:-1].strip()) * 1024 * 1024
        else:
            return float(s[:-1].strip())
    except (IndexError, ValueError, KeyError, TypeError):
        errmsg = ("Invalid memory format: %s") % s
        raise exception.SDKInternalError(msg=errmsg)
972969
public static void append(ByteBuffer to, byte[] b, int off, int len) throws BufferOverflowException {
        int pos = flipToFill(to);
        try {
            to.put(b, off, len);
        } finally {
            flipToFlush(to, pos);
        }
    }
695281
def convert(cgi_input, twobit_ref, twobit_name, var_only=False):
    """"""

    # Set up CGI input. Default is to assume a str generator.
    if isinstance(cgi_input, str) or isinstance(cgi_input, unicode):
        cgi_input = auto_zip_open(cgi_input, 'rb')

    # Set up TwoBitFile for retrieving reference sequences.
    reference = twobitreader.TwoBitFile(twobit_ref)

    # Output header.
    header = make_header(twobit_name).split('\n')
    for line in header:
        yield line

    while True:
        line = cgi_input.readline()
        if not line:
            break
        line = line.decode('utf-8')

        # Skip header lines.
        if re.search(r'^\W*$', line) or line.startswith('#'):
            continue

        # Store header row labels.
        if line.startswith('>'):
            header_data = line.lstrip('>').rstrip('\n').split('\t')
            header = {header_data[i]: i for i in range(len(header_data))}
            continue

        # If we reach this point, this is a line that contains data.
        data = line.rstrip('\n').split("\t")

        out = process_next_position(
            data=data, cgi_input=cgi_input, header=header, reference=reference,
            var_only=var_only)

        # process_next_position returns an array of one or more lines
        if out:
            for line in out:
                yield line
879857
def parse_buffer(self, s):
            ''''''
            m = self.parse_char(s)
            if m is None:
                return None
            ret = [m]
            while True:
                m = self.parse_char("")
                if m is None:
                    return ret
                ret.append(m)
            return ret
316584
def pair_strings_sum_formatter(a, b):
  
  if b[:1] == "-":
    return "{0} - {1}".format(a, b[1:])
  return "{0} + {1}".format(a, b)
173480
def convert(self, value, param, ctx):  # pylint: disable=inconsistent-return-statements
        """"""
        matches = MEMORY_RE.match(value.lower())
        if matches is None:
            self.fail('%s is not a valid value for memory amount' % value, param, ctx)
        amount_str, unit = matches.groups()
        amount = int(amount_str)
        if unit in [None, 'm', 'mb']:
            # Assume the user intends gigabytes if they specify a number < 1024
            if amount < 1024:
                return amount * 1024
            else:
                if amount % 1024 != 0:
                    self.fail('%s is not an integer that is divisable by 1024' % value, param, ctx)
                return amount
        elif unit in ['g', 'gb']:
            return amount * 1024
1150155
function parse(s, buf, offset) {
  const i = (buf && offset) || 0;
  var ii = 0;

  if (buf) buf.fill(0, i, i + 16);
  buf = buf || new Buffer(16);
  s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
    if (ii < 16) { // Don't overflow!
      buf[i + ii++] = _hexToByte[oct];
    }
  });

  var buf2 = new Buffer(buf.slice(i, i + 16));
  buf[i + 0] = buf2[3];
  buf[i + 1] = buf2[2];
  buf[i + 2] = buf2[1];
  buf[i + 3] = buf2[0];
  buf[i + 4] = buf2[5];
  buf[i + 5] = buf2[4];
  buf[i + 6] = buf2[7];
  buf[i + 7] = buf2[6];

  return buf;
}
1153937
def endianSwapU16(bytes):
    """"""
    for b in range(0, len(bytes), 2):
        bytes[b], bytes[b + 1] = bytes[b + 1], bytes[b]
    return bytes
984129
def xor(a, b):
        """"""
        return bytearray(i ^ j for i, j in zip(a, b))
256228
function fromBytes(input){
    var output = '';
    var len = input.length;
    var i = 0;
    var b1;
    var b2;

    while (i < len)
    {
      b1 = input[i++] || 0;
      b2 = input[i++] || 0;
      output += String.fromCharCode((b2 << 8) | b1);
    }
    return output;
  }
467068
def safe_lshift(a, b):
    """"""
    if b > MAX_SHIFT:
        raise RuntimeError("Invalid left shift, max left shift is {}".format(MAX_SHIFT))
    return a << b
1033406
public static byte[] sub(byte[] b, int off, int len) {
		byte[] result = new byte[len];
		System.arraycopy(b, off, result, 0, len);
		return result;
	}
133070
function toBuffer (chunk, encoding) {
  return !Buffer.isBuffer(chunk)
    ? Buffer.from(chunk, encoding)
    : chunk
}
1256914
def substitute_values(text, values):
    """"""
    shift, final_text, shifts = 0, text, defaultdict(int)
    for value in values:
        first = value['old_span'][0] + shift
        second = value['old_span'][1] + shift
        new_s = value['new_surface']
        final_text = final_text[0:first] + new_s + final_text[second:]
        shift += len(new_s) - len(value['old_surface'])
        for char in range(first + 1, len(final_text)):
            shifts[char] = shift

    logging.debug(u'Text after numeric conversion: "%s"', final_text)

    return final_text, shifts