Creates the Huffman codes for literals and distances for dynamic Huffman compression.
@param BitReader $bitReader Bit reader.

@return HuffmanTree[] Literals tree and distances tree.
971058
protected function getDynamicHuffmanTrees(BitReader $bitReader)
    {
        $literalsNumber = $bitReader->read(self::HLIT_BITS) + self::HLIT_INITIAL_VALUE;
        $distancesNumber = $bitReader->read(self::HDIST_BITS) + self::HDIST_INITIAL_VALUE;
        $codeLengthsNumber = $bitReader->read(self::HCLEN_BITS) + self::HCLEN_INITIAL_VALUE;

        // code lengths
        $codeLengths = [];
        for ($i = 0; $i < $codeLengthsNumber; $i++) {
            $codeLengths[$this->codeLenghtsOrders[$i]] = $bitReader->read(3);
        }

        // create code lengths huffman tree
        $codeLengthsTree = HuffmanTree::createFromLengths($codeLengths);

        $i = 0;
        $literalAndDistanceLengths = [];
        $previousCodeLength = 0;
        while ($i < ($literalsNumber + $distancesNumber)) {
            $symbol = $codeLengthsTree->findNextSymbol($bitReader);

            if (false === $symbol) {
                return false;
            }

            if ($symbol >= 0 && $symbol <= 15) {
                // "normal" length
                $literalAndDistanceLengths[] = $symbol;
                $previousCodeLength = $symbol;

                $i++;
            } elseif ($symbol >= 16 && $symbol <= 18) {
                // repeat
                switch ($symbol) {
                    case 16:
                        $times = $bitReader->read(2) + 3;
                        $repeatedValue = $previousCodeLength;
                        break;
                    case 17:
                        $times = $bitReader->read(3) + 3;
                        $repeatedValue = 0;
                        break;
                    default:
                        $times = $bitReader->read(7) + 11;
                        $repeatedValue = 0;
                        break;
                }

                for ($j = 0; $j < $times; $j++) {
                    $literalAndDistanceLengths[] = $repeatedValue;
                }

                $i += $times;
            }
        }

        return [
            HuffmanTree::createFromLengths(array_slice($literalAndDistanceLengths, 0, $literalsNumber)),
            HuffmanTree::createFromLengths(array_slice($literalAndDistanceLengths, $literalsNumber))
        ];
    }
558220
static protected byte[] getBytes(int bitString)
    {
        int bytes = 4;
        for (int i = 3; i >= 1; i--)
        {
            if ((bitString & (0xFF << (i * 8))) != 0)
            {
                break;
            }
            bytes--;
        }

        byte[] result = new byte[bytes];
        for (int i = 0; i < bytes; i++)
        {
            result[i] = (byte) ((bitString >> (i * 8)) & 0xFF);
        }

        return result;
    }
5849
private static List<String> buildSegmentedSentences(final BufferedReader breader) {
    String line;
    List<String> sentences = new ArrayList<>();
    try {
      while ((line = breader.readLine()) != null) {
        sentences.add(line);
      }
    } catch (final IOException e) {
      LOG.error("IOException", e);
    }
    return sentences;
  }
178143
public static function fromConcat(BitArray $bits1, BitArray $bits2)
	{
		$size = $bits1->size + $bits2->size;
		$concat = new BitArray($size);
		$concat->directCopy($bits1, 0, 0, $bits1->size);
		$concat->directCopy($bits2, $bits1->size, 0, $bits2->size);

		return $concat;
	}
1251454
public function readPair()
    {
        try {
            return new QtiPair($this->readString(), $this->readString());
        } catch (BinaryStreamAccessException $e) {
            $msg = "An error occured while reading a pair.";
            throw new QtiBinaryStreamAccessException($msg, $this, QtiBinaryStreamAccessException::PAIR, $e);
        }
    }
1189356
private function versionFromBits($bits)
    {
        $version = [];
        foreach (range(0, ($bits - 1)) as $bit) {
            $version[$bit] = $this->getVersionBits()[$bit];
        }
        return $version;
    }
