idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
31,900 | static int computeLgK ( final double threshold , final double rse ) { final double v = Math . ceil ( 1.0 / ( threshold * rse * rse ) ) ; final int lgK = ( int ) Math . ceil ( Math . log ( v ) / Math . log ( 2 ) ) ; if ( lgK > MAX_LG_NOM_LONGS ) { throw new SketchesArgumentException ( "Requested Sketch (LgK = " + lgK + " > 2^26), " + "either increase the threshold, the rse or both." ) ; } return lgK ; } | Computes LgK given the threshold and RSE . |
31,901 | T getQuantile ( final double fRank ) { checkFractionalRankBounds ( fRank ) ; if ( auxN_ <= 0 ) { return null ; } final long pos = QuantilesHelper . posOfPhi ( fRank , auxN_ ) ; return approximatelyAnswerPositionalQuery ( pos ) ; } | Get the estimated quantile given a fractional rank . |
31,902 | @ SuppressWarnings ( "unchecked" ) private T approximatelyAnswerPositionalQuery ( final long pos ) { assert 0 <= pos ; assert pos < auxN_ ; final int index = QuantilesHelper . chunkContainingPos ( auxCumWtsArr_ , pos ) ; return ( T ) this . auxSamplesArr_ [ index ] ; } | Assuming that there are n items in the true stream this asks what item would appear in position 0 &le ; pos < ; n of a hypothetical sorted version of that stream . |
31,903 | private final static < T > void populateFromItemsSketch ( final int k , final long n , final long bitPattern , final T [ ] combinedBuffer , final int baseBufferCount , final int numSamples , final T [ ] itemsArr , final long [ ] cumWtsArr , final Comparator < ? super T > comparator ) { long weight = 1 ; int nxt = 0 ; long bits = bitPattern ; assert bits == ( n / ( 2L * k ) ) ; for ( int lvl = 0 ; bits != 0L ; lvl ++ , bits >>>= 1 ) { weight *= 2 ; if ( ( bits & 1L ) > 0L ) { final int offset = ( 2 + lvl ) * k ; for ( int i = 0 ; i < k ; i ++ ) { itemsArr [ nxt ] = combinedBuffer [ i + offset ] ; cumWtsArr [ nxt ] = weight ; nxt ++ ; } } } weight = 1 ; final int startOfBaseBufferBlock = nxt ; for ( int i = 0 ; i < baseBufferCount ; i ++ ) { itemsArr [ nxt ] = combinedBuffer [ i ] ; cumWtsArr [ nxt ] = weight ; nxt ++ ; } assert nxt == numSamples ; Arrays . sort ( itemsArr , startOfBaseBufferBlock , numSamples , comparator ) ; cumWtsArr [ numSamples ] = 0 ; } | Populate the arrays and registers from an ItemsSketch |
31,904 | static DirectCompactUnorderedSketch wrapInstance ( final Memory srcMem , final long seed ) { final short memSeedHash = srcMem . getShort ( SEED_HASH_SHORT ) ; final short computedSeedHash = computeSeedHash ( seed ) ; checkSeedHashes ( memSeedHash , computedSeedHash ) ; return new DirectCompactUnorderedSketch ( srcMem ) ; } | Wraps the given Memory which must be a SerVer 3 unordered Compact Sketch image . Must check the validity of the Memory before calling . |
31,905 | static DirectCompactUnorderedSketch compact ( final UpdateSketch sketch , final WritableMemory dstMem ) { final int curCount = sketch . getRetainedEntries ( true ) ; long thetaLong = sketch . getThetaLong ( ) ; boolean empty = sketch . isEmpty ( ) ; thetaLong = thetaOnCompact ( empty , curCount , thetaLong ) ; empty = emptyOnCompact ( curCount , thetaLong ) ; final int preLongs = computeCompactPreLongs ( thetaLong , empty , curCount ) ; final short seedHash = sketch . getSeedHash ( ) ; final long [ ] cache = sketch . getCache ( ) ; final int requiredFlags = READ_ONLY_FLAG_MASK | COMPACT_FLAG_MASK ; final byte flags = ( byte ) ( requiredFlags | ( empty ? EMPTY_FLAG_MASK : 0 ) ) ; final boolean ordered = false ; final long [ ] compactCache = CompactSketch . compactCache ( cache , curCount , thetaLong , ordered ) ; loadCompactMemory ( compactCache , seedHash , curCount , thetaLong , dstMem , flags , preLongs ) ; return new DirectCompactUnorderedSketch ( dstMem ) ; } | Constructs given an UpdateSketch . |
31,906 | static DirectCompactUnorderedSketch compact ( final long [ ] cache , final boolean empty , final short seedHash , final int curCount , final long thetaLong , final WritableMemory dstMem ) { final int preLongs = computeCompactPreLongs ( thetaLong , empty , curCount ) ; final int requiredFlags = READ_ONLY_FLAG_MASK | COMPACT_FLAG_MASK ; final byte flags = ( byte ) ( requiredFlags | ( empty ? EMPTY_FLAG_MASK : 0 ) ) ; loadCompactMemory ( cache , seedHash , curCount , thetaLong , dstMem , flags , preLongs ) ; return new DirectCompactUnorderedSketch ( dstMem ) ; } | Constructs this sketch from correct valid components . |
31,907 | public long [ ] getSamples ( ) { if ( itemsSeen_ == 0 ) { return null ; } final int numSamples = ( int ) Math . min ( reservoirSize_ , itemsSeen_ ) ; return java . util . Arrays . copyOf ( data_ , numSamples ) ; } | Returns a copy of the items in the reservoir . The returned array length may be smaller than the reservoir capacity . |
31,908 | public static DeserializeResult < DoubleSummary > fromMemory ( final Memory mem ) { return new DeserializeResult < > ( new DoubleSummary ( mem . getDouble ( VALUE_DOUBLE ) , Mode . values ( ) [ mem . getByte ( MODE_BYTE ) ] ) , SERIALIZED_SIZE_BYTES ) ; } | Creates an instance of the DoubleSummary given a serialized representation |
31,909 | public void update ( final long datum ) { if ( gadget_ == null ) { gadget_ = ReservoirLongsSketch . newInstance ( maxK_ ) ; } gadget_ . update ( datum ) ; } | Present this union with a long . |
31,910 | static String preambleToString ( final byte [ ] byteArr ) { final Memory mem = Memory . wrap ( byteArr ) ; return preambleToString ( mem ) ; } | Returns a human readable string summary of the preamble state of the given byte array . Used primarily in testing . |
31,911 | private final static void populateFromDoublesSketch ( final int k , final long n , final long bitPattern , final DoublesSketchAccessor sketchAccessor , final double [ ] itemsArr , final long [ ] cumWtsArr ) { long weight = 1 ; int nxt = 0 ; long bits = bitPattern ; assert bits == ( n / ( 2L * k ) ) ; for ( int lvl = 0 ; bits != 0L ; lvl ++ , bits >>>= 1 ) { weight *= 2 ; if ( ( bits & 1L ) > 0L ) { sketchAccessor . setLevel ( lvl ) ; for ( int i = 0 ; i < sketchAccessor . numItems ( ) ; i ++ ) { itemsArr [ nxt ] = sketchAccessor . get ( i ) ; cumWtsArr [ nxt ] = weight ; nxt ++ ; } } } weight = 1 ; final int startOfBaseBufferBlock = nxt ; sketchAccessor . setLevel ( BB_LVL_IDX ) ; for ( int i = 0 ; i < sketchAccessor . numItems ( ) ; i ++ ) { itemsArr [ nxt ] = sketchAccessor . get ( i ) ; cumWtsArr [ nxt ] = weight ; nxt ++ ; } assert nxt == itemsArr . length ; final int numSamples = nxt ; Arrays . sort ( itemsArr , startOfBaseBufferBlock , numSamples ) ; cumWtsArr [ numSamples ] = 0 ; } | Populate the arrays and registers from a DoublesSketch |
31,912 | static void blockyTandemMergeSort ( final double [ ] keyArr , final long [ ] valArr , final int arrLen , final int blkSize ) { assert blkSize >= 1 ; if ( arrLen <= blkSize ) { return ; } int numblks = arrLen / blkSize ; if ( ( numblks * blkSize ) < arrLen ) { numblks += 1 ; } assert ( ( numblks * blkSize ) >= arrLen ) ; final double [ ] keyTmp = Arrays . copyOf ( keyArr , arrLen ) ; final long [ ] valTmp = Arrays . copyOf ( valArr , arrLen ) ; blockyTandemMergeSortRecursion ( keyTmp , valTmp , keyArr , valArr , 0 , numblks , blkSize , arrLen ) ; } | used by DoublesAuxiliary and UtilTest |
31,913 | private static void tandemMerge ( final double [ ] keySrc , final long [ ] valSrc , final int arrStart1 , final int arrLen1 , final int arrStart2 , final int arrLen2 , final double [ ] keyDst , final long [ ] valDst , final int arrStart3 ) { final int arrStop1 = arrStart1 + arrLen1 ; final int arrStop2 = arrStart2 + arrLen2 ; int i1 = arrStart1 ; int i2 = arrStart2 ; int i3 = arrStart3 ; while ( ( i1 < arrStop1 ) && ( i2 < arrStop2 ) ) { if ( keySrc [ i2 ] < keySrc [ i1 ] ) { keyDst [ i3 ] = keySrc [ i2 ] ; valDst [ i3 ] = valSrc [ i2 ] ; i2 ++ ; } else { keyDst [ i3 ] = keySrc [ i1 ] ; valDst [ i3 ] = valSrc [ i1 ] ; i1 ++ ; } i3 ++ ; } if ( i1 < arrStop1 ) { arraycopy ( keySrc , i1 , keyDst , i3 , arrStop1 - i1 ) ; arraycopy ( valSrc , i1 , valDst , i3 , arrStop1 - i1 ) ; } else { assert i2 < arrStop2 ; arraycopy ( keySrc , i2 , keyDst , i3 , arrStop2 - i2 ) ; arraycopy ( valSrc , i2 , valDst , i3 , arrStop2 - i2 ) ; } } | Performs two merges in tandem . One of them provides the sort keys while the other one passively undergoes the same data motion . |
31,914 | public static long [ ] hash ( final long [ ] in , final long seed ) { if ( ( in == null ) || ( in . length == 0 ) ) { return emptyOrNull ( seed , new long [ 2 ] ) ; } return hash ( Memory . wrap ( in ) , 0L , in . length << 3 , seed , new long [ 2 ] ) ; } | Returns a 128 - bit hash of the input . Provided for compatibility with older version of MurmurHash3 but empty or null input now returns a hash . |
31,915 | public static long [ ] hash ( final String in , final long seed , final long [ ] hashOut ) { if ( ( in == null ) || ( in . length ( ) == 0 ) ) { return emptyOrNull ( seed , hashOut ) ; } final byte [ ] byteArr = in . getBytes ( UTF_8 ) ; return hash ( Memory . wrap ( byteArr ) , 0L , byteArr . length , seed , hashOut ) ; } | Returns a 128 - bit hash of the input . |
31,916 | private static long mixK1 ( long k1 ) { k1 *= C1 ; k1 = Long . rotateLeft ( k1 , 31 ) ; k1 *= C2 ; return k1 ; } | Self mix of k1 |
31,917 | private static long mixK2 ( long k2 ) { k2 *= C2 ; k2 = Long . rotateLeft ( k2 , 33 ) ; k2 *= C1 ; return k2 ; } | Self mix of k2 |
31,918 | @ SuppressWarnings ( "unchecked" ) private static < T > T [ ] combinedBufferToItemsArray ( final ItemsSketch < T > sketch , final boolean ordered ) { final int extra = 2 ; final int outArrCap = sketch . getRetainedItems ( ) ; final T minValue = sketch . getMinValue ( ) ; final T [ ] outArr = ( T [ ] ) Array . newInstance ( minValue . getClass ( ) , outArrCap + extra ) ; outArr [ 0 ] = minValue ; outArr [ 1 ] = sketch . getMaxValue ( ) ; final int baseBufferCount = sketch . getBaseBufferCount ( ) ; final Object [ ] combinedBuffer = sketch . getCombinedBuffer ( ) ; System . arraycopy ( combinedBuffer , 0 , outArr , extra , baseBufferCount ) ; long bitPattern = sketch . getBitPattern ( ) ; if ( bitPattern > 0 ) { final int k = sketch . getK ( ) ; int index = extra + baseBufferCount ; for ( int level = 0 ; bitPattern != 0L ; level ++ , bitPattern >>>= 1 ) { if ( ( bitPattern & 1L ) > 0L ) { System . arraycopy ( combinedBuffer , ( 2 + level ) * k , outArr , index , k ) ; index += k ; } } } if ( ordered ) { Arrays . sort ( outArr , extra , baseBufferCount + extra , sketch . getComparator ( ) ) ; } return outArr ; } | Returns an array of items in compact form including min and max extracted from the Combined Buffer . |
31,919 | public static boolean exactlyEqual ( final Sketch sketchA , final Sketch sketchB ) { if ( ( sketchA == null ) || ( sketchB == null ) ) { return false ; } if ( sketchA == sketchB ) { return true ; } if ( sketchA . isEmpty ( ) && sketchB . isEmpty ( ) ) { return true ; } if ( sketchA . isEmpty ( ) || sketchB . isEmpty ( ) ) { return false ; } final int countA = sketchA . getRetainedEntries ( ) ; final int countB = sketchB . getRetainedEntries ( ) ; final Union union = SetOperation . builder ( ) . setNominalEntries ( ceilingPowerOf2 ( countA + countB ) ) . buildUnion ( ) ; union . update ( sketchA ) ; union . update ( sketchB ) ; final Sketch unionAB = union . getResult ( ) ; final long thetaLongUAB = unionAB . getThetaLong ( ) ; final long thetaLongA = sketchA . getThetaLong ( ) ; final long thetaLongB = sketchB . getThetaLong ( ) ; final int countUAB = unionAB . getRetainedEntries ( ) ; if ( ( countUAB == countA ) && ( countUAB == countB ) && ( thetaLongUAB == thetaLongA ) && ( thetaLongUAB == thetaLongB ) ) { return true ; } return false ; } | Returns true if the two given sketches have exactly the same hash values and the same theta values . Thus they are equivalent . |
31,920 | public void update ( final Sketch < S > sketchIn ) { if ( sketchIn == null || sketchIn . isEmpty ( ) ) { return ; } if ( sketchIn . theta_ < theta_ ) { theta_ = sketchIn . theta_ ; } final SketchIterator < S > it = sketchIn . iterator ( ) ; while ( it . next ( ) ) { sketch_ . merge ( it . getKey ( ) , it . getSummary ( ) , summarySetOps_ ) ; } } | Updates the internal set by adding entries from the given sketch |
31,921 | public List < Group > getGroupList ( final int [ ] priKeyIndices , final int numStdDev , final int limit ) { if ( ! mapValid ) { populateMap ( priKeyIndices ) ; } return populateList ( numStdDev , limit ) ; } | Return the most frequent Groups associated with Primary Keys based on the size of the groups . |
31,922 | private void populateMap ( final int [ ] priKeyIndices ) { final SketchIterator < ArrayOfStringsSummary > it = sketch . iterator ( ) ; Arrays . fill ( hashArr , 0L ) ; Arrays . fill ( priKeyArr , null ) ; Arrays . fill ( counterArr , 0 ) ; groupCount = 0 ; final int lgMapArrSize = Integer . numberOfTrailingZeros ( mapArrSize ) ; while ( it . next ( ) ) { final String [ ] arr = it . getSummary ( ) . getValue ( ) ; final String priKey = getPrimaryKey ( arr , priKeyIndices , sep ) ; final long hash = stringHash ( priKey ) ; final int index = hashSearchOrInsert ( hashArr , lgMapArrSize , hash ) ; if ( index < 0 ) { final int idx = - ( index + 1 ) ; counterArr [ idx ] = 1 ; groupCount ++ ; priKeyArr [ idx ] = priKey ; } else { counterArr [ index ] ++ ; } } mapValid = true ; } | Scan each entry in the sketch . Count the number of duplicate occurrences of each primary key in a hash map . |
31,923 | private List < Group > populateList ( final int numStdDev , final int limit ) { final List < Group > list = new ArrayList < > ( ) ; for ( int i = 0 ; i < mapArrSize ; i ++ ) { if ( hashArr [ i ] != 0 ) { final String priKey = priKeyArr [ i ] ; final int count = counterArr [ i ] ; final double est = sketch . getEstimate ( count ) ; final double ub = sketch . getUpperBound ( numStdDev , count ) ; final double lb = sketch . getLowerBound ( numStdDev , count ) ; final double thresh = ( double ) count / sketch . getRetainedEntries ( ) ; final double rse = ( sketch . getUpperBound ( 1 , count ) / est ) - 1.0 ; final Group gp = group . copy ( ) ; gp . init ( priKey , count , est , ub , lb , thresh , rse ) ; list . add ( gp ) ; } } list . sort ( null ) ; final int totLen = list . size ( ) ; final List < Group > returnList ; if ( ( limit > 0 ) && ( limit < totLen ) ) { returnList = list . subList ( 0 , limit ) ; } else { returnList = list ; } return returnList ; } | Create the list of groups along with the error statistics |
31,924 | private static String getPrimaryKey ( final String [ ] tuple , final int [ ] priKeyIndices , final char sep ) { assert priKeyIndices . length < tuple . length ; final StringBuilder sb = new StringBuilder ( ) ; final int keys = priKeyIndices . length ; for ( int i = 0 ; i < keys ; i ++ ) { final int idx = priKeyIndices [ i ] ; sb . append ( tuple [ idx ] ) ; if ( ( i + 1 ) < keys ) { sb . append ( sep ) ; } } return sb . toString ( ) ; } | also used by test |
31,925 | static final byte [ ] toHllByteArray ( final AbstractHllArray impl , final boolean compact ) { int auxBytes = 0 ; if ( impl . tgtHllType == TgtHllType . HLL_4 ) { final AuxHashMap auxHashMap = impl . getAuxHashMap ( ) ; if ( auxHashMap != null ) { auxBytes = ( compact ) ? auxHashMap . getCompactSizeBytes ( ) : auxHashMap . getUpdatableSizeBytes ( ) ; } else { auxBytes = ( compact ) ? 0 : 4 << LG_AUX_ARR_INTS [ impl . lgConfigK ] ; } } final int totBytes = HLL_BYTE_ARR_START + impl . getHllByteArrBytes ( ) + auxBytes ; final byte [ ] byteArr = new byte [ totBytes ] ; final WritableMemory wmem = WritableMemory . wrap ( byteArr ) ; insertHll ( impl , wmem , compact ) ; return byteArr ; } | To byte array used by the heap HLL types . |
31,926 | static int getAndCheckPreLongs ( final Memory mem ) { final long cap = mem . getCapacity ( ) ; if ( cap < 8 ) { throwNotBigEnough ( cap , 8 ) ; } final int preLongs = mem . getByte ( 0 ) & 0x3F ; final int required = Math . max ( preLongs << 3 , 8 ) ; if ( cap < required ) { throwNotBigEnough ( cap , required ) ; } return preLongs ; } | Checks Memory for capacity to hold the preamble and returns the extracted preLongs . |
31,927 | public void update ( final ArrayOfDoublesSketch sketchIn , final ArrayOfDoublesCombiner combiner ) { final boolean isFirstCall = isFirstCall_ ; isFirstCall_ = false ; if ( sketchIn == null ) { isEmpty_ = true ; sketch_ = null ; return ; } Util . checkSeedHashes ( seedHash_ , sketchIn . getSeedHash ( ) ) ; theta_ = min ( theta_ , sketchIn . getThetaLong ( ) ) ; isEmpty_ |= sketchIn . isEmpty ( ) ; if ( isEmpty_ || sketchIn . getRetainedEntries ( ) == 0 ) { sketch_ = null ; return ; } if ( isFirstCall ) { sketch_ = createSketch ( sketchIn . getRetainedEntries ( ) , numValues_ , seed_ ) ; final ArrayOfDoublesSketchIterator it = sketchIn . iterator ( ) ; while ( it . next ( ) ) { sketch_ . insert ( it . getKey ( ) , it . getValues ( ) ) ; } } else { final int matchSize = min ( sketch_ . getRetainedEntries ( ) , sketchIn . getRetainedEntries ( ) ) ; final long [ ] matchKeys = new long [ matchSize ] ; final double [ ] [ ] matchValues = new double [ matchSize ] [ ] ; int matchCount = 0 ; final ArrayOfDoublesSketchIterator it = sketchIn . iterator ( ) ; while ( it . next ( ) ) { final double [ ] values = sketch_ . find ( it . getKey ( ) ) ; if ( values != null ) { matchKeys [ matchCount ] = it . getKey ( ) ; matchValues [ matchCount ] = combiner . combine ( values , it . getValues ( ) ) ; matchCount ++ ; } } sketch_ = null ; if ( matchCount > 0 ) { sketch_ = createSketch ( matchCount , numValues_ , seed_ ) ; for ( int i = 0 ; i < matchCount ; i ++ ) { sketch_ . insert ( matchKeys [ i ] , matchValues [ i ] ) ; } } if ( sketch_ != null ) { sketch_ . setThetaLong ( theta_ ) ; sketch_ . setNotEmpty ( ) ; } } } | Updates the internal set by intersecting it with the given sketch . |
31,928 | public ArrayOfDoublesCompactSketch getResult ( final WritableMemory dstMem ) { if ( isFirstCall_ ) { throw new SketchesStateException ( "getResult() with no intervening intersections is not a legal result." ) ; } if ( sketch_ == null ) { return new HeapArrayOfDoublesCompactSketch ( null , null , Long . MAX_VALUE , true , numValues_ , seedHash_ ) ; } return sketch_ . compact ( dstMem ) ; } | Gets the internal set as an off - heap compact sketch using the given memory . |
31,929 | public void reset ( ) { isEmpty_ = false ; theta_ = Long . MAX_VALUE ; sketch_ = null ; isFirstCall_ = true ; } | Resets the internal set to the initial state which represents the Universal Set |
31,930 | public static ArrayOfDoublesSketch heapify ( final Memory mem , final long seed ) { final SerializerDeserializer . SketchType sketchType = SerializerDeserializer . getSketchType ( mem ) ; if ( sketchType == SerializerDeserializer . SketchType . ArrayOfDoublesQuickSelectSketch ) { return new HeapArrayOfDoublesQuickSelectSketch ( mem , seed ) ; } return new HeapArrayOfDoublesCompactSketch ( mem , seed ) ; } | Heapify the given Memory and seed as a ArrayOfDoublesSketch |
31,931 | public static ArrayOfDoublesSketch wrap ( final Memory mem , final long seed ) { final SerializerDeserializer . SketchType sketchType = SerializerDeserializer . getSketchType ( mem ) ; if ( sketchType == SerializerDeserializer . SketchType . ArrayOfDoublesQuickSelectSketch ) { return new DirectArrayOfDoublesQuickSelectSketchR ( mem , seed ) ; } return new DirectArrayOfDoublesCompactSketch ( mem , seed ) ; } | Wrap the given Memory and seed as a ArrayOfDoublesSketch |
31,932 | public CompactSketch aNotB ( final Sketch a , final Sketch b ) { return aNotB ( a , b , true , null ) ; } | Perform A - and - not - B set operation on the two given sketches and return the result as an ordered CompactSketch on the heap . |
31,933 | public static final HllSketch heapify ( final Memory srcMem ) { final CurMode curMode = checkPreamble ( srcMem ) ; final HllSketch heapSketch ; if ( curMode == CurMode . HLL ) { final TgtHllType tgtHllType = extractTgtHllType ( srcMem ) ; if ( tgtHllType == TgtHllType . HLL_4 ) { heapSketch = new HllSketch ( Hll4Array . heapify ( srcMem ) ) ; } else if ( tgtHllType == TgtHllType . HLL_6 ) { heapSketch = new HllSketch ( Hll6Array . heapify ( srcMem ) ) ; } else { heapSketch = new HllSketch ( Hll8Array . heapify ( srcMem ) ) ; } } else if ( curMode == CurMode . LIST ) { heapSketch = new HllSketch ( CouponList . heapifyList ( srcMem ) ) ; } else { heapSketch = new HllSketch ( CouponHashSet . heapifySet ( srcMem ) ) ; } return heapSketch ; } | Heapify the given Memory which must be a valid HllSketch image and may have data . |
31,934 | public static final HllSketch writableWrap ( final WritableMemory wmem ) { final boolean compact = extractCompactFlag ( wmem ) ; if ( compact ) { throw new SketchesArgumentException ( "Cannot perform a writableWrap of a writable sketch image that is in compact form." ) ; } final int lgConfigK = extractLgK ( wmem ) ; final TgtHllType tgtHllType = extractTgtHllType ( wmem ) ; final long minBytes = getMaxUpdatableSerializationBytes ( lgConfigK , tgtHllType ) ; final long capBytes = wmem . getCapacity ( ) ; HllUtil . checkMemSize ( minBytes , capBytes ) ; final CurMode curMode = checkPreamble ( wmem ) ; final HllSketch directSketch ; if ( curMode == CurMode . HLL ) { if ( tgtHllType == TgtHllType . HLL_4 ) { directSketch = new HllSketch ( new DirectHll4Array ( lgConfigK , wmem ) ) ; } else if ( tgtHllType == TgtHllType . HLL_6 ) { directSketch = new HllSketch ( new DirectHll6Array ( lgConfigK , wmem ) ) ; } else { directSketch = new HllSketch ( new DirectHll8Array ( lgConfigK , wmem ) ) ; } } else if ( curMode == CurMode . LIST ) { directSketch = new HllSketch ( new DirectCouponList ( lgConfigK , tgtHllType , curMode , wmem ) ) ; } else { directSketch = new HllSketch ( new DirectCouponHashSet ( lgConfigK , tgtHllType , wmem ) ) ; } return directSketch ; } | Wraps the given WritableMemory which must be a image of a valid updatable sketch and may have data . What remains on the java heap is a thin wrapper object that reads and writes to the given WritableMemory which depending on how the user configures the WritableMemory may actually reside on the Java heap or off - heap . |
31,935 | public static final int getMaxUpdatableSerializationBytes ( final int lgConfigK , final TgtHllType tgtHllType ) { final int arrBytes ; if ( tgtHllType == TgtHllType . HLL_4 ) { final int auxBytes = 4 << LG_AUX_ARR_INTS [ lgConfigK ] ; arrBytes = AbstractHllArray . hll4ArrBytes ( lgConfigK ) + auxBytes ; } else if ( tgtHllType == TgtHllType . HLL_6 ) { arrBytes = AbstractHllArray . hll6ArrBytes ( lgConfigK ) ; } else { arrBytes = AbstractHllArray . hll8ArrBytes ( lgConfigK ) ; } return HLL_BYTE_ARR_START + arrBytes ; } | Returns the maximum size in bytes that this sketch can grow to given lgConfigK . However for the HLL_4 sketch type this value can be exceeded in extremely rare cases . If exceeded it will be larger by only a few percent . |
31,936 | private static byte [ ] convertToByteArray ( final DoublesSketch sketch , final int flags , final boolean ordered , final boolean compact ) { final int preLongs = 2 ; final int extra = 2 ; final int prePlusExtraBytes = ( preLongs + extra ) << 3 ; final int k = sketch . getK ( ) ; final long n = sketch . getN ( ) ; final DoublesSketchAccessor dsa = DoublesSketchAccessor . wrap ( sketch , ! compact ) ; final int outBytes = ( compact ? sketch . getCompactStorageBytes ( ) : sketch . getUpdatableStorageBytes ( ) ) ; final byte [ ] outByteArr = new byte [ outBytes ] ; final WritableMemory memOut = WritableMemory . wrap ( outByteArr ) ; insertPre0 ( memOut , preLongs , flags , k ) ; if ( sketch . isEmpty ( ) ) { return outByteArr ; } insertN ( memOut , n ) ; insertMinDouble ( memOut , sketch . getMinValue ( ) ) ; insertMaxDouble ( memOut , sketch . getMaxValue ( ) ) ; long memOffsetBytes = prePlusExtraBytes ; final int bbCnt = Util . computeBaseBufferItems ( k , n ) ; if ( bbCnt > 0 ) { final double [ ] bbItemsArr = dsa . getArray ( 0 , bbCnt ) ; if ( ordered ) { Arrays . sort ( bbItemsArr ) ; } memOut . putDoubleArray ( memOffsetBytes , bbItemsArr , 0 , bbCnt ) ; } memOffsetBytes += ( compact ? bbCnt : 2 * k ) << 3 ; final int totalLevels = Util . computeTotalLevels ( sketch . getBitPattern ( ) ) ; for ( int lvl = 0 ; lvl < totalLevels ; ++ lvl ) { dsa . setLevel ( lvl ) ; if ( dsa . numItems ( ) > 0 ) { assert dsa . numItems ( ) == k ; memOut . putDoubleArray ( memOffsetBytes , dsa . getArray ( 0 , k ) , 0 , k ) ; memOffsetBytes += ( k << 3 ) ; } } return outByteArr ; } | Returns a byte array including preamble min max and data extracted from the sketch . |
31,937 | public void update ( final T item , final long count ) { if ( ( item == null ) || ( count == 0 ) ) { return ; } if ( count < 0 ) { throw new SketchesArgumentException ( "Count may not be negative" ) ; } this . streamWeight += count ; hashMap . adjustOrPutValue ( item , count ) ; if ( getNumActiveItems ( ) > curMapCap ) { if ( hashMap . getLgLength ( ) < lgMaxMapSize ) { hashMap . resize ( 2 * hashMap . getLength ( ) ) ; curMapCap = hashMap . getCapacity ( ) ; } else { offset += hashMap . purge ( sampleSize ) ; if ( getNumActiveItems ( ) > getMaximumMapCapacity ( ) ) { throw new SketchesStateException ( "Purge did not reduce active items." ) ; } } } } | Update this sketch with a item and a positive frequency count . |
31,938 | void adjustOrPutValue ( final T key , final long adjustAmount ) { final int arrayMask = keys . length - 1 ; int probe = ( int ) hash ( key . hashCode ( ) ) & arrayMask ; int drift = 1 ; while ( states [ probe ] != 0 && ! keys [ probe ] . equals ( key ) ) { probe = ( probe + 1 ) & arrayMask ; drift ++ ; assert ( drift < DRIFT_LIMIT ) : "drift: " + drift + " >= DRIFT_LIMIT" ; } if ( states [ probe ] == 0 ) { assert ( numActive <= loadThreshold ) : "numActive: " + numActive + " > loadThreshold: " + loadThreshold ; keys [ probe ] = key ; values [ probe ] = adjustAmount ; states [ probe ] = ( short ) drift ; numActive ++ ; } else { assert ( keys [ probe ] . equals ( key ) ) ; values [ probe ] += adjustAmount ; } } | Increments the value mapped to the key if the key is present in the map . Otherwise the key is inserted with the putAmount . |
31,939 | @ SuppressWarnings ( "unchecked" ) void resize ( final int newSize ) { final Object [ ] oldKeys = keys ; final long [ ] oldValues = values ; final short [ ] oldStates = states ; keys = new Object [ newSize ] ; values = new long [ newSize ] ; states = new short [ newSize ] ; loadThreshold = ( int ) ( newSize * LOAD_FACTOR ) ; lgLength = Integer . numberOfTrailingZeros ( newSize ) ; numActive = 0 ; for ( int i = 0 ; i < oldKeys . length ; i ++ ) { if ( oldStates [ i ] > 0 ) { adjustOrPutValue ( ( T ) oldKeys [ i ] , oldValues [ i ] ) ; } } } | assume newSize is power of 2 |
31,940 | long purge ( final int sampleSize ) { final int limit = Math . min ( sampleSize , getNumActive ( ) ) ; int numSamples = 0 ; int i = 0 ; final long [ ] samples = new long [ limit ] ; while ( numSamples < limit ) { if ( isActive ( i ) ) { samples [ numSamples ] = values [ i ] ; numSamples ++ ; } i ++ ; } final long val = QuickSelect . select ( samples , 0 , numSamples - 1 , limit / 2 ) ; adjustAllValuesBy ( - 1 * val ) ; keepOnlyPositiveCounts ( ) ; return val ; } | This function is called when a key is processed that is not currently assigned a counter and all the counters are in use . This function estimates the median of the counters in the sketch via sampling decrements all counts by this estimate throws out all counters that are no longer positive and increments offset accordingly . |
31,941 | static DoublesUnionImplR wrapInstance ( final Memory mem ) { final DirectUpdateDoublesSketchR sketch = DirectUpdateDoublesSketchR . wrapInstance ( mem ) ; final int k = sketch . getK ( ) ; final DoublesUnionImplR union = new DoublesUnionImplR ( k ) ; union . maxK_ = k ; union . gadget_ = sketch ; return union ; } | Returns a read - only Union object that wraps off - heap data structure of the given memory image of a non - compact DoublesSketch . The data structures of the Union remain off - heap . |
31,942 | final void updateMemory ( final WritableMemory newWmem ) { wmem = newWmem ; mem = newWmem ; memObj = wmem . getArray ( ) ; memAdd = wmem . getCumulativeOffset ( 0L ) ; } | only called by DirectAuxHashMap |
31,943 | static HeapUpdateDoublesSketch copyToHeap ( final DoublesSketch sketch ) { final HeapUpdateDoublesSketch qsCopy ; qsCopy = HeapUpdateDoublesSketch . newInstance ( sketch . getK ( ) ) ; qsCopy . putN ( sketch . getN ( ) ) ; qsCopy . putMinValue ( sketch . getMinValue ( ) ) ; qsCopy . putMaxValue ( sketch . getMaxValue ( ) ) ; qsCopy . putBaseBufferCount ( sketch . getBaseBufferCount ( ) ) ; qsCopy . putBitPattern ( sketch . getBitPattern ( ) ) ; if ( sketch . isCompact ( ) ) { final int combBufItems = Util . computeCombinedBufferItemCapacity ( sketch . getK ( ) , sketch . getN ( ) ) ; final double [ ] combBuf = new double [ combBufItems ] ; qsCopy . putCombinedBuffer ( combBuf ) ; final DoublesSketchAccessor sketchAccessor = DoublesSketchAccessor . wrap ( sketch ) ; final DoublesSketchAccessor copyAccessor = DoublesSketchAccessor . wrap ( qsCopy ) ; copyAccessor . putArray ( sketchAccessor . getArray ( 0 , sketchAccessor . numItems ( ) ) , 0 , 0 , sketchAccessor . numItems ( ) ) ; long bitPattern = sketch . getBitPattern ( ) ; for ( int lvl = 0 ; bitPattern != 0L ; ++ lvl , bitPattern >>>= 1 ) { if ( ( bitPattern & 1L ) > 0L ) { sketchAccessor . setLevel ( lvl ) ; copyAccessor . setLevel ( lvl ) ; copyAccessor . putArray ( sketchAccessor . getArray ( 0 , sketchAccessor . numItems ( ) ) , 0 , 0 , sketchAccessor . numItems ( ) ) ; } } } else { final double [ ] combBuf = sketch . getCombinedBuffer ( ) ; qsCopy . putCombinedBuffer ( Arrays . copyOf ( combBuf , combBuf . length ) ) ; } return qsCopy ; } | Returns an on - heap copy of the given sketch |
31,944 | static void checkDoublesSerVer ( final int serVer , final int minSupportedSerVer ) { final int max = DoublesSketch . DOUBLES_SER_VER ; if ( ( serVer > max ) || ( serVer < minSupportedSerVer ) ) { throw new SketchesArgumentException ( "Possible corruption: Unsupported Serialization Version: " + serVer ) ; } } | Check the validity of the given serialization version |
31,945 | static DirectCompactDoublesSketch wrapInstance ( final Memory srcMem ) { final long memCap = srcMem . getCapacity ( ) ; final int preLongs = extractPreLongs ( srcMem ) ; final int serVer = extractSerVer ( srcMem ) ; final int familyID = extractFamilyID ( srcMem ) ; final int flags = extractFlags ( srcMem ) ; final int k = extractK ( srcMem ) ; final boolean empty = ( flags & EMPTY_FLAG_MASK ) > 0 ; final long n = empty ? 0 : extractN ( srcMem ) ; DirectUpdateDoublesSketchR . checkPreLongs ( preLongs ) ; Util . checkFamilyID ( familyID ) ; DoublesUtil . checkDoublesSerVer ( serVer , MIN_DIRECT_DOUBLES_SER_VER ) ; checkCompact ( serVer , flags ) ; Util . checkK ( k ) ; checkDirectMemCapacity ( k , n , memCap ) ; DirectUpdateDoublesSketchR . checkEmptyAndN ( empty , n ) ; final DirectCompactDoublesSketch dds = new DirectCompactDoublesSketch ( k ) ; dds . mem_ = ( WritableMemory ) srcMem ; return dds ; } | Wrap this sketch around the given compact Memory image of a DoublesSketch . |
31,946 | static void checkCompact ( final int serVer , final int flags ) { final int compactFlagMask = COMPACT_FLAG_MASK | ORDERED_FLAG_MASK ; if ( ( serVer != 2 ) && ( ( flags & EMPTY_FLAG_MASK ) == 0 ) && ( ( flags & compactFlagMask ) != compactFlagMask ) ) { throw new SketchesArgumentException ( "Possible corruption: Must be v2, empty, or compact and ordered. Flags field: " + Integer . toBinaryString ( flags ) + ", SerVer: " + serVer ) ; } } | Checks a sketch s serial version and flags to see if the sketch can be wrapped as a DirectCompactDoubleSketch . Throws an exception if the sketch is neither empty nor compact and ordered unles the sketch uses serialization version 2 . |
31,947 | public static int countPart ( final long [ ] srcArr , final int lgArrLongs , final long thetaLong ) { int cnt = 0 ; final int len = 1 << lgArrLongs ; for ( int i = len ; i -- > 0 ; ) { final long hash = srcArr [ i ] ; if ( continueCondition ( thetaLong , hash ) ) { continue ; } cnt ++ ; } return cnt ; } | Counts the cardinality of the first Log2 values of the given source array . |
31,948 | public static int count ( final long [ ] srcArr , final long thetaLong ) { int cnt = 0 ; final int len = srcArr . length ; for ( int i = len ; i -- > 0 ; ) { final long hash = srcArr [ i ] ; if ( continueCondition ( thetaLong , hash ) ) { continue ; } cnt ++ ; } return cnt ; } | Counts the cardinality of the given source array . |
31,949 | public static int hashSearch ( final long [ ] hashTable , final int lgArrLongs , final long hash ) { if ( hash == 0 ) { throw new SketchesArgumentException ( "Given hash cannot be zero: " + hash ) ; } final int arrayMask = ( 1 << lgArrLongs ) - 1 ; final int stride = getStride ( hash , lgArrLongs ) ; int curProbe = ( int ) ( hash & arrayMask ) ; final int loopIndex = curProbe ; do { final long arrVal = hashTable [ curProbe ] ; if ( arrVal == EMPTY ) { return - 1 ; } else if ( arrVal == hash ) { return curProbe ; } curProbe = ( curProbe + stride ) & arrayMask ; } while ( curProbe != loopIndex ) ; return - 1 ; } | This is a classical Knuth - style Open Addressing Double Hash search scheme for on - heap . Returns the index if found - 1 if not found . |
31,950 | public static int hashArrayInsert ( final long [ ] srcArr , final long [ ] hashTable , final int lgArrLongs , final long thetaLong ) { int count = 0 ; final int arrLen = srcArr . length ; checkThetaCorruption ( thetaLong ) ; for ( int i = 0 ; i < arrLen ; i ++ ) { final long hash = srcArr [ i ] ; checkHashCorruption ( hash ) ; if ( continueCondition ( thetaLong , hash ) ) { continue ; } if ( hashSearchOrInsert ( hashTable , lgArrLongs , hash ) < 0 ) { count ++ ; } } return count ; } | Inserts the given long array into the given hash table array of the target size removes any negative input values ignores duplicates and counts the values inserted . The given hash table may have values but they must have been inserted by this method or one of the other OADH insert methods in this class and they may not be dirty . This method performs additional checks against potentially invalid hash values or theta values . Returns the count of values actually inserted . |
31,951 | public static int hashSearch ( final Memory mem , final int lgArrLongs , final long hash , final int memOffsetBytes ) { final int arrayMask = ( 1 << lgArrLongs ) - 1 ; final int stride = getStride ( hash , lgArrLongs ) ; int curProbe = ( int ) ( hash & arrayMask ) ; final int loopIndex = curProbe ; do { final int curProbeOffsetBytes = ( curProbe << 3 ) + memOffsetBytes ; final long curArrayHash = mem . getLong ( curProbeOffsetBytes ) ; if ( curArrayHash == EMPTY ) { return - 1 ; } else if ( curArrayHash == hash ) { return curProbe ; } curProbe = ( curProbe + stride ) & arrayMask ; } while ( curProbe != loopIndex ) ; return - 1 ; } | This is a classical Knuth - style Open Addressing Double Hash search scheme for off - heap . Returns the index if found - 1 if not found . |
31,952 | public static int fastHashInsertOnly ( final WritableMemory wmem , final int lgArrLongs , final long hash , final int memOffsetBytes ) { final int arrayMask = ( 1 << lgArrLongs ) - 1 ; final int stride = getStride ( hash , lgArrLongs ) ; int curProbe = ( int ) ( hash & arrayMask ) ; final int loopIndex = curProbe ; do { final int curProbeOffsetBytes = ( curProbe << 3 ) + memOffsetBytes ; final long curArrayHash = wmem . getLong ( curProbeOffsetBytes ) ; if ( curArrayHash == EMPTY ) { wmem . putLong ( curProbeOffsetBytes , hash ) ; return curProbe ; } curProbe = ( curProbe + stride ) & arrayMask ; } while ( curProbe != loopIndex ) ; throw new SketchesArgumentException ( "No empty slot in table!" ) ; } | This is a classical Knuth - style Open Addressing Double Hash insert scheme but inserts values directly into a Memory . This method assumes that the input hash is not a duplicate . Useful for rebuilding tables to avoid unnecessary comparisons . Returns the index of insertion which is always positive or zero . Throws an exception if table has no empty slot . |
31,953 | @ SuppressFBWarnings ( value = "VO_VOLATILE_INCREMENT" , justification = "False Positive" ) private void advanceEpoch ( ) { awaitBgPropagationTermination ( ) ; startEagerPropagation ( ) ; ConcurrentPropagationService . resetExecutorService ( Thread . currentThread ( ) . getId ( ) ) ; epoch_ ++ ; endPropagation ( null , true ) ; initBgPropagationService ( ) ; } | Advances the epoch while there is no background propagation This ensures a propagation invoked before the reset cannot affect the sketch after the reset is completed . |
31,954 | static HeapUpdateDoublesSketch newInstance ( final int k ) { final HeapUpdateDoublesSketch hqs = new HeapUpdateDoublesSketch ( k ) ; final int baseBufAlloc = 2 * Math . min ( DoublesSketch . MIN_K , k ) ; hqs . n_ = 0 ; hqs . combinedBuffer_ = new double [ baseBufAlloc ] ; hqs . baseBufferCount_ = 0 ; hqs . bitPattern_ = 0 ; hqs . minValue_ = Double . NaN ; hqs . maxValue_ = Double . NaN ; return hqs ; } | Obtains a new on - heap instance of a DoublesSketch . |
31,955 | private void srcMemoryToCombinedBuffer ( final Memory srcMem , final int serVer , final boolean srcIsCompact , final int combBufCap ) { final int preLongs = 2 ; final int extra = ( serVer == 1 ) ? 3 : 2 ; final int preBytes = ( preLongs + extra ) << 3 ; final int bbCnt = baseBufferCount_ ; final int k = getK ( ) ; final long n = getN ( ) ; final double [ ] combinedBuffer = new double [ combBufCap ] ; putMinValue ( srcMem . getDouble ( MIN_DOUBLE ) ) ; putMaxValue ( srcMem . getDouble ( MAX_DOUBLE ) ) ; if ( srcIsCompact ) { srcMem . getDoubleArray ( preBytes , combinedBuffer , 0 , bbCnt ) ; long bitPattern = bitPattern_ ; if ( bitPattern != 0 ) { long memOffset = preBytes + ( bbCnt << 3 ) ; int combBufOffset = 2 * k ; while ( bitPattern != 0L ) { if ( ( bitPattern & 1L ) > 0L ) { srcMem . getDoubleArray ( memOffset , combinedBuffer , combBufOffset , k ) ; memOffset += ( k << 3 ) ; } combBufOffset += k ; bitPattern >>>= 1 ; } } } else { final int levels = Util . computeNumLevelsNeeded ( k , n ) ; final int totItems = ( levels == 0 ) ? bbCnt : ( 2 + levels ) * k ; srcMem . getDoubleArray ( preBytes , combinedBuffer , 0 , totItems ) ; } putCombinedBuffer ( combinedBuffer ) ; } | Loads the Combined Buffer min and max from the given source Memory . The resulting Combined Buffer is always in non - compact form and must be pre - allocated . |
31,956 | static void checkHeapMemCapacity ( final int k , final long n , final boolean compact , final int serVer , final long memCapBytes ) { final int metaPre = Family . QUANTILES . getMaxPreLongs ( ) + ( ( serVer == 1 ) ? 3 : 2 ) ; final int retainedItems = computeRetainedItems ( k , n ) ; final int reqBufBytes ; if ( compact ) { reqBufBytes = ( metaPre + retainedItems ) << 3 ; } else { final int totLevels = Util . computeNumLevelsNeeded ( k , n ) ; reqBufBytes = ( totLevels == 0 ) ? ( metaPre + retainedItems ) << 3 : ( metaPre + ( ( 2 + totLevels ) * k ) ) << 3 ; } if ( memCapBytes < reqBufBytes ) { throw new SketchesArgumentException ( "Possible corruption: Memory capacity too small: " + memCapBytes + " < " + reqBufBytes ) ; } } | Checks the validity of the heap memory capacity assuming n k and the compact state . |
31,957 | static int getNumCoupons ( final Memory mem ) { final Format format = getFormat ( mem ) ; final HiField hiField = HiField . NUM_COUPONS ; final long offset = getHiFieldOffset ( format , hiField ) ; return mem . getInt ( offset ) ; } | PREAMBLE HI_FIELD GETS |
31,958 | static void putEmptyMerged ( final WritableMemory wmem , final int lgK , final short seedHash ) { final Format format = Format . EMPTY_MERGED ; final byte preInts = getDefinedPreInts ( format ) ; final byte fiCol = ( byte ) 0 ; final byte flags = ( byte ) ( ( format . ordinal ( ) << 2 ) | COMPRESSED_FLAG_MASK ) ; checkCapacity ( wmem . getCapacity ( ) , 8 ) ; putFirst8 ( wmem , preInts , ( byte ) lgK , fiCol , flags , seedHash ) ; } | PUT INTO MEMORY |
31,959 | static void checkLoPreamble ( final Memory mem ) { rtAssertEquals ( getSerVer ( mem ) , SER_VER & 0XFF ) ; final Format fmt = getFormat ( mem ) ; final int preIntsDef = getDefinedPreInts ( fmt ) & 0XFF ; rtAssertEquals ( getPreInts ( mem ) , preIntsDef ) ; final Family fam = getFamily ( mem ) ; rtAssert ( fam == Family . CPC ) ; final int lgK = getLgK ( mem ) ; rtAssert ( ( lgK >= 4 ) && ( lgK <= 26 ) ) ; final int fiCol = getFiCol ( mem ) ; rtAssert ( ( fiCol <= 63 ) && ( fiCol >= 0 ) ) ; } | basic checks of SerVer Format preInts Family fiCol lgK . |
31,960 | static final void validateValues ( final float [ ] values ) { for ( int i = 0 ; i < values . length ; i ++ ) { if ( Float . isNaN ( values [ i ] ) ) { throw new SketchesArgumentException ( "Values must not be NaN" ) ; } if ( ( i < ( values . length - 1 ) ) && ( values [ i ] >= values [ i + 1 ] ) ) { throw new SketchesArgumentException ( "Values must be unique and monotonically increasing" ) ; } } } | Checks the sequential validity of the given array of float values . They must be unique monotonically increasing and not NaN . |
31,961 | static CompactSketch compact ( final long [ ] cache , final boolean empty , final short seedHash , final int curCount , final long thetaLong ) { if ( ( curCount == 1 ) && ( thetaLong == Long . MAX_VALUE ) ) { return new SingleItemSketch ( cache [ 0 ] , seedHash ) ; } return new HeapCompactUnorderedSketch ( cache , empty , seedHash , curCount , thetaLong ) ; } | Constructs this sketch from correct valid arguments . |
31,962 | static DirectUpdateDoublesSketch newInstance ( final int k , final WritableMemory dstMem ) { final long memCap = dstMem . getCapacity ( ) ; checkDirectMemCapacity ( k , 0 , memCap ) ; dstMem . putLong ( 0 , 0L ) ; insertPreLongs ( dstMem , 2 ) ; insertSerVer ( dstMem , DoublesSketch . DOUBLES_SER_VER ) ; insertFamilyID ( dstMem , Family . QUANTILES . getID ( ) ) ; insertFlags ( dstMem , EMPTY_FLAG_MASK ) ; insertK ( dstMem , k ) ; if ( memCap >= COMBINED_BUFFER ) { insertN ( dstMem , 0L ) ; insertMinDouble ( dstMem , Double . NaN ) ; insertMaxDouble ( dstMem , Double . NaN ) ; } final DirectUpdateDoublesSketch dds = new DirectUpdateDoublesSketch ( k ) ; dds . mem_ = dstMem ; return dds ; } | Obtains a new Direct instance of a DoublesSketch which may be off - heap . |
31,963 | private WritableMemory growCombinedMemBuffer ( final int itemSpaceNeeded ) { final long memBytes = mem_ . getCapacity ( ) ; final int needBytes = ( itemSpaceNeeded << 3 ) + COMBINED_BUFFER ; assert needBytes > memBytes ; memReqSvr = ( memReqSvr == null ) ? mem_ . getMemoryRequestServer ( ) : memReqSvr ; final WritableMemory newMem = memReqSvr . request ( needBytes ) ; mem_ . copyTo ( 0 , newMem , 0 , memBytes ) ; memReqSvr . requestClose ( mem_ , newMem ) ; return newMem ; } | Direct supporting methods |
31,964 | public static < T > VarOptItemsSketch < T > newInstance ( final int k , final ResizeFactor rf ) { return new VarOptItemsSketch < > ( k , rf ) ; } | Construct a varopt sampling sketch with up to k samples using the specified resize factor . |
31,965 | static < T > VarOptItemsSketch < T > newInstanceAsGadget ( final int k ) { final VarOptItemsSketch < T > sketch = new VarOptItemsSketch < > ( k , DEFAULT_RESIZE_FACTOR ) ; sketch . marks_ = new ArrayList < > ( sketch . currItemsAlloc_ ) ; return sketch ; } | Construct a varopt sketch for use as a unioning gadget meaning the array of marked elements is also initialized . |
31,966 | VarOptItemsSketch < T > copyAndSetN ( final boolean asSketch , final long adjustedN ) { final VarOptItemsSketch < T > sketch ; sketch = new VarOptItemsSketch < > ( data_ , weights_ , k_ , n_ , currItemsAlloc_ , rf_ , h_ , r_ , totalWtR_ ) ; if ( ! asSketch ) { sketch . marks_ = this . marks_ ; sketch . numMarksInH_ = this . numMarksInH_ ; } if ( adjustedN >= 0 ) { sketch . n_ = adjustedN ; } return sketch ; } | Creates a copy of the sketch optionally discarding any information about marks that would indicate the class s use as a union gadget as opposed to a valid sketch . |
31,967 | void decreaseKBy1 ( ) { if ( k_ <= 1 ) { throw new SketchesStateException ( "Cannot decrease k below 1 in union" ) ; } if ( ( h_ == 0 ) && ( r_ == 0 ) ) { -- k_ ; } else if ( ( h_ > 0 ) && ( r_ == 0 ) ) { -- k_ ; if ( h_ > k_ ) { transitionFromWarmup ( ) ; } } else if ( ( h_ > 0 ) && ( r_ > 0 ) ) { final int oldGapIdx = h_ ; final int oldFinalRIdx = ( h_ + 1 + r_ ) - 1 ; assert oldFinalRIdx == k_ ; swapValues ( oldFinalRIdx , oldGapIdx ) ; final int pulledIdx = h_ - 1 ; final T pulledItem = data_ . get ( pulledIdx ) ; final double pulledWeight = weights_ . get ( pulledIdx ) ; final boolean pulledMark = marks_ . get ( pulledIdx ) ; if ( pulledMark ) { -- numMarksInH_ ; } weights_ . set ( pulledIdx , - 1.0 ) ; -- h_ ; -- k_ ; -- n_ ; update ( pulledItem , pulledWeight , pulledMark ) ; } else if ( ( h_ == 0 ) && ( r_ > 0 ) ) { assert r_ >= 2 ; final int rIdxToDelete = 1 + SamplingUtil . rand . nextInt ( r_ ) ; final int rightmostRIdx = ( 1 + r_ ) - 1 ; swapValues ( rIdxToDelete , rightmostRIdx ) ; weights_ . set ( rightmostRIdx , - 1.0 ) ; -- k_ ; -- r_ ; } } | Decreases sketch s value of k by 1 updating stored values as needed . |
31,968 | public ArrayOfDoublesUpdatableSketch build ( final WritableMemory dstMem ) { return new DirectArrayOfDoublesQuickSelectSketch ( nomEntries_ , resizeFactor_ . lg ( ) , samplingProbability_ , numValues_ , seed_ , dstMem ) ; } | Returns an ArrayOfDoublesUpdatableSketch with the current configuration of this Builder . |
31,969 | public static int bytesToInt ( final byte [ ] arr ) { int v = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) { v |= ( arr [ i ] & 0XFF ) << ( i * 8 ) ; } return v ; } | Returns an int extracted from a Little - Endian byte array . |
31,970 | public static long bytesToLong ( final byte [ ] arr ) { long v = 0 ; for ( int i = 0 ; i < 8 ; i ++ ) { v |= ( arr [ i ] & 0XFFL ) << ( i * 8 ) ; } return v ; } | Returns a long extracted from a Little - Endian byte array . |
31,971 | public static byte [ ] intToBytes ( int v , final byte [ ] arr ) { for ( int i = 0 ; i < 4 ; i ++ ) { arr [ i ] = ( byte ) ( v & 0XFF ) ; v >>>= 8 ; } return arr ; } | Returns a Little - Endian byte array extracted from the given int . |
31,972 | public static byte [ ] longToBytes ( long v , final byte [ ] arr ) { for ( int i = 0 ; i < 8 ; i ++ ) { arr [ i ] = ( byte ) ( v & 0XFFL ) ; v >>>= 8 ; } return arr ; } | Returns a Little - Endian byte array extracted from the given long . |
31,973 | public static String longToHexBytes ( final long v ) { final long mask = 0XFFL ; final StringBuilder sb = new StringBuilder ( ) ; for ( int i = 8 ; i -- > 0 ; ) { final String s = Long . toHexString ( ( v >>> ( i * 8 ) ) & mask ) ; sb . append ( zeroPad ( s , 2 ) ) . append ( " " ) ; } return sb . toString ( ) ; } | Returns a string of spaced hex bytes in Big - Endian order . |
31,974 | public static String bytesToString ( final byte [ ] arr , final boolean signed , final boolean littleEndian , final String sep ) { final StringBuilder sb = new StringBuilder ( ) ; final int mask = ( signed ) ? 0XFFFFFFFF : 0XFF ; final int arrLen = arr . length ; if ( littleEndian ) { for ( int i = 0 ; i < ( arrLen - 1 ) ; i ++ ) { sb . append ( arr [ i ] & mask ) . append ( sep ) ; } sb . append ( arr [ arrLen - 1 ] & mask ) ; } else { for ( int i = arrLen ; i -- > 1 ; ) { sb . append ( arr [ i ] & mask ) . append ( sep ) ; } sb . append ( arr [ 0 ] & mask ) ; } return sb . toString ( ) ; } | Returns a string view of a byte array |
31,975 | public static String nanoSecToString ( final long nS ) { final long rem_nS = ( long ) ( nS % 1000.0 ) ; final long rem_uS = ( long ) ( ( nS / 1000.0 ) % 1000.0 ) ; final long rem_mS = ( long ) ( ( nS / 1000000.0 ) % 1000.0 ) ; final long sec = ( long ) ( nS / 1000000000.0 ) ; final String nSstr = zeroPad ( Long . toString ( rem_nS ) , 3 ) ; final String uSstr = zeroPad ( Long . toString ( rem_uS ) , 3 ) ; final String mSstr = zeroPad ( Long . toString ( rem_mS ) , 3 ) ; return String . format ( "%d.%3s_%3s_%3s" , sec , mSstr , uSstr , nSstr ) ; } | Returns the given time in nanoseconds formatted as Sec . mSec uSec nSec |
31,976 | public static final String characterPad ( final String s , final int fieldLength , final char padChar , final boolean postpend ) { final char [ ] chArr = s . toCharArray ( ) ; final int sLen = chArr . length ; if ( sLen < fieldLength ) { final char [ ] out = new char [ fieldLength ] ; final int blanks = fieldLength - sLen ; if ( postpend ) { for ( int i = 0 ; i < sLen ; i ++ ) { out [ i ] = chArr [ i ] ; } for ( int i = sLen ; i < fieldLength ; i ++ ) { out [ i ] = padChar ; } } else { for ( int i = 0 ; i < blanks ; i ++ ) { out [ i ] = padChar ; } for ( int i = blanks ; i < fieldLength ; i ++ ) { out [ i ] = chArr [ i - blanks ] ; } } return String . valueOf ( out ) ; } return s ; } | Prepend or postpend the given string with the given character to fill the given field length . If the given string is equal or greater than the given field length it will be returned without modification . |
31,977 | public static short computeSeedHash ( final long seed ) { final long [ ] seedArr = { seed } ; final short seedHash = ( short ) ( ( hash ( seedArr , 0L ) [ 0 ] ) & 0xFFFFL ) ; if ( seedHash == 0 ) { throw new SketchesArgumentException ( "The given seed: " + seed + " produced a seedHash of zero. " + "You must choose a different seed." ) ; } return seedHash ; } | Computes and checks the 16 - bit seed hash from the given long seed . The seed hash may not be zero in order to maintain compatibility with older serialized versions that did not have this concept . |
31,978 | public static void checkIfMultipleOf8AndGT0 ( final long v , final String argName ) { if ( ( ( v & 0X7L ) == 0L ) && ( v > 0L ) ) { return ; } throw new SketchesArgumentException ( "The value of the parameter \"" + argName + "\" must be a positive multiple of 8 and greater than zero: " + v ) ; } | Checks if parameter v is a multiple of 8 and greater than zero . |
31,979 | public static void checkIfPowerOf2 ( final int v , final String argName ) { if ( ( v > 0 ) && ( ( v & ( v - 1 ) ) == 0 ) ) { return ; } throw new SketchesArgumentException ( "The value of the parameter \"" + argName + "\" must be a positive integer-power of 2" + " and greater than 0: " + v ) ; } | Checks the given parameter to make sure it is positive an integer - power of 2 and greater than zero . |
31,980 | public static int toLog2 ( final int value , final String argName ) { checkIfPowerOf2 ( value , argName ) ; return Integer . numberOfTrailingZeros ( value ) ; } | Checks the given value if it is a power of 2 . If not it throws an exception . Otherwise returns the log - base2 of the given value . |
31,981 | public static int [ ] evenlyLgSpaced ( final int lgStart , final int lgEnd , final int points ) { if ( points <= 0 ) { throw new SketchesArgumentException ( "points must be > 0" ) ; } if ( ( lgEnd < 0 ) || ( lgStart < 0 ) ) { throw new SketchesArgumentException ( "lgStart and lgEnd must be >= 0." ) ; } final int [ ] out = new int [ points ] ; out [ 0 ] = 1 << lgStart ; if ( points == 1 ) { return out ; } final double delta = ( lgEnd - lgStart ) / ( points - 1.0 ) ; for ( int i = 1 ; i < points ; i ++ ) { final double mXpY = ( delta * i ) + lgStart ; out [ i ] = ( int ) round ( pow ( 2 , mXpY ) ) ; } return out ; } | Returns an int array of points that will be evenly spaced on a log axis . This is designed for Log_base2 numbers . |
31,982 | public static int simpleIntLog2 ( final int x ) { final int exp = Integer . numberOfTrailingZeros ( x ) ; if ( x != ( 1 << exp ) ) { throw new SketchesArgumentException ( "Argument x cannot be negative or zero." ) ; } return exp ; } | Gives the log2 of an integer that is known to be a power of 2 . |
31,983 | public static final int startingSubMultiple ( final int lgTarget , final ResizeFactor rf , final int lgMin ) { final int lgRF = rf . lg ( ) ; return ( lgTarget <= lgMin ) ? lgMin : ( lgRF == 0 ) ? lgTarget : ( ( lgTarget - lgMin ) % lgRF ) + lgMin ; } | Gets the smallest allowed exponent of 2 that it is a sub - multiple of the target by zero one or more resize factors . |
31,984 | public static UpdateSketch heapify ( final Memory srcMem , final long seed ) { final Family family = Family . idToFamily ( srcMem . getByte ( FAMILY_BYTE ) ) ; if ( family . equals ( Family . ALPHA ) ) { return HeapAlphaSketch . heapifyInstance ( srcMem , seed ) ; } return HeapQuickSelectSketch . heapifyInstance ( srcMem , seed ) ; } | Instantiates an on - heap UpdateSketch from Memory . |
31,985 | public UpdateReturnState update ( final String datum ) { if ( ( datum == null ) || datum . isEmpty ( ) ) { return RejectedNullOrEmpty ; } final byte [ ] data = datum . getBytes ( UTF_8 ) ; return hashUpdate ( hash ( data , getSeed ( ) ) [ 0 ] >>> 1 ) ; } | Present this sketch with the given String . The string is converted to a byte array using UTF8 encoding . If the string is null or empty no update attempt is made and the method returns . |
31,986 | public UpdateReturnState update ( final byte [ ] data ) { if ( ( data == null ) || ( data . length == 0 ) ) { return RejectedNullOrEmpty ; } return hashUpdate ( hash ( data , getSeed ( ) ) [ 0 ] >>> 1 ) ; } | Present this sketch with the given byte array . If the byte array is null or empty no update attempt is made and the method returns . |
31,987 | public static DoublesSketch heapify ( final Memory srcMem ) { if ( checkIsCompactMemory ( srcMem ) ) { return CompactDoublesSketch . heapify ( srcMem ) ; } return UpdateDoublesSketch . heapify ( srcMem ) ; } | Heapify takes the sketch image in Memory and instantiates an on - heap Sketch . The resulting sketch will not retain any link to the source Memory . |
31,988 | public static DoublesSketch wrap ( final Memory srcMem ) { if ( checkIsCompactMemory ( srcMem ) ) { return DirectCompactDoublesSketch . wrapInstance ( srcMem ) ; } return DirectUpdateDoublesSketchR . wrapInstance ( srcMem ) ; } | Wrap this sketch around the given Memory image of a DoublesSketch compact or non - compact . |
31,989 | public DoublesSketch downSample ( final DoublesSketch srcSketch , final int smallerK , final WritableMemory dstMem ) { return downSampleInternal ( srcSketch , smallerK , dstMem ) ; } | From an source sketch create a new sketch that must have a smaller value of K . The original sketch is not modified . |
31,990 | public void putMemory ( final WritableMemory dstMem , final boolean compact ) { if ( isDirect ( ) && ( isCompact ( ) == compact ) ) { final Memory srcMem = getMemory ( ) ; srcMem . copyTo ( 0 , dstMem , 0 , getStorageBytes ( ) ) ; } else { final byte [ ] byteArr = toByteArray ( compact ) ; final int arrLen = byteArr . length ; final long memCap = dstMem . getCapacity ( ) ; if ( memCap < arrLen ) { throw new SketchesArgumentException ( "Destination Memory not large enough: " + memCap + " < " + arrLen ) ; } dstMem . putByteArray ( 0 , byteArr , 0 , arrLen ) ; } } | Puts the current sketch into the given Memory if there is sufficient space otherwise throws an error . |
31,991 | public static long convertToPrecedingCummulative ( final long [ ] array ) { long subtotal = 0 ; for ( int i = 0 ; i < array . length ; i ++ ) { final long newSubtotal = subtotal + array [ i ] ; array [ i ] = subtotal ; subtotal = newSubtotal ; } return subtotal ; } | Convert the weights into totals of the weights preceding each item |
31,992 | public static int chunkContainingPos ( final long [ ] arr , final long pos ) { final int nominalLength = arr . length - 1 ; assert nominalLength > 0 ; final long n = arr [ nominalLength ] ; assert 0 <= pos ; assert pos < n ; final int l = 0 ; final int r = nominalLength ; assert l < r ; assert arr [ l ] <= pos ; assert pos < arr [ r ] ; return searchForChunkContainingPos ( arr , pos , l , r ) ; } | This is written in terms of a plain array to facilitate testing . |
31,993 | public CompactSketch < S > getResult ( ) { if ( count_ == 0 ) { return new CompactSketch < S > ( null , null , theta_ , isEmpty_ ) ; } final CompactSketch < S > result = new CompactSketch < S > ( Arrays . copyOfRange ( keys_ , 0 , count_ ) , Arrays . copyOfRange ( summaries_ , 0 , count_ ) , theta_ , isEmpty_ ) ; reset ( ) ; return result ; } | Gets the result of this operation |
31,994 | static final < T > void validateValues ( final T [ ] values , final Comparator < ? super T > comparator ) { final int lenM1 = values . length - 1 ; for ( int j = 0 ; j < lenM1 ; j ++ ) { if ( ( values [ j ] != null ) && ( values [ j + 1 ] != null ) && ( comparator . compare ( values [ j ] , values [ j + 1 ] ) < 0 ) ) { continue ; } throw new SketchesArgumentException ( "Values must be unique, monotonically increasing and not null." ) ; } } | Checks the sequential validity of the given array of values . They must be unique monotonically increasing and not null . |
31,995 | PairTable rebuild ( final int newLgSizeInts ) { checkLgSizeInts ( newLgSizeInts ) ; final int newSize = 1 << newLgSizeInts ; final int oldSize = 1 << lgSizeInts ; rtAssert ( newSize > numPairs ) ; final int [ ] oldSlotsArr = slotsArr ; slotsArr = new int [ newSize ] ; Arrays . fill ( slotsArr , - 1 ) ; lgSizeInts = newLgSizeInts ; for ( int i = 0 ; i < oldSize ; i ++ ) { final int item = oldSlotsArr [ i ] ; if ( item != - 1 ) { mustInsert ( this , item ) ; } } return this ; } | Rebuilds to a larger size . NumItems and validBits remain unchanged . |
31,996 | static int [ ] unwrappingGetItems ( final PairTable table , final int numPairs ) { if ( numPairs < 1 ) { return null ; } final int [ ] slotsArr = table . slotsArr ; final int tableSize = 1 << table . lgSizeInts ; final int [ ] result = new int [ numPairs ] ; int i = 0 ; int l = 0 ; int r = numPairs - 1 ; final int hiBit = 1 << ( table . validBits - 1 ) ; while ( ( i < tableSize ) && ( slotsArr [ i ] != - 1 ) ) { final int item = slotsArr [ i ++ ] ; if ( ( item & hiBit ) != 0 ) { result [ r -- ] = item ; } else { result [ l ++ ] = item ; } } while ( i < tableSize ) { final int look = slotsArr [ i ++ ] ; if ( look != - 1 ) { result [ l ++ ] = look ; } } assert l == ( r + 1 ) ; return result ; } | While extracting the items from a linear probing hashtable this will usually undo the wrap - around provided that the table isn t too full . Experiments suggest that for sufficiently large tables the load factor would have to be over 90 percent before this would fail frequently and even then the subsequent sort would fix things up . |
31,997 | static void introspectiveInsertionSort ( final int [ ] a , final int l , final int r ) { final int length = ( r - l ) + 1 ; long cost = 0 ; final long costLimit = 8L * length ; for ( int i = l + 1 ; i <= r ; i ++ ) { int j = i ; final long v = a [ i ] & 0XFFFF_FFFFL ; while ( ( j >= ( l + 1 ) ) && ( v < ( ( a [ j - 1 ] ) & 0XFFFF_FFFFL ) ) ) { a [ j ] = a [ j - 1 ] ; j -= 1 ; } a [ j ] = ( int ) v ; cost += ( i - j ) ; if ( cost > costLimit ) { final long [ ] b = new long [ a . length ] ; for ( int m = 0 ; m < a . length ; m ++ ) { b [ m ] = a [ m ] & 0XFFFF_FFFFL ; } Arrays . sort ( b , l , r + 1 ) ; for ( int m = 0 ; m < a . length ; m ++ ) { a [ m ] = ( int ) b [ m ] ; } return ; } } } | In applications where the input array is already nearly sorted insertion sort runs in linear time with a very small constant . This introspective version of insertion sort protects against the quadratic cost of sorting bad input arrays . It keeps track of how much work has been done and if that exceeds a constant times the array length it switches to a different sorting algorithm . |
31,998 | public double update ( final byte [ ] key , final byte [ ] identifier ) { if ( key == null ) { return Double . NaN ; } checkMethodKeySize ( key ) ; if ( identifier == null ) { return getEstimate ( key ) ; } final short coupon = ( short ) Map . coupon16 ( identifier ) ; final int baseMapIndex = maps_ [ 0 ] . findOrInsertKey ( key ) ; final double baseMapEstimate = maps_ [ 0 ] . update ( baseMapIndex , coupon ) ; if ( baseMapEstimate > 0 ) { return baseMapEstimate ; } final int level = - ( int ) baseMapEstimate ; if ( level == 0 ) { return promote ( key , coupon , maps_ [ 0 ] , baseMapIndex , level , baseMapIndex , 0 ) ; } final Map map = maps_ [ level ] ; final int index = map . findOrInsertKey ( key ) ; final double estimate = map . update ( index , coupon ) ; if ( estimate > 0 ) { return estimate ; } return promote ( key , coupon , map , index , level , baseMapIndex , - estimate ) ; } | Updates the map with a given key and identifier and returns the estimate of the number of unique identifiers encountered so far for the given key . |
31,999 | public double getEstimate ( final byte [ ] key ) { if ( key == null ) { return Double . NaN ; } checkMethodKeySize ( key ) ; final double est = maps_ [ 0 ] . getEstimate ( key ) ; if ( est >= 0.0 ) { return est ; } final int level = - ( int ) est ; final Map map = maps_ [ level ] ; return map . getEstimate ( key ) ; } | Retrieves the current estimate of unique count for a given key . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.