Decode binary data into structures needed to process adhoc queries.
This code was pulled out of runAdHoc so it could be shared there and with
adHocSQLStringFromPlannedStatement.
763157
public static Pair<Object[], AdHocPlannedStatement[]> decodeSerializedBatchData(byte[] serializedBatchData) {
        // Collections must be the same size since they all contain slices of the same data.
        assert(serializedBatchData != null);

        ByteBuffer buf = ByteBuffer.wrap(serializedBatchData);
        AdHocPlannedStatement[] statements = null;
        Object[] userparams = null;
        try {
            userparams = AdHocPlannedStmtBatch.userParamsFromBuffer(buf);
            statements = AdHocPlannedStmtBatch.planArrayFromBuffer(buf);
        }
        catch (IOException e) {
            throw new VoltAbortException(e);
        }
        return new Pair<Object[], AdHocPlannedStatement[]>(userparams, statements);
    }
544135
private static void decode(InputStream in, StringBuilder result) throws ApiDataException, ApiConnectionException {
        try {
            int len = readLen(in);
            if (len > 0) {
                byte buf[] = new byte[len];
                for (int i = 0; i < len; ++i) {
                    int c = in.read();
                    if (c < 0) {
                        throw new ApiDataException("Truncated data. Expected to read more bytes");
                    }
                    buf[i] = (byte) (c & 0xFF);
                }
                String res = new String(buf, Charset.forName("UTF-8"));
                if (result.length() > 0) {
                    result.append("\n");
                }
                result.append(res);
                decode(in, result);
            }
        } catch (IOException ex) {
            throw new ApiConnectionException(ex.getMessage(), ex);
        }
    }
417005
def decode(decoder, data, length, frame_size, decode_fec, channels=2):
    

    pcm_size = frame_size * channels * ctypes.sizeof(ctypes.c_int16)
    pcm = (ctypes.c_int16 * pcm_size)()
    pcm_pointer = ctypes.cast(pcm, c_int16_pointer)

    # Converting from a boolean to int
    decode_fec = int(bool(decode_fec))

    result = _decode(decoder, data, length, pcm_pointer, frame_size, decode_fec)
    if result < 0:
        raise OpusError(result)

    return array.array('h', pcm).tostring()
317019
public static byte[] decode(char[] data) {

        int tempLen = data.length;
        for (int ix = 0; ix < data.length; ix++) {
            if ((data[ix] > 255) || codes[data[ix]] < 0) {
                --tempLen; // ignore non-valid chars and padding
            }
        }
        // calculate required length:
        // -- 3 bytes for every 4 valid base64 chars
        // -- plus 2 bytes if there are 3 extra base64 chars,
        // or plus 1 byte if there are 2 extra.

        int len = (tempLen / 4) * 3;
        if ((tempLen % 4) == 3) {
            len += 2;
        }
        if ((tempLen % 4) == 2) {
            len += 1;

        }
        byte[] out = new byte[len];

        int shift = 0; // # of excess bits stored in accum
        int accum = 0; // excess bits
        int index = 0;

        // we now go through the entire array (NOT using the 'tempLen' value)
        for (int ix = 0; ix < data.length; ix++) {
            int value = (data[ix] > 255) ? -1 : codes[data[ix]];

            if (value >= 0) { // skip over non-code
                accum <<= 6; // bits shift up by 6 each time thru
                shift += 6; // loop, with new bits being put in
                accum |= value; // at the bottom.
                if (shift >= 8) { // whenever there are 8 or more shifted in,
                    shift -= 8; // write them out (from the top, leaving any
                    out[index++] = // excess at the bottom for next iteration.
                            (byte) ((accum >> shift) & 0xff);
                }
            }
        }

        // if there is STILL something wrong we just have to throw up now!
        if (index != out.length) {
            throw new Error("Miscalculated data length (wrote " + index
                    + " instead of " + out.length + ")");
        }

        return out;
    }