1263716
protected function parseElement(\XMLReader $xmlReader)
    {
        $elementName = $xmlReader->name;
        switch ($elementName) {
            case 'node':
                // update current node identifier
                $this->nodeIdentifierStack[] = $xmlReader->getAttribute('identifier');
                // update current path
                $nodeName = $xmlReader->getAttribute('nodeName');
                if ($nodeName !== '/' && $nodeName !== '') {
                    $this->nodeNameStack[] = Utility::renderValidNodeName($nodeName);
                }
                break;
            case 'variant':
                $path = $this->getCurrentPath();
                $parentPath = $this->getParentPath($path);

                $now = new Now();
                $currentNodeIdentifier = $this->nodeIdentifierStack[count($this->nodeIdentifierStack) - 1];
                $this->nodeDataStack[] = [
                    'Persistence_Object_Identifier' => Algorithms::generateUUID(),
                    'identifier' => $currentNodeIdentifier,
                    'nodeType' => $xmlReader->getAttribute('nodeType'),
                    'workspace' => $xmlReader->getAttribute('workspace'),
                    'sortingIndex' => $xmlReader->getAttribute('sortingIndex'),
                    'version' => $xmlReader->getAttribute('version'),
                    'removed' => (boolean)$xmlReader->getAttribute('removed'),
                    'hidden' => (boolean)$xmlReader->getAttribute('hidden'),
                    'hiddenInIndex' => (boolean)$xmlReader->getAttribute('hiddenInIndex'),
                    'path' => $path,
                    'pathHash' => md5($path),
                    'parentPath' => $parentPath,
                    'parentPathHash' => md5($parentPath),
                    'properties' => [],
                    'accessRoles' => [],
                    'creationDateTime' => $now,
                    'lastModificationDateTime' => $now,
                    'dimensionValues' => [] // is post-processed before save in END_ELEMENT-case
                ];
                break;
            case 'dimensions':
                $this->nodeDataStack[count($this->nodeDataStack) - 1]['dimensionValues'] = $this->parseDimensionsElement($xmlReader);
                break;
            case 'properties':
                $currentNodeIdentifier = $this->nodeDataStack[count($this->nodeDataStack) - 1]['identifier'];
                $this->nodeDataStack[count($this->nodeDataStack) - 1][$elementName] = $this->parsePropertiesElement($xmlReader, $currentNodeIdentifier);
                break;
            case 'accessRoles':
                $currentNodeIdentifier = $this->nodeDataStack[count($this->nodeDataStack) - 1]['identifier'];
                $this->nodeDataStack[count($this->nodeDataStack) - 1][$elementName] = $this->parseArrayElements($xmlReader, 'accessRoles', $currentNodeIdentifier);
                break;
            case 'hiddenBeforeDateTime':
            case 'hiddenAfterDateTime':
            case 'creationDateTime':
            case 'lastModificationDateTime':
            case 'lastPublicationDateTime':
                $stringValue = trim($xmlReader->readString());
                $dateValue = $this->propertyMapper->convert($stringValue, 'DateTime', $this->propertyMappingConfiguration);
                $this->nodeDataStack[count($this->nodeDataStack) - 1][$elementName] = $dateValue;
                break;
            default:
                throw new ImportException(sprintf('Unexpected element <%s> ', $elementName), 1423578065);
                break;
        }
    }
929204
def split(self, bits_count):
		
		result = []
		array = WBinArray(self.__value, self.__size)

		if (len(array) % bits_count) > 0:
			array.resize(len(array) + (bits_count - (len(array) % bits_count)))

		while len(array):
			result.append(WBinArray(array[:bits_count], bits_count))
			array = array[bits_count:]
		return result
743839
public function read_long()
    {
        $this->bitcount = $this->bits = 0;
        list(, $res) = unpack('N', $this->rawread(4));

        return empty($this->is64bits) && self::getLongMSB($res) ? sprintf('%u', $res) : $res;
    }
