signature
stringlengths 43
39.1k
| implementation
stringlengths 0
450k
|
|---|---|
public class Params { /** * Retrieve a param given its identifier . Callers are expected to know the
* exact type of parameter that will be returned . Such assumption is
* possible because as indicated in { @ link Param } implementations will
* only come from Infinispan itself . */
@ SuppressWarnings ( "unchecked" ) public < T > Param < T > get ( int index ) { } }
|
// TODO : Provide a more type safe API . E . g . make index a pojo typed on T which is aligned with the Param < T >
return ( Param < T > ) params [ index ] ;
|
public class AbstractDoclet { /** * Verify that the only doclet that is using this toolkit is
* { @ value # TOOLKIT _ DOCLET _ NAME } . */
private boolean isValidDoclet ( ) { } }
|
if ( ! getClass ( ) . getName ( ) . equals ( TOOLKIT_DOCLET_NAME ) ) { configuration . message . error ( "doclet.Toolkit_Usage_Violation" , TOOLKIT_DOCLET_NAME ) ; return false ; } return true ;
|
public class ConciseSet { /** * { @ inheritDoc } */
public boolean remove ( int o ) { } }
|
if ( isEmpty ( ) ) { return false ; } // the element cannot exist
if ( o > last ) { return false ; } // check if the element can be removed from a literal word
int blockIndex = maxLiteralLengthDivision ( o ) ; int bitPosition = maxLiteralLengthModulus ( o ) ; for ( int i = 0 ; i <= lastWordIndex && blockIndex >= 0 ; i ++ ) { final int w = words [ i ] ; if ( isLiteral ( w ) ) { // check if the current literal word is the " right " one
if ( blockIndex == 0 ) { // the bit is already unset
if ( ( w & ( 1 << bitPosition ) ) == 0 ) { return false ; } // By removing the bit we potentially create a sequence :
// - - If the literal is made up of all ones , it definitely
// cannot be part of a sequence ( otherwise it would not have
// been created ) . Thus , we can create a 30 - bit literal word
// - - If there are 2 set bits , by removing the specified
// one we potentially allow for a 1 ' s sequence together with
// the successive word
// - - If there is 1 set bit , by removing the new one we
// potentially allow for a 0 ' s sequence
// together with the successive and / or the preceding words
if ( ! simulateWAH ) { int bitCount = getLiteralBitCount ( w ) ; if ( bitCount <= 2 ) { break ; } } else { final int l = getLiteralBits ( w ) ; if ( l == 0 || containsOnlyOneBit ( l ) ) { break ; } } // unset the bit
words [ i ] &= ~ ( 1 << bitPosition ) ; if ( size >= 0 ) { size -- ; } // if the bit is the maximal element , update it
if ( o == last ) { last -= maxLiteralLengthModulus ( last ) - ( ConciseSetUtils . MAX_LITERAL_LENGTH - Integer . numberOfLeadingZeros ( getLiteralBits ( words [ i ] ) ) ) ; } return true ; } blockIndex -- ; } else { if ( simulateWAH ) { if ( isZeroSequence ( w ) && blockIndex <= getSequenceCount ( w ) ) { return false ; } } else { // if we are at the beginning of a sequence , and it is
// an unset bit , the bit does not exist
if ( blockIndex == 0 && ( getLiteral ( w ) & ( 1 << bitPosition ) ) == 0 ) { return false ; } // if we are in the middle of a sequence of 0 ' s , the bit does not exist
if ( blockIndex > 0 && blockIndex <= getSequenceCount ( w ) && isZeroSequence ( w ) ) { return false ; } } // next word
blockIndex -= getSequenceCount ( w ) + 1 ; } } // the bit is in the middle of a sequence or it may cause a literal to
// become a sequence , thus the " easiest " way to remove it by ANDNOTing
return replaceWith ( performOperation ( convert ( o ) , Operator . ANDNOT ) ) ;
|
public class DerValue { /** * Returns a DER - encoded value , such that if it ' s passed to the
* DerValue constructor , a value equivalent to " this " is returned .
* @ return DER - encoded value , including tag and length . */
public byte [ ] toByteArray ( ) throws IOException { } }
|
DerOutputStream out = new DerOutputStream ( ) ; encode ( out ) ; data . reset ( ) ; return out . toByteArray ( ) ;
|
public class WsLocationAdminImpl { /** * { @ inheritDoc } */
@ Override public String printLocations ( boolean formatOutput ) { } }
|
StringBuilder sb = new StringBuilder ( ) ; if ( formatOutput ) { java . util . Formatter f = new java . util . Formatter ( ) ; f . format ( "%26s: %s%n" , "Install root" , installRoot . getNormalizedPath ( ) ) ; f . format ( "%26s: %s%n" , "System libraries" , bootstrapLib . getNormalizedPath ( ) ) ; f . format ( "%26s: %s%n" , "User root" , userRoot . getNormalizedPath ( ) ) ; f . format ( "%26s: %s%n" , "Server config" , serverConfigDir . getNormalizedPath ( ) ) ; f . format ( "%26s: %s%n" , "Server output" , serverOutputDir . getNormalizedPath ( ) ) ; sb . append ( f . toString ( ) ) ; } else { sb . append ( "installRoot=" ) . append ( installRoot . getNormalizedPath ( ) ) . append ( "," ) ; sb . append ( "bootstrapLib=" ) . append ( bootstrapLib . getNormalizedPath ( ) ) . append ( "," ) ; sb . append ( "userRoot=" ) . append ( userRoot . getNormalizedPath ( ) ) . append ( "," ) ; sb . append ( "serverConfigDir=" ) . append ( serverConfigDir . getNormalizedPath ( ) ) . append ( "," ) ; sb . append ( "serverOutputDir=" ) . append ( serverOutputDir . getNormalizedPath ( ) ) . append ( "," ) ; } return sb . toString ( ) ;
|
public class ResponseField { /** * Factory method for creating a Field instance representing { @ link Type # INT } .
* @ param responseName alias for the result of a field
* @ param fieldName name of the field in the GraphQL operation
* @ param arguments arguments to be passed along with the field
* @ param optional whether the arguments passed along are optional or required
* @ param conditions list of conditions for this field
* @ return Field instance representing { @ link Type # INT } */
public static ResponseField forInt ( String responseName , String fieldName , Map < String , Object > arguments , boolean optional , List < Condition > conditions ) { } }
|
return new ResponseField ( Type . INT , responseName , fieldName , arguments , optional , conditions ) ;
|
public class X509Utils { /** * Open a keystore . Store type is determined by file extension of name . If
* undetermined , JKS is assumed . The keystore does not need to exist .
* @ param storeFile
* @ param storePassword
* @ return a KeyStore */
public static KeyStore openKeyStore ( File storeFile , String storePassword ) { } }
|
String lc = storeFile . getName ( ) . toLowerCase ( ) ; String type = "JKS" ; String provider = null ; if ( lc . endsWith ( ".p12" ) || lc . endsWith ( ".pfx" ) ) { type = "PKCS12" ; provider = BC ; } try { KeyStore store ; if ( provider == null ) { store = KeyStore . getInstance ( type ) ; } else { store = KeyStore . getInstance ( type , provider ) ; } storeFile . getParentFile ( ) . mkdirs ( ) ; if ( storeFile . exists ( ) ) { FileInputStream fis = null ; try { fis = new FileInputStream ( storeFile ) ; store . load ( fis , storePassword . toCharArray ( ) ) ; } finally { if ( fis != null ) { fis . close ( ) ; } } } else { store . load ( null ) ; } return store ; } catch ( Exception e ) { throw new RuntimeException ( "Could not open keystore " + storeFile , e ) ; }
|
public class AbstractBuilder { /** * Creates a dot - separated string of the given parts .
* @ param parts A collections of parts .
* @ return a dot - separated string of the parts . */
protected String getPropertyPath ( Collection < String > parts ) { } }
|
StringBuilder propertyPath = new StringBuilder ( ) ; Iterator < String > partsIterator = parts . iterator ( ) ; propertyPath . append ( partsIterator . next ( ) ) ; while ( partsIterator . hasNext ( ) ) propertyPath . append ( "." ) . append ( partsIterator . next ( ) ) ; return propertyPath . toString ( ) ;
|
public class MapKeyLoader { /** * Notifies the record store of this map key loader that key loading has
* completed .
* @ param t an exception that occurred during key loading or { @ code null }
* if there was no exception */
private void updateLocalKeyLoadStatus ( Throwable t ) { } }
|
Operation op = new KeyLoadStatusOperation ( mapName , t ) ; // This updates the local record store on the partition thread .
// If invoked by the SENDER _ BACKUP however it ' s the replica index has to be set to 1 , otherwise
// it will be a remote call to the SENDER who is the owner of the given partitionId .
if ( hasBackup && role . is ( Role . SENDER_BACKUP ) ) { opService . createInvocationBuilder ( SERVICE_NAME , op , partitionId ) . setReplicaIndex ( 1 ) . invoke ( ) ; } else { opService . createInvocationBuilder ( SERVICE_NAME , op , partitionId ) . invoke ( ) ; }
|
public class ClasspathScanner { /** * Returns a list of the classes on the
* classpath . The names returned will
* be appropriate for using Class . forName ( String )
* in that the slashes will be changed to dots
* and the . class file extension will be removed . */
static String [ ] getClasspathClassNames ( ) throws ZipException , IOException { } }
|
final String [ ] classes = getClasspathFileNamesWithExtension ( ".class" ) ; for ( int i = 0 ; i < classes . length ; i ++ ) { classes [ i ] = classes [ i ] . substring ( 0 , classes [ i ] . length ( ) - 6 ) . replace ( "/" , "." ) ; } return classes ;
|
public class Plan { /** * register cache files in program level
* @ param filePath The files must be stored in a place that can be accessed from all workers ( most commonly HDFS )
* @ param name user defined name of that file
* @ throws java . io . IOException */
public void registerCachedFile ( String filePath , String name ) throws IOException { } }
|
if ( ! this . cacheFile . containsKey ( name ) ) { try { URI u = new URI ( filePath ) ; if ( ! u . getPath ( ) . startsWith ( "/" ) ) { u = new URI ( new File ( filePath ) . getAbsolutePath ( ) ) ; } FileSystem fs = FileSystem . get ( u ) ; if ( fs . exists ( new Path ( u . getPath ( ) ) ) ) { this . cacheFile . put ( name , u . toString ( ) ) ; } else { throw new RuntimeException ( "File " + u . toString ( ) + " doesn't exist." ) ; } } catch ( URISyntaxException ex ) { throw new RuntimeException ( "Invalid path: " + filePath , ex ) ; } } else { throw new RuntimeException ( "cache file " + name + "already exists!" ) ; }
|
public class JavacParser { /** * VariableDeclaratorRest = BracketsOpt [ " = " VariableInitializer ]
* ConstantDeclaratorRest = BracketsOpt " = " VariableInitializer
* @ param reqInit Is an initializer always required ?
* @ param dc The documentation comment for the variable declarations , or null . */
JCVariableDecl variableDeclaratorRest ( int pos , JCModifiers mods , JCExpression type , Name name , boolean reqInit , Comment dc ) { } }
|
type = bracketsOpt ( type ) ; JCExpression init = null ; if ( token . kind == EQ ) { nextToken ( ) ; init = variableInitializer ( ) ; } else if ( reqInit ) syntaxError ( token . pos , "expected" , EQ ) ; JCVariableDecl result = toP ( F . at ( pos ) . VarDef ( mods , name , type , init ) ) ; attach ( result , dc ) ; return result ;
|
public class PrecisionRecallCurve { /** * Get the binary confusion matrix for the given threshold . As per { @ link # getPointAtThreshold ( double ) } ,
* if the threshold is not found exactly , the next highest threshold exceeding the requested threshold
* is returned
* @ param threshold Threshold at which to get the confusion matrix
* @ return Binary confusion matrix */
public Confusion getConfusionMatrixAtThreshold ( double threshold ) { } }
|
Point p = getPointAtThreshold ( threshold ) ; int idx = p . idx ; int tn = totalCount - ( tpCount [ idx ] + fpCount [ idx ] + fnCount [ idx ] ) ; return new Confusion ( p , tpCount [ idx ] , fpCount [ idx ] , fnCount [ idx ] , tn ) ;
|
public class AbstractCandidateFactory { /** * { @ inheritDoc }
* If the number of seed candidates is less than the required population
* size , the remainder of the population will be generated randomly via
* the { @ link # generateRandomCandidate ( Random ) } method . */
public List < T > generateInitialPopulation ( int populationSize , Collection < T > seedCandidates , Random rng ) { } }
|
if ( seedCandidates . size ( ) > populationSize ) { throw new IllegalArgumentException ( "Too many seed candidates for specified population size." ) ; } List < T > population = new ArrayList < T > ( populationSize ) ; population . addAll ( seedCandidates ) ; for ( int i = seedCandidates . size ( ) ; i < populationSize ; i ++ ) { population . add ( generateRandomCandidate ( rng ) ) ; } return Collections . unmodifiableList ( population ) ;
|
public class Trie2Writable { /** * Find the start of the last range in the trie by enumerating backward .
* Indexes for supplementary code points higher than this will be omitted . */
private int findHighStart ( int highValue ) { } }
|
int value ; int c , prev ; int i1 , i2 , j , i2Block , prevI2Block , block , prevBlock ; /* set variables for previous range */
if ( highValue == initialValue ) { prevI2Block = index2NullOffset ; prevBlock = dataNullOffset ; } else { prevI2Block = - 1 ; prevBlock = - 1 ; } prev = 0x110000 ; /* enumerate index - 2 blocks */
i1 = UNEWTRIE2_INDEX_1_LENGTH ; c = prev ; while ( c > 0 ) { i2Block = index1 [ -- i1 ] ; if ( i2Block == prevI2Block ) { /* the index - 2 block is the same as the previous one , and filled with highValue */
c -= UTRIE2_CP_PER_INDEX_1_ENTRY ; continue ; } prevI2Block = i2Block ; if ( i2Block == index2NullOffset ) { /* this is the null index - 2 block */
if ( highValue != initialValue ) { return c ; } c -= UTRIE2_CP_PER_INDEX_1_ENTRY ; } else { /* enumerate data blocks for one index - 2 block */
for ( i2 = UTRIE2_INDEX_2_BLOCK_LENGTH ; i2 > 0 ; ) { block = index2 [ i2Block + -- i2 ] ; if ( block == prevBlock ) { /* the block is the same as the previous one , and filled with highValue */
c -= UTRIE2_DATA_BLOCK_LENGTH ; continue ; } prevBlock = block ; if ( block == dataNullOffset ) { /* this is the null data block */
if ( highValue != initialValue ) { return c ; } c -= UTRIE2_DATA_BLOCK_LENGTH ; } else { for ( j = UTRIE2_DATA_BLOCK_LENGTH ; j > 0 ; ) { value = data [ block + -- j ] ; if ( value != highValue ) { return c ; } -- c ; } } } } } /* deliver last range */
return 0 ;
|
public class StartDataCollectionByAgentIdsRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( StartDataCollectionByAgentIdsRequest startDataCollectionByAgentIdsRequest , ProtocolMarshaller protocolMarshaller ) { } }
|
if ( startDataCollectionByAgentIdsRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( startDataCollectionByAgentIdsRequest . getAgentIds ( ) , AGENTIDS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; }
|
public class ModelsImpl { /** * Gets information about the intent models .
* @ param appId The application ID .
* @ param versionId The version ID .
* @ param listIntentsOptionalParameter the object representing the optional parameters to be set before calling this API
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the List & lt ; IntentClassifier & gt ; object */
public Observable < List < IntentClassifier > > listIntentsAsync ( UUID appId , String versionId , ListIntentsOptionalParameter listIntentsOptionalParameter ) { } }
|
return listIntentsWithServiceResponseAsync ( appId , versionId , listIntentsOptionalParameter ) . map ( new Func1 < ServiceResponse < List < IntentClassifier > > , List < IntentClassifier > > ( ) { @ Override public List < IntentClassifier > call ( ServiceResponse < List < IntentClassifier > > response ) { return response . body ( ) ; } } ) ;
|
public class DerIndefLenConverter { /** * Converts a indefinite length DER encoded byte array to
* a definte length DER encoding .
* @ param indefData the byte array holding the indefinite
* length encoding .
* @ return the byte array containing the definite length
* DER encoding .
* @ exception IOException on parsing or re - writing errors . */
byte [ ] convert ( byte [ ] indefData ) throws IOException { } }
|
data = indefData ; dataPos = 0 ; index = 0 ; dataSize = data . length ; int len = 0 ; int unused = 0 ; // parse and set up the vectors of all the indefinite - lengths
while ( dataPos < dataSize ) { parseTag ( ) ; len = parseLength ( ) ; parseValue ( len ) ; if ( unresolved == 0 ) { unused = dataSize - dataPos ; dataSize = dataPos ; break ; } } if ( unresolved != 0 ) { throw new IOException ( "not all indef len BER resolved" ) ; } newData = new byte [ dataSize + numOfTotalLenBytes + unused ] ; dataPos = 0 ; newDataPos = 0 ; index = 0 ; // write out the new byte array replacing all the indefinite - lengths
// and EOCs
while ( dataPos < dataSize ) { writeTag ( ) ; writeLengthAndValue ( ) ; } System . arraycopy ( indefData , dataSize , newData , dataSize + numOfTotalLenBytes , unused ) ; return newData ;
|
public class WonderPushConfiguration { /** * Gets the WonderPush shared preferences for that application . */
static SharedPreferences getSharedPreferences ( ) { } }
|
if ( null == getApplicationContext ( ) ) return null ; SharedPreferences rtn = getApplicationContext ( ) . getSharedPreferences ( PREF_FILE , Context . MODE_PRIVATE ) ; if ( null == rtn ) { Log . e ( WonderPush . TAG , "Could not get shared preferences" , new NullPointerException ( "Stack" ) ) ; } return rtn ;
|
public class TwoDimensionalMesh { /** * Returns the neighbor of solution
* @ param solution Represents the location of the solution
* @ param neighbor Represents the neighbor we want to get as a shift of solution . The first component
* represents the shift on rows , and the second the shift on column
* @ return */
private int getNeighbor ( int solution , int [ ] neighbor ) { } }
|
int row = getRow ( solution ) ; int col = getColumn ( ( solution ) ) ; int r ; int c ; r = ( row + neighbor [ 0 ] ) % this . rows ; if ( r < 0 ) r = rows - 1 ; c = ( col + neighbor [ 1 ] ) % this . columns ; if ( c < 0 ) c = columns - 1 ; return this . mesh [ r ] [ c ] ;
|
public class BigramExtractor { /** * Returns the point - wise mutual information ( PMI ) score of the contingency
* table */
private double pmi ( int [ ] contingencyTable ) { } }
|
// Rename for short - hand convenience
int [ ] t = contingencyTable ; double probOfBigram = t [ 0 ] / ( double ) numBigramsInCorpus ; double probOfFirstTok = ( t [ 0 ] + t [ 2 ] ) / ( double ) numBigramsInCorpus ; double probOfSecondTok = ( t [ 0 ] + t [ 1 ] ) / ( double ) numBigramsInCorpus ; return probOfBigram / ( probOfFirstTok * probOfSecondTok ) ;
|
public class CheckBoxJList { /** * ListSelectionListener implementation */
public void valueChanged ( ListSelectionEvent lse ) { } }
|
if ( ! lse . getValueIsAdjusting ( ) ) { removeListSelectionListener ( this ) ; // remember everything selected as a result of this action
HashSet < Integer > newSelections = new HashSet < > ( ) ; int size = getModel ( ) . getSize ( ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( getSelectionModel ( ) . isSelectedIndex ( i ) ) { newSelections . add ( i ) ; } } // turn on everything that was previously selected
Iterator < Integer > it = selectionCache . iterator ( ) ; while ( it . hasNext ( ) ) { int index = it . next ( ) ; getSelectionModel ( ) . addSelectionInterval ( index , index ) ; } // add or remove the delta
it = newSelections . iterator ( ) ; while ( it . hasNext ( ) ) { Integer nextInt = it . next ( ) ; int index = nextInt ; if ( selectionCache . contains ( nextInt ) ) { getSelectionModel ( ) . removeSelectionInterval ( index , index ) ; } else { getSelectionModel ( ) . addSelectionInterval ( index , index ) ; } } // save selections for next time
selectionCache . clear ( ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( getSelectionModel ( ) . isSelectedIndex ( i ) ) { selectionCache . add ( i ) ; } } addListSelectionListener ( this ) ; }
|
public class RaftClusterContext { /** * Starts the join to the cluster . */
private synchronized CompletableFuture < Void > join ( ) { } }
|
joinFuture = new CompletableFuture < > ( ) ; raft . getThreadContext ( ) . execute ( ( ) -> { // Transition the server to the appropriate state for the local member type .
raft . transition ( member . getType ( ) ) ; // Attempt to join the cluster . If the local member is ACTIVE then failing to join the cluster
// will result in the member attempting to get elected . This allows initial clusters to form .
List < RaftMemberContext > activeMembers = getActiveMemberStates ( ) ; if ( ! activeMembers . isEmpty ( ) ) { join ( getActiveMemberStates ( ) . iterator ( ) ) ; } else { joinFuture . complete ( null ) ; } } ) ; return joinFuture . whenComplete ( ( result , error ) -> joinFuture = null ) ;
|
public class VirtualMachineHandler { /** * Detach from the virtual machine
* @ param pVm the virtual machine to detach from */
public void detachAgent ( Object pVm ) { } }
|
try { if ( pVm != null ) { Class clazz = pVm . getClass ( ) ; Method method = clazz . getMethod ( "detach" ) ; method . setAccessible ( true ) ; // on J9 you get IllegalAccessException otherwise .
method . invoke ( pVm ) ; } } catch ( InvocationTargetException e ) { throw new ProcessingException ( "Error while detaching" , e , options ) ; } catch ( NoSuchMethodException e ) { throw new ProcessingException ( "Error while detaching" , e , options ) ; } catch ( IllegalAccessException e ) { throw new ProcessingException ( "Error while detaching" , e , options ) ; }
|
import java . util . Arrays ; class VerifyNone { /** * A function to verify whether an array contains any ' null ' value .
* Examples :
* verifyNone ( new Object [ ] { 10 , 4 , 5 , 6 , null } ) - > True
* verifyNone ( new Object [ ] { 7 , 8 , 9 , 11 , 14 } ) - > False
* verifyNone ( new Object [ ] { 1 , 2 , 3 , 4 , null } ) - > True
* @ param elements : Array of one or more elements of any type
* @ return : Returns True if array contains any ' null ' value , otherwise False */
public static Boolean verifyNone ( Object [ ] elements ) { } }
|
return Arrays . stream ( elements ) . anyMatch ( x -> x == null ) ;
|
public class LinkListPanel { /** * { @ inheritDoc } */
@ Override protected Component newListComponent ( final String id , final ListItem < LinkItem > item ) { } }
|
final LinkItem model = item . getModelObject ( ) ; final Label itemLinkLabel = newItemLinkLabel ( "itemLinkLabel" , model ) ; final AbstractLink link = newAbstractLink ( id , model ) ; link . add ( itemLinkLabel ) ; return link ;
|
public class DefaultDecoder { /** * Create a bitmap from an input stream .
* @ param inputStream the InputStream
* @ param options the { @ link android . graphics . BitmapFactory . Options } used to decode the stream
* @ param regionToDecode optional image region to decode or null to decode the whole image
* @ param colorSpace the target color space of the decoded bitmap , must be one of the named color
* space in { @ link android . graphics . ColorSpace . Named } . If null , then SRGB color space is
* assumed if the SDK version > = 26.
* @ return the bitmap */
private CloseableReference < Bitmap > decodeFromStream ( InputStream inputStream , BitmapFactory . Options options , @ Nullable Rect regionToDecode , @ Nullable final ColorSpace colorSpace ) { } }
|
Preconditions . checkNotNull ( inputStream ) ; int targetWidth = options . outWidth ; int targetHeight = options . outHeight ; if ( regionToDecode != null ) { targetWidth = regionToDecode . width ( ) / options . inSampleSize ; targetHeight = regionToDecode . height ( ) / options . inSampleSize ; } @ Nullable Bitmap bitmapToReuse = null ; boolean shouldUseHardwareBitmapConfig = false ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . O ) { shouldUseHardwareBitmapConfig = mPreverificationHelper != null && mPreverificationHelper . shouldUseHardwareBitmapConfig ( options . inPreferredConfig ) ; } if ( regionToDecode == null && shouldUseHardwareBitmapConfig ) { // Cannot reuse bitmaps with Bitmap . Config . HARDWARE
options . inMutable = false ; } else { if ( regionToDecode != null && shouldUseHardwareBitmapConfig ) { // If region decoding was requested we need to fallback to default config
options . inPreferredConfig = Bitmap . Config . ARGB_8888 ; } final int sizeInBytes = getBitmapSize ( targetWidth , targetHeight , options ) ; bitmapToReuse = mBitmapPool . get ( sizeInBytes ) ; if ( bitmapToReuse == null ) { throw new NullPointerException ( "BitmapPool.get returned null" ) ; } } // inBitmap can be nullable
// noinspection ConstantConditions
options . inBitmap = bitmapToReuse ; // Performs transformation at load time to target color space .
if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . O ) { options . inPreferredColorSpace = colorSpace == null ? ColorSpace . get ( ColorSpace . Named . SRGB ) : colorSpace ; } Bitmap decodedBitmap = null ; ByteBuffer byteBuffer = mDecodeBuffers . acquire ( ) ; if ( byteBuffer == null ) { byteBuffer = ByteBuffer . allocate ( DECODE_BUFFER_SIZE ) ; } try { options . inTempStorage = byteBuffer . array ( ) ; if ( regionToDecode != null && bitmapToReuse != null ) { BitmapRegionDecoder bitmapRegionDecoder = null ; try { bitmapToReuse . reconfigure ( targetWidth , targetHeight , options . inPreferredConfig ) ; bitmapRegionDecoder = BitmapRegionDecoder . newInstance ( inputStream , true ) ; decodedBitmap = bitmapRegionDecoder . decodeRegion ( regionToDecode , options ) ; } catch ( IOException e ) { FLog . e ( TAG , "Could not decode region %s, decoding full bitmap instead." , regionToDecode ) ; } finally { if ( bitmapRegionDecoder != null ) { bitmapRegionDecoder . recycle ( ) ; } } } if ( decodedBitmap == null ) { decodedBitmap = BitmapFactory . decodeStream ( inputStream , null , options ) ; } } catch ( IllegalArgumentException e ) { if ( bitmapToReuse != null ) { mBitmapPool . release ( bitmapToReuse ) ; } // This is thrown if the Bitmap options are invalid , so let ' s just try to decode the bitmap
// as - is , which might be inefficient - but it works .
try { // We need to reset the stream first
inputStream . reset ( ) ; Bitmap naiveDecodedBitmap = BitmapFactory . decodeStream ( inputStream ) ; if ( naiveDecodedBitmap == null ) { throw e ; } return CloseableReference . of ( naiveDecodedBitmap , SimpleBitmapReleaser . getInstance ( ) ) ; } catch ( IOException re ) { // We throw the original exception instead since it ' s the one causing this workaround in the
// first place .
throw e ; } } catch ( RuntimeException re ) { if ( bitmapToReuse != null ) { mBitmapPool . release ( bitmapToReuse ) ; } throw re ; } finally { mDecodeBuffers . release ( byteBuffer ) ; } // If bitmap with Bitmap . Config . HARDWARE was used , ` bitmapToReuse ` will be null and it ' s
// expected
if ( bitmapToReuse != null && bitmapToReuse != decodedBitmap ) { mBitmapPool . release ( bitmapToReuse ) ; decodedBitmap . recycle ( ) ; throw new IllegalStateException ( ) ; } return CloseableReference . of ( decodedBitmap , mBitmapPool ) ;
|
import java . util . List ; class MinInRotatedArray { /** * A function in Java to determine the minimum element in a sorted array that has been rotated .
* For instance :
* > > > min _ in _ rotated _ array ( [ 1 , 2 , 3 , 4 , 5 ] , 0 , 4)
* > > > min _ in _ rotated _ array ( [ 4 , 6 , 8 ] , 0 , 2)
* > > > min _ in _ rotated _ array ( [ 2 , 3 , 5 , 7 , 9 ] , 0 , 4) */
public static int minInRotatedArray ( List < Integer > array , int start , int end ) { } }
|
while ( start < end ) { int center = start + ( end - start ) / 2 ; if ( array . get ( center ) . equals ( array . get ( end ) ) ) { end -= 1 ; } else if ( array . get ( center ) > array . get ( end ) ) { start = center + 1 ; } else { end = center ; } } return array . get ( end ) ;
|
public class SequenceGibbsSampler { /** * Samples the sequence repeatedly , making numSamples passes over the entire sequence .
* Destructively modifies the sequence in place . */
public void sampleSequenceRepeatedly ( SequenceModel model , int numSamples ) { } }
|
int [ ] sequence = getRandomSequence ( model ) ; sampleSequenceRepeatedly ( model , sequence , numSamples ) ;
|
public class EntityTemplate { /** * 批量操作
* @ param entities
* @ param batchType
* @ param batchSize */
protected void batchHandle ( Iterable < ? > entities , BatchType batchType , int batchSize ) { } }
|
Session session = getCurrentSession ( ) ; Iterator < ? > it = entities . iterator ( ) ; int count = 0 ; while ( it . hasNext ( ) ) { count ++ ; Object entity = it . next ( ) ; switch ( batchType ) { case SAVE : session . save ( entity ) ; break ; case UPDATE : session . update ( entity ) ; break ; case SAVE_OR_UPDATE : session . saveOrUpdate ( entity ) ; break ; case DELETE : session . delete ( entity ) ; break ; } if ( count % batchSize == 0 ) { session . flush ( ) ; session . clear ( ) ; } }
|
public class ParosTableScan { /** * / * ( non - Javadoc )
* @ see org . parosproxy . paros . db . paros . TableScan # read ( int ) */
@ Override public synchronized RecordScan read ( int scanId ) throws DatabaseException { } }
|
try { psRead . setInt ( 1 , scanId ) ; try ( ResultSet rs = psRead . executeQuery ( ) ) { RecordScan result = build ( rs ) ; return result ; } } catch ( SQLException e ) { throw new DatabaseException ( e ) ; }
|
public class HostProcess { /** * Skips the given { @ code plugin } with the given { @ code reason } .
* Ideally the { @ code reason } should be internationalised as it is shown in the GUI .
* @ param plugin the plugin that will be skipped , must not be { @ code null }
* @ param reason the reason why the plugin was skipped , might be { @ code null }
* @ since 2.6.0 */
public void pluginSkipped ( Plugin plugin , String reason ) { } }
|
if ( isStop ( ) ) { return ; } PluginStats pluginStats = mapPluginStats . get ( plugin . getId ( ) ) ; if ( pluginStats == null || pluginStats . isSkipped ( ) || pluginFactory . getCompleted ( ) . contains ( plugin ) ) { return ; } pluginStats . skip ( ) ; pluginStats . setSkippedReason ( reason ) ; for ( Plugin dependent : pluginFactory . getDependentPlugins ( plugin ) ) { pluginStats = mapPluginStats . get ( dependent . getId ( ) ) ; if ( pluginStats != null && ! pluginStats . isSkipped ( ) && ! pluginFactory . getCompleted ( ) . contains ( dependent ) ) { pluginStats . skip ( ) ; pluginStats . setSkippedReason ( Constant . messages . getString ( "ascan.progress.label.skipped.reason.dependency" ) ) ; } }
|
public class ReplicationUsagesInner { /** * Fetches the replication usages of the vault .
* @ param resourceGroupName The name of the resource group where the recovery services vault is present .
* @ param vaultName The name of the recovery services vault .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the List & lt ; ReplicationUsageInner & gt ; object */
public Observable < List < ReplicationUsageInner > > listAsync ( String resourceGroupName , String vaultName ) { } }
|
return listWithServiceResponseAsync ( resourceGroupName , vaultName ) . map ( new Func1 < ServiceResponse < List < ReplicationUsageInner > > , List < ReplicationUsageInner > > ( ) { @ Override public List < ReplicationUsageInner > call ( ServiceResponse < List < ReplicationUsageInner > > response ) { return response . body ( ) ; } } ) ;
|
public class Chronology { /** * Obtains an instance of { @ code Chronology } from a temporal object .
* A { @ code TemporalAccessor } represents some form of date and time information .
* This factory converts the arbitrary temporal object to an instance of { @ code Chronology } .
* If the specified temporal object does not have a chronology , { @ link IsoChronology } is returned .
* The conversion will obtain the chronology using { @ link TemporalQueries # chronology ( ) } .
* This method matches the signature of the functional interface { @ link TemporalQuery }
* allowing it to be used in queries via method reference , { @ code Chrono : : from } .
* @ param temporal the temporal to convert , not null
* @ return the chronology , not null
* @ throws DateTimeException if unable to convert to an { @ code Chronology } */
public static Chronology from ( TemporalAccessor temporal ) { } }
|
Jdk8Methods . requireNonNull ( temporal , "temporal" ) ; Chronology obj = temporal . query ( TemporalQueries . chronology ( ) ) ; return ( obj != null ? obj : IsoChronology . INSTANCE ) ;
|
public class AbstractItemLink { /** * Simple function to check if the item link state is
* in ItemLinkState . STATE _ LOCKED . Seperate function is
* created to acquire the lock
* @ return */
private synchronized final boolean isStateLocked ( ) { } }
|
if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) { SibTr . entry ( this , tc , "isStateLocked" ) ; SibTr . exit ( this , tc , "isStateLocked" , _itemLinkState ) ; } if ( _itemLinkState == ItemLinkState . STATE_LOCKED ) { return true ; } else { return false ; }
|
public class CmsPasswordForm { /** * Sets the password 2 error . < p >
* @ param error the error
* @ param style the style class */
public void setErrorPassword2 ( UserError error , String style ) { } }
|
m_passwordField2 . setComponentError ( error ) ; m_password2Style . setStyle ( style ) ;
|
public class PatternsImpl { /** * Deletes the pattern with the specified ID .
* @ param appId The application ID .
* @ param versionId The version ID .
* @ param patternId The pattern ID .
* @ param serviceCallback the async ServiceCallback to handle successful and failed responses .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceFuture } object */
public ServiceFuture < OperationStatus > deletePatternAsync ( UUID appId , String versionId , UUID patternId , final ServiceCallback < OperationStatus > serviceCallback ) { } }
|
return ServiceFuture . fromResponse ( deletePatternWithServiceResponseAsync ( appId , versionId , patternId ) , serviceCallback ) ;
|
public class ExtractorClientHandler { /** * ( non - Javadoc )
* @ see com . stratio . deep . rdd . IDeepRDD # getPartitions ( org . apache . spark . broadcast . Broadcast , int ) */
@ Override public Partition [ ] getPartitions ( ExtractorConfig < T > config ) { } }
|
GetPartitionsAction < T > getPartitionsAction = new GetPartitionsAction < > ( config ) ; channel . writeAndFlush ( getPartitionsAction ) ; Response response ; boolean interrupted = false ; for ( ; ; ) { try { response = answer . take ( ) ; break ; } catch ( InterruptedException ignore ) { interrupted = true ; } } if ( interrupted ) { Thread . currentThread ( ) . interrupt ( ) ; } return ( ( GetPartitionsResponse ) response ) . getPartitions ( ) ;
|
public class ObjectMapper { /** * Finds tables used in mappings and joins and adds them to the tables
* Hashtable , with the table name as key , and the join as value . */
private void tableJoins ( String pColumn , boolean pWhereJoin ) { } }
|
String join = null ; String table = null ; if ( pColumn == null ) { // Identity
join = getIdentityJoin ( ) ; table = getTable ( getProperty ( getPrimaryKey ( ) ) ) ; } else { // Normal
int dotIndex = - 1 ; if ( ( dotIndex = pColumn . lastIndexOf ( "." ) ) <= 0 ) { // No table qualifier
return ; } // Get table qualifier .
table = pColumn . substring ( 0 , dotIndex ) ; // Don ' t care about the tables that are not supposed to be selected from
String property = ( String ) getProperty ( pColumn ) ; if ( property != null ) { String mapType = ( String ) mMapTypes . get ( property ) ; if ( ! pWhereJoin && mapType != null && ! mapType . equals ( DIRECTMAP ) ) { return ; } join = ( String ) mJoins . get ( property ) ; } } // If table is not in the tables Hash , add it , and check for joins .
if ( mTables . get ( table ) == null ) { if ( join != null ) { mTables . put ( table , join ) ; StringTokenizer tok = new StringTokenizer ( join , "= " ) ; String next = null ; while ( tok . hasMoreElements ( ) ) { next = tok . nextToken ( ) ; // Don ' t care about SQL keywords
if ( next . equals ( "AND" ) || next . equals ( "OR" ) || next . equals ( "NOT" ) || next . equals ( "IN" ) ) { continue ; } // Check for new tables and joins in this join clause .
tableJoins ( next , false ) ; } } else { // No joins for this table .
join = "" ; mTables . put ( table , join ) ; } }
|
public class AbstractAPIGenerator { /** * Generates the API client files of the given API implementors .
* @ param implementors the API implementors , must not be { @ code null }
* @ throws IOException if an error occurred while writing the API files */
public void generateAPIFiles ( List < ApiImplementor > implementors ) throws IOException { } }
|
for ( ApiImplementor implementor : implementors ) { this . generateAPIFiles ( implementor ) ; }
|
public class SwingBindingFactory { /** * Binds the values specified in the collection contained within
* < code > selectableItems < / code > ( which will be wrapped in a
* { @ link ValueHolder } to a { @ link ShuttleList } , with any user selection
* being placed in the form property referred to by
* < code > selectionFormProperty < / code > . Each item in the list will be
* rendered as a String .
* Note that the selection in the bound list will track any changes to the
* < code > selectionFormProperty < / code > . This is especially useful to
* preselect items in the list - if < code > selectionFormProperty < / code > is
* not empty when the list is bound , then its content will be used for the
* initial selection .
* @ param selectionFormProperty form property to hold user ' s selection . This
* property must be a < code > Collection < / code > or array type .
* @ param selectableItems Collection or array containing the items with
* which to populate the selectable list ( this object will be wrapped
* in a ValueHolder ) .
* @ return constructed { @ link Binding } . Note that the bound control is of
* type { @ link ShuttleList } . Access this component to set specific
* display properties . */
public Binding createBoundShuttleList ( String selectionFormProperty , Object selectableItems ) { } }
|
return createBoundShuttleList ( selectionFormProperty , new ValueHolder ( selectableItems ) , null ) ;
|
public class DistributedCache { /** * Update the maps baseDirSize and baseDirNumberSubDir when deleting cache .
* @ param cacheStatus cache status of the cache is deleted */
private static void deleteCacheInfoUpdate ( CacheStatus cacheStatus ) { } }
|
if ( ! cacheStatus . isInited ( ) ) { // if it is not created yet , do nothing .
return ; } synchronized ( baseDirSize ) { Long dirSize = baseDirSize . get ( cacheStatus . getBaseDir ( ) ) ; if ( dirSize != null ) { dirSize -= cacheStatus . size ; baseDirSize . put ( cacheStatus . getBaseDir ( ) , dirSize ) ; } } synchronized ( baseDirNumberSubDir ) { Integer dirSubDir = baseDirNumberSubDir . get ( cacheStatus . getBaseDir ( ) ) ; if ( dirSubDir != null ) { dirSubDir -- ; baseDirNumberSubDir . put ( cacheStatus . getBaseDir ( ) , dirSubDir ) ; } }
|
public class TrainingsImpl { /** * Get images that were sent to your prediction endpoint .
* @ param projectId The project id
* @ param query Parameters used to query the predictions . Limited to combining 2 tags
* @ param serviceCallback the async ServiceCallback to handle successful and failed responses .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceFuture } object */
public ServiceFuture < PredictionQueryResult > queryPredictionsAsync ( UUID projectId , PredictionQueryToken query , final ServiceCallback < PredictionQueryResult > serviceCallback ) { } }
|
return ServiceFuture . fromResponse ( queryPredictionsWithServiceResponseAsync ( projectId , query ) , serviceCallback ) ;
|
public class CreatePlacementRequest { /** * Optional user - defined key / value pairs providing contextual data ( such as location or function ) for the placement .
* @ param attributes
* Optional user - defined key / value pairs providing contextual data ( such as location or function ) for the
* placement .
* @ return Returns a reference to this object so that method calls can be chained together . */
public CreatePlacementRequest withAttributes ( java . util . Map < String , String > attributes ) { } }
|
setAttributes ( attributes ) ; return this ;
|
public class CompatibilityRepositoryExporter { /** * Stores a RepositoryLogRecord into the proper text format
* @ param record RepositoryLogRecord which formatter will convert to Basic or Advanced output format */
public void storeRecord ( RepositoryLogRecord record ) { } }
|
if ( isClosed ) { throw new IllegalStateException ( "This instance of the exporter is already closed" ) ; } if ( ! isInitialized ) { throw new IllegalStateException ( "This instance of the exporter does not have header information yet" ) ; } String formatRecord = formatter . formatRecord ( record ) ; out . print ( formatRecord ) ; out . print ( formatter . getLineSeparator ( ) ) ;
|
public class DescribeReservedDBInstancesResult { /** * A list of reserved DB instances .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setReservedDBInstances ( java . util . Collection ) } or { @ link # withReservedDBInstances ( java . util . Collection ) }
* if you want to override the existing values .
* @ param reservedDBInstances
* A list of reserved DB instances .
* @ return Returns a reference to this object so that method calls can be chained together . */
public DescribeReservedDBInstancesResult withReservedDBInstances ( ReservedDBInstance ... reservedDBInstances ) { } }
|
if ( this . reservedDBInstances == null ) { setReservedDBInstances ( new com . amazonaws . internal . SdkInternalList < ReservedDBInstance > ( reservedDBInstances . length ) ) ; } for ( ReservedDBInstance ele : reservedDBInstances ) { this . reservedDBInstances . add ( ele ) ; } return this ;
|
import java . util . * ; class FindRightPosition { /** * Function to find the right place for insertion of a specific value maintaining sorted order .
* > > > find _ right _ position ( [ 1 , 2 , 4 , 5 ] , 6)
* > > > find _ right _ position ( [ 1 , 2 , 4 , 5 ] , 3)
* > > > find _ right _ position ( [ 1 , 2 , 4 , 5 ] , 7) */
public static int findRightPosition ( List < Integer > sortedList , int value ) { } }
|
int position = Collections . binarySearch ( sortedList , value ) ; if ( position < 0 ) { position = ( position * - 1 ) - 1 ; } else { while ( position < sortedList . size ( ) && sortedList . get ( position ) == value ) { position ++ ; } } return position ;
|
public class Frame { void write ( Writer out ) throws IOException { } }
|
out . write ( "<frame scrolling=\"" + scrolling + "\"" + resize + border ) ; if ( src != null ) out . write ( " src=\"" + src + "\"" ) ; if ( name != null ) out . write ( " name=\"" + name + "\"" ) ; out . write ( ">" ) ;
|
public class IntMath { /** * Returns the sum of { @ code a } and { @ code b } , provided it does not overflow .
* @ throws ArithmeticException if { @ code a + b } overflows in signed { @ code int } arithmetic */
public static int checkedAdd ( int a , int b ) { } }
|
long result = ( long ) a + b ; checkNoOverflow ( result == ( int ) result ) ; return ( int ) result ;
|
public class TableSlice { /** * Returns the result of applying the given function to the specified column
* @ param numberColumnName The name of a numeric column in this table
* @ param function A numeric reduce function
* @ return the function result
* @ throws IllegalArgumentException if numberColumnName doesn ' t name a numeric column in this table */
public double reduce ( String numberColumnName , NumericAggregateFunction function ) { } }
|
NumberColumn < ? > column = table . numberColumn ( numberColumnName ) ; return function . summarize ( column . where ( selection ) ) ;
|
public class NetUtil { /** * Registers the password from the URL string , and returns the URL object .
* @ param pURL the string representation of the URL , possibly including authorization part
* @ param pProperties the
* @ return the URL created from { @ code pURL } .
* @ throws java . net . MalformedURLException if there ' s a syntax error in { @ code pURL } */
private static URL getURLAndSetAuthorization ( final String pURL , final Properties pProperties ) throws MalformedURLException { } }
|
String url = pURL ; // Split user / password away from url
String userPass = null ; String protocolPrefix = HTTP ; int httpIdx = url . indexOf ( HTTPS ) ; if ( httpIdx >= 0 ) { protocolPrefix = HTTPS ; url = url . substring ( httpIdx + HTTPS . length ( ) ) ; } else { httpIdx = url . indexOf ( HTTP ) ; if ( httpIdx >= 0 ) { url = url . substring ( httpIdx + HTTP . length ( ) ) ; } } // Get authorization part
int atIdx = url . indexOf ( "@" ) ; if ( atIdx >= 0 ) { userPass = url . substring ( 0 , atIdx ) ; url = url . substring ( atIdx + 1 ) ; } // Set authorization if user / password is present
if ( userPass != null ) { // System . out . println ( " Setting password ( " + userPass + " ) ! " ) ;
pProperties . setProperty ( "Authorization" , "Basic " + BASE64 . encode ( userPass . getBytes ( ) ) ) ; } // Return URL
return new URL ( protocolPrefix + url ) ;
|
public class Indexer { /** * Index or reindex using the Indexdefinitions .
* @ throws EFapsException the e faps exception */
public static void index ( ) throws EFapsException { } }
|
final List < IndexDefinition > defs = IndexDefinition . get ( ) ; for ( final IndexDefinition def : defs ) { final QueryBuilder queryBldr = new QueryBuilder ( def . getUUID ( ) ) ; final InstanceQuery query = queryBldr . getQuery ( ) ; index ( query . execute ( ) ) ; }
|
public class SingleItemSketch { /** * Create this sketch with a long and a seed .
* @ param datum The given long datum .
* @ param seed used to hash the given value .
* @ return a SingleItemSketch */
public static SingleItemSketch create ( final long datum , final long seed ) { } }
|
final long [ ] data = { datum } ; return new SingleItemSketch ( hash ( data , seed ) [ 0 ] >>> 1 ) ;
|
import java . util . List ; import java . util . stream . Collectors ; class CommonElements { /** * The function identifies the common elements in two provided lists
* Examples :
* common _ elements ( [ 1 , 2 , 3 , 5 , 7 , 8 , 9 , 10 ] , [ 1 , 2 , 4 , 8 , 9 ] ) - > [ 1 , 2 , 8 , 9]
* common _ elements ( [ 1 , 2 , 3 , 5 , 7 , 8 , 9 , 10 ] , [ 3 , 5 , 7 , 9 ] ) - > [ 3 , 5 , 7 , 9]
* common _ elements ( [ 1 , 2 , 3 , 5 , 7 , 8 , 9 , 10 ] , [ 10 , 20 , 30 , 40 ] ) - > [ 10]
* @ param list1 : The first list of numbers .
* @ param list2 : The second list of numbers .
* @ return : Returns a list containing the common elements present
* in both input lists . */
public static List < Integer > commonElements ( List < Integer > list1 , List < Integer > list2 ) { } }
|
return list2 . stream ( ) . filter ( list1 :: contains ) . collect ( Collectors . toList ( ) ) ;
|
public class XSplitter { /** * Generate the split distribution for a given sorting of entry positions
* using the given split position < code > limit < / code > . All
* entries referenced by < code > entrySorting < / code > from < code > 0 < / code > to
* < code > limit - 1 < / code > are put into the first list ( < code > ret [ 0 ] < / code > ) , the
* other entries are put into the second list ( < code > ret [ 1 ] < / code > ) .
* @ param sorting this splitDistribution
* @ return the split distribution for the given sorting and split point */
@ SuppressWarnings ( "unchecked" ) private List < SpatialEntry > [ ] generateDistribution ( SplitSorting sorting ) { } }
|
List < SpatialEntry > [ ] distibution ; distibution = new List [ 2 ] ; distibution [ 0 ] = new ArrayList < > ( ) ; distibution [ 1 ] = new ArrayList < > ( ) ; List < SpatialEntry > sorted_entries = sorting . getSortedEntries ( ) ; for ( int i = 0 ; i < sorting . getSplitPoint ( ) ; i ++ ) { distibution [ 0 ] . add ( sorted_entries . get ( i ) ) ; } for ( int i = sorting . getSplitPoint ( ) ; i < node . getNumEntries ( ) ; i ++ ) { distibution [ 1 ] . add ( sorted_entries . get ( i ) ) ; } return distibution ;
|
public class DynamicOutputBuffer { /** * Writes all non - flushed internal buffers to the given channel .
* If { @ link # flushTo ( WritableByteChannel ) } has not been called
* before , this method writes the whole buffer to the channel .
* @ param out the channel to write to
* @ throws IOException if the buffer could not be written */
public void writeTo ( WritableByteChannel out ) throws IOException { } }
|
int n1 = _flushPosition / _bufferSize ; int n2 = _buffers . size ( ) ; int toWrite = _size - _flushPosition ; while ( n1 < n2 ) { int curWrite = Math . min ( toWrite , _bufferSize ) ; ByteBuffer bb = _buffers . get ( n1 ) ; bb . position ( curWrite ) ; bb . flip ( ) ; out . write ( bb ) ; ++ n1 ; toWrite -= curWrite ; }
|
public class StreamingSheetReader { /** * Tries to format the contents of the last contents appropriately based on
* the provided type and the discovered numeric format .
* @ return */
private Supplier getFormatterForType ( String type ) { } }
|
switch ( type ) { case "s" : // string stored in shared table
if ( ! lastContents . isEmpty ( ) ) { int idx = Integer . parseInt ( lastContents ) ; return new StringSupplier ( new XSSFRichTextString ( sst . getEntryAt ( idx ) ) . toString ( ) ) ; } return new StringSupplier ( lastContents ) ; case "inlineStr" : // inline string ( not in sst )
case "str" : return new StringSupplier ( new XSSFRichTextString ( lastContents ) . toString ( ) ) ; case "e" : // error type
return new StringSupplier ( "ERROR: " + lastContents ) ; case "n" : // numeric type
if ( currentCell . getNumericFormat ( ) != null && lastContents . length ( ) > 0 ) { // the formatRawCellContents operation incurs a significant overhead on large sheets ,
// and we want to defer the execution of this method until the value is actually needed .
// it is not needed in all cases . .
final String currentLastContents = lastContents ; final int currentNumericFormatIndex = currentCell . getNumericFormatIndex ( ) ; final String currentNumericFormat = currentCell . getNumericFormat ( ) ; return new Supplier ( ) { String cachedContent ; @ Override public Object getContent ( ) { if ( cachedContent == null ) { cachedContent = dataFormatter . formatRawCellContents ( Double . parseDouble ( currentLastContents ) , currentNumericFormatIndex , currentNumericFormat ) ; } return cachedContent ; } } ; } else { return new StringSupplier ( lastContents ) ; } default : return new StringSupplier ( lastContents ) ; }
|
public class CmsPrincipalSelect { /** * Sets the principal type and name . < p >
* @ param type the principal type
* @ param principalName the principal name */
protected void setPrincipal ( int type , String principalName ) { } }
|
m_principalName . setValue ( principalName ) ; String typeName = null ; switch ( type ) { case 0 : typeName = I_CmsPrincipal . PRINCIPAL_GROUP ; break ; case 1 : default : typeName = I_CmsPrincipal . PRINCIPAL_USER ; break ; } if ( typeName != null ) { m_principalTypeSelect . setValue ( typeName ) ; }
|
public class NIOFileUtil { /** * Merge the given part files in order into an output stream .
* This deletes the parts .
* @ param parts the part files to merge
* @ param out the stream to write each file into , in order
* @ throws IOException */
static void mergeInto ( List < Path > parts , OutputStream out ) throws IOException { } }
|
for ( final Path part : parts ) { Files . copy ( part , out ) ; Files . delete ( part ) ; }
|
public class Database { public void delete_class_property ( String name , DbDatum [ ] properties ) throws DevFailed { } }
|
databaseDAO . delete_class_property ( this , name , properties ) ;
|
public class BoneCPPoolAdapter { /** * { @ inheritDoc } */
@ Override protected boolean isAcquireTimeoutException ( Exception e ) { } }
|
return e . getMessage ( ) != null && ACQUIRE_TIMEOUT_MESSAGE . equals ( e . getMessage ( ) ) ;
|
public class CleverTapAPI { /** * Session */
private void _clearARP ( Context context ) { } }
|
final String nameSpaceKey = getNamespaceARPKey ( ) ; if ( nameSpaceKey == null ) return ; final SharedPreferences prefs = StorageHelper . getPreferences ( context , nameSpaceKey ) ; final SharedPreferences . Editor editor = prefs . edit ( ) ; editor . clear ( ) ; StorageHelper . persist ( editor ) ;
|
public class Applications { /** * Add the instance to the given map based if the vip address matches with
* that of the instance . Note that an instance can be mapped to multiple vip
* addresses . */
private void addInstanceToMap ( InstanceInfo info , String vipAddresses , Map < String , VipIndexSupport > vipMap ) { } }
|
if ( vipAddresses != null ) { String [ ] vipAddressArray = vipAddresses . toUpperCase ( Locale . ROOT ) . split ( "," ) ; for ( String vipAddress : vipAddressArray ) { VipIndexSupport vis = vipMap . computeIfAbsent ( vipAddress , k -> new VipIndexSupport ( ) ) ; vis . instances . add ( info ) ; } }
|
public class GraphL3Undirected { /** * Gets wrappers of given elements
* @ param objects Wrapped objects
* @ return wrappers */
public Set < Node > getWrapperSet ( Set < ? > objects ) { } }
|
Set < Node > wrapped = new HashSet < Node > ( ) ; for ( Object object : objects ) { Node node = ( Node ) getGraphObject ( object ) ; if ( node != null ) { wrapped . add ( node ) ; } } return wrapped ;
|
public class ProducerSequenceFactory { /** * post - processor producer - > copy producer - > inputProducer */
private synchronized Producer < CloseableReference < CloseableImage > > getPostprocessorSequence ( Producer < CloseableReference < CloseableImage > > inputProducer ) { } }
|
if ( ! mPostprocessorSequences . containsKey ( inputProducer ) ) { PostprocessorProducer postprocessorProducer = mProducerFactory . newPostprocessorProducer ( inputProducer ) ; PostprocessedBitmapMemoryCacheProducer postprocessedBitmapMemoryCacheProducer = mProducerFactory . newPostprocessorBitmapMemoryCacheProducer ( postprocessorProducer ) ; mPostprocessorSequences . put ( inputProducer , postprocessedBitmapMemoryCacheProducer ) ; } return mPostprocessorSequences . get ( inputProducer ) ;
|
public class FuncCeiling { /** * Execute the function . The function must return
* a valid object .
* @ param xctxt The current execution context .
* @ return A valid XObject .
* @ throws javax . xml . transform . TransformerException */
public XObject execute ( XPathContext xctxt ) throws javax . xml . transform . TransformerException { } }
|
return new XNumber ( Math . ceil ( m_arg0 . execute ( xctxt ) . num ( ) ) ) ;
|
public class BtcFormat { /** * Return a representation of the pattern used by this instance for formatting and
* parsing . The format is similar to , but not the same as the format recognized by the
* { @ link Builder # pattern } and { @ link Builder # localizedPattern } methods . The pattern
* returned by this method is localized , any currency signs expressed are literally , and
* optional fractional decimal places are shown grouped in parentheses . */
public String pattern ( ) { } }
|
synchronized ( numberFormat ) { StringBuilder groups = new StringBuilder ( ) ; for ( int group : decimalGroups ) { groups . append ( "(" ) . append ( Strings . repeat ( "#" , group ) ) . append ( ")" ) ; } DecimalFormatSymbols s = numberFormat . getDecimalFormatSymbols ( ) ; String digit = String . valueOf ( s . getDigit ( ) ) ; String exp = s . getExponentSeparator ( ) ; String groupSep = String . valueOf ( s . getGroupingSeparator ( ) ) ; String moneySep = String . valueOf ( s . getMonetaryDecimalSeparator ( ) ) ; String zero = String . valueOf ( s . getZeroDigit ( ) ) ; String boundary = String . valueOf ( s . getPatternSeparator ( ) ) ; String minus = String . valueOf ( s . getMinusSign ( ) ) ; String decSep = String . valueOf ( s . getDecimalSeparator ( ) ) ; String prefixAndNumber = "(^|" + boundary + ")" + "([^" + Matcher . quoteReplacement ( digit + zero + groupSep + decSep + moneySep ) + "']*('[^']*')?)*" + "[" + Matcher . quoteReplacement ( digit + zero + groupSep + decSep + moneySep + exp ) + "]+" ; return numberFormat . toLocalizedPattern ( ) . replaceAll ( prefixAndNumber , "$0" + groups . toString ( ) ) . replaceAll ( "¤¤" , Matcher . quoteReplacement ( coinCode ( ) ) ) . replaceAll ( "¤" , Matcher . quoteReplacement ( coinSymbol ( ) ) ) ; }
|
public class ImageInterleaved { /** * Sets this image equal to the specified image . Automatically resized to match the input image .
* @ param orig The original image whose value is to be copied into this one */
@ SuppressWarnings ( { } }
|
"SuspiciousSystemArraycopy" } ) @ Override public void setTo ( T orig ) { if ( orig . width != width || orig . height != height || orig . numBands != numBands ) reshape ( orig . width , orig . height , orig . numBands ) ; if ( ! orig . isSubimage ( ) && ! isSubimage ( ) ) { System . arraycopy ( orig . _getData ( ) , orig . startIndex , _getData ( ) , startIndex , stride * height ) ; } else { int indexSrc = orig . startIndex ; int indexDst = startIndex ; for ( int y = 0 ; y < height ; y ++ ) { System . arraycopy ( orig . _getData ( ) , indexSrc , _getData ( ) , indexDst , width * numBands ) ; indexSrc += orig . stride ; indexDst += stride ; } }
|
public class ServletUtils { /** * Print attributes in the given ServletContext .
* @ param context the current ServletContext .
* @ param output a PrintStream to which to output ServletContext attributes ; if < code > null < / null > ,
* < code > System . err < / code > is used . */
public static void dumpServletContext ( ServletContext context , PrintStream output ) { } }
|
if ( output == null ) { output = System . err ; } output . println ( "*** ServletContext " + context ) ; for ( Enumeration e = context . getAttributeNames ( ) ; e . hasMoreElements ( ) ; ) { String name = ( String ) e . nextElement ( ) ; output . println ( " attribute " + name + " = " + context . getAttribute ( name ) ) ; }
|
public class ResourceRegistryImpl { /** * Scans the classpath for resources .
* @ param packages
* @ throws Siren4JException */
@ SuppressWarnings ( "deprecation" ) private void init ( String ... packages ) throws Siren4JException { } }
|
LOG . info ( "Siren4J scanning classpath for resource entries..." ) ; Reflections reflections = null ; ConfigurationBuilder builder = new ConfigurationBuilder ( ) ; Collection < URL > urls = new HashSet < URL > ( ) ; if ( packages != null && packages . length > 0 ) { // limit scan to packages
for ( String pkg : packages ) { urls . addAll ( ClasspathHelper . forPackage ( pkg ) ) ; } } else { urls . addAll ( ClasspathHelper . forPackage ( "com." ) ) ; urls . addAll ( ClasspathHelper . forPackage ( "org." ) ) ; urls . addAll ( ClasspathHelper . forPackage ( "net." ) ) ; } // Always add Siren4J Resources by default , this will add the collection resource
// and what ever other resource gets added to this package and has the entity annotation .
urls . addAll ( ClasspathHelper . forPackage ( "com.google.code.siren4j.resource" ) ) ; builder . setUrls ( urls ) ; reflections = new Reflections ( builder ) ; Set < Class < ? > > types = reflections . getTypesAnnotatedWith ( Siren4JEntity . class ) ; for ( Class < ? > c : types ) { Siren4JEntity anno = c . getAnnotation ( Siren4JEntity . class ) ; String name = StringUtils . defaultIfBlank ( anno . name ( ) , anno . entityClass ( ) . length > 0 ? anno . entityClass ( ) [ 0 ] : c . getName ( ) ) ; putEntry ( StringUtils . defaultIfEmpty ( name , c . getName ( ) ) , c , false ) ; // Always add the class name as an entry in the index if it does not already exist .
if ( ! containsEntityEntry ( c . getName ( ) ) ) { putEntry ( StringUtils . defaultIfEmpty ( c . getName ( ) , c . getName ( ) ) , c , false ) ; } }
|
public class ErrorReportingServlet { /** * Any error that occurs during a < code > doPost < / code > is caught and reported here . */
@ Override final protected void doPost ( HttpServletRequest req , HttpServletResponse resp ) throws ServletException , IOException { } }
|
resp . setBufferSize ( BUFFER_SIZE ) ; postCount . incrementAndGet ( ) ; try { reportingDoPost ( req , resp ) ; } catch ( ThreadDeath t ) { throw t ; } catch ( RuntimeException | ServletException | IOException e ) { getLogger ( ) . log ( Level . SEVERE , null , e ) ; throw e ; } catch ( SQLException t ) { getLogger ( ) . log ( Level . SEVERE , null , t ) ; throw new ServletException ( t ) ; }
|
public class CopyFileExtensions { /** * Copies the given source file to the given destination directory .
* @ param source
* The source file to copy in the destination directory .
* @ param destinationDir
* The destination directory .
* @ return ' s true if the file is copied to the destination directory , otherwise false .
* @ throws FileIsNotADirectoryException
* Is thrown if the source file is not a directory .
* @ throws IOException
* Is thrown if an error occurs by reading or writing .
* @ throws FileIsADirectoryException
* Is thrown if the destination file is a directory . */
public static boolean copyFileToDirectory ( final File source , final File destinationDir ) throws FileIsNotADirectoryException , IOException , FileIsADirectoryException { } }
|
return copyFileToDirectory ( source , destinationDir , true ) ;
|
public class ManagePathUtils { /** * 返回对应的termin root path ( 不依赖对应的config信息 ) */
public static String getTerminRoot ( Long channelId , Long pipelineId ) { } }
|
// 根据channelId , pipelineId构造path
return MessageFormat . format ( ArbitrateConstants . NODE_TERMIN_ROOT , String . valueOf ( channelId ) , String . valueOf ( pipelineId ) ) ;
|
public class ReservedElasticsearchInstanceMarshaller { /** * Marshall the given parameter object . */
public void marshall ( ReservedElasticsearchInstance reservedElasticsearchInstance , ProtocolMarshaller protocolMarshaller ) { } }
|
if ( reservedElasticsearchInstance == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( reservedElasticsearchInstance . getReservationName ( ) , RESERVATIONNAME_BINDING ) ; protocolMarshaller . marshall ( reservedElasticsearchInstance . getReservedElasticsearchInstanceId ( ) , RESERVEDELASTICSEARCHINSTANCEID_BINDING ) ; protocolMarshaller . marshall ( reservedElasticsearchInstance . getReservedElasticsearchInstanceOfferingId ( ) , RESERVEDELASTICSEARCHINSTANCEOFFERINGID_BINDING ) ; protocolMarshaller . marshall ( reservedElasticsearchInstance . getElasticsearchInstanceType ( ) , ELASTICSEARCHINSTANCETYPE_BINDING ) ; protocolMarshaller . marshall ( reservedElasticsearchInstance . getStartTime ( ) , STARTTIME_BINDING ) ; protocolMarshaller . marshall ( reservedElasticsearchInstance . getDuration ( ) , DURATION_BINDING ) ; protocolMarshaller . marshall ( reservedElasticsearchInstance . getFixedPrice ( ) , FIXEDPRICE_BINDING ) ; protocolMarshaller . marshall ( reservedElasticsearchInstance . getUsagePrice ( ) , USAGEPRICE_BINDING ) ; protocolMarshaller . marshall ( reservedElasticsearchInstance . getCurrencyCode ( ) , CURRENCYCODE_BINDING ) ; protocolMarshaller . marshall ( reservedElasticsearchInstance . getElasticsearchInstanceCount ( ) , ELASTICSEARCHINSTANCECOUNT_BINDING ) ; protocolMarshaller . marshall ( reservedElasticsearchInstance . getState ( ) , STATE_BINDING ) ; protocolMarshaller . marshall ( reservedElasticsearchInstance . getPaymentOption ( ) , PAYMENTOPTION_BINDING ) ; protocolMarshaller . marshall ( reservedElasticsearchInstance . getRecurringCharges ( ) , RECURRINGCHARGES_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; }
|
public class PermissionMapper { /** * Convert permissions yml string to map with role and privilege keys .
* Return map fo specific service or all .
* @ param yml string
* @ param msName service name
* @ return permissions map */
public Map < String , Permission > ymlToPermissions ( String yml , String msName ) { } }
|
Map < String , Permission > result = new TreeMap < > ( ) ; try { Map < String , Map < String , Set < Permission > > > map = mapper . readValue ( yml , new TypeReference < TreeMap < String , TreeMap < String , TreeSet < Permission > > > > ( ) { } ) ; map . entrySet ( ) . stream ( ) . filter ( entry -> StringUtils . isBlank ( msName ) || StringUtils . startsWithIgnoreCase ( entry . getKey ( ) , msName ) ) . filter ( entry -> entry . getValue ( ) != null ) . forEach ( entry -> entry . getValue ( ) . forEach ( ( roleKey , permissions ) -> permissions . forEach ( permission -> { permission . setMsName ( entry . getKey ( ) ) ; permission . setRoleKey ( roleKey ) ; result . put ( roleKey + ":" + permission . getPrivilegeKey ( ) , permission ) ; } ) ) ) ; } catch ( Exception e ) { log . error ( "Failed to create permissions collection from YML file, error: {}" , e . getMessage ( ) , e ) ; } return Collections . unmodifiableMap ( result ) ;
|
public class HBaseWriter { /** * ( non - Javadoc )
* @ see
* com . impetus . client . hbase . Writer # delete ( org . apache . hadoop . hbase . client
* . HTable , java . lang . String , java . lang . String ) */
public void delete ( HTableInterface hTable , Object rowKey , String columnFamily ) { } }
|
try { byte [ ] rowBytes = HBaseUtils . getBytes ( rowKey ) ; Delete delete = new Delete ( rowBytes ) ; byte [ ] family = HBaseUtils . getBytes ( columnFamily ) ; delete . deleteFamily ( family ) ; hTable . delete ( delete ) ; } catch ( IOException e ) { log . error ( "Error while delete on hbase for : " + rowKey ) ; throw new PersistenceException ( e ) ; }
|
public class JavaEscape { /** * Perform a Java level 2 ( basic set and all non - ASCII chars ) < strong > escape < / strong > operation
* on a < tt > String < / tt > input , writing results to a < tt > Writer < / tt > .
* < em > Level 2 < / em > means this method will escape :
* < ul >
* < li > The Java basic escape set :
* < ul >
* < li > The < em > Single Escape Characters < / em > :
* < tt > & # 92 ; b < / tt > ( < tt > U + 0008 < / tt > ) ,
* < tt > & # 92 ; t < / tt > ( < tt > U + 0009 < / tt > ) ,
* < tt > & # 92 ; n < / tt > ( < tt > U + 000A < / tt > ) ,
* < tt > & # 92 ; f < / tt > ( < tt > U + 000C < / tt > ) ,
* < tt > & # 92 ; r < / tt > ( < tt > U + 000D < / tt > ) ,
* < tt > & # 92 ; & quot ; < / tt > ( < tt > U + 0022 < / tt > ) ,
* < tt > & # 92 ; & # 39 ; < / tt > ( < tt > U + 0027 < / tt > ) and
* < tt > & # 92 ; & # 92 ; < / tt > ( < tt > U + 005C < / tt > ) . Note < tt > & # 92 ; & # 39 ; < / tt > is not really needed in
* String literals ( only in Character literals ) , so it won ' t be used until escape level 3.
* < / li >
* < li >
* Two ranges of non - displayable , control characters ( some of which are already part of the
* < em > single escape characters < / em > list ) : < tt > U + 0000 < / tt > to < tt > U + 001F < / tt >
* and < tt > U + 007F < / tt > to < tt > U + 009F < / tt > .
* < / li >
* < / ul >
* < / li >
* < li > All non ASCII characters . < / li >
* < / ul >
* This escape will be performed by using the Single Escape Chars whenever possible . For escaped
* characters that do not have an associated SEC , default to < tt > & # 92 ; uFFFF < / tt >
* Hexadecimal Escapes .
* This method calls { @ link # escapeJava ( String , Writer , JavaEscapeLevel ) }
* with the following preconfigured values :
* < ul >
* < li > < tt > level < / tt > :
* { @ link JavaEscapeLevel # LEVEL _ 2 _ ALL _ NON _ ASCII _ PLUS _ BASIC _ ESCAPE _ SET } < / li >
* < / ul >
* This method is < strong > thread - safe < / strong > .
* @ param text the < tt > String < / tt > to be escaped .
* @ param writer the < tt > java . io . Writer < / tt > to which the escaped result will be written . Nothing will
* be written at all to this writer if input is < tt > null < / tt > .
* @ throws IOException if an input / output exception occurs
* @ since 1.1.2 */
public static void escapeJava ( final String text , final Writer writer ) throws IOException { } }
|
escapeJava ( text , writer , JavaEscapeLevel . LEVEL_2_ALL_NON_ASCII_PLUS_BASIC_ESCAPE_SET ) ;
|
public class EntityMention { /** * setter for head - sets
* @ generated
* @ param v value to set into the feature */
public void setHead ( Head v ) { } }
|
if ( EntityMention_Type . featOkTst && ( ( EntityMention_Type ) jcasType ) . casFeat_head == null ) jcasType . jcas . throwFeatMissing ( "head" , "de.julielab.jules.types.ace.EntityMention" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( EntityMention_Type ) jcasType ) . casFeatCode_head , jcasType . ll_cas . ll_getFSRef ( v ) ) ;
|
public class DomHelper { /** * Retrieves the TagName for the supplied Node if it is an Element , and null otherwise .
* @ param aNode A DOM Node .
* @ return The TagName of the Node if it is an Element , and null otherwise . */
public static String getElementTagName ( final Node aNode ) { } }
|
if ( aNode != null && aNode . getNodeType ( ) == Node . ELEMENT_NODE ) { final Element theElement = ( Element ) aNode ; return theElement . getTagName ( ) ; } // The Node was not an Element .
return null ;
|
public class Matrix4x3d { /** * Apply a " lookat " transformation to this matrix for a right - handed coordinate system ,
* that aligns < code > - z < / code > with < code > center - eye < / code > and store the result in < code > dest < / code > .
* If < code > M < / code > is < code > this < / code > matrix and < code > L < / code > the lookat matrix ,
* then the new matrix will be < code > M * L < / code > . So when transforming a
* vector < code > v < / code > with the new matrix by using < code > M * L * v < / code > ,
* the lookat transformation will be applied first !
* In order to set the matrix to a lookat transformation without post - multiplying it ,
* use { @ link # setLookAt ( double , double , double , double , double , double , double , double , double ) setLookAt ( ) } .
* @ see # lookAt ( Vector3dc , Vector3dc , Vector3dc )
* @ see # setLookAt ( double , double , double , double , double , double , double , double , double )
* @ param eyeX
* the x - coordinate of the eye / camera location
* @ param eyeY
* the y - coordinate of the eye / camera location
* @ param eyeZ
* the z - coordinate of the eye / camera location
* @ param centerX
* the x - coordinate of the point to look at
* @ param centerY
* the y - coordinate of the point to look at
* @ param centerZ
* the z - coordinate of the point to look at
* @ param upX
* the x - coordinate of the up vector
* @ param upY
* the y - coordinate of the up vector
* @ param upZ
* the z - coordinate of the up vector
* @ param dest
* will hold the result
* @ return dest */
public Matrix4x3d lookAt ( double eyeX , double eyeY , double eyeZ , double centerX , double centerY , double centerZ , double upX , double upY , double upZ , Matrix4x3d dest ) { } }
|
if ( ( properties & PROPERTY_IDENTITY ) != 0 ) return dest . setLookAt ( eyeX , eyeY , eyeZ , centerX , centerY , centerZ , upX , upY , upZ ) ; return lookAtGeneric ( eyeX , eyeY , eyeZ , centerX , centerY , centerZ , upX , upY , upZ , dest ) ;
|
public class StreamSnapshotDataTarget { /** * Idempotent , synchronized method to perform all cleanup of outstanding
* work so buffers aren ' t leaked . */
synchronized void clearOutstanding ( ) { } }
|
if ( m_outstandingWork . isEmpty ( ) && ( m_outstandingWorkCount . get ( ) == 0 ) ) { return ; } rejoinLog . trace ( "Clearing outstanding work." ) ; for ( Entry < Integer , SendWork > e : m_outstandingWork . entrySet ( ) ) { e . getValue ( ) . discard ( ) ; } m_outstandingWork . clear ( ) ; m_outstandingWorkCount . set ( 0 ) ;
|
public class AtomicRateLimiter { /** * { @ inheritDoc } */
@ Override public void changeLimitForPeriod ( final int limitForPeriod ) { } }
|
RateLimiterConfig newConfig = RateLimiterConfig . from ( state . get ( ) . config ) . limitForPeriod ( limitForPeriod ) . build ( ) ; state . updateAndGet ( currentState -> new State ( newConfig , currentState . activeCycle , currentState . activePermissions , currentState . nanosToWait ) ) ;
|
public class CommerceRegionUtil { /** * Returns the first commerce region in the ordered set where uuid = & # 63 ; .
* @ param uuid the uuid
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the first matching commerce region , or < code > null < / code > if a matching commerce region could not be found */
public static CommerceRegion fetchByUuid_First ( String uuid , OrderByComparator < CommerceRegion > orderByComparator ) { } }
|
return getPersistence ( ) . fetchByUuid_First ( uuid , orderByComparator ) ;
|
public class Resolver { /** * Resolves a BelTerm to an equivalent { @ link KamNode } in the { @ link Kam } .
* @ param kam { @ link Kam } , the KAM to resolve against
* @ param kAMStore { @ link KAMStore } , the KAM store to use in resolving the
* bel term expression
* @ param belTerm { @ link BelTerm } , the BelTerm which cannot be null
* @ return the resolved { @ link KamNode } for the BelTerm , or null if one
* could not be found
* @ throws InvalidArgument Thrown when a parameter is { @ code null }
* @ throws ResolverException Thrown if an error occurred resolving the
* BelTerm ; exceptions will be wrapped */
public KamNode resolve ( final Kam kam , final KAMStore kAMStore , final BelTerm belTerm ) throws ResolverException { } }
|
if ( nulls ( kam , kAMStore , belTerm ) ) { throw new InvalidArgument ( "null parameter(s) provided to resolve API." ) ; } if ( null == belTerm ) { throw new InvalidArgument ( "belTerm" , belTerm ) ; } KamNode kamNode = null ; try { // If we parsed Ok we can go ahead and lookup the string in the KAMStore
kamNode = kAMStore . getKamNode ( kam , belTerm ) ; } catch ( KAMStoreException e ) { throw new ResolverException ( e ) ; } return kamNode ;
|
public class Util { /** * Given a class , return the closest visible super class .
* @ param classDoc the class we are searching the parent for .
* @ param configuration the current configuration of the doclet .
* @ return the closest visible super class . Return null if it cannot
* be found ( i . e . classDoc is java . lang . Object ) . */
public static Type getFirstVisibleSuperClass ( ClassDoc classDoc , Configuration configuration ) { } }
|
if ( classDoc == null ) { return null ; } Type sup = classDoc . superclassType ( ) ; ClassDoc supClassDoc = classDoc . superclass ( ) ; while ( sup != null && ( ! ( supClassDoc . isPublic ( ) || isLinkable ( supClassDoc , configuration ) ) ) ) { if ( supClassDoc . superclass ( ) . qualifiedName ( ) . equals ( supClassDoc . qualifiedName ( ) ) ) break ; sup = supClassDoc . superclassType ( ) ; supClassDoc = supClassDoc . superclass ( ) ; } if ( classDoc . equals ( supClassDoc ) ) { return null ; } return sup ;
|
public class AbstractMatrixAligner { /** * Returns score for the alignment of the query column to all target columns
* @ param queryColumn
* @ param subproblem
* @ return */
protected int [ ] getSubstitutionScoreVector ( int queryColumn , Subproblem subproblem ) { } }
|
int [ ] subs = new int [ subproblem . getTargetEndIndex ( ) + 1 ] ; if ( queryColumn > 0 ) { for ( int y = Math . max ( 1 , subproblem . getTargetStartIndex ( ) ) ; y <= subproblem . getTargetEndIndex ( ) ; y ++ ) { subs [ y ] = getSubstitutionScore ( queryColumn , y ) ; } } return subs ;
|
public class UpdateUserImpl { /** * / * ( non - Javadoc )
* @ see com . tvd12 . ezyfox . core . command . UpdateUser # exclude ( java . lang . String [ ] ) */
@ Override public UpdateUser exclude ( String ... varnames ) { } }
|
excludedVars . addAll ( Arrays . asList ( varnames ) ) ; return this ;
|
public class WebSphereSecurityPermission { /** * initialize a WebSphereSecurityPermission object . Common to all constructors .
* @ param max the most privileged permission to use . */
private void init ( int max ) { } }
|
if ( ( max != INTERNAL ) && ( max != PROVIDER ) && ( max != PRIVILEGED ) ) throw new IllegalArgumentException ( "invalid action" ) ; if ( max == NONE ) throw new IllegalArgumentException ( "missing action" ) ; if ( getName ( ) == null ) throw new NullPointerException ( "action can't be null" ) ; this . max = max ;
|
public class MapperTemplate { /** * 设置返回值类型 - 为了让typeHandler在select时有效 , 改为设置resultMap
* @ param ms
* @ param entityClass */
protected void setResultType ( MappedStatement ms , Class < ? > entityClass ) { } }
|
EntityTable entityTable = EntityHelper . getEntityTable ( entityClass ) ; List < ResultMap > resultMaps = new ArrayList < ResultMap > ( ) ; resultMaps . add ( entityTable . getResultMap ( ms . getConfiguration ( ) ) ) ; MetaObject metaObject = MetaObjectUtil . forObject ( ms ) ; metaObject . setValue ( "resultMaps" , Collections . unmodifiableList ( resultMaps ) ) ;
|
public class Streams { /** * Create stream converter with custom { @ link ObjectMapper object mapper } , and custom list of
* { @ link MediaType supported media types } .
* @ param < T > generic stream element type
* @ param mapper custom { @ link ObjectMapper object mapper } .
* @ param supportedMediaTypes custom list of { @ link MediaType media types } .
* @ return stream converter with customer object mapper . */
@ SuppressWarnings ( "unchecked" ) public static < T > StreamConverter < T > streamConverter ( final ObjectMapper mapper , final List < MediaType > supportedMediaTypes ) { } }
|
return new StreamConverter ( mapper , supportedMediaTypes ) ;
|
public class PageFlowUtils { /** * Resolve the given action to a URI by running an entire request - processing cycle on the given ScopedRequest
* and ScopedResponse .
* @ exclude
* @ param context the current ServletContext
* @ param request the ServletRequest , which must be a { @ link ScopedRequest } .
* @ param response the ServletResponse , which must be a { @ link ScopedResponse } .
* @ param actionOverride if not < code > null < / code > , this qualified action - path is used to construct an action
* URI which is set as the request URI . The action - path < strong > must < / strong > begin with ' / ' ,
* which makes it qualified from the webapp root .
* @ param autoResolveExtensions a list of URI extensions ( e . g . , " . do " , " . jpf " ) that will be auto - resolved , i . e . ,
* on which this method will be recursively called . If < code > null < / code > , the
* default extensions " . do " and " . jpf " will be used . */
public static ActionResult strutsLookup ( ServletContext context , ServletRequest request , HttpServletResponse response , String actionOverride , String [ ] autoResolveExtensions ) throws Exception { } }
|
ScopedRequest scopedRequest = ScopedServletUtils . unwrapRequest ( request ) ; ScopedResponse scopedResponse = ScopedServletUtils . unwrapResponse ( response ) ; assert scopedRequest != null : request . getClass ( ) . getName ( ) ; assert scopedResponse != null : response . getClass ( ) . getName ( ) ; assert request instanceof HttpServletRequest : request . getClass ( ) . getName ( ) ; if ( scopedRequest == null ) { throw new IllegalArgumentException ( "request must be of type " + ScopedRequest . class . getName ( ) ) ; } if ( scopedResponse == null ) { throw new IllegalArgumentException ( "response must be of type " + ScopedResponse . class . getName ( ) ) ; } ActionServlet as = InternalUtils . getActionServlet ( context ) ; if ( actionOverride != null ) { // The action must be fully - qualified with its module path .
assert actionOverride . charAt ( 0 ) == '/' : actionOverride ; InternalStringBuilder uri = new InternalStringBuilder ( scopedRequest . getContextPath ( ) ) ; uri . append ( actionOverride ) ; uri . append ( PageFlowConstants . ACTION_EXTENSION ) ; scopedRequest . setRequestURI ( uri . toString ( ) ) ; } // In case the request was already forwarded once , clear out the recorded forwarded - URI . This
// will allow us to tell whether processing the request actually forwarded somewhere .
scopedRequest . setForwardedURI ( null ) ; // Now process the request . We create a PageFlowRequestWrapper for pageflow - specific request - scoped info .
PageFlowRequestWrapper wrappedRequest = PageFlowRequestWrapper . wrapRequest ( ( HttpServletRequest ) request ) ; wrappedRequest . setScopedLookup ( true ) ; if ( as != null ) { as . doGet ( wrappedRequest , scopedResponse ) ; // this just calls process ( ) - - same as doPost ( )
} else { // The normal servlet initialization has not completed yet
// so rather than call doGet ( ) directly , aquire the request
// dispatcher from the unwrapped outer request and call
// forward to trigger the servlet initialization .
HttpServletRequest req = scopedRequest . getOuterRequest ( ) ; RequestDispatcher rd = req . getRequestDispatcher ( scopedRequest . getRequestURI ( ) ) ; rd . forward ( wrappedRequest , scopedResponse ) ; } String returnURI ; if ( ! scopedResponse . didRedirect ( ) ) { returnURI = scopedRequest . getForwardedURI ( ) ; if ( autoResolveExtensions == null ) { autoResolveExtensions = DEFAULT_AUTORESOLVE_EXTENSIONS ; } if ( returnURI != null ) { for ( int i = 0 ; i < autoResolveExtensions . length ; ++ i ) { if ( FileUtils . uriEndsWith ( returnURI , autoResolveExtensions [ i ] ) ) { scopedRequest . doForward ( ) ; return strutsLookup ( context , wrappedRequest , scopedResponse , null , autoResolveExtensions ) ; } } } } else { returnURI = scopedResponse . getRedirectURI ( ) ; } RequestContext requestContext = new RequestContext ( scopedRequest , scopedResponse ) ; Handlers . get ( context ) . getStorageHandler ( ) . applyChanges ( requestContext ) ; if ( returnURI != null ) { return new ActionResultImpl ( returnURI , scopedResponse . didRedirect ( ) , scopedResponse . getStatusCode ( ) , scopedResponse . getStatusMessage ( ) , scopedResponse . isError ( ) ) ; } else { return null ; }
|
public class ContextManager { /** * Format the given address as an IPv6 Address .
* @ param host The address .
* @ return The IPv6 formatted address . */
private static String formatIPv6Addr ( String host ) { } }
|
if ( host == null ) { return null ; } else { return ( new StringBuilder ( ) ) . append ( "[" ) . append ( host ) . append ( "]" ) . toString ( ) ; }
|
public class AcceptableUsagePolicyWebflowConfigurer { /** * Create acceptable usage policy view .
* @ param flow the flow */
protected void createAcceptableUsagePolicyView ( final Flow flow ) { } }
|
val viewState = createViewState ( flow , VIEW_ID_ACCEPTABLE_USAGE_POLICY_VIEW , "casAcceptableUsagePolicyView" ) ; createTransitionForState ( viewState , CasWebflowConstants . TRANSITION_ID_SUBMIT , AUP_ACCEPTED_ACTION ) ;
|
public class GroupBy { /** * Create a new GroupByBuilder for the given key expressions
* @ param keys keys for aggregation
* @ return builder for further specification */
public static GroupByBuilder < List < ? > > groupBy ( Expression < ? > ... keys ) { } }
|
return new GroupByBuilder < List < ? > > ( Projections . list ( keys ) ) ;
|
public class RobotRules { /** * Read rules from InputStream argument into this RobotRules , as a
* side - effect , sets the bSyntaxErrors property .
* @ param is InputStream containing the robots . txt document
* @ throws IOException for usual reasons */
public void parse ( InputStream is ) throws IOException { } }
|
BufferedReader br = new BufferedReader ( new InputStreamReader ( ( InputStream ) is , ByteOp . UTF8 ) ) ; String read ; boolean allowRuleFound = false ; // true if curr or last line read was a User - agent line
boolean currLineUA = false ; boolean lastLineUA = false ; ArrayList < String > current = null ; while ( br != null ) { lastLineUA = currLineUA ; do { read = br . readLine ( ) ; // Skip comments & blanks
} while ( ( read != null ) && ( ( read = read . trim ( ) ) . startsWith ( "#" ) || read . length ( ) == 0 ) ) ; if ( read == null ) { br . close ( ) ; br = null ; } else { currLineUA = false ; int commentIndex = read . indexOf ( "#" ) ; if ( commentIndex > - 1 ) { // Strip trailing comment
read = read . substring ( 0 , commentIndex ) ; } read = read . trim ( ) ; Matcher uaMatcher = USER_AGENT_PATTERN . matcher ( read ) ; if ( uaMatcher . matches ( ) ) { String ua = uaMatcher . group ( 1 ) . trim ( ) . toLowerCase ( ) ; if ( current == null || current . size ( ) != 0 || allowRuleFound || ! lastLineUA ) { // only create new rules - list if necessary
// otherwise share with previous user - agent
current = new ArrayList < String > ( ) ; } rules . put ( ua , current ) ; allowRuleFound = false ; currLineUA = true ; LOGGER . fine ( "Found User-agent(" + ua + ") rules..." ) ; continue ; } Matcher disallowMatcher = DISALLOW_PATTERN . matcher ( read ) ; if ( disallowMatcher . matches ( ) ) { if ( current == null ) { // buggy robots . txt
bSyntaxErrors = true ; continue ; } String path = disallowMatcher . group ( 1 ) . trim ( ) ; // Disallow : without path is just ignored .
if ( ! path . isEmpty ( ) ) current . add ( path ) ; continue ; } Matcher allowMatcher = ALLOW_PATTERN . matcher ( read ) ; if ( allowMatcher . matches ( ) ) { // Mark that there was an allow rule to clear the current list for next user - agent
allowRuleFound = true ; } // unknown line ; do nothing for now
// TODO : check for " Allow " lines , and flag a syntax error if
// we encounter any unknown lines ?
} }
|
public class FutureUtils { /** * Creates a future that is complete once multiple other futures completed .
* The future fails ( completes exceptionally ) once one of the futures in the
* conjunction fails . Upon successful completion , the future returns the
* collection of the futures ' results .
* < p > The ConjunctFuture gives access to how many Futures in the conjunction have already
* completed successfully , via { @ link ConjunctFuture # getNumFuturesCompleted ( ) } .
* @ param futures The futures that make up the conjunction . No null entries are allowed .
* @ return The ConjunctFuture that completes once all given futures are complete ( or one fails ) . */
public static < T > ConjunctFuture < Collection < T > > combineAll ( Collection < ? extends CompletableFuture < ? extends T > > futures ) { } }
|
checkNotNull ( futures , "futures" ) ; return new ResultConjunctFuture < > ( futures ) ;
|
public class ConstantsSummaryBuilder { /** * Return true if the given package name has been printed . Also
* return true if the root of this package has been printed .
* @ param pkgname the name of the package to check . */
private boolean hasPrintedPackageIndex ( String pkgname ) { } }
|
String [ ] list = printedPackageHeaders . toArray ( new String [ ] { } ) ; for ( String packageHeader : list ) { if ( pkgname . startsWith ( packageHeader ) ) { return true ; } } return false ;
|
public class Representation { /** * Returns a { @ code Reader } over the character data of this representation object . Conversion
* from byte to character data , if required , is performed according to the charset specified
* by the MIME type metadata property ( { @ link NIE # MIME _ TYPE } ) .
* @ return a { @ code Reader } providing access to the character data of the representation . */
public Reader getReader ( ) { } }
|
if ( this . data instanceof Reader ) { return ( Reader ) this . data ; } else { final InputStream stream = ( InputStream ) this . data ; return new InputStreamReader ( stream , getCharset ( ) ) ; }
|
public class AndroidMobileCommandHelper { /** * This method forms a { @ link Map } of parameters for the toggle airplane mode .
* @ return a key - value pair . The key is the command name . The value is a { @ link Map } command arguments . */
public static Map . Entry < String , Map < String , ? > > toggleAirplaneCommand ( ) { } }
|
return new AbstractMap . SimpleEntry < > ( TOGGLE_AIRPLANE_MODE , ImmutableMap . of ( ) ) ;
|
public class LollipopDrawablesCompat { /** * Create a drawable from an XML document . For more information on how to create resources in
* XML , see
* < a href = " { @ docRoot } guide / topics / resources / drawable - resource . html " > Drawable Resources < / a > . */
public static Drawable createFromXml ( Resources r , XmlPullParser parser ) throws XmlPullParserException , IOException { } }
|
return createFromXml ( r , parser , null ) ;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.