AND count bits from source with map contents starting at pos
770060
public static void and(byte[] map, int pos, byte source, int count) {

        int shift     = pos & 0x07;
        int mask      = (source & 0xff) >>> shift;
        int innermask = 0xff >> shift;
        int index     = pos / 8;

        if (count < 8) {
            innermask = innermask >>> (8 - count);
            innermask = innermask << (8 - count);
        }

        mask      &= innermask;
        innermask = ~innermask;

        if (index >= map.length) {
            return;
        }

        byte b = map[index];

        map[index] = (byte) (b & innermask);
        b          = (byte) (b & mask);
        map[index] = (byte) (map[index] | b);

        if (shift == 0) {
            return;
        }

        shift = 8 - shift;

        if (count > shift) {
            mask           = ((source & 0xff) << 8) >>> shift;
            innermask      = 0xff00 >>> shift;
            innermask      = ~innermask;
            b              = map[index + 1];
            map[index + 1] = (byte) (b & innermask);
            b              = (byte) (b & mask);
            map[index + 1] = (byte) (map[index + 1] | b);
        }
    }
749959
def RRlist2bitmap(lst):
    
    # RFC 4034, 4.1.2. The Type Bit Maps Field

    import math

    bitmap = b""
    lst = list(set(lst))
    lst.sort()
    
    #lst = filter(lambda x: x <= 65535, lst)
    #lst = map(lambda x: abs(x), lst)
    lst = [ abs(x) for x in lst if x<= 65535 ]

    # number of window blocks
    max_window_blocks = int(math.ceil(lst[-1] / 256.))
    min_window_blocks = int(math.floor(lst[0] / 256.))
    if min_window_blocks == max_window_blocks:
        max_window_blocks += 1

    for wb in range(min_window_blocks, max_window_blocks+1):
        # First, filter out RR not encoded in the current window block
        # i.e. keep everything between 256*wb <= 256*(wb+1)
        #rrlist = filter(lambda x: 256*wb <= x and x < 256*(wb+1), lst)
        rrlist = [ x for x in lst if 256*wb <= x and x < 256*(wb+1) ]
        rrlist.sort()
        if rrlist == []:
            continue
     
        # Compute the number of bytes used to store the bitmap
        if rrlist[-1] == 0: # only one element in the list
            bs = 1
        else:
            max = rrlist[-1] - 256*wb
            #bs = int(math.ceil(max / 8)) + 1  # use at least 1 byte
            bs = int(max // 8) + 1  # use at least 1 byte
        if bs > 32: # Don't encode more than 256 bits / values
            bs = 32

        bitmap += struct.pack("B", wb)
        bitmap += struct.pack("B", bs)

        # Generate the bitmap
        for tmp in range(bs):
            v = 0
            # Remove out of range Ressource Records
            #tmp_rrlist = filter(lambda x: 256*wb+8*tmp <= x and x < 256*wb+8*tmp+8, rrlist)
            tmp_rrlist = [ x for x in rrlist if 256*wb+8*tmp <= x and x < 256*wb+8*tmp+8 ]
            if not tmp_rrlist == []:
                # 1. rescale to fit into 8 bits
                tmp_rrlist = map(lambda x: (x-256*wb)-(tmp*8), tmp_rrlist)
                # 2. x gives the bit position ; compute the corresponding value
                tmp_rrlist = map(lambda x: 2**(7-x) , tmp_rrlist)
                # 3. sum everything
                #v = reduce(lambda x,y: x+y, tmp_rrlist)
                v = sum(tmp_rrlist)
            bitmap += struct.pack("B", v)
   
    return bitmap
1219439
def store_pos(mdTopLt, mdBotRt, x1, y1, x2, y2)  # :nodoc:
    record  = 0x104F     # Record identifier.
    length  = 0x0014     # Number of bytes to follow.
    # mdTopLt            # Top left.
    # mdBotRt            # Bottom right.
    # x1                 # X coordinate.
    # y1                 # Y coordinate.
    # x2                 # Width.
    # y2                 # Height.

    header = [record, length].pack('vv')
    data  = [mdTopLt].pack('v')
    data += [mdBotRt].pack('v')
    data += [x1].pack('V')
    data += [y1].pack('V')
    data += [x2].pack('V')
    data += [y2].pack('V')

    append(header, data)
  end
65165
private static void buildHashTableStrict(
            Block keyBlock,
            int keyOffset,
            int keyCount,
            MethodHandle keyBlockEquals,
            MethodHandle keyBlockHashCode,
            int[] outputHashTable,
            int hashTableOffset,
            int hashTableSize)
            throws DuplicateMapKeyException
    {
        for (int i = 0; i < keyCount; i++) {
            int hash = getHashPosition(keyBlock, keyOffset + i, keyBlockHashCode, hashTableSize);
            while (true) {
                if (outputHashTable[hashTableOffset + hash] == -1) {
                    outputHashTable[hashTableOffset + hash] = i;
                    break;
                }

                Boolean isDuplicateKey;
                try {
                    // assuming maps with indeterminate keys are not supported
                    isDuplicateKey = (Boolean) keyBlockEquals.invokeExact(keyBlock, keyOffset + i, keyBlock, keyOffset + outputHashTable[hashTableOffset + hash]);
                }
                catch (RuntimeException e) {
                    throw e;
                }
                catch (Throwable throwable) {
                    throw new RuntimeException(throwable);
                }

                if (isDuplicateKey == null) {
                    throw new PrestoException(NOT_SUPPORTED, "map key cannot be null or contain nulls");
                }

                if (isDuplicateKey) {
                    throw new DuplicateMapKeyException(keyBlock, keyOffset + i);
                }

                hash++;
                if (hash == hashTableSize) {
                    hash = 0;
                }
            }
        }
    }
734853
private void parseAndAddMapTaskCounters(MapTaskStatistics mapTask, String counters) throws ParseException {
    Counters cnt = Counters.fromEscapedCompactString(counters);
    for (java.util.Iterator<Counters.Group> grps = cnt.iterator(); grps.hasNext(); ) {
      Counters.Group grp = grps.next();
      //String groupname = "<" + grp.getName() + ">::<" + grp.getDisplayName() + ">";
      for (java.util.Iterator<Counters.Counter> mycounters = grp.iterator(); mycounters.hasNext(); ) {
        Counters.Counter counter = mycounters.next();
        //String countername = "<"+counter.getName()+">::<"+counter.getDisplayName()+">::<"+counter.getValue()+">";
        //System.out.println("groupName:"+groupname+",countername: "+countername);
        String countername = grp.getDisplayName()+"."+counter.getDisplayName();
        String value = (new Long(counter.getValue())).toString();
        String[] parts = {countername,value};
        //System.out.println("part0:"+parts[0]+",:part1 "+parts[1]);
        if (parts[0].equals("FileSystemCounters.FILE_BYTES_READ")) {
          mapTask.setValue(MapTaskKeys.FILE_BYTES_READ, parts[1]);
        } else if (parts[0].equals("FileSystemCounters.FILE_BYTES_WRITTEN")) {
          mapTask.setValue(MapTaskKeys.FILE_BYTES_WRITTEN, parts[1]);
        } else if (parts[0].equals("FileSystemCounters.HDFS_BYTES_READ")) {
          mapTask.setValue(MapTaskKeys.HDFS_BYTES_READ, parts[1]);
        } else if (parts[0].equals("FileSystemCounters.HDFS_BYTES_WRITTEN")) {
          mapTask.setValue(MapTaskKeys.HDFS_BYTES_WRITTEN, parts[1]);
        } else if (parts[0].equals("Map-Reduce Framework.Map input records")) {
          mapTask.setValue(MapTaskKeys.INPUT_RECORDS, parts[1]);
        } else if (parts[0].equals("Map-Reduce Framework.Map output records")) {
          mapTask.setValue(MapTaskKeys.OUTPUT_RECORDS, parts[1]);
        } else if (parts[0].equals("Map-Reduce Framework.Map input bytes")) {
          mapTask.setValue(MapTaskKeys.INPUT_BYTES, parts[1]);
        } else if (parts[0].equals("Map-Reduce Framework.Map output bytes")) {
          mapTask.setValue(MapTaskKeys.OUTPUT_BYTES, parts[1]);
        } else if (parts[0].equals("Map-Reduce Framework.Combine input records")) {
          mapTask.setValue(MapTaskKeys.COMBINE_INPUT_RECORDS, parts[1]);
        } else if (parts[0].equals("Map-Reduce Framework.Combine output records")) {
          mapTask.setValue(MapTaskKeys.COMBINE_OUTPUT_RECORDS, parts[1]);
        } else if (parts[0].equals("Map-Reduce Framework.Spilled Records")) {
          mapTask.setValue(MapTaskKeys.SPILLED_RECORDS, parts[1]);
        } else {
          System.err.println("MapCounterKey:<"+parts[0]+"> ==> NOT INCLUDED IN PERFORMANCE ADVISOR MAP TASK");
        }
      }    
    }
  }
485845
public void putInt(int pos, int i) {
		adaptSize(pos + 4);
		ByteBuffer bb = getBuffer(pos);
		int index = pos % _bufferSize;
		if (bb.limit() - index >= 4) {
			bb.putInt(index, i);
		} else {
			byte b0 = (byte)i;
			byte b1 = (byte)(i >> 8);
			byte b2 = (byte)(i >> 16);
			byte b3 = (byte)(i >> 24);
			
			if (_order == ByteOrder.BIG_ENDIAN) {
				putBytes(pos, b3, b2, b1, b0);
			} else {
				putBytes(pos, b0, b1, b2, b3);
			}
		}
	}
419874
def count(self):
        
        result = 0
        bits = self._bits
        while bits:
            result += bits % 2
            bits >>= 1
        return result
1158678
def parseBits(self, hexcode, width):
        """"""
        bitarray = []
        for byte in hexcode[::-1]:
            bits = int(byte, 16)
            for x in range(4):
                bitarray.append(bool((2 ** x) & bits))
        bitarray = bitarray[::-1]
        return enumerate(bitarray[:width])
721077
function bitop(operation, destkey /* key1, keyN, req */) {
  var keys = slice.call(arguments, 2)
    , req = typeof keys[keys.length - 1] === 'object' ? keys.pop() : null
    , buffers = []
    , plen
    , ind
    , len = 0
    , out
    , buf
    , byte
    , i
    , j
    , v;

  // unary operation, ensure keys length is one
  if(operation === BITOP.NOT) {
    keys = keys.slice(0, 1);
  }

  for(i = 0;i < keys.length;i++) {
    v = this.getKey(keys[i], req);
    if(v === undefined) {
      buffers.push(EMPTY);
    }else if(typeof v === 'number') {
      buffers.push(new Buffer([v]));
    }else if(typeof v === 'string') {
      buffers.push(new Buffer(v));
    /* istanbul ignore else: not testing unsupported types */
    }else if(Buffer.isBuffer(v)) {
      buffers.push(v);
    }

    // last buffer added, used to get longest buffer length
    buf = buffers[buffers.length - 1];

    // previous length so we can get index of longest buffer
    plen = len;

    // calculate longest buffer length
    len = Math.max(len, buf.length);

    // find index of longest buffer
    if(len > plen) {
      ind = buffers.length - 1;
    }
  }

  // use the longest one as the start buffer
  // and copy so as not to modify the original
  // key data if it was already a buffer
  buf = buffers.splice(ind, 1)[0];
  out = new Buffer(buf);

  // give us something for the outer loop to
  // iterate over
  if(operation === BITOP.NOT) {
    buffers.push(out);
  }

  for(i = 0;i < buffers.length;i++) {
    buf = buffers[i];
    for(j = 0;j < out.length;j++) {
      if(operation === BITOP.NOT) {
        out[j] = ~out[j];
        continue;
      }
      byte = j < buf.length ? buf[j] : 0;
      switch(operation) {
        case BITOP.AND:
          out[j] &= byte;
          break;
        case BITOP.OR:
          out[j] |= byte;
          break;
        case BITOP.XOR:
          out[j] ^= byte;
          break;
      }
    }
  }

  if(len) this.setKey(destkey, out, undefined, undefined, undefined, req);
  return len;
}
1174404
def _parse_tile_part_bit_stream(self, fptr, sod_marker, tile_length):
        """"""
        read_buffer = fptr.read(tile_length)
        # The tile length could possibly be too large and extend past
        # the end of file.  We need to be a bit resilient.
        count = min(tile_length, len(read_buffer))
        packet = np.frombuffer(read_buffer, dtype=np.uint8, count=count)

        indices = np.where(packet == 0xff)
        for idx in indices[0]:
            try:
                if packet[idx + 1] == 0x91 and (idx < (len(packet) - 5)):
                    offset = sod_marker.offset + 2 + idx
                    length = 4
                    nsop = packet[(idx + 4):(idx + 6)].view('uint16')[0]
                    if sys.byteorder == 'little':
                        nsop = nsop.byteswap()
                    segment = SOPsegment(nsop, length, offset)
                    self.segment.append(segment)
                elif packet[idx + 1] == 0x92:
                    offset = sod_marker.offset + 2 + idx
                    length = 0
                    segment = EPHsegment(length, offset)
                    self.segment.append(segment)
            except IndexError:
                continue
1392
def _readoct(self, length, start):
        """"""
        if length % 3:
            raise InterpretError("Cannot convert to octal unambiguously - "
                                 "not multiple of 3 bits.")
        if not length:
            return ''
        # Get main octal bit by converting from int.
        # Strip starting 0 or 0o depending on Python version.
        end = oct(self._readuint(length, start))[LEADING_OCT_CHARS:]
        if end.endswith('L'):
            end = end[:-1]
        middle = '0' * (length // 3 - len(end))
        return middle + end
1135490
def _get_node_pos(self, key):
        """"""
        if not self._hashring:
            return

        k = md5_bytes(key)
        key = (k[3] << 24) | (k[2] << 16) | (k[1] << 8) | k[0]

        nodes = self._sorted_keys
        pos = bisect(nodes, key)

        if pos == len(nodes):
            return 0
        return pos
36904
void readCheckpointFull(InputStream is)
    throws IOException
  {
    _blobTail = BitsUtil.readInt16(is);
    
    if (_blobTail < 0 || _buffer.length < _blobTail) {
      throw new IllegalStateException("Invalid blob tail: " + _blobTail
                                      //+ " pos=" + (is.getPosition() - 2)
                                      + " " + this);
    }
    
    byte []buffer = _buffer;
    
    IoUtil.readAll(is, buffer, 0, _blobTail);
    
    int rowLength = BitsUtil.readInt16(is);
    
    rowHead(_buffer.length - rowLength);
    
    int rowHead = rowHead();
    
    if (rowHead < getBlobTail() || buffer.length < rowHead) {
      throw new IllegalStateException(L.l("Invalid row-head={0} blob-tail={1}",
                                          rowHead(), getBlobTail()));
    }
    IoUtil.readAll(is, buffer, rowHead, buffer.length - rowHead);
    
    // validateBlock(row);    
  }
245637
def get_bits( self, count ):
        """"""
        result = 0
        for i in range( count ):
            if self.bits_remaining <= 0:
                self._fill_buffer()
            if self.bits_reverse:
                bit = (1 if (self.current_bits & (0x80 << 8*(self.bytes_to_cache-1))) else 0)
                self.current_bits <<= 1
                self.current_bits &= 0xff
            else:
                bit = (self.current_bits & 1)
                self.current_bits >>= 1

            self.bits_remaining -= 1

            if self.output_reverse:
                result <<= 1
                result |= bit
            else:
                result |= bit << i
        return result
890891
private void pp20DoUnpack(RandomAccessInputStream source, byte [] buffer) throws IOException
	{
		BitBuffer bitBuffer = new BitBuffer(source, (int)source.getLength()-4);
		source.seek(source.getLength()-1);
		int skip = source.read();
		bitBuffer.getBits(skip);
		int nBytesLeft = buffer.length;
		while (nBytesLeft > 0)
		{
			if (bitBuffer.getBits(1) == 0)
			{
				int n = 1;
				while (n < nBytesLeft)
				{
					int code = (int)bitBuffer.getBits(2);
					n += code;
					if (code != 3) break;
				}
				for (int i=0; i<n; i++)
				{
					buffer[--nBytesLeft] = (byte)bitBuffer.getBits(8);
				}
				if (nBytesLeft == 0) break;
			}
			
			int n = bitBuffer.getBits(2)+1;
			source.seek(n+3);
			int nbits = source.read();
			int nofs;
			if (n==4)
			{
				nofs = bitBuffer.getBits( (bitBuffer.getBits(1)!=0) ? nbits : 7 );
				while (n < nBytesLeft)
				{
					int code = bitBuffer.getBits(3);
					n += code;
					if (code != 7) break;
				}
			} 
			else
			{
				nofs = bitBuffer.getBits(nbits);
			}
			for (int i=0; i<=n; i++)
			{
				buffer[nBytesLeft-1] = (nBytesLeft+nofs < buffer.length) ? buffer[nBytesLeft+nofs] : 0;
				if ((--nBytesLeft)==0) break;
			}
		}
	}
473425
def _count_righthand_zero_bits(number, bits):
    
    if number == 0:
        return bits
    for i in range(bits):
        if (number >> i) & 1:
            return i
    # All bits of interest were zero, even if there are more in the number
    return bits
192516
public static void bits2prm_ld8k(
	 short bits[], int bitss,          /* input : serial bits (80)                       */
	 int   prm[], int ps            /* output: decoded parameters (11 parameters)     */
	)
	{
	   short i;
	   for (i = 0; i < LD8KConstants.PRM_SIZE; i++)
	     {
	        prm[i+ps] = bin2int(TabLD8k.bitsno[i], bits,bitss);
	        bitss  += TabLD8k.bitsno[i];
	     }

	}