681245
public function import_from_reader(FileReader $reader)
    {
        $endian_string = $this->get_byteorder($reader->readint32());
        if (false === $endian_string) {
            return false;
        }
        $reader->setEndian($endian_string);

        $endian = ('big' == $endian_string) ? 'N' : 'V';

        $header = $reader->read(24);
        if ($reader->strlen($header) != 24) {
            return false;
        }

        // parse header
        $header = unpack("{$endian}revision/{$endian}total/{$endian}originals_lenghts_addr/{$endian}translations_lenghts_addr/{$endian}hash_length/{$endian}hash_addr", $header);
        if (!is_array($header)) {
            return false;
        }

        // support revision 0 of MO format specs, only
        if ($header['revision'] != 0) {
            return false;
        }

        // seek to data blocks
        $reader->seekto($header['originals_lenghts_addr']);

        // read originals' indices
        $originals_lengths_length = $header['translations_lenghts_addr'] - $header['originals_lenghts_addr'];
        if ($originals_lengths_length != $header['total'] * 8) {
            return false;
        }

        $originals = $reader->read($originals_lengths_length);
        if ($reader->strlen($originals) != $originals_lengths_length) {
            return false;
        }

        // read translations' indices
        $translations_lenghts_length = $header['hash_addr'] - $header['translations_lenghts_addr'];
        if ($translations_lenghts_length != $header['total'] * 8) {
            return false;
        }

        $translations = $reader->read($translations_lenghts_length);
        if ($reader->strlen($translations) != $translations_lenghts_length) {
            return false;
        }

        // transform raw data into set of indices
        $originals = $reader->str_split($originals, 8);
        $translations = $reader->str_split($translations, 8);

        // skip hash table
        $strings_addr = $header['hash_addr'] + $header['hash_length'] * 4;

        $reader->seekto($strings_addr);

        $strings = $reader->read_all();
        $reader->close();

        for ($i = 0; $i < $header['total']; $i++) {
            $o = unpack("{$endian}length/{$endian}pos", $originals[$i]);
            $t = unpack("{$endian}length/{$endian}pos", $translations[$i]);
            if (!$o || !$t) {
                return false;
            }

            // adjust offset due to reading strings to separate space before
            $o['pos'] -= $strings_addr;
            $t['pos'] -= $strings_addr;

            $original = $reader->substr($strings, $o['pos'], $o['length']);
            $translation = $reader->substr($strings, $t['pos'], $t['length']);

            if ('' === $original) {
                $this->set_headers($this->make_headers($translation));
            } else {
                $entry = &static::make_entry($original, $translation);
                $this->entries[$entry->key()] = &$entry;
            }
        }

        return true;
    }
575577
function() {
    var max_blindex;  // index of last bit length code of non zero freq

    // Determine the bit length frequencies for literal and distance trees
    zip_scan_tree(zip_dyn_ltree, zip_l_desc.max_code);
    zip_scan_tree(zip_dyn_dtree, zip_d_desc.max_code);

    // Build the bit length tree:
    zip_build_tree(zip_bl_desc);
    /* opt_len now includes the length of the tree representations, except
     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
     */

    /* Determine the number of bit length codes to send. The pkzip format
     * requires that at least 4 bit length codes be sent. (appnote.txt says
     * 3 but the actual value used is 4.)
     */
    for(max_blindex = zip_BL_CODES-1; max_blindex >= 3; max_blindex--) {
	if(zip_bl_tree[zip_bl_order[max_blindex]].dl != 0) break;
    }
    /* Update opt_len to include the bit length tree and counts */
    zip_opt_len += 3*(max_blindex+1) + 5+5+4;
//    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
//	    encoder->opt_len, encoder->static_len));

    return max_blindex;
}
31398
private function iterateKeyReader()
    {
        $results = $this->index->getKeyReader()->readKeys(
            $this->offset,
            $this->direction,
            $this->parseHints
        );
        if (empty($results)) {
            return $results;
            
        }
        
        // reverse order if iterating backwards
        if ($this->direction == KeyReader::DIRECTION_BACKWARD) {
            // $results = array_reverse($results);
            
            // trim results to the offset and reverse the order
            $revertBackwardResults = array();
            foreach ($results as $result) {
                if ($result->getOffset() > $this->offset) {
                    break;
                    
                }
                array_unshift($revertBackwardResults, $result);
                
            }
            $results = $revertBackwardResults;

        }

        // shift offset
        $end = end($results);
        switch ($this->direction) {

            case KeyReader::DIRECTION_FORWARD:
                $this->setOffset($end->getOffset() + strlen($end->getData()));
                break;

            case KeyReader::DIRECTION_BACKWARD:
                $this->setOffset($end->getOffset() - 1);
                break;

            default:
                throw new \LogicException("invalid direction");

        }
        
        // remove duplicates (BACKWARD only)
        $this->avoidBackwardDuplicates($results);
        
        reset($results);
        return $results;
    }