14372
public void decode(ByteBuffer buffer, boolean moreData) throws HpackException {
        while (buffer.hasRemaining()) {
            int originalPos = buffer.position();
            byte b = buffer.get();
            if ((b & 0b10000000) != 0) {
                first = false;
                //if the first bit is set it is an indexed header field
                buffer.position(buffer.position() - 1); //unget the byte
                int index = Hpack.decodeInteger(buffer, 7); //prefix is 7
                if (index == -1) {
                    if(!moreData) {
                        throw UndertowMessages.MESSAGES.hpackFailed();
                    }
                    buffer.position(originalPos);
                    return;
                } else if(index == 0) {
                    throw UndertowMessages.MESSAGES.zeroNotValidHeaderTableIndex();
                }
                handleIndex(index);
            } else if ((b & 0b01000000) != 0) {
                first = false;
                //Literal Header Field with Incremental Indexing
                HttpString headerName = readHeaderName(buffer, 6);
                if (headerName == null) {
                    if(!moreData) {
                        throw UndertowMessages.MESSAGES.hpackFailed();
                    }
                    buffer.position(originalPos);
                    return;
                }
                String headerValue = readHpackString(buffer);
                if (headerValue == null) {
                    if(!moreData) {
                        throw UndertowMessages.MESSAGES.hpackFailed();
                    }
                    buffer.position(originalPos);
                    return;
                }
                headerEmitter.emitHeader(headerName, headerValue, false);
                addEntryToHeaderTable(new HeaderField(headerName, headerValue));
            } else if ((b & 0b11110000) == 0) {
                first = false;
                //Literal Header Field without Indexing
                HttpString headerName = readHeaderName(buffer, 4);
                if (headerName == null) {
                    if(!moreData) {
                        throw UndertowMessages.MESSAGES.hpackFailed();
                    }
                    buffer.position(originalPos);
                    return;
                }
                String headerValue = readHpackString(buffer);
                if (headerValue == null) {
                    if(!moreData) {
                        throw UndertowMessages.MESSAGES.hpackFailed();
                    }
                    buffer.position(originalPos);
                    return;
                }
                headerEmitter.emitHeader(headerName, headerValue, false);
            } else if ((b & 0b11110000) == 0b00010000) {
                first = false;
                //Literal Header Field never indexed
                HttpString headerName = readHeaderName(buffer, 4);
                if (headerName == null) {
                    buffer.position(originalPos);
                    return;
                }
                String headerValue = readHpackString(buffer);
                if (headerValue == null) {
                    if(!moreData) {
                        throw UndertowMessages.MESSAGES.hpackFailed();
                    }
                    buffer.position(originalPos);
                    return;
                }
                headerEmitter.emitHeader(headerName, headerValue, true);
            } else if ((b & 0b11100000) == 0b00100000) {
                if(!first) {
                    throw new HpackException();
                }
                //context update max table size change
                if (!handleMaxMemorySizeChange(buffer, originalPos)) {
                    return;
                }
            } else {
                throw UndertowMessages.MESSAGES.invalidHpackEncoding(b);
            }
        }
        if(!moreData) {
            first = true;
        }
    }
1261268
def decode(query)
      return nil if query.nil?

      params = {}
      query.split('&').each do |pair|
        next if pair.empty?

        key, value = pair.split('=', 2)
        key = unescape(key)
        value = unescape(value.tr('+', ' ')) if value
        decode_pair(key, value, params)
      end

      dehash(params, 0)
    end
1220038
@Override
    protected void decode(DataInputStream buffer) throws IOException
    {
        entityId = buffer.readShort();
        final int number = buffer.readByte();
        for (int i = 0; i < number; i++)
        {
            decode(buffer, i);
        }
    }
320823
function _decodeBlob(encodedBlob) {
    var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
    return createBlob([arrayBuff], { type: encodedBlob.type });
}
481855
public static String adHocSQLStringFromPlannedStatement(AdHocPlannedStatement statement, Object[] userparams) {
        final int MAX_PARAM_LINE_CHARS = 120;

        StringBuilder sb = new StringBuilder();
        String sql = new String(statement.sql, Charsets.UTF_8);
        sb.append(sql);

        Object[] params = paramsForStatement(statement, userparams);
        // convert params to strings of a certain max length
        for (int i = 0; i < params.length; i++) {
            Object param = params[i];

            String paramLineStr = String.format("    Param %d: %s", i, param.toString());
            // trim param line if it's silly long
            if (paramLineStr.length() > MAX_PARAM_LINE_CHARS) {
                paramLineStr = paramLineStr.substring(0, MAX_PARAM_LINE_CHARS - 3);
                paramLineStr += "...";
            }

            sb.append('\n').append(paramLineStr);
        }

        return sb.toString();
    }
