idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
32,000 | private static double contClassicLB ( final double numSamplesF , final double theta , final double numSDev ) { final double nHat = ( numSamplesF - 0.5 ) / theta ; final double b = numSDev * Math . sqrt ( ( 1.0 - theta ) / theta ) ; final double d = 0.5 * b * Math . sqrt ( ( b * b ) + ( 4.0 * nHat ) ) ; final double center = nHat + ( 0.5 * ( b * b ) ) ; return ( center - d ) ; } | our classic bounds but now with continuity correction | 129 | 8 |
32,001 | public static double getLowerBound ( final long numSamples , final double theta , final int numSDev , final boolean noDataSeen ) { //in earlier code numSamples was called numSamplesI if ( noDataSeen ) { return 0.0 ; } checkArgs ( numSamples , theta , numSDev ) ; final double lb = computeApproxBinoLB ( numSamples , theta , numSDev ) ; final double numSamplesF = numSamples ; final double est = numSamplesF / theta ; return ( Math . min ( est , Math . max ( numSamplesF , lb ) ) ) ; } | Returns the approximate lower bound value | 143 | 6 |
32,002 | public static double getUpperBound ( final long numSamples , final double theta , final int numSDev , final boolean noDataSeen ) { //in earlier code numSamples was called numSamplesI if ( noDataSeen ) { return 0.0 ; } checkArgs ( numSamples , theta , numSDev ) ; final double ub = computeApproxBinoUB ( numSamples , theta , numSDev ) ; final double numSamplesF = numSamples ; final double est = numSamplesF / theta ; return ( Math . max ( est , ub ) ) ; } | Returns the approximate upper bound value | 134 | 6 |
32,003 | static final void checkArgs ( final long numSamples , final double theta , final int numSDev ) { if ( ( numSDev | ( numSDev - 1 ) | ( 3 - numSDev ) | numSamples ) < 0 ) { throw new SketchesArgumentException ( "numSDev must only be 1,2, or 3 and numSamples must >= 0: numSDev=" + numSDev + ", numSamples=" + numSamples ) ; } if ( ( theta < 0.0 ) || ( theta > 1.0 ) ) { throw new SketchesArgumentException ( "0.0 < theta <= 1.0: " + theta ) ; } } | exposed only for test | 156 | 5 |
32,004 | public void update ( final ReservoirItemsSketch < T > sketchIn ) { if ( sketchIn == null ) { return ; } final ReservoirItemsSketch < T > ris = ( sketchIn . getK ( ) <= maxK_ ? sketchIn : sketchIn . downsampledCopy ( maxK_ ) ) ; // can modify the sketch if we downsampled, otherwise may need to copy it final boolean isModifiable = ( sketchIn != ris ) ; if ( gadget_ == null ) { createNewGadget ( ris , isModifiable ) ; } else { twoWayMergeInternal ( ris , isModifiable ) ; } } | Union the given sketch . This method can be repeatedly called . If the given sketch is null it is interpreted as an empty sketch . | 140 | 26 |
32,005 | public void update ( final T datum ) { if ( datum == null ) { return ; } if ( gadget_ == null ) { gadget_ = ReservoirItemsSketch . newInstance ( maxK_ ) ; } gadget_ . update ( datum ) ; } | Present this union with a single item to be added to the union . | 58 | 14 |
32,006 | public byte [ ] toByteArray ( final ArrayOfItemsSerDe < T > serDe ) { if ( ( gadget_ == null ) || ( gadget_ . getNumSamples ( ) == 0 ) ) { return toByteArray ( serDe , null ) ; } else { return toByteArray ( serDe , gadget_ . getValueAtPosition ( 0 ) . getClass ( ) ) ; } } | Returns a byte array representation of this union | 86 | 8 |
32,007 | static double getRelErr ( final boolean upperBound , final boolean oooFlag , final int lgK , final int stdDev ) { final int idx = ( ( lgK - 4 ) * 3 ) + ( stdDev - 1 ) ; final int sw = ( oooFlag ? 2 : 0 ) | ( upperBound ? 1 : 0 ) ; double f = 0 ; switch ( sw ) { case 0 : { //HIP, LB f = HIP_LB [ idx ] ; break ; } case 1 : { //HIP, UB f = HIP_UB [ idx ] ; break ; } case 2 : { //NON_HIP, LB f = NON_HIP_LB [ idx ] ; break ; } case 3 : { //NON_HIP, UB f = NON_HIP_UB [ idx ] ; break ; } } return f ; } | Return Relative Error for UB or LB for HIP or Non - HIP as a function of numStdDev . | 194 | 23 |
32,008 | public double getEstimate ( ) { if ( ! hasHip ( mem ) ) { return getIconEstimate ( PreambleUtil . getLgK ( mem ) , getNumCoupons ( mem ) ) ; } return getHipAccum ( mem ) ; } | Returns the best estimate of the cardinality of the sketch . | 61 | 12 |
32,009 | static CompactSketch heapifyInstance ( final Memory srcMem , final long seed ) { final short memSeedHash = ( short ) extractSeedHash ( srcMem ) ; final short computedSeedHash = computeSeedHash ( seed ) ; checkSeedHashes ( memSeedHash , computedSeedHash ) ; final int preLongs = extractPreLongs ( srcMem ) ; final boolean empty = PreambleUtil . isEmpty ( srcMem ) ; int curCount = 0 ; long thetaLong = Long . MAX_VALUE ; long [ ] cache = new long [ 0 ] ; if ( preLongs == 1 ) { if ( ! empty ) { //singleItem return new SingleItemSketch ( srcMem . getLong ( 8 ) , memSeedHash ) ; } //else empty } else { //preLongs > 1 curCount = extractCurCount ( srcMem ) ; cache = new long [ curCount ] ; if ( preLongs == 2 ) { srcMem . getLongArray ( 16 , cache , 0 , curCount ) ; } else { //preLongs == 3 srcMem . getLongArray ( 24 , cache , 0 , curCount ) ; thetaLong = extractThetaLong ( srcMem ) ; } } return new HeapCompactOrderedSketch ( cache , empty , memSeedHash , curCount , thetaLong ) ; } | Heapifies the given source Memory with seed | 301 | 9 |
32,010 | static CompactSketch compact ( final UpdateSketch sketch ) { final int curCount = sketch . getRetainedEntries ( true ) ; long thetaLong = sketch . getThetaLong ( ) ; boolean empty = sketch . isEmpty ( ) ; thetaLong = thetaOnCompact ( empty , curCount , thetaLong ) ; empty = emptyOnCompact ( curCount , thetaLong ) ; final short seedHash = sketch . getSeedHash ( ) ; final long [ ] cache = sketch . getCache ( ) ; final boolean ordered = true ; final long [ ] cacheOut = CompactSketch . compactCache ( cache , curCount , thetaLong , ordered ) ; if ( ( curCount == 1 ) && ( thetaLong == Long . MAX_VALUE ) ) { return new SingleItemSketch ( cacheOut [ 0 ] , seedHash ) ; } return new HeapCompactOrderedSketch ( cacheOut , empty , seedHash , curCount , thetaLong ) ; } | Converts the given UpdateSketch to this compact form . | 220 | 13 |
32,011 | public static double select ( final double [ ] arr , int lo , int hi , final int pivot ) { while ( hi > lo ) { final int j = partition ( arr , lo , hi ) ; if ( j == pivot ) { return arr [ pivot ] ; } if ( j > pivot ) { hi = j - 1 ; } else { lo = j + 1 ; } } return arr [ pivot ] ; } | Gets the 0 - based kth order statistic from the array . Warning! This changes the ordering of elements in the given array! | 87 | 27 |
32,012 | public static double selectIncludingZeros ( final double [ ] arr , final int pivot ) { final int arrSize = arr . length ; final int adj = pivot - 1 ; return select ( arr , 0 , arrSize - 1 , adj ) ; } | Gets the 1 - based kth order statistic from the array including any zero values in the array . Warning! This changes the ordering of elements in the given array! | 53 | 34 |
32,013 | public static double selectExcludingZeros ( final double [ ] arr , final int nonZeros , final int pivot ) { if ( pivot > nonZeros ) { return 0L ; } final int arrSize = arr . length ; final int zeros = arrSize - nonZeros ; final int adjK = ( pivot + zeros ) - 1 ; return select ( arr , 0 , arrSize - 1 , adjK ) ; } | Gets the 1 - based kth order statistic from the array excluding any zero values in the array . Warning! This changes the ordering of elements in the given array! | 92 | 34 |
32,014 | static final CouponHashSet heapifySet ( final Memory mem ) { final int lgConfigK = extractLgK ( mem ) ; final TgtHllType tgtHllType = extractTgtHllType ( mem ) ; final CurMode curMode = extractCurMode ( mem ) ; final int memArrStart = ( curMode == CurMode . LIST ) ? LIST_INT_ARR_START : HASH_SET_INT_ARR_START ; final CouponHashSet set = new CouponHashSet ( lgConfigK , tgtHllType ) ; set . putOutOfOrderFlag ( true ) ; final boolean memIsCompact = extractCompactFlag ( mem ) ; final int couponCount = extractHashSetCount ( mem ) ; int lgCouponArrInts = extractLgArr ( mem ) ; if ( lgCouponArrInts < LG_INIT_SET_SIZE ) { lgCouponArrInts = computeLgArr ( mem , couponCount , lgConfigK ) ; } if ( memIsCompact ) { for ( int i = 0 ; i < couponCount ; i ++ ) { set . couponUpdate ( extractInt ( mem , memArrStart + ( i << 2 ) ) ) ; } } else { //updatable set . couponCount = couponCount ; set . lgCouponArrInts = lgCouponArrInts ; final int couponArrInts = 1 << lgCouponArrInts ; set . couponIntArr = new int [ couponArrInts ] ; mem . getIntArray ( HASH_SET_INT_ARR_START , set . couponIntArr , 0 , couponArrInts ) ; } return set ; } | will also accept List but results in a Set | 398 | 9 |
32,015 | static HeapQuickSelectSketch heapifyInstance ( final Memory srcMem , final long seed ) { final int preambleLongs = extractPreLongs ( srcMem ) ; //byte 0 final int lgNomLongs = extractLgNomLongs ( srcMem ) ; //byte 3 final int lgArrLongs = extractLgArrLongs ( srcMem ) ; //byte 4 checkUnionQuickSelectFamily ( srcMem , preambleLongs , lgNomLongs ) ; checkMemIntegrity ( srcMem , seed , preambleLongs , lgNomLongs , lgArrLongs ) ; final float p = extractP ( srcMem ) ; //bytes 12-15 final int lgRF = extractLgResizeFactor ( srcMem ) ; //byte 0 ResizeFactor myRF = ResizeFactor . getRF ( lgRF ) ; final int familyID = extractFamilyID ( srcMem ) ; final Family family = Family . idToFamily ( familyID ) ; if ( ( myRF == ResizeFactor . X1 ) && ( lgArrLongs != Util . startingSubMultiple ( lgNomLongs + 1 , myRF , MIN_LG_ARR_LONGS ) ) ) { myRF = ResizeFactor . X2 ; } final HeapQuickSelectSketch hqss = new HeapQuickSelectSketch ( lgNomLongs , seed , p , myRF , preambleLongs , family ) ; hqss . lgArrLongs_ = lgArrLongs ; hqss . hashTableThreshold_ = setHashTableThreshold ( lgNomLongs , lgArrLongs ) ; hqss . curCount_ = extractCurCount ( srcMem ) ; hqss . thetaLong_ = extractThetaLong ( srcMem ) ; hqss . empty_ = PreambleUtil . isEmpty ( srcMem ) ; hqss . cache_ = new long [ 1 << lgArrLongs ] ; srcMem . getLongArray ( preambleLongs << 3 , hqss . cache_ , 0 , 1 << lgArrLongs ) ; //read in as hash table return hqss ; } | Heapify a sketch from a Memory UpdateSketch or Union object containing sketch data . | 504 | 19 |
32,016 | private final void quickSelectAndRebuild ( ) { final int arrLongs = 1 << lgArrLongs_ ; final int pivot = ( 1 << lgNomLongs_ ) + 1 ; // pivot for QS thetaLong_ = selectExcludingZeros ( cache_ , curCount_ , pivot ) ; //messes up the cache_ // now we rebuild to clean up dirty data, update count, reconfigure as a hash table final long [ ] tgtArr = new long [ arrLongs ] ; curCount_ = HashOperations . hashArrayInsert ( cache_ , tgtArr , lgArrLongs_ , thetaLong_ ) ; cache_ = tgtArr ; //hashTableThreshold stays the same } | array stays the same size . Changes theta and thus count | 165 | 12 |
32,017 | public T items ( final int i ) { loadArrays ( ) ; return ( sampleLists == null ? null : sampleLists . items [ i ] ) ; } | Returns a single item from the samples contained in the sketch . Does not perform bounds checking on the input . If this is the first getter call copies data arrays from the sketch . | 36 | 36 |
32,018 | public double weights ( final int i ) { loadArrays ( ) ; return ( sampleLists == null ? Double . NaN : sampleLists . weights [ i ] ) ; } | Returns a single weight from the samples contained in the sketch . Does not perform bounds checking on the input . If this is the first getter call copies data arrays from the sketch . | 39 | 36 |
32,019 | public SetOperationBuilder setNominalEntries ( final int nomEntries ) { bLgNomLongs = Integer . numberOfTrailingZeros ( ceilingPowerOf2 ( nomEntries ) ) ; if ( ( bLgNomLongs > MAX_LG_NOM_LONGS ) || ( bLgNomLongs < MIN_LG_NOM_LONGS ) ) { throw new SketchesArgumentException ( "Nominal Entries must be >= 16 and <= 67108864: " + nomEntries ) ; } return this ; } | Sets the Nominal Entries for this set operation . The minimum value is 16 and the maximum value is 67 108 864 which is 2^26 . Be aware that Unions as large as this maximum value have not been thoroughly tested or characterized for performance . | 129 | 53 |
32,020 | public SetOperation build ( final Family family , final WritableMemory dstMem ) { SetOperation setOp = null ; switch ( family ) { case UNION : { if ( dstMem == null ) { setOp = UnionImpl . initNewHeapInstance ( bLgNomLongs , bSeed , bP , bRF ) ; } else { setOp = UnionImpl . initNewDirectInstance ( bLgNomLongs , bSeed , bP , bRF , bMemReqSvr , dstMem ) ; } break ; } case INTERSECTION : { if ( dstMem == null ) { setOp = IntersectionImpl . initNewHeapInstance ( bSeed ) ; } else { setOp = IntersectionImpl . initNewDirectInstance ( bSeed , dstMem ) ; } break ; } case A_NOT_B : { if ( dstMem == null ) { setOp = new HeapAnotB ( bSeed ) ; } else { throw new SketchesArgumentException ( "AnotB is a stateless operation and cannot be persisted." ) ; } break ; } default : throw new SketchesArgumentException ( "Given Family cannot be built as a SetOperation: " + family . toString ( ) ) ; } return setOp ; } | Returns a SetOperation with the current configuration of this Builder the given Family and the given destination memory . Note that the destination memory cannot be used with AnotB . | 280 | 33 |
32,021 | static ReversePurgeLongHashMap getInstance ( final String string ) { final String [ ] tokens = string . split ( "," ) ; if ( tokens . length < 2 ) { throw new SketchesArgumentException ( "String not long enough to specify length and capacity." ) ; } final int numActive = Integer . parseInt ( tokens [ 0 ] ) ; final int length = Integer . parseInt ( tokens [ 1 ] ) ; final ReversePurgeLongHashMap table = new ReversePurgeLongHashMap ( length ) ; int j = 2 ; for ( int i = 0 ; i < numActive ; i ++ ) { final long key = Long . parseLong ( tokens [ j ++ ] ) ; final long value = Long . parseLong ( tokens [ j ++ ] ) ; table . adjustOrPutValue ( key , value ) ; } return table ; } | Returns an instance of this class from the given String which must be a String representation of this class . | 182 | 20 |
32,022 | String serializeToString ( ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( "%d,%d," , numActive , keys . length ) ) ; for ( int i = 0 ; i < keys . length ; i ++ ) { if ( states [ i ] != 0 ) { sb . append ( String . format ( "%d,%d," , keys [ i ] , values [ i ] ) ) ; } } return sb . toString ( ) ; } | Returns a String representation of this hash map . | 112 | 9 |
32,023 | void keepOnlyPositiveCounts ( ) { // Starting from the back, find the first empty cell, which marks a boundary between clusters. int firstProbe = keys . length - 1 ; while ( states [ firstProbe ] > 0 ) { firstProbe -- ; } //Work towards the front; delete any non-positive entries. for ( int probe = firstProbe ; probe -- > 0 ; ) { // When we find the next non-empty cell, we know we are at the high end of a cluster, // which is tracked by firstProbe. if ( ( states [ probe ] > 0 ) && ( values [ probe ] <= 0 ) ) { hashDelete ( probe ) ; //does the work of deletion and moving higher items towards the front. numActive -- ; } } //now work on the first cluster that was skipped. for ( int probe = keys . length ; probe -- > firstProbe ; ) { if ( ( states [ probe ] > 0 ) && ( values [ probe ] <= 0 ) ) { hashDelete ( probe ) ; numActive -- ; } } } | Processes the map arrays and retains only keys with positive counts . | 229 | 13 |
32,024 | public static double getLowerBoundForBoverA ( final Sketch sketchA , final Sketch sketchB ) { final double thetaA = sketchA . getTheta ( ) ; final double thetaB = sketchB . getTheta ( ) ; checkThetas ( thetaA , thetaB ) ; final int countB = sketchB . getRetainedEntries ( true ) ; final int countA = ( thetaB == thetaA ) ? sketchA . getRetainedEntries ( true ) : sketchA . getCountLessThanTheta ( thetaB ) ; if ( countA <= 0 ) { return 0 ; } return BoundsOnRatiosInSampledSets . getLowerBoundForBoverA ( countA , countB , thetaB ) ; } | Gets the approximate lower bound for B over A based on a 95% confidence interval | 170 | 17 |
32,025 | static < T > void blockyTandemMergeSort ( final T [ ] keyArr , final long [ ] valArr , final int arrLen , final int blkSize , final Comparator < ? super T > comparator ) { assert blkSize >= 1 ; if ( arrLen <= blkSize ) { return ; } int numblks = arrLen / blkSize ; if ( ( numblks * blkSize ) < arrLen ) { numblks += 1 ; } assert ( ( numblks * blkSize ) >= arrLen ) ; // duplicate the input is preparation for the "ping-pong" copy reduction strategy. final T [ ] keyTmp = Arrays . copyOf ( keyArr , arrLen ) ; final long [ ] valTmp = Arrays . copyOf ( valArr , arrLen ) ; blockyTandemMergeSortRecursion ( keyTmp , valTmp , keyArr , valArr , 0 , numblks , blkSize , arrLen , comparator ) ; } | also used by ItemsAuxiliary | 229 | 7 |
32,026 | public static int decodeValue ( final short encodedSize ) { final int value = encodedSize & 0xFFFF ; if ( value > MAX_ENC_VALUE ) { throw new SketchesArgumentException ( "Maximum valid encoded value is " + Integer . toHexString ( MAX_ENC_VALUE ) + ", found: " + value ) ; } final int p = ( value >>> EXPONENT_SHIFT ) & EXPONENT_MASK ; final int i = value & INDEX_MASK ; return ( int ) ( ( 1 << p ) * ( ( i * INV_BINS_PER_OCTAVE ) + 1.0 ) ) ; } | Decodes the 16 - bit reservoir size value into an int . | 143 | 13 |
32,027 | public static ConcurrentLimitRule of ( int concurrentLimit , TimeUnit timeOutUnit , long timeOut ) { requireNonNull ( timeOutUnit , "time out unit can not be null" ) ; return new ConcurrentLimitRule ( concurrentLimit , timeOutUnit . toMillis ( timeOut ) ) ; } | Initialise a concurrent rate limit . | 66 | 7 |
32,028 | public static RequestLimitRule of ( Duration duration , long limit ) { checkDuration ( duration ) ; if ( limit < 0 ) { throw new IllegalArgumentException ( "limit must be greater than zero." ) ; } int durationSeconds = ( int ) duration . getSeconds ( ) ; return new RequestLimitRule ( durationSeconds , limit , durationSeconds ) ; } | Initialise a request rate limit . Imagine the whole duration window as being one large bucket with a single count . | 79 | 22 |
32,029 | public RequestLimitRule withName ( String name ) { return new RequestLimitRule ( this . durationSeconds , this . limit , this . precision , name , this . keys ) ; } | Applies a name to the rate limit that is useful for metrics . | 39 | 14 |
32,030 | public RequestLimitRule matchingKeys ( String ... keys ) { Set < String > keySet = keys . length > 0 ? new HashSet <> ( Arrays . asList ( keys ) ) : null ; return matchingKeys ( keySet ) ; } | Applies a key to the rate limit that defines to which keys the rule applies empty for any unmatched key . | 52 | 22 |
32,031 | public RequestLimitRule matchingKeys ( Set < String > keys ) { return new RequestLimitRule ( this . durationSeconds , this . limit , this . precision , this . name , keys ) ; } | Applies a key to the rate limit that defines to which keys the rule applies null for any unmatched key . | 42 | 22 |
32,032 | public void addScopeBindings ( Map < Class < ? extends Annotation > , Scope > bindings ) { if ( scopeCleaner . isRunning ( ) ) { scopeBindings . putAll ( bindings ) ; } } | allows late - binding of scopes to PreDestroyMonitor useful if more than one Injector contributes scope bindings | 46 | 22 |
32,033 | @ Override public void close ( ) throws Exception { if ( scopeCleaner . close ( ) ) { // executor thread to exit processing loop LOGGER . info ( "closing PreDestroyMonitor..." ) ; List < Map . Entry < Object , UnscopedCleanupAction > > actions = new ArrayList <> ( cleanupActions . entrySet ( ) ) ; if ( actions . size ( ) > 0 ) { LOGGER . warn ( "invoking predestroy action for {} unscoped instances" , actions . size ( ) ) ; actions . stream ( ) . map ( Map . Entry :: getValue ) . collect ( Collectors . groupingBy ( UnscopedCleanupAction :: getContext , Collectors . counting ( ) ) ) . forEach ( ( source , count ) -> { LOGGER . warn ( " including {} objects from source '{}'" , count , source ) ; } ) ; } actions . stream ( ) . sorted ( Map . Entry . comparingByValue ( ) ) . forEach ( action -> { Optional . ofNullable ( action . getKey ( ) ) . ifPresent ( obj -> action . getValue ( ) . call ( obj ) ) ; } ) ; actions . clear ( ) ; cleanupActions . clear ( ) ; scopeBindings . clear ( ) ; scopeBindings = Collections . emptyMap ( ) ; } else { LOGGER . warn ( "PreDestroyMonitor.close() invoked but instance is not running" ) ; } } | final cleanup of managed instances if any | 312 | 7 |
32,034 | public InjectorBuilder combineWith ( Module ... modules ) { List < Module > m = new ArrayList <> ( ) ; m . add ( module ) ; m . addAll ( Arrays . asList ( modules ) ) ; this . module = Modules . combine ( m ) ; return this ; } | Add additional bindings to the module tracked by the DSL | 65 | 10 |
32,035 | public < T > InjectorBuilder forEachElement ( ElementVisitor < T > visitor , Consumer < T > consumer ) { Elements . getElements ( module ) . forEach ( element -> Optional . ofNullable ( element . acceptVisitor ( visitor ) ) . ifPresent ( consumer ) ) ; return this ; } | Iterate through all elements of the current module and pass the output of the ElementVisitor to the provided consumer . null responses from the visitor are ignored . | 68 | 31 |
32,036 | public < T > InjectorBuilder forEachElement ( ElementVisitor < T > visitor ) { Elements . getElements ( module ) . forEach ( element -> element . acceptVisitor ( visitor ) ) ; return this ; } | Call the provided visitor for all elements of the current module . | 49 | 12 |
32,037 | public InjectorBuilder filter ( ElementVisitor < Boolean > predicate ) { List < Element > elements = new ArrayList < Element > ( ) ; for ( Element element : Elements . getElements ( Stage . TOOL , module ) ) { if ( element . acceptVisitor ( predicate ) ) { elements . add ( element ) ; } } this . module = Elements . getModule ( elements ) ; return this ; } | Filter out elements for which the provided visitor returns true . | 88 | 11 |
32,038 | public static Module combineAndOverride ( List < ? extends Module > modules ) { Iterator < ? extends Module > iter = modules . iterator ( ) ; Module current = Modules . EMPTY_MODULE ; if ( iter . hasNext ( ) ) { current = iter . next ( ) ; if ( iter . hasNext ( ) ) { current = Modules . override ( current ) . with ( iter . next ( ) ) ; } } return current ; } | Generate a single module that is produced by accumulating and overriding each module with the next . | 96 | 18 |
32,039 | public static Module fromClass ( final Class < ? > cls , final boolean override ) { List < Module > modules = new ArrayList <> ( ) ; // Iterate through all annotations of the main class, create a binding for the annotation // and add the module to the list of modules to install for ( final Annotation annot : cls . getDeclaredAnnotations ( ) ) { final Class < ? extends Annotation > type = annot . annotationType ( ) ; Bootstrap bootstrap = type . getAnnotation ( Bootstrap . class ) ; if ( bootstrap != null ) { LOG . info ( "Adding Module {}" , bootstrap . module ( ) ) ; try { modules . add ( bootstrap . module ( ) . getConstructor ( type ) . newInstance ( annot ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } try { if ( override ) { return Modules . override ( combineAndOverride ( modules ) ) . with ( ( Module ) cls . newInstance ( ) ) ; } else { return Modules . combine ( Modules . combine ( modules ) , ( Module ) cls . newInstance ( ) ) ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Create a single module that derived from all bootstrap annotations on a class where that class itself is a module . | 268 | 22 |
32,040 | public < T > Governator setFeature ( GovernatorFeature < T > feature , T value ) { this . featureOverrides . put ( feature , value ) ; return this ; } | Set a feature | 39 | 3 |
32,041 | private LifecycleInjector run ( Module externalModule , final String [ ] args ) { return InjectorBuilder . fromModules ( modules ) . combineWith ( externalModule ) . map ( new ModuleTransformer ( ) { @ Override public Module transform ( Module module ) { List < Module > modulesToTransform = Collections . singletonList ( module ) ; for ( ModuleListTransformer transformer : transformers ) { modulesToTransform = transformer . transform ( Collections . unmodifiableList ( modulesToTransform ) ) ; } return Modules . combine ( modulesToTransform ) ; } } ) . overrideWith ( overrideModules ) . createInjector ( new LifecycleInjectorCreator ( ) . withArguments ( args ) . withFeatures ( featureOverrides ) . withProfiles ( profiles ) ) ; } | Create the injector and call any LifecycleListeners | 174 | 11 |
32,042 | public String toFile ( ) throws Exception { File file = File . createTempFile ( "GuiceDependencies_" , ".dot" ) ; toFile ( file ) ; return file . getCanonicalPath ( ) ; } | Writes the Dot graph to a new temp file . | 50 | 11 |
32,043 | public void toFile ( File file ) throws Exception { PrintWriter out = new PrintWriter ( file , "UTF-8" ) ; try { out . write ( graph ( ) ) ; } finally { Closeables . close ( out , true ) ; } } | Writes the Dot graph to a given file . | 54 | 10 |
32,044 | public String graph ( ) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; PrintWriter out = new PrintWriter ( baos ) ; Injector localInjector = Guice . createInjector ( new GraphvizModule ( ) ) ; GraphvizGrapher renderer = localInjector . getInstance ( GraphvizGrapher . class ) ; renderer . setOut ( out ) ; renderer . setRankdir ( "TB" ) ; if ( ! roots . isEmpty ( ) ) { renderer . graph ( injector , roots ) ; } renderer . graph ( injector ) ; return fixupGraph ( baos . toString ( "UTF-8" ) ) ; } | Returns a String containing the Dot graph definition . | 160 | 9 |
32,045 | public boolean isGuiceConstructorInjected ( Class < ? > c ) { for ( Constructor < ? > con : c . getDeclaredConstructors ( ) ) { if ( isInjectable ( con ) ) { return true ; } } return false ; } | Determine if a class is an implicit Guice component that can be instantiated by Guice and the life - cycle managed by Jersey . | 57 | 29 |
32,046 | public Map < Scope , ComponentScope > createScopeMap ( ) { Map < Scope , ComponentScope > result = new HashMap < Scope , ComponentScope > ( ) ; result . put ( Scopes . SINGLETON , ComponentScope . Singleton ) ; result . put ( Scopes . NO_SCOPE , ComponentScope . PerRequest ) ; result . put ( ServletScopes . REQUEST , ComponentScope . PerRequest ) ; return result ; } | Maps a Guice scope to a Jersey scope . | 96 | 10 |
32,047 | void addColumn ( String columnName ) { data . add ( new ArrayList < String > ( ) ) ; columnNames . add ( columnName ) ; } | Add a column | 33 | 3 |
32,048 | void addValue ( String columnName , String value ) { addValue ( columnNames . indexOf ( columnName ) , value ) ; } | Add a value to the first column with the given name | 29 | 11 |
32,049 | void addValue ( int columnIndex , String value ) { if ( ( columnIndex < 0 ) || ( columnIndex >= data . size ( ) ) ) { throw new IllegalArgumentException ( ) ; } List < String > stringList = data . get ( columnIndex ) ; stringList . add ( value ) ; } | Add a value to the nth column | 67 | 8 |
32,050 | List < String > generate ( ) { List < String > lines = Lists . newArrayList ( ) ; StringBuilder workStr = new StringBuilder ( ) ; List < AtomicInteger > columnWidths = getColumnWidths ( ) ; List < Iterator < String > > dataIterators = getDataIterators ( ) ; Iterator < AtomicInteger > columnWidthIterator = columnWidths . iterator ( ) ; for ( String columnName : columnNames ) { int thisWidth = columnWidthIterator . next ( ) . intValue ( ) ; printValue ( workStr , columnName , thisWidth ) ; } pushLine ( lines , workStr ) ; boolean done = false ; while ( ! done ) { boolean hadValue = false ; Iterator < Iterator < String > > rowIterator = dataIterators . iterator ( ) ; for ( AtomicInteger width : columnWidths ) { Iterator < String > thisDataIterator = rowIterator . next ( ) ; if ( thisDataIterator . hasNext ( ) ) { hadValue = true ; String value = thisDataIterator . next ( ) ; printValue ( workStr , value , width . intValue ( ) ) ; } else { printValue ( workStr , "" , width . intValue ( ) ) ; } } pushLine ( lines , workStr ) ; if ( ! hadValue ) { done = true ; } } return lines ; } | Generate the output as a list of string lines | 291 | 10 |
32,051 | public static void start ( Class < ? > mainClass , final String [ ] args ) { try { LifecycleInjector . bootstrap ( mainClass , new AbstractModule ( ) { @ Override protected void configure ( ) { bind ( String [ ] . class ) . annotatedWith ( Main . class ) . toInstance ( args ) ; } } ) ; } catch ( Exception e ) { throw new ProvisionException ( "Error instantiating main class" , e ) ; } } | Utility method to start the CommonsCli using a main class and command line arguments | 101 | 17 |
32,052 | public void output ( Logger log ) { Map < String , Entry > entries = config . getSortedEntries ( ) ; if ( entries . isEmpty ( ) ) { return ; } ColumnPrinter printer = build ( entries ) ; log . debug ( "Configuration Details" ) ; for ( String line : printer . generate ( ) ) { log . debug ( line ) ; } } | Write the documentation table to a logger | 81 | 7 |
32,053 | public void output ( PrintWriter out ) { Map < String , Entry > entries = config . getSortedEntries ( ) ; if ( entries . isEmpty ( ) ) { return ; } ColumnPrinter printer = build ( entries ) ; out . println ( "Configuration Details" ) ; printer . print ( out ) ; } | Output documentation table to a PrintWriter | 68 | 7 |
32,054 | private ColumnPrinter build ( Map < String , Entry > entries ) { ColumnPrinter printer = new ColumnPrinter ( ) ; printer . addColumn ( "PROPERTY" ) ; printer . addColumn ( "FIELD" ) ; printer . addColumn ( "DEFAULT" ) ; printer . addColumn ( "VALUE" ) ; printer . addColumn ( "DESCRIPTION" ) ; Map < String , Entry > sortedEntries = Maps . newTreeMap ( ) ; sortedEntries . putAll ( entries ) ; for ( Entry entry : sortedEntries . values ( ) ) { printer . addValue ( 0 , entry . configurationName ) ; printer . addValue ( 1 , entry . field . getDeclaringClass ( ) . getName ( ) + "#" + entry . field . getName ( ) ) ; printer . addValue ( 2 , entry . defaultValue ) ; printer . addValue ( 3 , entry . has ? entry . value : "" ) ; printer . addValue ( 4 , entry . documentation ) ; } return printer ; } | Construct a ColumnPrinter using the entries | 220 | 8 |
32,055 | public static List < ConfigurationKeyPart > parse ( String raw , Map < String , String > contextOverrides ) { List < ConfigurationKeyPart > parts = Lists . newArrayList ( ) ; int caret = 0 ; for ( ; ; ) { int startIndex = raw . indexOf ( "${" , caret ) ; if ( startIndex < 0 ) { break ; } int endIndex = raw . indexOf ( "}" , startIndex ) ; if ( endIndex < 0 ) { break ; } if ( startIndex > caret ) { parts . add ( new ConfigurationKeyPart ( raw . substring ( caret , startIndex ) , false ) ) ; } startIndex += 2 ; if ( startIndex < endIndex ) { String name = raw . substring ( startIndex , endIndex ) ; if ( contextOverrides != null && contextOverrides . containsKey ( name ) ) { parts . add ( new ConfigurationKeyPart ( contextOverrides . get ( name ) , false ) ) ; } else { parts . add ( new ConfigurationKeyPart ( name , true ) ) ; } } caret = endIndex + 1 ; } if ( caret < raw . length ( ) ) { parts . add ( new ConfigurationKeyPart ( raw . substring ( caret ) , false ) ) ; } if ( parts . size ( ) == 0 ) { parts . add ( new ConfigurationKeyPart ( "" , false ) ) ; } return parts ; } | Parse a key into parts | 310 | 6 |
32,056 | @ Deprecated public void add ( Object ... objects ) throws Exception { for ( Object obj : objects ) { add ( obj ) ; } } | Add the objects to the container . Their assets will be loaded post construct methods called etc . | 29 | 18 |
32,057 | @ Deprecated public void add ( Object obj ) throws Exception { add ( obj , null , new LifecycleMethods ( obj . getClass ( ) ) ) ; } | Add the object to the container . Its assets will be loaded post construct methods called etc . | 34 | 18 |
32,058 | public LifecycleState getState ( Object obj ) { LifecycleStateWrapper lifecycleState = objectStates . get ( obj ) ; if ( lifecycleState == null ) { return hasStarted ( ) ? LifecycleState . ACTIVE : LifecycleState . LATENT ; } else { synchronized ( lifecycleState ) { return lifecycleState . get ( ) ; } } } | Return the current state of the given object or LATENT if unknown | 80 | 13 |
32,059 | public String getKey ( Map < String , String > variableValues ) { StringBuilder key = new StringBuilder ( ) ; for ( ConfigurationKeyPart p : parts ) { if ( p . isVariable ( ) ) { String value = variableValues . get ( p . getValue ( ) ) ; if ( value == null ) { log . warn ( "No value found for variable: " + p . getValue ( ) ) ; value = "" ; } key . append ( value ) ; } else { key . append ( p . getValue ( ) ) ; } } return key . toString ( ) ; } | Return the final key applying variables as needed | 127 | 8 |
32,060 | public Collection < String > getVariableNames ( ) { ImmutableSet . Builder < String > builder = ImmutableSet . builder ( ) ; for ( ConfigurationKeyPart p : parts ) { if ( p . isVariable ( ) ) { builder . add ( p . getValue ( ) ) ; } } return builder . build ( ) ; } | Return the names of the variables specified in the key if any | 71 | 12 |
32,061 | public Injector createChildInjector ( Collection < Module > modules ) { Injector childInjector ; Collection < Module > localModules = modules ; for ( ModuleTransformer transformer : transformers ) { localModules = transformer . call ( localModules ) ; } //noinspection deprecation if ( mode == LifecycleInjectorMode . REAL_CHILD_INJECTORS ) { childInjector = injector . createChildInjector ( localModules ) ; } else { childInjector = createSimulatedChildInjector ( localModules ) ; } for ( PostInjectorAction action : actions ) { action . call ( childInjector ) ; } return childInjector ; } | Create an injector that is a child of the bootstrap bindings only | 159 | 14 |
32,062 | public Injector createInjector ( Collection < Module > additionalModules ) { List < Module > localModules = Lists . newArrayList ( ) ; // Add the discovered modules FIRST. The discovered modules // are added, and will subsequently be configured, in module dependency // order which will ensure that any singletons bound in these modules // will be created in the same order as the bind() calls are made. // Note that the singleton ordering is only guaranteed for // singleton scope. //Add the LifecycleListener module localModules . add ( new LifecycleListenerModule ( ) ) ; localModules . add ( new AbstractModule ( ) { @ Override public void configure ( ) { if ( requireExplicitBindings ) { binder ( ) . requireExplicitBindings ( ) ; } } } ) ; if ( additionalModules != null ) { localModules . addAll ( additionalModules ) ; } localModules . addAll ( modules ) ; // Finally, add the AutoBind module, which will use classpath scanning // to creating singleton bindings. These singletons will be instantiated // in an indeterminate order but are guaranteed to occur AFTER singletons // bound in any of the discovered modules. if ( ! ignoreAllClasses ) { Collection < Class < ? > > localIgnoreClasses = Sets . newHashSet ( ignoreClasses ) ; localModules . add ( new InternalAutoBindModule ( injector , scanner , localIgnoreClasses ) ) ; } return createChildInjector ( localModules ) ; } | Create the main injector | 332 | 5 |
32,063 | public void stop ( ) { stopWrites ( ) ; stopReads ( ) ; if ( timerRef != null && timerRef . get ( ) != null ) { timerRef . get ( ) . shutdownNow ( ) ; timerRef . set ( null ) ; } ndBenchMonitor . resetStats ( ) ; } | FUNCTIONALITY FOR STOPPING THE WORKERS | 67 | 12 |
32,064 | public String nonPipelineRead ( String key ) throws Exception { String res = jedisClient . get ( ) . get ( key ) ; if ( res != null ) { if ( res . isEmpty ( ) ) { throw new Exception ( "Data retrieved is not ok " ) ; } } else { return CacheMiss ; } return ResultOK ; } | This is the non pipelined version of the reads | 75 | 11 |
32,065 | public String pipelineRead ( String key , int max_pipe_keys , int min_pipe_keys ) throws Exception { int pipe_keys = randomGenerator . nextInt ( max_pipe_keys ) ; pipe_keys = Math . max ( min_pipe_keys , pipe_keys ) ; DynoJedisPipeline pipeline = this . jedisClient . get ( ) . pipelined ( ) ; Map < String , Response < String > > responses = new HashMap <> ( ) ; for ( int n = 0 ; n < pipe_keys ; ++ n ) { String nth_key = key + "_" + n ; // NOTE: Dyno Jedis works on only one key, so we always use the same // key in every get operation Response < String > resp = pipeline . get ( key ) ; // We however use the nth key as the key in the hashmap to check // individual response on every operation. responses . put ( nth_key , resp ) ; } pipeline . sync ( ) ; for ( int n = 0 ; n < pipe_keys ; ++ n ) { String nth_key = key + "_" + n ; Response < String > resp = responses . get ( nth_key ) ; if ( resp == null || resp . get ( ) == null ) { logger . info ( "Cache Miss on pipelined read: key:" + key ) ; return null ; } else { if ( resp . get ( ) . startsWith ( "ERR" ) ) { throw new Exception ( String . format ( "DynoJedisPipeline: error %s" , resp . get ( ) ) ) ; } if ( ! isValidResponse ( key , resp . get ( ) ) ) { throw new Exception ( String . format ( "DynoJedisPipeline: pipeline read: value %s does not contain key %s" , resp . get ( ) , key ) ) ; } } } return "OK" ; } | This is the pipelined version of the reads | 426 | 10 |
32,066 | public String pipelineReadHGETALL ( String key , String hm_key_prefix ) throws Exception { DynoJedisPipeline pipeline = jedisClient . get ( ) . pipelined ( ) ; Response < Map < byte [ ] , byte [ ] > > resp = pipeline . hgetAll ( ( hm_key_prefix + key ) . getBytes ( ) ) ; pipeline . sync ( ) ; if ( resp == null || resp . get ( ) == null ) { logger . info ( "Cache Miss: key:" + key ) ; return null ; } else { StringBuilder sb = new StringBuilder ( ) ; for ( byte [ ] bytes : resp . get ( ) . keySet ( ) ) { if ( sb . length ( ) > 0 ) { sb . append ( "," ) ; } sb . append ( new String ( bytes ) ) ; } return "HGETALL:" + sb . toString ( ) ; } } | This the pipelined HGETALL | 208 | 8 |
32,067 | public String nonPipelineZRANGE ( String key , int max_score ) { StringBuilder sb = new StringBuilder ( ) ; // Return all elements Set < String > returnEntries = this . jedisClient . get ( ) . zrange ( key , 0 , - 1 ) ; if ( returnEntries . isEmpty ( ) ) { logger . error ( "The number of entries in the sorted set are less than the number of entries written" ) ; return null ; } returnEntries . forEach ( sb :: append ) ; return sb . toString ( ) ; } | Exercising ZRANGE to receive all keys between 0 and MAX_SCORE | 127 | 17 |
32,068 | public String nonpipelineWrite ( String key , DataGenerator dataGenerator ) { String value = key + "__" + dataGenerator . getRandomValue ( ) + "__" + key ; String result = this . jedisClient . get ( ) . set ( key , value ) ; if ( ! "OK" . equals ( result ) ) { logger . error ( "SET_ERROR: GOT " + result + " for SET operation" ) ; throw new RuntimeException ( String . format ( "DynoJedis: value %s for SET operation is NOT VALID" , value , key ) ) ; } return result ; } | a simple write without a pipeline | 139 | 6 |
32,069 | public String pipelineWrite ( String key , DataGenerator dataGenerator , int max_pipe_keys , int min_pipe_keys ) throws Exception { // Create a random key between [0,MAX_PIPE_KEYS] int pipe_keys = randomGenerator . nextInt ( max_pipe_keys ) ; // Make sure that the number of keys in the pipeline are at least // MIN_PIPE_KEYS pipe_keys = Math . max ( min_pipe_keys , pipe_keys ) ; DynoJedisPipeline pipeline = this . jedisClient . get ( ) . pipelined ( ) ; Map < String , Response < String > > responses = new HashMap <> ( ) ; /** * writeSingle returns a single string, so we want to create a * StringBuilder to append all the keys in the form "key_n". This is * just used to return a single string */ StringBuilder sb = new StringBuilder ( ) ; // Iterate across the number of keys in the pipeline and set for ( int n = 0 ; n < pipe_keys ; ++ n ) { String nth_key = key + "_" + n ; sb . append ( nth_key ) ; Response < String > resp = pipeline . set ( key , key + dataGenerator . getRandomValue ( ) + key ) ; responses . put ( nth_key , resp ) ; } pipeline . sync ( ) ; return sb . toString ( ) ; } | pipelined version of the write | 320 | 7 |
32,070 | public String pipelineWriteHMSET ( String key , DataGenerator dataGenerator , String hm_key_prefix ) { Map < String , String > map = new HashMap <> ( ) ; String hmKey = hm_key_prefix + key ; map . put ( ( hmKey + "__1" ) , ( key + "__" + dataGenerator . getRandomValue ( ) + "__" + key ) ) ; map . put ( ( hmKey + "__2" ) , ( key + "__" + dataGenerator . getRandomValue ( ) + "__" + key ) ) ; DynoJedisPipeline pipeline = jedisClient . get ( ) . pipelined ( ) ; pipeline . hmset ( hmKey , map ) ; pipeline . expire ( hmKey , 3600 ) ; pipeline . sync ( ) ; return "HMSET:" + hmKey ; } | writes with an pipelined HMSET | 205 | 9 |
32,071 | public String nonPipelineZADD ( String key , DataGenerator dataGenerator , String z_key_prefix , int max_score ) throws Exception { String zKey = z_key_prefix + key ; int success = 0 ; long returnOp = 0 ; for ( int i = 0 ; i < max_score ; i ++ ) { returnOp = jedisClient . get ( ) . zadd ( zKey , i , dataGenerator . getRandomValue ( ) + "__" + zKey ) ; success += returnOp ; } // all the above operations will separate entries if ( success != max_score - 1 ) { return null ; } return "OK" ; } | This adds MAX_SCORE of elements in a sorted set | 147 | 12 |
32,072 | public static String humanReadableByteCount ( final long bytes ) { final int base = 1024 ; // When using the smallest unit no decimal point is needed, because it's the exact number. if ( bytes < base ) { return bytes + " " + BINARY_UNITS [ 0 ] ; } final int exponent = ( int ) ( Math . log ( bytes ) / Math . log ( base ) ) ; final String unit = BINARY_UNITS [ exponent ] ; return String . format ( "%.1f %s" , bytes / Math . pow ( base , exponent ) , unit ) ; } | FileUtils . byteCountToDisplaySize rounds down the size hence using this for more precision . | 128 | 20 |
32,073 | static String constructIndexName ( String indexName , int indexRollsPerDay , Date date ) { if ( indexRollsPerDay > 0 ) { ZonedDateTime zdt = ZonedDateTime . ofInstant ( date . toInstant ( ) , ZoneId . of ( "UTC" ) ) ; int minutesPerRoll = 1440 / indexRollsPerDay ; int minutesElapsedSinceStartOfDay = zdt . getHour ( ) * 60 + zdt . getMinute ( ) ; int nthRoll = minutesElapsedSinceStartOfDay / minutesPerRoll ; String retval = String . format ( "%s-%s.%04d" , indexName , zdt . format ( DateTimeFormatter . ofPattern ( "yyyy-MM-dd" ) ) , nthRoll ) ; logger . debug ( "constructIndexName from rolls per day = {} gives: {}" , indexRollsPerDay , retval ) ; return retval ; } else { return indexName ; } } | methods below are package scoped to facilitate unit testing | 216 | 11 |
32,074 | public List < String > readBulk ( final List < String > keys ) throws Exception { List < String > responses = new ArrayList <> ( keys . size ( ) ) ; JanusGraphTransaction transaction = useJanusgraphTransaction ? graph . newTransaction ( ) : null ; try { for ( String key : keys ) { String response = readSingleInternal ( key , transaction ) ; responses . add ( response ) ; } } finally { if ( transaction != null ) transaction . close ( ) ; } return responses ; } | Perform a bulk read operation | 109 | 6 |
32,075 | public List < String > writeBulk ( final List < String > keys ) throws Exception { List < String > responses = new ArrayList <> ( keys . size ( ) ) ; for ( String key : keys ) { String response = writeSingle ( key ) ; responses . add ( response ) ; } return responses ; } | Perform a bulk write operation | 67 | 6 |
32,076 | public String getNDelimitedStrings ( int n ) { return IntStream . range ( 0 , config . getColsPerRow ( ) ) . mapToObj ( i -> "'" + dataGenerator . getRandomValue ( ) + "'" ) . collect ( Collectors . joining ( "," ) ) ; } | Assumes delimiter to be comma since that covers all the usecase for now . Will parameterize if use cases differ on delimiter . | 69 | 28 |
32,077 | protected void doBindView ( View itemView , Context context , Cursor cursor ) { try { @ SuppressWarnings ( "unchecked" ) ViewType itemViewType = ( ViewType ) itemView ; bindView ( itemViewType , context , cursorToObject ( cursor ) ) ; } catch ( SQLException e ) { throw new RuntimeException ( e ) ; } } | This is here to make sure that the user really wants to override it . | 82 | 15 |
32,078 | public T getTypedItem ( int position ) { try { return cursorToObject ( ( Cursor ) super . getItem ( position ) ) ; } catch ( SQLException e ) { throw new RuntimeException ( e ) ; } } | Returns a T object at the current position . | 51 | 9 |
32,079 | protected T cursorToObject ( Cursor cursor ) throws SQLException { return preparedQuery . mapRow ( new AndroidDatabaseResults ( cursor , null , true ) ) ; } | Map a single row to our cursor object . | 37 | 9 |
32,080 | public void changeCursor ( Cursor cursor , PreparedQuery < T > preparedQuery ) { setPreparedQuery ( preparedQuery ) ; super . changeCursor ( cursor ) ; } | Change the cursor associated with the prepared query . | 39 | 9 |
32,081 | static int execSql ( SQLiteDatabase db , String label , String finalSql , Object [ ] argArray ) throws SQLException { try { db . execSQL ( finalSql , argArray ) ; } catch ( android . database . SQLException e ) { throw SqlExceptionUtil . create ( "Problems executing " + label + " Android statement: " + finalSql , e ) ; } int result ; SQLiteStatement stmt = null ; try { // ask sqlite how many rows were just changed stmt = db . compileStatement ( "SELECT CHANGES()" ) ; result = ( int ) stmt . simpleQueryForLong ( ) ; } catch ( android . database . SQLException e ) { // ignore the exception and just return 1 if it failed result = 1 ; } finally { if ( stmt != null ) { stmt . close ( ) ; } } logger . trace ( "executing statement {} changed {} rows: {}" , label , result , finalSql ) ; return result ; } | Execute some SQL on the database and return the number of rows changed . | 224 | 15 |
32,082 | public static void writeConfigFile ( String fileName , boolean sortClasses ) throws SQLException , IOException { List < Class < ? > > classList = new ArrayList < Class < ? > > ( ) ; findAnnotatedClasses ( classList , new File ( "." ) , 0 ) ; writeConfigFile ( fileName , classList . toArray ( new Class [ classList . size ( ) ] ) , sortClasses ) ; } | Finds the annotated classes in the current directory or below and writes a configuration file to the file - name in the raw folder . | 98 | 27 |
32,083 | public static void writeConfigFile ( File configFile , boolean sortClasses ) throws SQLException , IOException { writeConfigFile ( configFile , new File ( "." ) , sortClasses ) ; } | Finds the annotated classes in the current directory or below and writes a configuration file . | 45 | 18 |
32,084 | protected static File findRawDir ( File dir ) { for ( int i = 0 ; dir != null && i < 20 ; i ++ ) { File rawDir = findResRawDir ( dir ) ; if ( rawDir != null ) { return rawDir ; } dir = dir . getParentFile ( ) ; } return null ; } | Look for the resource - directory in the current directory or the directories above . Then look for the raw - directory underneath the resource - directory . | 70 | 28 |
32,085 | private static String getPackageOfClass ( File file ) throws IOException { BufferedReader reader = new BufferedReader ( new FileReader ( file ) ) ; try { while ( true ) { String line = reader . readLine ( ) ; if ( line == null ) { return null ; } if ( line . contains ( "package" ) ) { String [ ] parts = line . split ( "[ \t;]" ) ; if ( parts . length > 1 && parts [ 0 ] . equals ( "package" ) ) { return parts [ 1 ] ; } } } } finally { reader . close ( ) ; } } | Returns the package name of a file that has one of the annotations we are looking for . | 130 | 18 |
32,086 | private static File findResRawDir ( File dir ) { for ( File file : dir . listFiles ( ) ) { if ( file . getName ( ) . equals ( RESOURCE_DIR_NAME ) && file . isDirectory ( ) ) { File [ ] rawFiles = file . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File file ) { return file . getName ( ) . equals ( RAW_DIR_NAME ) && file . isDirectory ( ) ; } } ) ; if ( rawFiles . length == 1 ) { return rawFiles [ 0 ] ; } } } return null ; } | Look for the resource directory with raw beneath it . | 132 | 10 |
32,087 | private static void innerSetHelperClass ( Class < ? extends OrmLiteSqliteOpenHelper > openHelperClass ) { // make sure if that there are not 2 helper classes in an application if ( openHelperClass == null ) { throw new IllegalStateException ( "Helper class was trying to be reset to null" ) ; } else if ( helperClass == null ) { helperClass = openHelperClass ; } else if ( helperClass != openHelperClass ) { throw new IllegalStateException ( "Helper class was " + helperClass + " but is trying to be reset to " + openHelperClass ) ; } } | Set the helper class and make sure we aren t changing it to another class . | 129 | 16 |
32,088 | private static OrmLiteSqliteOpenHelper constructHelper ( Context context , Class < ? extends OrmLiteSqliteOpenHelper > openHelperClass ) { Constructor < ? > constructor ; try { constructor = openHelperClass . getConstructor ( Context . class ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Could not find public constructor that has a single (Context) argument for helper class " + openHelperClass , e ) ; } try { return ( OrmLiteSqliteOpenHelper ) constructor . newInstance ( context ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Could not construct instance of helper class " + openHelperClass , e ) ; } } | Call the constructor on our helper class . | 151 | 8 |
32,089 | private static Class < ? extends OrmLiteSqliteOpenHelper > lookupHelperClass ( Context context , Class < ? > componentClass ) { // see if we have the magic resource class name set Resources resources = context . getResources ( ) ; int resourceId = resources . getIdentifier ( HELPER_CLASS_RESOURCE_NAME , "string" , context . getPackageName ( ) ) ; if ( resourceId != 0 ) { String className = resources . getString ( resourceId ) ; try { @ SuppressWarnings ( "unchecked" ) Class < ? extends OrmLiteSqliteOpenHelper > castClass = ( Class < ? extends OrmLiteSqliteOpenHelper > ) Class . forName ( className ) ; return castClass ; } catch ( Exception e ) { throw new IllegalStateException ( "Could not create helper instance for class " + className , e ) ; } } // try walking the context class to see if we can get the OrmLiteSqliteOpenHelper from a generic parameter for ( Class < ? > componentClassWalk = componentClass ; componentClassWalk != null ; componentClassWalk = componentClassWalk . getSuperclass ( ) ) { Type superType = componentClassWalk . getGenericSuperclass ( ) ; if ( superType == null || ! ( superType instanceof ParameterizedType ) ) { continue ; } // get the generic type arguments Type [ ] types = ( ( ParameterizedType ) superType ) . getActualTypeArguments ( ) ; // defense if ( types == null || types . length == 0 ) { continue ; } for ( Type type : types ) { // defense if ( ! ( type instanceof Class ) ) { continue ; } Class < ? > clazz = ( Class < ? > ) type ; if ( OrmLiteSqliteOpenHelper . class . isAssignableFrom ( clazz ) ) { @ SuppressWarnings ( "unchecked" ) Class < ? extends OrmLiteSqliteOpenHelper > castOpenHelperClass = ( Class < ? extends OrmLiteSqliteOpenHelper > ) clazz ; return castOpenHelperClass ; } } } throw new IllegalStateException ( "Could not find OpenHelperClass because none of the generic parameters of class " + componentClass + " extends OrmLiteSqliteOpenHelper. You should use getHelper(Context, Class) instead." ) ; } | Lookup the helper class either from the resource string or by looking for a generic parameter . | 512 | 18 |
32,090 | public static < T > DatabaseTableConfig < T > fromClass ( ConnectionSource connectionSource , Class < T > clazz ) throws SQLException { DatabaseType databaseType = connectionSource . getDatabaseType ( ) ; String tableName = DatabaseTableConfig . extractTableName ( databaseType , clazz ) ; List < DatabaseFieldConfig > fieldConfigs = new ArrayList < DatabaseFieldConfig > ( ) ; for ( Class < ? > classWalk = clazz ; classWalk != null ; classWalk = classWalk . getSuperclass ( ) ) { for ( Field field : classWalk . getDeclaredFields ( ) ) { DatabaseFieldConfig config = configFromField ( databaseType , tableName , field ) ; if ( config != null && config . isPersisted ( ) ) { fieldConfigs . add ( config ) ; } } } if ( fieldConfigs . size ( ) == 0 ) { return null ; } else { return new DatabaseTableConfig < T > ( clazz , tableName , fieldConfigs ) ; } } | Build our list table config from a class using some annotation fu around . | 219 | 14 |
32,091 | private static int [ ] lookupClasses ( ) { Class < ? > annotationMemberArrayClazz ; try { annotationFactoryClazz = Class . forName ( "org.apache.harmony.lang.annotation.AnnotationFactory" ) ; annotationMemberClazz = Class . forName ( "org.apache.harmony.lang.annotation.AnnotationMember" ) ; annotationMemberArrayClazz = Class . forName ( "[Lorg.apache.harmony.lang.annotation.AnnotationMember;" ) ; } catch ( ClassNotFoundException e ) { return null ; } Field fieldField ; try { elementsField = annotationFactoryClazz . getDeclaredField ( "elements" ) ; elementsField . setAccessible ( true ) ; nameField = annotationMemberClazz . getDeclaredField ( "name" ) ; nameField . setAccessible ( true ) ; valueField = annotationMemberClazz . getDeclaredField ( "value" ) ; valueField . setAccessible ( true ) ; fieldField = DatabaseFieldSample . class . getDeclaredField ( "field" ) ; } catch ( SecurityException e ) { return null ; } catch ( NoSuchFieldException e ) { return null ; } DatabaseField databaseField = fieldField . getAnnotation ( DatabaseField . class ) ; InvocationHandler proxy = Proxy . getInvocationHandler ( databaseField ) ; if ( proxy . getClass ( ) != annotationFactoryClazz ) { return null ; } try { // this should be an array of AnnotationMember objects Object elements = elementsField . get ( proxy ) ; if ( elements == null || elements . getClass ( ) != annotationMemberArrayClazz ) { return null ; } Object [ ] elementArray = ( Object [ ] ) elements ; int [ ] configNums = new int [ elementArray . length ] ; // build our array of field-numbers that match the AnnotationMember array for ( int i = 0 ; i < elementArray . length ; i ++ ) { String name = ( String ) nameField . get ( elementArray [ i ] ) ; configNums [ i ] = configFieldNameToNum ( name ) ; } return configNums ; } catch ( IllegalAccessException e ) { return null ; } } | This does all of the class reflection fu to find our classes find the order of field names and construct our array of ConfigField entries the correspond to the AnnotationMember array . | 479 | 35 |
32,092 | private static int configFieldNameToNum ( String configName ) { if ( configName . equals ( "columnName" ) ) { return COLUMN_NAME ; } else if ( configName . equals ( "dataType" ) ) { return DATA_TYPE ; } else if ( configName . equals ( "defaultValue" ) ) { return DEFAULT_VALUE ; } else if ( configName . equals ( "width" ) ) { return WIDTH ; } else if ( configName . equals ( "canBeNull" ) ) { return CAN_BE_NULL ; } else if ( configName . equals ( "id" ) ) { return ID ; } else if ( configName . equals ( "generatedId" ) ) { return GENERATED_ID ; } else if ( configName . equals ( "generatedIdSequence" ) ) { return GENERATED_ID_SEQUENCE ; } else if ( configName . equals ( "foreign" ) ) { return FOREIGN ; } else if ( configName . equals ( "useGetSet" ) ) { return USE_GET_SET ; } else if ( configName . equals ( "unknownEnumName" ) ) { return UNKNOWN_ENUM_NAME ; } else if ( configName . equals ( "throwIfNull" ) ) { return THROW_IF_NULL ; } else if ( configName . equals ( "persisted" ) ) { return PERSISTED ; } else if ( configName . equals ( "format" ) ) { return FORMAT ; } else if ( configName . equals ( "unique" ) ) { return UNIQUE ; } else if ( configName . equals ( "uniqueCombo" ) ) { return UNIQUE_COMBO ; } else if ( configName . equals ( "index" ) ) { return INDEX ; } else if ( configName . equals ( "uniqueIndex" ) ) { return UNIQUE_INDEX ; } else if ( configName . equals ( "indexName" ) ) { return INDEX_NAME ; } else if ( configName . equals ( "uniqueIndexName" ) ) { return UNIQUE_INDEX_NAME ; } else if ( configName . equals ( "foreignAutoRefresh" ) ) { return FOREIGN_AUTO_REFRESH ; } else if ( configName . equals ( "maxForeignAutoRefreshLevel" ) ) { return MAX_FOREIGN_AUTO_REFRESH_LEVEL ; } else if ( configName . equals ( "persisterClass" ) ) { return PERSISTER_CLASS ; } else if ( configName . equals ( "allowGeneratedIdInsert" ) ) { return ALLOW_GENERATED_ID_INSERT ; } else if ( configName . equals ( "columnDefinition" ) ) { return COLUMN_DEFINITON ; } else if ( configName . equals ( "fullColumnDefinition" ) ) { return FULL_COLUMN_DEFINITON ; } else if ( configName . equals ( "foreignAutoCreate" ) ) { return FOREIGN_AUTO_CREATE ; } else if ( configName . equals ( "version" ) ) { return VERSION ; } else if ( configName . equals ( "foreignColumnName" ) ) { return FOREIGN_COLUMN_NAME ; } else if ( configName . equals ( "readOnly" ) ) { return READ_ONLY ; } else { throw new IllegalStateException ( "Could not find support for DatabaseField " + configName ) ; } } | Convert the name of the | 765 | 6 |
32,093 | private static DatabaseFieldConfig buildConfig ( DatabaseField databaseField , String tableName , Field field ) throws Exception { InvocationHandler proxy = Proxy . getInvocationHandler ( databaseField ) ; if ( proxy . getClass ( ) != annotationFactoryClazz ) { return null ; } // this should be an array of AnnotationMember objects Object elementsObject = elementsField . get ( proxy ) ; if ( elementsObject == null ) { return null ; } DatabaseFieldConfig config = new DatabaseFieldConfig ( field . getName ( ) ) ; Object [ ] objs = ( Object [ ] ) elementsObject ; for ( int i = 0 ; i < configFieldNums . length ; i ++ ) { Object value = valueField . get ( objs [ i ] ) ; if ( value != null ) { assignConfigField ( configFieldNums [ i ] , config , field , value ) ; } } return config ; } | Instead of calling the annotation methods directly we peer inside the proxy and investigate the array of AnnotationMember objects stored by the AnnotationFactory . | 192 | 28 |
32,094 | public H getHelper ( ) { if ( helper == null ) { if ( ! created ) { throw new IllegalStateException ( "A call has not been made to onCreate() yet so the helper is null" ) ; } else if ( destroyed ) { throw new IllegalStateException ( "A call to onDestroy has already been made and the helper cannot be used after that point" ) ; } else { throw new IllegalStateException ( "Helper is null for some unknown reason" ) ; } } else { return helper ; } } | Get a helper for this action . | 110 | 7 |
32,095 | @ Override protected void onStartLoading ( ) { // XXX: do we really return the cached results _before_ checking if the content has changed? if ( cachedResults != null ) { deliverResult ( cachedResults ) ; } if ( takeContentChanged ( ) || cachedResults == null ) { forceLoad ( ) ; } // watch for data changes dao . registerObserver ( this ) ; } | Starts an asynchronous load of the data . When the result is ready the callbacks will be called on the UI thread . If a previous load has been completed and is still valid the result may be passed to the callbacks immediately . | 83 | 47 |
32,096 | private ResponseEntity < String > executeRequest ( final TelemetryEventData eventData ) { final HttpHeaders headers = new HttpHeaders ( ) ; headers . add ( HttpHeaders . CONTENT_TYPE , APPLICATION_JSON . toString ( ) ) ; try { final RestTemplate restTemplate = new RestTemplate ( ) ; final HttpEntity < String > body = new HttpEntity <> ( MAPPER . writeValueAsString ( eventData ) , headers ) ; return restTemplate . exchange ( TELEMETRY_TARGET_URL , HttpMethod . POST , body , String . class ) ; } catch ( JsonProcessingException | HttpClientErrorException ignore ) { log . warn ( "Failed to exchange telemetry request, {}." , ignore . getMessage ( ) ) ; } return null ; } | Align the retry times with sdk | 178 | 9 |
32,097 | @ Override public < S extends T > S save ( S entity ) { Assert . notNull ( entity , "entity must not be null" ) ; // save entity if ( information . isNew ( entity ) ) { return operation . insert ( information . getCollectionName ( ) , entity , createKey ( information . getPartitionKeyFieldValue ( entity ) ) ) ; } else { operation . upsert ( information . getCollectionName ( ) , entity , createKey ( information . getPartitionKeyFieldValue ( entity ) ) ) ; } return entity ; } | save entity without partition | 119 | 4 |
32,098 | @ Override public < S extends T > Iterable < S > saveAll ( Iterable < S > entities ) { Assert . notNull ( entities , "Iterable entities should not be null" ) ; entities . forEach ( this :: save ) ; return entities ; } | batch save entities | 58 | 3 |
32,099 | @ Override public Iterable < T > findAll ( ) { return operation . findAll ( information . getCollectionName ( ) , information . getJavaType ( ) ) ; } | find all entities from one collection without configuring partition key value | 38 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.