511110
public static byte[] str2bin(final String values, final JBBPBitOrder bitOrder) {
    if (values == null) {
      return new byte[0];
    }

    int buff = 0;
    int cnt = 0;

    final ByteArrayOutputStream buffer = new ByteArrayOutputStream((values.length() + 7) >> 3);

    final boolean msb0 = bitOrder == JBBPBitOrder.MSB0;

    for (final char v : values.toCharArray()) {
      switch (v) {
        case '_':
        case ' ':
          continue;
        case '0':
        case 'X':
        case 'x':
        case 'Z':
        case 'z': {
          if (msb0) {
            buff >>= 1;
          } else {
            buff <<= 1;
          }
        }
        break;
        case '1': {
          if (msb0) {
            buff = (buff >> 1) | 0x80;
          } else {
            buff = (buff << 1) | 1;
          }
        }
        break;
        default:
          throw new IllegalArgumentException("Detected unsupported char '" + v + ']');
      }
      cnt++;
      if (cnt == 8) {
        buffer.write(buff);
        cnt = 0;
        buff = 0;
      }
    }
    if (cnt > 0) {
      buffer.write(msb0 ? buff >>> (8 - cnt) : buff);
    }
    return buffer.toByteArray();
  }
873511
function readBits() {
		$value  = ($this->r & 1) << 2;
 		$value += ($this->g & 1) << 1;
 		$value += ($this->b & 1) << 0;

		return $value;
	}
825464
public function getStreamReader()
    {
        if ($this->streamReader !== null) {
            return $this->streamReader;
        }

        return $this->streamReader = new StreamReader($this);
    }
1247968
protected function parseArrayElements(\XMLReader $reader, $elementName, $currentNodeIdentifier)
    {
        $values = [];
        $depth = 0;

        // The following silences static code analysis warnings about undefined variables.
        // during runtime this doesn't happen, because the $reader must be at an ELEMENT,
        // thus the variables would be defined in the first case block before they can be
        // used.
        $currentType = null;
        $currentEncoding = null;
        $currentClassName = null;
        $currentIdentifier = null;

        do {
            switch ($reader->nodeType) {
                case \XMLReader::ELEMENT:
                    $depth++;
                    // __type="object" __classname="Neos\Media\Domain\Model\ImageVariant" __encoding="json"
                    $currentType = $reader->getAttribute('__type');
                    $currentClassName = $reader->getAttribute('__classname');
                    $currentEncoding = $reader->getAttribute('__encoding');
                    break;
                case \XMLReader::END_ELEMENT:
                    if ($reader->name === $elementName) {
                        return $values;
                    }
                    break;
                case \XMLReader::CDATA:
                case \XMLReader::TEXT:
                    $values[] = $this->convertElementToValue($reader, $currentType, $currentEncoding, $currentClassName, $currentNodeIdentifier, $elementName);
                    break;
            }
        } while ($reader->read());
    }
167950
public static function getNormalized(array $bitList)
    {
        $bitListNormalized = [];
        foreach ($bitList as $bitRow) {
            $matches = [];
            preg_match('/^(?<first>[\d]+)(-(?<second>[\d]+))?$/', (string)$bitRow, $matches);
            if (empty($matches)) {
                throw new WrongBitMappingRule("Incorrect Bit syntax: '{$bitRow}'");
            }

            if (!isset($matches['second'])) {
                if (isset($bitListNormalized[$matches['first']])) {
                    throw new WrongBitMappingRule('You can`t add "-" after number.');
                }
                $bitListNormalized[$matches['first']] = (int)$matches['first'];
                continue;
            }

            if ($matches['first'] > $matches['second']) {
                throw new WrongBitMappingRule("Start bit zone should be greater than end. But got: {$matches['first']} - {$matches['second']}");
            }
            if (!is_numeric($matches['first']) || !is_numeric($matches['second'])) {
                throw new WrongBitMappingRule("Start and end of zone should be numbers, but got: {$matches['first']} - {$matches['second']}");
            }

            for ($i = (int)$matches['first'], $end = $matches['second']; $i <= $end; $i++) {
                if (isset($bitListNormalized[$i])) {
                    throw new WrongBitMappingRule("Bit {$bitListNormalized[$i]} used more than once");
                }
                $bitListNormalized[$i] = $i; // Bits started from 1, but in array we start working with 0
            }
        }

        return array_values($bitListNormalized);
    }