1314905
public static int decodeSequence(byte[] flakeBytes) {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        buffer.put(flakeBytes);
        buffer.flip();
        buffer.getLong();
        return (int)(buffer.getLong() & 0x000000000000FFFF);
    }
1114679
def decode(self, buf):
        
        index = 0
        if self.length > len(buf):
            raise exc.ParseError("Insufficient data for reading header.") 
        for (name, nbytes, typecode) in self.format:
            string = buf[index:index + nbytes]
            index += nbytes
            value = struct.unpack('<' + typecode, string)[0]
            setattr(self, name, value)
        if const.DB_SIGNATURE1 != self.signature1 or \
                const.DB_SIGNATURE2 != self.signature2:
            msg = 'Bad signatures: {0} {0}'.format(hex(self.signature1),
                                                   hex(self.signature2))
            raise exc.InvalidDatabase(msg)
1130135
private int decodeBlackCodeWord() {
        int current, entry, bits, isT, code = -1;
        int runLength = 0;
        boolean isWhite = false;
        
        while (!isWhite) {
            current = nextLesserThan8Bits(4);
            entry = initBlack[current];
            
            // Get the 3 fields from the entry
            isT = entry & 0x0001;
            bits = (entry >>> 1) & 0x000f;
            code = (entry >>> 5) & 0x07ff;
            
            if (code == 100) {
                current = nextNBits(9);
                entry = black[current];
                
                // Get the 3 fields from the entry
                isT = entry & 0x0001;
                bits = (entry >>> 1) & 0x000f;
                code = (entry >>> 5) & 0x07ff;
                
                if (bits == 12) {
                    // Additional makeup codes
                    updatePointer(5);
                    current = nextLesserThan8Bits(4);
                    entry = additionalMakeup[current];
                    bits = (entry >>> 1) & 0x07;     // 3 bits 0000 0111
                    code  = (entry >>> 4) & 0x0fff;  // 12 bits
                    runLength += code;
                    
                    updatePointer(4 - bits);
                } else if (bits == 15) {
                	// EOL code
                	if ( runLength == 0 ) {
                		isWhite = true;
                	}
                	else {
                		throw new RuntimeException("EOL code word encountered in Black run.");
                	}
                } else {
                    runLength += code;
                    updatePointer(9 - bits);
                    if (isT == 0) {
                        isWhite = true;
                    }
                }
            } else if (code == 200) {
                // Is a Terminating code
                current = nextLesserThan8Bits(2);
                entry = twoBitBlack[current];
                code = (entry >>> 5) & 0x07ff;
                runLength += code;
                bits = (entry >>> 1) & 0x0f;
                updatePointer(2 - bits);
                isWhite = true;
            } else {
                // Is a Terminating code
                runLength += code;
                updatePointer(4 - bits);
                isWhite = true;
            }
        }
        
        return runLength;
    }
528996
private static void decodeEdifactSegment(BitSource bits, StringBuilder result) {
    do {
      // If there is only two or less bytes left then it will be encoded as ASCII
      if (bits.available() <= 16) {
        return;
      }

      for (int i = 0; i < 4; i++) {
        int edifactValue = bits.readBits(6);

        // Check for the unlatch character
        if (edifactValue == 0x1F) {  // 011111
          // Read rest of byte, which should be 0, and stop
          int bitsLeft = 8 - bits.getBitOffset();
          if (bitsLeft != 8) {
            bits.readBits(bitsLeft);
          }
          return;
        }

        if ((edifactValue & 0x20) == 0) {  // no 1 in the leading (6th) bit
          edifactValue |= 0x40;  // Add a leading 01 to the 6 bit binary value
        }
        result.append((char) edifactValue);
      }
    } while (bits.available() > 0);
  }
257685
function decode(data) {
  return io.tmpFile().then(function(file) {
    var buf = new Buffer(data, 'base64');
    return promise.checkedNodeCall(fs.writeFile, file, buf).then(function() {
      return io.tmpDir();
    }).then(function(dir) {
      var zip = new AdmZip(file);
      zip.extractAllTo(dir);  // Sync only? Why?? :-(
      return dir;
    });
  });
}
399509
function DBCSCodec(codecOptions, iconv) {
    this.encodingName = codecOptions.encodingName;
    if (!codecOptions)
        throw new Error("DBCS codec is called without the data.")
    if (!codecOptions.table)
        throw new Error("Encoding '" + this.encodingName + "' has no data.");

    // Load tables.
    var mappingTable = codecOptions.table();


    // Decode tables: MBCS -> Unicode.

    // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
    // Trie root is decodeTables[0].
    // Values: >=  0 -> unicode character code. can be > 0xFFFF
    //         == UNASSIGNED -> unknown/unassigned sequence.
    //         == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
    //         <= NODE_START -> index of the next node in our trie to process next byte.
    //         <= SEQ_START  -> index of the start of a character code sequence, in decodeTableSeq.
    this.decodeTables = [];
    this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.

    // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. 
    this.decodeTableSeq = [];

    // Actual mapping tables consist of chunks. Use them to fill up decode tables.
    for (var i = 0; i < mappingTable.length; i++)
        this._addDecodeChunk(mappingTable[i]);

    this.defaultCharUnicode = iconv.defaultCharUnicode;

    
    // Encode tables: Unicode -> DBCS.

    // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
    // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
    // Values: >=  0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
    //         == UNASSIGNED -> no conversion found. Output a default char.
    //         <= SEQ_START  -> it's an index in encodeTableSeq, see below. The character starts a sequence.
    this.encodeTable = [];
    
    // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
    // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
    // means end of sequence (needed when one sequence is a strict subsequence of another).
    // Objects are kept separately from encodeTable to increase performance.
    this.encodeTableSeq = [];

    // Some chars can be decoded, but need not be encoded.
    var skipEncodeChars = {};
    if (codecOptions.encodeSkipVals)
        for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {
            var val = codecOptions.encodeSkipVals[i];
            if (typeof val === 'number')
                skipEncodeChars[val] = true;
            else
                for (var j = val.from; j <= val.to; j++)
                    skipEncodeChars[j] = true;
        }
        
    // Use decode trie to recursively fill out encode tables.
    this._fillEncodeTable(0, 0, skipEncodeChars);

    // Add more encoding pairs when needed.
    if (codecOptions.encodeAdd) {
        for (var uChar in codecOptions.encodeAdd)
            if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))
                this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
    }

    this.defCharSB  = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
    if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];
    if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);


    // Load & create GB18030 tables when needed.
    if (typeof codecOptions.gb18030 === 'function') {
        this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.

        // Add GB18030 decode tables.
        var thirdByteNodeIdx = this.decodeTables.length;
        var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0);

        var fourthByteNodeIdx = this.decodeTables.length;
        var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0);

        for (var i = 0x81; i <= 0xFE; i++) {
            var secondByteNodeIdx = NODE_START - this.decodeTables[0][i];
            var secondByteNode = this.decodeTables[secondByteNodeIdx];
            for (var j = 0x30; j <= 0x39; j++)
                secondByteNode[j] = NODE_START - thirdByteNodeIdx;
        }
        for (var i = 0x81; i <= 0xFE; i++)
            thirdByteNode[i] = NODE_START - fourthByteNodeIdx;
        for (var i = 0x30; i <= 0x39; i++)
            fourthByteNode[i] = GB18030_CODE
    }        
}
184536
@Override
    public void decode(byte[] bytes, StringBuilder buffer) {
        if (bytes == null) {
            // append nothing
            return;
        }

        char[] table = CHAR_TABLE;
        for (int i = 0; i < bytes.length; i++) {
            int code = (int)bytes[i] & 0x000000ff;
            if (code == EXTENDED_ESCAPE) {
                // take next char from extension table
                table = EXT_CHAR_TABLE;
            } else {
                buffer.append((code >= table.length) ? '?' : table[code]);
                // go back to the default table
                table = CHAR_TABLE;
            }
        }
    }
251815
private byte[][] decode(byte[] encodedPublicKey) {
        byte[][] decodedKey = new byte[2][];
        decodedKey[MODULUS] = new byte[MODULUS_LENGTH];
        decodedKey[EXPONENT] = new byte[EXPONENT_LENGTH];
        System.arraycopy(encodedPublicKey, 0, decodedKey[MODULUS], 0, MODULUS_LENGTH);
        System.arraycopy(encodedPublicKey, MODULUS_LENGTH, decodedKey[EXPONENT], 0, EXPONENT_LENGTH);
        return decodedKey;
    }