signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class JMElasticsearchBulk { /** * Build delete bulk request builder bulk request builder .
* @ param deleteRequestBuilderList the delete request builder list
* @ return the bulk request builder */
public BulkRequestBuilder buildDeleteBulkRequestBuilder ( List < DeleteRequestBuilder > deleteRequestBuilderList ) { } } | BulkRequestBuilder bulkRequestBuilder = jmESClient . prepareBulk ( ) ; for ( DeleteRequestBuilder deleteRequestBuilder : deleteRequestBuilderList ) bulkRequestBuilder . add ( deleteRequestBuilder ) ; return bulkRequestBuilder ; |
public class Correlation { /** * Returns the standard deviation of the second value distribution . < br >
* The standard deviation shows the variation / dispersion from the average . < br >
* A low standard deviation indicates that the data points tend to be very close to the mean , < br >
* whereas high standard deviation indicates that the data are spread out over a large range of values . < br >
* @ return The standard deviation of the second value distribution */
public double getStandardDeviationB ( ) { } } | if ( standardDeviationB == null ) { standardDeviationB = Math . sqrt ( observationB . getMoments ( ) . get ( 2 ) ) ; } return standardDeviationB ; |
public class SimpsonIntegral { /** * Calculate the integral with the simpson method of the equation implemented in the method
* equation
* @ return
* @ throws Exception */
protected double simpson ( ) { } } | double s = 0f ; double st = 0f ; double ost = 0f ; double os = 0f ; for ( int i = 1 ; i < maxsteps ; i ++ ) { st = trapezoid ( i ) ; s = ( 4f * st - ost ) / 3f ; if ( i > 5 ) { if ( Math . abs ( s - os ) < accuracy * Math . abs ( os ) || ( s == 0f && os == 0f ) ) { return s ; } } os = s ; ost = st ; } return 0d ; |
public class SlideShowView { /** * Move to the next slide */
public void next ( ) { } } | final PlayList pl = getPlaylist ( ) ; final int previousPosition = pl . getCurrentSlide ( ) ; pl . next ( ) ; final int currentPosition = pl . getCurrentSlide ( ) ; playSlide ( currentPosition , previousPosition ) ; |
public class NoMatchException { protected static Location loc ( String s , int pos ) { } } | int line = 1 ; int lineStart = 0 ; int nl = s . indexOf ( '\n' ) ; while ( nl < pos && nl > - 1 ) { nl ++ ; if ( s . charAt ( nl ) == '\r' ) nl ++ ; lineStart = nl ; nl = s . indexOf ( '\n' , nl ) ; } if ( lineStart > pos ) { assert s . charAt ( pos ) == '\r' ; lineStart = pos ; } int col = pos - lineStart ; int lineEnd = nl < 0 ? s . length ( ) : nl ; if ( lineEnd > 1 && s . charAt ( lineEnd - 1 ) == '\r' ) lineEnd -- ; return new Location ( line , col , pos , lineEnd ) ; |
public class IPv6Address { /** * Create an IPv6 address from a byte array .
* @ param bytes byte array with 16 bytes ( interpreted unsigned )
* @ return IPv6 address */
public static IPv6Address fromByteArray ( final byte [ ] bytes ) { } } | if ( bytes == null ) throw new IllegalArgumentException ( "can not construct from [null]" ) ; if ( bytes . length != N_BYTES ) throw new IllegalArgumentException ( "the byte array to construct from should be 16 bytes long" ) ; ByteBuffer buf = ByteBuffer . allocate ( N_BYTES ) ; for ( byte b : bytes ) { buf . put ( b ) ; } buf . rewind ( ) ; LongBuffer longBuffer = buf . asLongBuffer ( ) ; return new IPv6Address ( longBuffer . get ( ) , longBuffer . get ( ) ) ; |
public class XHtmlEntityResolver { /** * Resolve XHtml resource entities , load from classpath resources . */
@ Override public InputSource resolveEntity ( String publicId , String systemId ) throws SAXException , IOException { } } | String filename = xhtmlResourceMap . get ( publicId ) ; if ( filename != null ) { String resourceName = resourceFolder + "/" + filename ; InputStream is = XHtmlEntityResolver . class . getResourceAsStream ( resourceName ) ; if ( is == null ) { throw new IOException ( "Resource '" + resourceName + "' not found in class path." ) ; } return new InputSource ( is ) ; } return null ; |
public class SchemaUtil { /** * Creates a { @ link Schema } for the keys of a { @ link PartitionStrategy } based
* on an entity { @ code Schema } .
* The partition strategy and schema are assumed to be compatible and this
* will result in NullPointerExceptions if they are not .
* @ param schema an entity schema { @ code Schema }
* @ param strategy a { @ code PartitionStrategy }
* @ return a { @ code Schema } for the storage keys of the partition strategy */
public static Schema keySchema ( Schema schema , PartitionStrategy strategy ) { } } | List < Schema . Field > partitionFields = new ArrayList < Schema . Field > ( ) ; for ( FieldPartitioner < ? , ? > fp : Accessor . getDefault ( ) . getFieldPartitioners ( strategy ) ) { partitionFields . add ( partitionField ( fp , schema ) ) ; } Schema keySchema = Schema . createRecord ( schema . getName ( ) + "KeySchema" , null , null , false ) ; keySchema . setFields ( partitionFields ) ; return keySchema ; |
public class AuditLogGeneratorDriver { /** * / * ( non - Javadoc )
* @ see org . duracloud . mill . util . DriverSupport # executeImpl ( org . apache . commons . cli . CommandLine ) */
@ Override protected void executeImpl ( CommandLine cmd ) { } } | PropertyDefinitionListBuilder builder = new PropertyDefinitionListBuilder ( ) ; List < PropertyDefinition > list = builder . addAws ( ) . addMillDb ( ) . addDuracloudAuditSpace ( ) . addWorkDir ( ) . addGlobalWorkDir ( ) . build ( ) ; new PropertyVerifier ( list ) . verify ( System . getProperties ( ) ) ; SystemConfig config = SystemConfig . instance ( ) ; config . setAuditLogSpaceId ( System . getProperty ( ConfigConstants . AUDIT_LOGS_SPACE_ID ) ) ; String workDir = System . getProperty ( ConfigConstants . GLOBAL_WORK_DIRECTORY_PATH ) ; if ( workDir == null ) { // for backwards compatibility use old work directory if no global work dir configured .
workDir = System . getProperty ( ConfigConstants . WORK_DIRECTORY_PATH ) ; } String logRootDir = workDir + File . separator + "audit-logs" ; initializeLogRoot ( logRootDir ) ; ApplicationContext context = new AnnotationConfigApplicationContext ( "org.duracloud.mill" ) ; log . info ( "spring context initialized." ) ; AuditLogGenerator generator = context . getBean ( AuditLogGenerator . class ) ; generator . execute ( ) ; log . info ( "exiting..." ) ; |
public class MStress_Client { /** * Creates directories and files . See CreateDFSPath ( ) , the main recursive
* portion of this method .
* @ return - 1 on error , 0 on success */
private static int createDFSPaths ( ) { } } | String basePath = new String ( TEST_BASE_DIR ) + "/" + hostName_ + "_" + processName_ ; try { long startTime = System . nanoTime ( ) ; Boolean ret = dfsClient_ . mkdirs ( basePath ) ; timingMkdirs_ . add ( new Double ( ( System . nanoTime ( ) - startTime ) / ( 1E9 ) ) ) ; if ( ! ret ) { System . out . printf ( "Error: failed to create test base dir [%s]\n" , basePath ) ; return - 1 ; } } catch ( IOException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( ) ; } Date alpha = new Date ( ) ; if ( CreateDFSPaths ( 0 , basePath ) < 0 ) { return - 1 ; } Date zigma = new Date ( ) ; System . out . printf ( "Client: %d paths created in %d msec\n" , totalCreateCount , timeDiffMilliSec ( alpha , zigma ) ) ; return 0 ; |
public class SiliCompressor { /** * Gets a valid path from the supply contentURI
* @ param contentURI
* @ return A validPath of the image */
private String getRealPathFromURI ( String contentURI ) { } } | Uri contentUri = Uri . parse ( contentURI ) ; Cursor cursor = mContext . getContentResolver ( ) . query ( contentUri , null , null , null , null ) ; if ( cursor == null ) { return contentUri . getPath ( ) ; } else { cursor . moveToFirst ( ) ; int index = cursor . getColumnIndex ( MediaStore . Images . ImageColumns . DATA ) ; Log . e ( LOG_TAG , String . format ( "%d" , index ) ) ; String str = cursor . getString ( index ) ; cursor . close ( ) ; return str ; } |
public class ProvFactory { /** * A factory method to create an instance of a delegation { @ link ActedOnBehalfOf }
* @ param id identifier for the delegation association between delegate and responsible
* @ param delegate identifier for the agent associated with an activity , acting on behalf of the responsible agent
* @ param responsible identifier for the agent , on behalf of which the delegate agent acted
* @ param activity optional identifier of an activity for which the delegation association holds
* @ return an instance of { @ link ActedOnBehalfOf } */
public ActedOnBehalfOf newActedOnBehalfOf ( QualifiedName id , QualifiedName delegate , QualifiedName responsible , QualifiedName activity ) { } } | ActedOnBehalfOf res = of . createActedOnBehalfOf ( ) ; res . setId ( id ) ; res . setActivity ( activity ) ; res . setDelegate ( delegate ) ; res . setResponsible ( responsible ) ; return res ; |
public class RedisRealm { /** * Execute a script .
* @ param scriptUrl */
protected void executeScript ( URL scriptUrl ) { } } | log . debug ( "Executing script '{}'" , scriptUrl ) ; final Jedis jedis = pool . getResource ( ) ; try ( BufferedReader reader = new BufferedReader ( new InputStreamReader ( scriptUrl . openStream ( ) , StandardCharsets . UTF_8 ) ) ) { reader . lines ( ) . filter ( line -> ! Strings . isNullOrEmpty ( line ) && line . charAt ( 0 ) != '#' && ! line . startsWith ( "//" ) ) . forEach ( line -> { try { log . trace ( "execute: {}" , line ) ; String [ ] args = line . split ( " " , 3 ) ; String command = null ; if ( args . length == 1 ) { command = String . format ( "return redis.call('%s')" , args [ 0 ] ) ; } else if ( args . length == 2 ) { command = String . format ( "return redis.call('%s', '%s')" , args [ 0 ] , args [ 1 ] ) ; } else if ( args . length == 3 ) { command = String . format ( "return redis.call('%s', '%s', '%s')" , args [ 0 ] , args [ 1 ] , unwrapQuotes ( args [ 2 ] ) ) ; } else { log . error ( "Unexpected number of script arguments {}" , args . length ) ; } log . trace ( "command: {}" , command ) ; Object result = jedis . eval ( command ) ; } catch ( Exception e ) { log . error ( "Failed to execute '{}'" , line , e ) ; } } ) ; } catch ( IOException e ) { log . error ( "Failed to execute script '{}'" , scriptUrl , e ) ; pool . returnBrokenResource ( jedis ) ; // jedis = null ;
} finally { if ( jedis != null ) { pool . returnResource ( jedis ) ; } } |
public class Whitebox { /** * Invoke a private or inner class method . This might be useful to test
* private methods . */
public static synchronized < T > T invokeMethod ( Object instance , String methodToExecute , Object ... arguments ) throws Exception { } } | return WhiteboxImpl . invokeMethod ( instance , methodToExecute , arguments ) ; |
public class DelimiterWriterFactory { /** * Convenience method to add a series of cols in one go .
* @ param columnTitles
* @ return this
* @ since 4.0 */
public DelimiterWriterFactory addColumnTitles ( final Collection < String > columnTitles ) { } } | if ( columnTitles != null ) { for ( final String columnTitle : columnTitles ) { addColumnTitle ( columnTitle ) ; } } return this ; |
public class PatreonAPI { /** * Get the user object of the creator
* @ param optionalFields A list of optional fields to request , or null . See { @ link User . UserField }
* @ return the current user
* @ throws IOException Thrown when the GET request failed */
public JSONAPIDocument < User > fetchUser ( Collection < User . UserField > optionalFields ) throws IOException { } } | URIBuilder pathBuilder = new URIBuilder ( ) . setPath ( "current_user" ) . addParameter ( "include" , "pledges" ) ; if ( optionalFields != null ) { Set < User . UserField > optionalAndDefaultFields = new HashSet < > ( optionalFields ) ; optionalAndDefaultFields . addAll ( User . UserField . getDefaultFields ( ) ) ; addFieldsParam ( pathBuilder , User . class , optionalAndDefaultFields ) ; } return converter . readDocument ( getDataStream ( pathBuilder . toString ( ) ) , User . class ) ; |
public class AdminClient { /** * Retrieve a Gobblin job by its id .
* @ param id Id of the job to retrieve
* @ return JobExecutionInfo representing the job */
public Optional < JobExecutionInfo > queryByJobId ( String id ) throws RemoteInvocationException { } } | JobExecutionQuery query = new JobExecutionQuery ( ) ; query . setIdType ( QueryIdTypeEnum . JOB_ID ) ; query . setId ( JobExecutionQuery . Id . create ( id ) ) ; query . setLimit ( 1 ) ; List < JobExecutionInfo > results = executeQuery ( query ) ; return getFirstFromQueryResults ( results ) ; |
public class Rule { /** * Whether this rule can be used for text in the given language .
* Since LanguageTool 2.6 , this also works { @ link org . languagetool . rules . patterns . PatternRule } s
* ( before , it used to always return { @ code false } for those ) . */
public boolean supportsLanguage ( Language language ) { } } | try { List < Class < ? extends Rule > > relevantRuleClasses = new ArrayList < > ( ) ; UserConfig config = new UserConfig ( ) ; List < Rule > relevantRules = new ArrayList < > ( language . getRelevantRules ( JLanguageTool . getMessageBundle ( ) , config , null , Collections . emptyList ( ) ) ) ; // empty UserConfig has to be added to prevent null pointer exception
relevantRules . addAll ( language . getRelevantLanguageModelCapableRules ( JLanguageTool . getMessageBundle ( ) , null , config , null , Collections . emptyList ( ) ) ) ; for ( Rule relevantRule : relevantRules ) { relevantRuleClasses . add ( relevantRule . getClass ( ) ) ; } return relevantRuleClasses . contains ( this . getClass ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } |
public class SerialArrayList { /** * Add serial array list .
* @ param right the right
* @ return the serial array list */
public SerialArrayList < U > add ( SerialArrayList < U > right ) { } } | return new SerialArrayList < U > ( factory , this , right ) ; |
public class ParseLong { /** * { @ inheritDoc }
* @ throws SuperCsvCellProcessorException
* if value is null , isn ' t a Long or String , or can ' t be parsed as a Long */
public Object execute ( final Object value , final CsvContext context ) { } } | validateInputNotNull ( value , context ) ; final Long result ; if ( value instanceof Long ) { result = ( Long ) value ; } else if ( value instanceof String ) { try { result = Long . parseLong ( ( String ) value ) ; } catch ( final NumberFormatException e ) { throw new SuperCsvCellProcessorException ( String . format ( "'%s' could not be parsed as an Long" , value ) , context , this , e ) ; } } else { final String actualClassName = value . getClass ( ) . getName ( ) ; throw new SuperCsvCellProcessorException ( String . format ( "the input value should be of type Long or String but is of type %s" , actualClassName ) , context , this ) ; } return next . execute ( result , context ) ; |
public class JumblrClient { /** * Follow a given blog
* @ param blogName The name of the blog to follow */
public void follow ( String blogName ) { } } | Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "url" , JumblrClient . blogUrl ( blogName ) ) ; requestBuilder . post ( "/user/follow" , map ) ; |
public class ExpressionInfoValueRenderer { /** * Returns a string representation of a value , or < tt > null < / tt > if
* the value should not be shown ( because it does not add any valuable
* information ) . Note that the method may also change rendered values
* of child expression .
* @ param expr the expression whose value is to be rendered
* @ return a string representation of the value */
@ Nullable static String renderValue ( ExpressionInfo expr ) { } } | Object value = expr . getValue ( ) ; if ( value == null ) return "null" ; if ( "" . equals ( value ) ) return "\"\"" ; // value . equals ( ) might throw exception , so we use " " . equals ( ) instead
String str ; try { str = doRenderValue ( expr ) ; } catch ( Exception e ) { return String . format ( "%s (renderer threw %s)" , javaLangObjectToString ( value ) , e . getClass ( ) . getSimpleName ( ) ) ; } if ( value instanceof Throwable ) { Throwable throwable = ( Throwable ) value ; genericStackTraceFilter . filter ( throwable ) ; StringWriter stackTrace = new StringWriter ( ) ; throwable . printStackTrace ( new PrintWriter ( stackTrace ) ) ; return stackTrace . toString ( ) ; } if ( str == null || "" . equals ( str ) ) { return javaLangObjectToString ( value ) ; } // only print enum values that add valuable information
if ( value instanceof Enum ) { String text = expr . getText ( ) . trim ( ) ; int index = text . lastIndexOf ( '.' ) ; String potentialEnumConstantNameInText = text . substring ( index + 1 ) ; if ( str . equals ( potentialEnumConstantNameInText ) ) return null ; } return str ; |
public class AbstractFacade { /** * { @ inheritDoc } */
@ Override public < E extends R > boolean exists ( final Class < E > clazz , final Object ... keyPart ) { } } | return exists ( Key . create ( clazz , keyPart ) ) ; |
public class Parser { /** * Parses the math expression ( complicated formula ) and stores the result
* @ param expression < code > String < / code > input expression ( math formula )
* @ throws < code > ParseException < / code > if the input expression is not
* correct
* @ since 3.0 */
protected void parse ( String expression ) { } } | /* cleaning stacks */
stackOperations . clear ( ) ; stackRPN . clear ( ) ; QScanner scanner = new QScanner ( expression ) ; /* loop for handling each token - shunting - yard algorithm */
String stringToken , prevToken = null ; while ( ( stringToken = scanner . readNext ( ) ) != null ) { if ( isSeparator ( stringToken ) ) { while ( ! stackOperations . empty ( ) && ! isOpenBracket ( stackOperations . lastElement ( ) ) ) { stackRPN . push ( stackOperations . pop ( ) ) ; } } else if ( isOpenBracket ( stringToken ) ) { Object last = stackRPN . isEmpty ( ) ? null : stackRPN . lastElement ( ) ; if ( last instanceof VarPath && isFunction ( ( ( VarPath ) last ) . field ) ) { stackRPN . pop ( ) ; stackOperations . push ( functions . get ( ( ( VarPath ) last ) . field ) ) ; } stackOperations . push ( stringToken ) ; } else if ( isCloseBracket ( stringToken ) ) { while ( ! stackOperations . empty ( ) && ! isOpenBracket ( stackOperations . lastElement ( ) ) ) { stackRPN . push ( stackOperations . pop ( ) ) ; } stackOperations . pop ( ) ; if ( ! stackOperations . empty ( ) && stackOperations . lastElement ( ) instanceof FuncOperand ) { stackRPN . push ( stackOperations . pop ( ) ) ; } } else if ( isNumber ( stringToken ) ) { if ( stringToken . indexOf ( '.' ) < 0 ) { Long i = Long . parseLong ( stringToken ) ; stackRPN . push ( new LongValue ( i ) ) ; } else { Double d = Double . parseDouble ( stringToken ) ; stackRPN . push ( new DoubleValue ( d ) ) ; } } else if ( operators . containsKey ( stringToken ) ) { Operator op = operators . get ( stringToken ) ; // test for prefix op
boolean prefix = false ; if ( ( stringToken . equals ( "+" ) || stringToken . equals ( "-" ) ) && ( prevToken == null || operators . containsKey ( prevToken ) || isOpenBracket ( prevToken ) || isSeparator ( prevToken ) ) ) { prefix = true ; stackRPN . push ( new LongValue ( 0 ) ) ; } while ( ! stackOperations . empty ( ) && ! prefix && stackOperations . lastElement ( ) instanceof Operator && op . getPrecedence ( ) <= ( ( Operator ) stackOperations . lastElement ( ) ) . getPrecedence ( ) ) { stackRPN . push ( stackOperations . pop ( ) ) ; } stackOperations . push ( op ) ; } else { if ( stringToken . startsWith ( "'" ) && stringToken . endsWith ( "'" ) ) { stackRPN . push ( new StringValue ( stringToken . substring ( 1 , stringToken . length ( ) - 1 ) ) ) ; } else if ( stringToken . startsWith ( "\"" ) && stringToken . endsWith ( "\"" ) ) { stackRPN . push ( new StringValue ( stringToken . substring ( 1 , stringToken . length ( ) - 1 ) ) ) ; } else // if ( stringToken . startsWith ( VARIABLE + " . " ) )
{ stackRPN . push ( new VarPath ( stringToken , ctxRef ) ) ; } } prevToken = stringToken ; } while ( ! stackOperations . empty ( ) ) { stackRPN . push ( stackOperations . pop ( ) ) ; } /* reverse stack */
Collections . reverse ( stackRPN ) ; |
public class JADT { /** * Create a dummy configged jADT based on the provided syntaxErrors , semanticErrors , testSrcInfo , and sink factory
* Useful for testing */
public static JADT createDummyJADT ( List < SyntaxError > syntaxErrors , List < SemanticError > semanticErrors , String testSrcInfo , SinkFactoryFactory factory ) { } } | final SourceFactory sourceFactory = new StringSourceFactory ( TEST_STRING ) ; final Doc doc = new Doc ( TEST_SRC_INFO , Pkg . _Pkg ( NO_COMMENTS , "pkg" ) , Util . < Imprt > list ( ) , Util . < DataType > list ( ) ) ; final ParseResult parseResult = new ParseResult ( doc , syntaxErrors ) ; final DocEmitter docEmitter = new DummyDocEmitter ( doc , TEST_CLASS_NAME ) ; final Parser parser = new DummyParser ( parseResult , testSrcInfo , TEST_STRING ) ; final Checker checker = new DummyChecker ( semanticErrors ) ; final JADT jadt = new JADT ( sourceFactory , parser , checker , docEmitter , factory ) ; return jadt ; |
public class TrainingsImpl { /** * Get iterations for the project .
* @ param projectId The project id
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the List & lt ; Iteration & gt ; object */
public Observable < List < Iteration > > getIterationsAsync ( UUID projectId ) { } } | return getIterationsWithServiceResponseAsync ( projectId ) . map ( new Func1 < ServiceResponse < List < Iteration > > , List < Iteration > > ( ) { @ Override public List < Iteration > call ( ServiceResponse < List < Iteration > > response ) { return response . body ( ) ; } } ) ; |
public class ErrorPageHandler { public void handle ( String pathInContext , String pathParams , HttpRequest request , HttpResponse response ) throws HttpException , IOException { } } | response . setContentType ( HttpFields . __TextHtml ) ; ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer ( 2048 ) ; writeErrorPage ( request , writer , response . getStatus ( ) , response . getReason ( ) ) ; writer . flush ( ) ; response . setContentLength ( writer . size ( ) ) ; writer . writeTo ( response . getOutputStream ( ) ) ; writer . destroy ( ) ; |
public class MtasToken { /** * Gets the postfix from value .
* @ param value the value
* @ return the postfix from value */
public static String getPostfixFromValue ( String value ) { } } | String postfix = "" ; Matcher m = patternPrePostFix . matcher ( value ) ; if ( m . find ( ) ) { postfix = m . group ( 2 ) ; } return postfix ; |
public class audit_stats { /** * < pre >
* converts nitro response into object and returns the object array in case of get request .
* < / pre > */
protected base_resource [ ] get_nitro_response ( nitro_service service , String response ) throws Exception { } } | audit_stats [ ] resources = new audit_stats [ 1 ] ; audit_response result = ( audit_response ) service . get_payload_formatter ( ) . string_to_resource ( audit_response . class , response ) ; if ( result . errorcode != 0 ) { if ( result . errorcode == 444 ) { service . clear_session ( ) ; } if ( result . severity != null ) { if ( result . severity . equals ( "ERROR" ) ) throw new nitro_exception ( result . message , result . errorcode ) ; } else { throw new nitro_exception ( result . message , result . errorcode ) ; } } resources [ 0 ] = result . audit ; return resources ; |
public class App { /** * Select a frame by its ( zero - based ) index . That is , if a page has three
* frames , the first frame would be at index 0 , the second at index 1 and
* the third at index 2 . Once the frame has been selected , all subsequent
* calls on the WebDriver interface are made to that frame .
* @ param frameNumber - the frame number , starts at 0 */
public void selectFrame ( int frameNumber ) { } } | String action = "Switching to frame <b>" + frameNumber + "</b>" ; String expected = FRAME + frameNumber + AVAILABLE ; try { driver . switchTo ( ) . frame ( frameNumber ) ; } catch ( Exception e ) { reporter . fail ( action , expected , FRAME + frameNumber + NOT_SELECTED + ". " + e . getMessage ( ) ) ; log . warn ( e ) ; return ; } reporter . pass ( action , expected , expected ) ; |
public class Utils { /** * Avoid using this method for constant reads , use it only for one time only reads from resources in the classpath */
public static String readFileToString ( @ NotNull String resource ) { } } | try { try ( Reader r = new BufferedReader ( new InputStreamReader ( new FileInputStream ( resource ) , "UTF-8" ) ) ) { Writer writer = new StringWriter ( ) ; char [ ] buffer = new char [ 1024 ] ; int n ; while ( ( n = r . read ( buffer ) ) != - 1 ) { writer . write ( buffer , 0 , n ) ; } return writer . toString ( ) ; } } catch ( IOException ioe ) { throw new RuntimeException ( ioe ) ; } |
public class DBFDriverFunction { /** * Return SQL Columns declaration
* @ param header DBAse file header
* @ param isH2Database true if H2 database
* @ return Array of columns ex : [ " id INTEGER " , " len DOUBLE " ]
* @ throws IOException */
public static String getSQLColumnTypes ( DbaseFileHeader header , boolean isH2Database ) throws IOException { } } | StringBuilder stringBuilder = new StringBuilder ( ) ; for ( int idColumn = 0 ; idColumn < header . getNumFields ( ) ; idColumn ++ ) { if ( idColumn > 0 ) { stringBuilder . append ( ", " ) ; } String fieldName = TableLocation . capsIdentifier ( header . getFieldName ( idColumn ) , isH2Database ) ; stringBuilder . append ( TableLocation . quoteIdentifier ( fieldName , isH2Database ) ) ; stringBuilder . append ( " " ) ; switch ( header . getFieldType ( idColumn ) ) { // ( L ) logical ( T , t , F , f , Y , y , N , n )
case 'l' : case 'L' : stringBuilder . append ( "BOOLEAN" ) ; break ; // ( C ) character ( String )
case 'c' : case 'C' : stringBuilder . append ( "VARCHAR(" ) ; // Append size
int length = header . getFieldLength ( idColumn ) ; stringBuilder . append ( String . valueOf ( length ) ) ; stringBuilder . append ( ")" ) ; break ; // ( D ) date ( Date )
case 'd' : case 'D' : stringBuilder . append ( "DATE" ) ; break ; // ( F ) floating ( Double )
case 'n' : case 'N' : if ( ( header . getFieldDecimalCount ( idColumn ) == 0 ) ) { if ( ( header . getFieldLength ( idColumn ) >= 0 ) && ( header . getFieldLength ( idColumn ) < 10 ) ) { stringBuilder . append ( "INT4" ) ; } else { stringBuilder . append ( "INT8" ) ; } } else { stringBuilder . append ( "FLOAT8" ) ; } break ; case 'f' : case 'F' : // floating point number
case 'o' : case 'O' : // floating point number
stringBuilder . append ( "FLOAT8" ) ; break ; default : throw new IOException ( "Unknown DBF field type " + header . getFieldType ( idColumn ) ) ; } } return stringBuilder . toString ( ) ; |
public class CountedCompleter { /** * If this task does not have a completer , invokes { @ link ForkJoinTask # quietlyComplete } and
* returns { @ code null } . Or , if the completer ' s pending count is non - zero , decrements that pending
* count and returns { @ code null } . Otherwise , returns the completer . This method can be used as
* part of a completion traversal loop for homogeneous task hierarchies :
* < pre >
* { @ code
* for ( CountedCompleter < ? > c = firstComplete ( ) ;
* c ! = null ;
* c = c . nextComplete ( ) ) {
* / / . . . process c . . .
* < / pre >
* @ return the completer , or { @ code null } if none */
public final CountedCompleter < ? > nextComplete ( ) { } } | CountedCompleter < ? > p ; if ( ( p = completer ) != null ) return p . firstComplete ( ) ; else { quietlyComplete ( ) ; return null ; } |
public class AbstractCopyDependenciesMojo { /** * Copies dependencies to / target / dependency or to target / { outputSubdirectory } if the outputSubdirectory parameter is
* provided */
protected void copyDependencies ( String outputSubdirectory ) throws MojoExecutionException { } } | outputDirectory = project . getBuild ( ) . getDirectory ( ) ; baseDirectory = project . getBasedir ( ) . getAbsolutePath ( ) ; String outputDirectory = outputSubdirectory == null ? this . outputDirectory + "/dependency" : this . outputDirectory + "/" + outputSubdirectory ; executeMojo ( plugin ( groupId ( "org.apache.maven.plugins" ) , artifactId ( "maven-dependency-plugin" ) , version ( MojoConstants . MAVEN_DEPENDENCY_PLUGIN_VERSION ) ) , goal ( "copy-dependencies" ) , configuration ( element ( "includeScope" , "runtime" ) , element ( "overWriteSnapshots" , "true" ) , element ( "excludeArtifactIds" , "kumuluzee-loader" ) , element ( "outputDirectory" , outputDirectory ) ) , executionEnvironment ( project , session , buildPluginManager ) ) ; copyOrCreateWebapp ( ) ; |
public class CmsFlexCache { /** * Clears all entries from offline projects in the cache . < p >
* The keys from the offline projects are not cleared .
* Cached resources from the online project are not touched . < p >
* Only users with administrator permissions are allowed
* to perform this operation . < p > */
private void clearOfflineEntries ( ) { } } | if ( ! isEnabled ( ) ) { return ; } if ( LOG . isInfoEnabled ( ) ) { LOG . info ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_FLEXCACHE_CLEAR_OFFLINE_ENTRIES_0 ) ) ; } clearAccordingToSuffix ( CACHE_OFFLINESUFFIX , true ) ; |
public class EJSWrapperCommon { /** * d419704 - rewrote for new WrapperId fields and remove the todo . */
public BusinessRemoteWrapper getRemoteBusinessWrapper ( WrapperId wrapperId ) { } } | int remoteIndex = wrapperId . ivInterfaceIndex ; BusinessRemoteWrapper wrapper = null ; String wrapperInterfaceName = "" ; if ( remoteIndex < ivBusinessRemote . length ) { wrapper = ivBusinessRemote [ remoteIndex ] ; wrapperInterfaceName = ivBMD . ivBusinessRemoteInterfaceClasses [ remoteIndex ] . getName ( ) ; } // Is the BusinessRemoteWrapper for the correct interface name ?
String interfaceName = wrapperId . ivInterfaceClassName ; if ( ( wrapper == null ) || ( ! wrapperInterfaceName . equals ( interfaceName ) ) ) { // Nope , index must be invalid , so we need to search the entire
// array to find the one that matches the desired interface name .
// Fix up the WrapperId with index that matches this server .
wrapper = null ; for ( int i = 0 ; i < ivBusinessRemote . length ; ++ i ) { wrapperInterfaceName = ivBMD . ivBusinessRemoteInterfaceClasses [ i ] . getName ( ) ; if ( wrapperInterfaceName . equals ( interfaceName ) ) { // This is the correct wrapper .
remoteIndex = i ; wrapper = ivBusinessRemote [ remoteIndex ] ; wrapperId . ivInterfaceIndex = remoteIndex ; break ; } } // d739542 Begin
if ( wrapper == null ) { throw new IllegalStateException ( "Remote " + interfaceName + " interface not defined" ) ; } // d739542 End
} registerServant ( wrapper , remoteIndex ) ; return wrapper ; |
public class IntervalST { /** * Get the value associated with the given key ( Interval ) . Interval must match exactly .
* @ return null if no such key */
public Node < K , V > get ( Interval1D < K > interval ) { } } | return get ( root , interval ) ; |
public class DataSiftClient { /** * Compile a CSDL string to a stream hash to which you can later subscribe and receive interactions from
* @ param csdl the CSDL to compile
* @ return a stream object representing the DataSift compiled CSDL , use { @ link com . datasift . client . core
* . Stream # hash ( ) }
* to list the hash for the compiled CSDL */
public FutureData < Stream > compile ( String csdl ) { } } | FutureData < Stream > future = new FutureData < Stream > ( ) ; URI uri = newParams ( ) . forURL ( config . newAPIEndpointURI ( COMPILE ) ) ; POST request = config . http ( ) . POST ( uri , new PageReader ( newRequestCallback ( future , new Stream ( ) , config ) ) ) . form ( "csdl" , csdl ) ; performRequest ( future , request ) ; return future ; |
public class EventMapper { /** * convert Event bean to EventType manually .
* @ param event the event
* @ return the event type */
public static EventType map ( Event event ) { } } | EventType eventType = new EventType ( ) ; eventType . setTimestamp ( Converter . convertDate ( event . getTimestamp ( ) ) ) ; eventType . setEventType ( convertEventType ( event . getEventType ( ) ) ) ; OriginatorType origType = mapOriginator ( event . getOriginator ( ) ) ; eventType . setOriginator ( origType ) ; MessageInfoType miType = mapMessageInfo ( event . getMessageInfo ( ) ) ; eventType . setMessageInfo ( miType ) ; eventType . setCustomInfo ( convertCustomInfo ( event . getCustomInfo ( ) ) ) ; eventType . setContentCut ( event . isContentCut ( ) ) ; if ( event . getContent ( ) != null ) { DataHandler datHandler = getDataHandlerForString ( event ) ; eventType . setContent ( datHandler ) ; } return eventType ; |
public class ExcelItemWriter { /** * getTitleStyle .
* @ return a { @ link org . apache . poi . hssf . usermodel . HSSFCellStyle } object . */
protected HSSFCellStyle getTitleStyle ( ) { } } | HSSFCellStyle style = workbook . createCellStyle ( ) ; style . setAlignment ( HorizontalAlignment . CENTER ) ; // 左右居中
style . setVerticalAlignment ( VerticalAlignment . CENTER ) ; // 上下居中
style . setFillPattern ( FillPatternType . SOLID_FOREGROUND ) ; style . setFillForegroundColor ( HSSFColorPredefined . GREY_25_PERCENT . getIndex ( ) ) ; return style ; |
public class MarketplaceListing { /** * Return a JSON representation of this object
* @ return JSONObject */
public JSONObject jsonify ( ) { } } | JSONObject ret = new JSONObject ( ) ; ret . put ( "title" , getTitle ( ) ) ; ret . put ( "category" , getCategory ( ) ) ; ret . put ( "subcategory" , getSubCategory ( ) ) ; ret . put ( "description" , getDescription ( ) ) ; if ( null != this . _extraAttributes && ! this . _extraAttributes . isEmpty ( ) ) { ret . putAll ( this . _extraAttributes ) ; } return ret ; |
public class DefaultPlatformManager { /** * Locates all modules in the local repository . */
private List < File > locateModules ( ) { } } | File [ ] files = modRoot . listFiles ( ) ; List < File > modFiles = new ArrayList < > ( ) ; for ( File file : files ) { if ( file . isDirectory ( ) ) { // Check to determine whether the directory is a valid module directory .
boolean isValid = true ; try { new ModuleIdentifier ( file . getName ( ) ) ; } catch ( Exception e ) { isValid = false ; } // If the directory is a valid module name then check for a mod . json file .
if ( isValid ) { File modJson = new File ( file , MOD_JSON_FILE ) ; if ( modJson . exists ( ) ) { modFiles . add ( file ) ; } } } } return modFiles ; |
public class MinguoDate { /** * Obtains a { @ code MinguoDate } representing a date in the Minguo calendar
* system from the proleptic - year , month - of - year and day - of - month fields .
* This returns a { @ code MinguoDate } with the specified fields .
* The day must be valid for the year and month , otherwise an exception will be thrown .
* @ param prolepticYear the Minguo proleptic - year
* @ param month the Minguo month - of - year , from 1 to 12
* @ param dayOfMonth the Minguo day - of - month , from 1 to 31
* @ return the date in Minguo calendar system , not null
* @ throws DateTimeException if the value of any field is out of range ,
* or if the day - of - month is invalid for the month - year */
public static MinguoDate of ( int prolepticYear , int month , int dayOfMonth ) { } } | return MinguoChronology . INSTANCE . date ( prolepticYear , month , dayOfMonth ) ; |
public class AtomContainer { /** * { @ inheritDoc } */
@ Override public Order getMinimumBondOrder ( IAtom atom ) { } } | IBond . Order min = null ; for ( IBond bond : bonds ( ) ) { if ( ! bond . contains ( atom ) ) continue ; if ( min == null || bond . getOrder ( ) . numeric ( ) < min . numeric ( ) ) { min = bond . getOrder ( ) ; } } if ( min == null ) { if ( ! contains ( atom ) ) throw new NoSuchAtomException ( "Atom does not belong to this container!" ) ; if ( atom . getImplicitHydrogenCount ( ) != null && atom . getImplicitHydrogenCount ( ) > 0 ) min = Order . SINGLE ; else min = Order . UNSET ; } return min ; |
public class PeasyRecyclerView { /** * Present as Horizontal List View
* Execute { @ link # resetItemDecorations ( ) }
* Execute { @ link # resetItemAnimator ( ) }
* @ return LinearLayoutManager */
public LinearLayoutManager asHorizontalListView ( ) { } } | this . presentation = PeasyPresentation . HorizontalList ; final LinearLayoutManager layoutManager = PeasyRecyclerView . HorizontalList . newLayoutManager ( getContext ( ) ) ; getRecyclerView ( ) . setLayoutManager ( layoutManager ) ; getRecyclerView ( ) . addItemDecoration ( new DividerItemDecoration ( getContext ( ) , layoutManager . getOrientation ( ) ) ) ; getRecyclerView ( ) . setItemAnimator ( new DefaultItemAnimator ( ) ) ; return layoutManager ; |
public class task_command_log { /** * < pre >
* Performs generic data validation for the operation to be performed
* < / pre > */
protected void validate ( String operationType ) throws Exception { } } | super . validate ( operationType ) ; MPSString id_validator = new MPSString ( ) ; id_validator . setConstraintIsReq ( MPSConstants . ADD_CONSTRAINT , true ) ; id_validator . setConstraintIsReq ( MPSConstants . MODIFY_CONSTRAINT , true ) ; id_validator . validate ( operationType , id , "\"id\"" ) ; MPSString task_device_id_validator = new MPSString ( ) ; task_device_id_validator . validate ( operationType , task_device_id , "\"task_device_id\"" ) ; MPSString command_validator = new MPSString ( ) ; command_validator . setConstraintMaxStrLen ( MPSConstants . GENERIC_CONSTRAINT , 1024 ) ; command_validator . setConstraintMinStrLen ( MPSConstants . GENERIC_CONSTRAINT , 1 ) ; command_validator . validate ( operationType , command , "\"command\"" ) ; MPSString protocol_validator = new MPSString ( ) ; protocol_validator . setConstraintMaxStrLen ( MPSConstants . GENERIC_CONSTRAINT , 32 ) ; protocol_validator . setConstraintMinStrLen ( MPSConstants . GENERIC_CONSTRAINT , 1 ) ; protocol_validator . validate ( operationType , protocol , "\"protocol\"" ) ; MPSInt starttime_validator = new MPSInt ( ) ; starttime_validator . validate ( operationType , starttime , "\"starttime\"" ) ; MPSInt endtime_validator = new MPSInt ( ) ; endtime_validator . validate ( operationType , endtime , "\"endtime\"" ) ; MPSString status_validator = new MPSString ( ) ; status_validator . setConstraintMaxStrLen ( MPSConstants . GENERIC_CONSTRAINT , 128 ) ; status_validator . validate ( operationType , status , "\"status\"" ) ; MPSString statusmessage_validator = new MPSString ( ) ; statusmessage_validator . setConstraintMaxStrLen ( MPSConstants . GENERIC_CONSTRAINT , 4096 ) ; statusmessage_validator . validate ( operationType , statusmessage , "\"statusmessage\"" ) ; |
public class AnnotationExtensions { /** * Gets all the classes from the class loader that belongs to the given package path .
* @ param packagePath
* the package path
* @ param annotationClasses
* the annotation classes
* @ return the all classes
* @ throws ClassNotFoundException
* occurs if a given class cannot be located by the specified class loader
* @ throws IOException
* Signals that an I / O exception has occurred .
* @ throws URISyntaxException
* is thrown if a string could not be parsed as a URI reference . */
public static Set < Class < ? > > getAllClasses ( final String packagePath , final Set < Class < ? extends Annotation > > annotationClasses ) throws ClassNotFoundException , IOException , URISyntaxException { } } | return getAllAnnotatedClassesFromSet ( packagePath , annotationClasses ) ; |
public class CompareFilter { /** * @ see org . springframework . ldap . filter . AbstractFilter # encode ( java . lang . StringBuffer ) */
public StringBuffer encode ( StringBuffer buff ) { } } | buff . append ( '(' ) ; buff . append ( attribute ) . append ( getCompareString ( ) ) . append ( encodedValue ) ; buff . append ( ')' ) ; return buff ; |
public class ResourceInjection { /** * Determines the injection target { @ link Resource } by its lookup name
* @ param lookup
* the lookup name for the resoure
* @ return this { @ link ResourceInjection } */
public ResourceInjection byLookup ( final String lookup ) { } } | final ResourceLiteral resource = new ResourceLiteral ( ) ; resource . setLookup ( lookup ) ; matchingResources . add ( resource ) ; return this ; |
public class STRtreeJGT { /** * Queries the tree and returns { @ link org . locationtech . jts . index . strtree . ItemBoundable } s instead of only the values .
* < p > Also builds the tree , if necessary . < / p >
* @ param searchBounds the bounds to search for .
* @ return the list of { @ link org . locationtech . jts . index . strtree . ItemBoundable } s . */
public List queryBoundables ( Object searchBounds ) { } } | build ( ) ; ArrayList matches = new ArrayList ( ) ; if ( isEmpty ( ) ) { // Assert . isTrue ( root . getBounds ( ) = = null ) ;
return matches ; } if ( getIntersectsOp ( ) . intersects ( root . getBounds ( ) , searchBounds ) ) { queryBoundables ( searchBounds , root , matches ) ; } return matches ; |
public class lbvserver_dnspolicy64_binding { /** * Use this API to fetch lbvserver _ dnspolicy64 _ binding resources of given name . */
public static lbvserver_dnspolicy64_binding [ ] get ( nitro_service service , String name ) throws Exception { } } | lbvserver_dnspolicy64_binding obj = new lbvserver_dnspolicy64_binding ( ) ; obj . set_name ( name ) ; lbvserver_dnspolicy64_binding response [ ] = ( lbvserver_dnspolicy64_binding [ ] ) obj . get_resources ( service ) ; return response ; |
public class CmsJspTagContainer { /** * Sets the setting presets . < p >
* @ param presets a map with string keys and values , or null */
@ SuppressWarnings ( "unchecked" ) public void setSettings ( Object presets ) { } } | if ( presets == null ) { m_settingPresets = null ; } else if ( ! ( presets instanceof Map ) ) { throw new IllegalArgumentException ( "cms:container -- value of 'settings' attribute should be a map, but is " + ClassUtils . getCanonicalName ( presets ) ) ; } else { m_settingPresets = new HashMap < > ( ( Map < String , String > ) presets ) ; } |
public class TokenReader { /** * read string like " a encoded \ u0098 \ " str " */
String readString ( ) throws IOException { } } | StringBuilder sb = new StringBuilder ( 50 ) ; // first char must be " :
char ch = reader . next ( ) ; if ( ch != '\"' ) { throw new JsonParseException ( "Expected \" but actual is: " + ch , reader . readed ) ; } for ( ; ; ) { ch = reader . next ( ) ; if ( ch == '\\' ) { // escape : \ " \ \ \ / \ b \ f \ n \ r \ t
char ech = reader . next ( ) ; switch ( ech ) { case '\"' : sb . append ( '\"' ) ; break ; case '\\' : sb . append ( '\\' ) ; break ; case '/' : sb . append ( '/' ) ; break ; case 'b' : sb . append ( '\b' ) ; break ; case 'f' : sb . append ( '\f' ) ; break ; case 'n' : sb . append ( '\n' ) ; break ; case 'r' : sb . append ( '\r' ) ; break ; case 't' : sb . append ( '\t' ) ; break ; case 'u' : // read an unicode uXXXX :
int u = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) { char uch = reader . next ( ) ; if ( uch >= '0' && uch <= '9' ) { u = ( u << 4 ) + ( uch - '0' ) ; } else if ( uch >= 'a' && uch <= 'f' ) { u = ( u << 4 ) + ( uch - 'a' ) + 10 ; } else if ( uch >= 'A' && uch <= 'F' ) { u = ( u << 4 ) + ( uch - 'A' ) + 10 ; } else { throw new JsonParseException ( "Unexpected char: " + uch , reader . readed ) ; } } sb . append ( ( char ) u ) ; break ; default : throw new JsonParseException ( "Unexpected char: " + ch , reader . readed ) ; } } else if ( ch == '\"' ) { // end of string :
break ; } else if ( ch == '\r' || ch == '\n' ) { throw new JsonParseException ( "Unexpected char: " + ch , reader . readed ) ; } else { sb . append ( ch ) ; } } return sb . toString ( ) ; |
public class TemporaryFileScanWriter { /** * Blocks until the number of open shards is equal to or less than the provided threshold or the current time
* is after the timeout timestamp . */
private boolean blockUntilOpenShardsAtMost ( int maxOpenShards , @ Nullable TransferKey permittedKey , Instant timeout ) throws IOException , InterruptedException { } } | Stopwatch stopWatch = Stopwatch . createStarted ( ) ; Instant now ; _lock . lock ( ) ; try { while ( ! _closed && maxOpenShardsGreaterThan ( maxOpenShards , permittedKey ) && ( now = Instant . now ( ) ) . isBefore ( timeout ) ) { // Stop blocking if there is an exception
propagateExceptionIfPresent ( ) ; // Wait no longer than 30 seconds ; we want to log at least every 30 seconds we ' ve been waiting .
long waitTime = Math . min ( Duration . ofSeconds ( 30 ) . toMillis ( ) , Duration . between ( now , timeout ) . toMillis ( ) ) ; _shardFilesClosedOrExceptionCaught . await ( waitTime , TimeUnit . MILLISECONDS ) ; if ( ! maxOpenShardsGreaterThan ( maxOpenShards , permittedKey ) ) { propagateExceptionIfPresent ( ) ; return true ; } _log . debug ( "After {} seconds task {} still has {} open shards" , stopWatch . elapsed ( TimeUnit . SECONDS ) , _taskId , _openShardFiles . size ( ) ) ; } propagateExceptionIfPresent ( ) ; return ! maxOpenShardsGreaterThan ( maxOpenShards , permittedKey ) ; } finally { _lock . unlock ( ) ; } |
public class SmileConverter { /** * Returns a dataset where the response column is numeric . E . g . to be used for a regression */
public AttributeDataset numericDataset ( int responseColIndex , int ... variablesColIndices ) { } } | return dataset ( table . numberColumn ( responseColIndex ) , AttributeType . NUMERIC , table . columns ( variablesColIndices ) ) ; |
public class SqlBuilder { /** * 配合JOIN的 ON语句 , 多表关联的条件语句 < br >
* 只支持单一的逻辑运算符 ( 例如多个条件之间 )
* @ param logicalOperator 逻辑运算符
* @ param conditions 条件
* @ return 自己 */
public SqlBuilder on ( LogicalOperator logicalOperator , Condition ... conditions ) { } } | if ( ArrayUtil . isNotEmpty ( conditions ) ) { if ( null != wrapper ) { // 包装字段名
conditions = wrapper . wrap ( conditions ) ; } on ( buildCondition ( logicalOperator , conditions ) ) ; } return this ; |
public class Jsr250Utils { /** * Checks if the passed in method already exists in the list of methods . Checks for equality by the name of the method .
* @ param method
* @ param methods
* @ return */
private static boolean containsMethod ( Method method , List < Method > methods ) { } } | if ( methods != null ) { for ( Method aMethod : methods ) { if ( method . getName ( ) . equals ( aMethod . getName ( ) ) ) { return true ; } } } return false ; |
public class XMLSystemProperties { /** * Limit the number of entity expansions . < br >
* This setting only takes effect if a parser with < b > explicitly < / b > disabled
* " Secure processing " feature is used . Otherwise this setting has no effect !
* @ param sEntityExpansionLimit
* A positive integer as a String . Values & le ; 0 are treated as no
* limit . < code > null < / code > means the property is deleted */
public static void setXMLEntityExpansionLimit ( @ Nullable final String sEntityExpansionLimit ) { } } | SystemProperties . setPropertyValue ( SYSTEM_PROPERTY_ENTITY_EXPANSION_LIMIT , sEntityExpansionLimit ) ; SystemProperties . setPropertyValue ( SYSTEM_PROPERTY_JDX_XML_ENTITY_EXPANSION_LIMIT , sEntityExpansionLimit ) ; _onSystemPropertyChange ( ) ; |
public class YearPage { /** * Sets the graphic node on the display mode button based on the current display
* mode ( column or grid ) . */
private void updateDisplayModeIcon ( ) { } } | FontAwesomeIcon icon = FontAwesomeIcon . CALENDAR ; if ( getDisplayMode ( ) . equals ( DisplayMode . GRID ) ) { icon = FontAwesomeIcon . CALENDAR_ALT ; } final Text graphic = FontAwesomeIconFactory . get ( ) . createIcon ( icon ) ; graphic . getStyleClass ( ) . addAll ( "button-icon" , "display-mode-icon" ) ; displayModeButton . setGraphic ( graphic ) ; |
public class JKAbstractContext { /** * Sets the application map .
* @ param applicationMap the application map */
public void setApplicationMap ( final Map < String , Object > applicationMap ) { } } | JKThreadLocal . setValue ( JKContextConstants . APPLICATION_MAP , applicationMap ) ; |
public class NoSonarFilter { /** * Register lines in a file that contains the NOSONAR flag .
* @ param inputFile
* @ param noSonarLines Line number starts at 1 in a file
* @ since 5.0
* @ since 7.6 the method can be called multiple times by different sensors , and NOSONAR lines are merged */
public NoSonarFilter noSonarInFile ( InputFile inputFile , Set < Integer > noSonarLines ) { } } | ( ( DefaultInputFile ) inputFile ) . noSonarAt ( noSonarLines ) ; return this ; |
public class EDBConverter { /** * Adds to the EDBObject special entries which mark that a model is referring to other models through
* OpenEngSBForeignKey annotations */
private void fillEDBObjectWithEngineeringObjectInformation ( EDBObject object , OpenEngSBModel model ) throws IllegalAccessException { } } | if ( ! new AdvancedModelWrapper ( model ) . isEngineeringObject ( ) ) { return ; } for ( Field field : model . getClass ( ) . getDeclaredFields ( ) ) { OpenEngSBForeignKey annotation = field . getAnnotation ( OpenEngSBForeignKey . class ) ; if ( annotation == null ) { continue ; } String value = ( String ) FieldUtils . readField ( field , model , true ) ; if ( value == null ) { continue ; } value = String . format ( "%s/%s" , ContextHolder . get ( ) . getCurrentContextId ( ) , value ) ; String key = getEOReferenceStringFromAnnotation ( annotation ) ; object . put ( key , new EDBObjectEntry ( key , value , String . class ) ) ; } |
public class Statistics { /** * Returns the mode value of the array of doubles */
public static double mode ( double [ ] values ) { } } | if ( values . length == 0 ) throw new IllegalArgumentException ( "No mode in an empty array" ) ; Counter < Double > c = new ObjectCounter < Double > ( ) ; for ( double d : values ) c . count ( d ) ; return c . max ( ) ; |
public class CommonOps_DDF3 { /** * Changes the sign of every element in the vector . < br >
* < br >
* a < sub > i < / sub > = - a < sub > i < / sub >
* @ param a A vector . Modified . */
public static void changeSign ( DMatrix3 a ) { } } | a . a1 = - a . a1 ; a . a2 = - a . a2 ; a . a3 = - a . a3 ; |
public class StandardTypeMerger { /** * Determine if the given typecode refers to a reference type . This
* implementation just checks that the type code is T _ OBJECT , T _ ARRAY ,
* T _ NULL , or T _ EXCEPTION . Subclasses should override this if they have
* defined new object types with different type codes . */
protected boolean isReferenceType ( byte type ) { } } | return type == Const . T_OBJECT || type == Const . T_ARRAY || type == T_NULL || type == T_EXCEPTION ; |
public class FSDataset { /** * Try to update an old block to a new block .
* If there are ongoing create threads running for the old block ,
* the threads will be returned without updating the block .
* @ return ongoing create threads if there is any . Otherwise , return null . */
private List < Thread > tryUpdateBlock ( int namespaceId , Block oldblock , Block newblock ) throws IOException { } } | lock . writeLock ( ) . lock ( ) ; try { // check ongoing create threads
ArrayList < Thread > activeThreads = getActiveThreads ( namespaceId , oldblock ) ; if ( activeThreads != null ) { return activeThreads ; } DatanodeBlockInfo binfo = volumeMap . get ( namespaceId , oldblock ) ; if ( binfo == null ) { throw new IOException ( "Block " + oldblock + " doesn't exist or has been recovered to a new generation " ) ; } File blockFile = binfo . getBlockDataFile ( ) . getFile ( ) ; long oldgs ; File oldMetaFile = null ; if ( binfo . isInlineChecksum ( ) ) { oldgs = BlockInlineChecksumReader . getGenerationStampFromInlineChecksumFile ( blockFile . getName ( ) ) ; } else { oldMetaFile = BlockWithChecksumFileWriter . findMetaFile ( blockFile ) ; oldgs = BlockWithChecksumFileReader . parseGenerationStampInMetaFile ( blockFile , oldMetaFile ) ; } // First validate the update
// update generation stamp
if ( oldgs > newblock . getGenerationStamp ( ) ) { throw new IOException ( "Cannot update block (id=" + newblock . getBlockId ( ) + ") generation stamp from " + oldgs + " to " + newblock . getGenerationStamp ( ) ) ; } // update length
if ( newblock . getNumBytes ( ) > oldblock . getNumBytes ( ) ) { throw new IOException ( "Cannot update block file (=" + blockFile + ") length from " + oldblock . getNumBytes ( ) + " to " + newblock . getNumBytes ( ) ) ; } // Although we ' ve waited for the active threads all dead before updating
// the map so there should be no data race there , we still create new
// ActiveFile object to make sure in case another thread holds it ,
// it won ' t cause any problem for us .
try { volumeMap . copyOngoingCreates ( namespaceId , oldblock ) ; } catch ( CloneNotSupportedException e ) { // It should never happen .
throw new IOException ( "Cannot clone ActiveFile object" , e ) ; } // Now perform the update
File tmpMetaFile = null ; if ( ! binfo . isInlineChecksum ( ) ) { // rename meta file to a tmp file
tmpMetaFile = new File ( oldMetaFile . getParent ( ) , oldMetaFile . getName ( ) + "_tmp" + newblock . getGenerationStamp ( ) ) ; if ( ! oldMetaFile . renameTo ( tmpMetaFile ) ) { throw new IOException ( "Cannot rename block meta file to " + tmpMetaFile ) ; } } long oldBlockLength ; if ( ! binfo . isInlineChecksum ( ) ) { oldBlockLength = blockFile . length ( ) ; } else { oldBlockLength = BlockInlineChecksumReader . getBlockSizeFromFileLength ( blockFile . length ( ) , binfo . getChecksumType ( ) , binfo . getBytesPerChecksum ( ) ) ; } ActiveFile file = null ; if ( newblock . getNumBytes ( ) < oldBlockLength ) { if ( ! binfo . isInlineChecksum ( ) ) { new BlockWithChecksumFileWriter ( binfo . getBlockDataFile ( ) , tmpMetaFile ) . truncateBlock ( oldBlockLength , newblock . getNumBytes ( ) ) ; } else { new BlockInlineChecksumWriter ( binfo . getBlockDataFile ( ) , binfo . getChecksumType ( ) , binfo . getBytesPerChecksum ( ) , datanode . writePacketSize ) . truncateBlock ( newblock . getNumBytes ( ) ) ; } file = volumeMap . getOngoingCreates ( namespaceId , oldblock ) ; if ( file != null ) { file . setBytesAcked ( newblock . getNumBytes ( ) ) ; file . setBytesOnDisk ( newblock . getNumBytes ( ) ) ; file . setBytesReceived ( newblock . getNumBytes ( ) ) ; } else { // This should never happen unless called from unit tests .
binfo . syncInMemorySize ( ) ; } } String newDataFileName ; if ( ! binfo . isInlineChecksum ( ) ) { // rename the tmp file to the new meta file ( with new generation stamp )
File newMetaFile = BlockWithChecksumFileWriter . getMetaFile ( blockFile , newblock ) ; if ( ! tmpMetaFile . renameTo ( newMetaFile ) ) { throw new IOException ( "Cannot rename tmp meta file to " + newMetaFile ) ; } } else { newDataFileName = BlockInlineChecksumWriter . getInlineChecksumFileName ( newblock , binfo . getChecksumType ( ) , binfo . getBytesPerChecksum ( ) ) ; File newDataFile = new File ( blockFile . getParent ( ) , newDataFileName ) ; if ( ! blockFile . renameTo ( newDataFile ) ) { throw new IOException ( "Cannot rename data file to " + newDataFileName ) ; } // fsyncIfPossible parent directory to persist rename .
if ( datanode . syncOnClose ) { NativeIO . fsyncIfPossible ( newDataFile . getParent ( ) ) ; } setDataFileForBlock ( namespaceId , oldblock , newDataFile ) ; } if ( volumeMap . getOngoingCreates ( namespaceId , oldblock ) != null ) { ActiveFile af = volumeMap . removeOngoingCreates ( namespaceId , oldblock ) ; volumeMap . addOngoingCreates ( namespaceId , newblock , af ) ; } volumeMap . update ( namespaceId , oldblock , newblock ) ; // paranoia ! verify that the contents of the stored block
// matches the block file on disk .
validateBlockMetadata ( namespaceId , newblock ) ; return null ; } finally { lock . writeLock ( ) . unlock ( ) ; } |
public class BaseMessageTransport { /** * Get this Property for this key .
* Override this to do something other than return the parent ' s property .
* @ param strProperty The key to lookup .
* @ return The value for this key . */
public String getProperty ( String strProperty ) { } } | if ( m_propTransport != null ) if ( m_propTransport . get ( strProperty ) != null ) return ( String ) m_propTransport . get ( strProperty ) ; return super . getProperty ( strProperty ) ; |
public class FilterFileSystem { /** * { @ inheritDoc } */
@ Override public void setOwner ( Path p , String username , String groupname ) throws IOException { } } | fs . setOwner ( p , username , groupname ) ; |
public class GeometryService { /** * Get the index of the ( smallest ) linear ring of the geometry that contains this coordinate .
* @ param geometry
* @ param c
* @ return the index ( empty array indicates no containment )
* @ since 1.3.0 */
public static GeometryIndex getLinearRingIndex ( Geometry geometry , Coordinate c ) { } } | if ( Geometry . LINEAR_RING . equals ( geometry . getGeometryType ( ) ) ) { IndexedLinearRing ring = helper . createLinearRing ( geometry ) ; if ( ring . containsCoordinate ( c ) ) { return ring . getIndex ( ) ; } } else if ( Geometry . POLYGON . equals ( geometry . getGeometryType ( ) ) ) { IndexedPolygon polygon = helper . createPolygon ( geometry ) ; for ( IndexedLinearRing hole : polygon . getHoles ( ) ) { if ( hole . containsCoordinate ( c ) ) { return hole . getIndex ( ) ; } } if ( polygon . getShell ( ) . containsCoordinate ( c ) ) { return polygon . getShell ( ) . getIndex ( ) ; } } else if ( Geometry . MULTI_POLYGON . equals ( geometry . getGeometryType ( ) ) ) { IndexedMultiPolygon multipolygon = helper . createMultiPolygon ( geometry ) ; for ( IndexedPolygon polygon : multipolygon . getPolygons ( ) ) { for ( IndexedLinearRing hole : polygon . getHoles ( ) ) { if ( hole . containsCoordinate ( c ) ) { return hole . getIndex ( ) ; } } if ( polygon . getShell ( ) . containsCoordinate ( c ) ) { return polygon . getShell ( ) . getIndex ( ) ; } } } return null ; |
public class FilePath { /** * Place the data from { @ link FileItem } into the file location specified by this { @ link FilePath } object . */
public void copyFrom ( FileItem file ) throws IOException , InterruptedException { } } | if ( channel == null ) { try { file . write ( writing ( new File ( remote ) ) ) ; } catch ( IOException e ) { throw e ; } catch ( Exception e ) { throw new IOException ( e ) ; } } else { try ( InputStream i = file . getInputStream ( ) ; OutputStream o = write ( ) ) { org . apache . commons . io . IOUtils . copy ( i , o ) ; } } |
public class EnumHelper { /** * Creates a lookup array based on the " value " associated with an MpxjEnum .
* @ param < E > target enumeration
* @ param c enumeration class
* @ return lookup array */
public static final < E extends Enum < E > > E [ ] createTypeArray ( Class < E > c ) { } } | return createTypeArray ( c , 0 ) ; |
public class CommerceDiscountPersistenceImpl { /** * Returns all the commerce discounts where groupId = & # 63 ; .
* @ param groupId the group ID
* @ return the matching commerce discounts */
@ Override public List < CommerceDiscount > findByGroupId ( long groupId ) { } } | return findByGroupId ( groupId , QueryUtil . ALL_POS , QueryUtil . ALL_POS , null ) ; |
public class Promises { /** * Gets { @ code Promise } s from provided { @ code AsyncSupplier } s ,
* end executes them consequently , discarding their results . */
@ NotNull public static Promise < Void > sequence ( @ NotNull AsyncSupplier < Void > promise1 , @ NotNull AsyncSupplier < Void > promise2 ) { } } | return promise1 . get ( ) . then ( $ -> sequence ( promise2 ) ) ; |
public class FPGrowth { /** * Build a forward map , item id ( dimension ) to frequency position
* @ param counts Item counts
* @ param positions Position index ( output )
* @ param minsupp Minimum support
* @ return Forward index */
private int [ ] buildIndex ( final int [ ] counts , int [ ] positions , int minsupp ) { } } | // Count the number of frequent items :
int numfreq = 0 ; for ( int i = 0 ; i < counts . length ; i ++ ) { if ( counts [ i ] >= minsupp ) { ++ numfreq ; } } // Build the index table
int [ ] idx = new int [ numfreq ] ; for ( int i = 0 , j = 0 ; i < counts . length ; i ++ ) { if ( counts [ i ] >= minsupp ) { idx [ j ++ ] = i ; } } IntegerArrayQuickSort . sort ( idx , ( x , y ) -> Integer . compare ( counts [ y ] , counts [ x ] ) ) ; Arrays . fill ( positions , - 1 ) ; for ( int i = 0 ; i < idx . length ; i ++ ) { positions [ idx [ i ] ] = i ; } return idx ; |
public class DefaultAccumulatorInfoSupplier { /** * only for testing */
public int accumulatorInfoCountOfMap ( String mapName ) { } } | ConcurrentMap < String , AccumulatorInfo > accumulatorInfo = cacheInfoPerMap . get ( mapName ) ; if ( accumulatorInfo == null ) { return 0 ; } else { return accumulatorInfo . size ( ) ; } |
public class OptionalUtils { /** * Throws an { @ link IllegalStateException } if it is not true that exactly one of the provided
* { @ link Optional } s { @ link Optional # isPresent ( ) } . */
public static < T > void exactlyOnePresentOrIllegalState ( Iterable < ? extends Optional < ? extends T > > optionals , final String msg ) { } } | if ( numPresent ( optionals ) != 1 ) { throw new IllegalStateException ( msg ) ; } |
public class AbstractRedisStorage { /** * Determine if the given job is blocked by an active instance
* @ param jobHashKey the job in question
* @ param jedis a thread - safe Redis connection
* @ return true if the given job is blocked by an active instance */
protected boolean isBlockedJob ( String jobHashKey , T jedis ) { } } | JobKey jobKey = redisSchema . jobKey ( jobHashKey ) ; return jedis . sismember ( redisSchema . blockedJobsSet ( ) , jobHashKey ) && isActiveInstance ( jedis . get ( redisSchema . jobBlockedKey ( jobKey ) ) , jedis ) ; |
public class ApacheHTTPClient { /** * This function creates a multi part type request entity and populates it
* with the data from the provided HTTP request .
* @ param httpRequest
* The HTTP request
* @ param httpMethodClient
* The apache HTTP method
* @ return The request entity */
protected RequestEntity createMultiPartRequestContent ( HTTPRequest httpRequest , HttpMethodBase httpMethodClient ) { } } | RequestEntity requestEntity = null ; ContentPart < ? > [ ] contentParts = httpRequest . getContentAsParts ( ) ; if ( contentParts != null ) { int partsAmount = contentParts . length ; if ( partsAmount > 0 ) { // init array
Part [ ] parts = new Part [ partsAmount ] ; ContentPart < ? > contentPart = null ; String name = null ; Object content = null ; ContentPartType contentPartType = null ; for ( int index = 0 ; index < partsAmount ; index ++ ) { // get next part
contentPart = contentParts [ index ] ; if ( contentPart != null ) { // get part values
name = contentPart . getName ( ) ; content = contentPart . getContent ( ) ; contentPartType = contentPart . getType ( ) ; // create new part
switch ( contentPartType ) { case FILE : File file = ( File ) content ; try { parts [ index ] = new FilePart ( name , file ) ; } catch ( FileNotFoundException exception ) { throw new FaxException ( "Fax file: " + file . getAbsolutePath ( ) + " not found." , exception ) ; } break ; case STRING : parts [ index ] = new StringPart ( name , ( String ) content ) ; break ; default : throw new FaxException ( "Unsupported content type provided: " + contentPartType ) ; } } } requestEntity = new MultipartRequestEntity ( parts , httpMethodClient . getParams ( ) ) ; } } return requestEntity ; |
public class HList { /** * Static factory method for creating a 6 - element HList .
* @ param _ 1 the head element
* @ param _ 2 the second element
* @ param _ 3 the third element
* @ param _ 4 the fourth element
* @ param _ 5 the fifth element
* @ param _ 6 the sixth element
* @ param < _ 1 > the head element type
* @ param < _ 2 > the second element type
* @ param < _ 3 > the third element type
* @ param < _ 4 > the fourth element type
* @ param < _ 5 > the fifth element type
* @ param < _ 6 > the sixth element type
* @ return the 6 - element HList
* @ see Tuple6 */
@ SuppressWarnings ( "JavaDoc" ) public static < _1 , _2 , _3 , _4 , _5 , _6 > Tuple6 < _1 , _2 , _3 , _4 , _5 , _6 > tuple ( _1 _1 , _2 _2 , _3 _3 , _4 _4 , _5 _5 , _6 _6 ) { } } | return tuple ( _2 , _3 , _4 , _5 , _6 ) . cons ( _1 ) ; |
public class IOManager { /** * Creates a block channel writer that writes to the given channel . The writer adds the
* written segment to its return - queue afterwards ( to allow for asynchronous implementations ) .
* @ param channelID The descriptor for the channel to write to .
* @ return A block channel writer that writes to the given channel .
* @ throws IOException Thrown , if the channel for the writer could not be opened . */
public BlockChannelWriter < MemorySegment > createBlockChannelWriter ( FileIOChannel . ID channelID ) throws IOException { } } | return createBlockChannelWriter ( channelID , new LinkedBlockingQueue < MemorySegment > ( ) ) ; |
public class WeekDay { /** * Returns a weekday / offset representation of the specified calendar .
* @ param cal a calendar ( java . util )
* @ return a weekday instance representing the specified calendar */
public static WeekDay getMonthlyOffset ( final Calendar cal ) { } } | return new WeekDay ( getDay ( cal . get ( Calendar . DAY_OF_WEEK ) ) , cal . get ( Calendar . DAY_OF_WEEK_IN_MONTH ) ) ; |
public class AWSRoboMakerClient { /** * Returns a list of simulation jobs . You can optionally provide filters to retrieve specific simulation jobs .
* @ param listSimulationJobsRequest
* @ return Result of the ListSimulationJobs operation returned by the service .
* @ throws InvalidParameterException
* A parameter specified in a request is not valid , is unsupported , or cannot be used . The returned message
* provides an explanation of the error value .
* @ throws InternalServerException
* AWS RoboMaker experienced a service issue . Try your call again .
* @ throws ThrottlingException
* AWS RoboMaker is temporarily unable to process the request . Try your call again .
* @ sample AWSRoboMaker . ListSimulationJobs
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / robomaker - 2018-06-29 / ListSimulationJobs " target = " _ top " > AWS
* API Documentation < / a > */
@ Override public ListSimulationJobsResult listSimulationJobs ( ListSimulationJobsRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeListSimulationJobs ( request ) ; |
public class ContentTypeEngines { /** * Registers a content type engine if no other engine has been registered
* for the content type .
* @ param engineClass
* @ return the engine instance , if it is registered */
public ContentTypeEngine registerContentTypeEngine ( Class < ? extends ContentTypeEngine > engineClass ) { } } | ContentTypeEngine engine ; try { engine = engineClass . newInstance ( ) ; } catch ( Exception e ) { throw new PippoRuntimeException ( e , "Failed to instantiate '{}'" , engineClass . getName ( ) ) ; } if ( ! engines . containsKey ( engine . getContentType ( ) ) ) { setContentTypeEngine ( engine ) ; return engine ; } else { log . debug ( "'{}' content engine already registered, ignoring '{}'" , engine . getContentType ( ) , engineClass . getName ( ) ) ; return null ; } |
public class CommerceWishListItemUtil { /** * Returns an ordered range of all the commerce wish list items where commerceWishListId = & # 63 ; and CProductId = & # 63 ; .
* Useful when paginating results . Returns a maximum of < code > end - start < / code > instances . < code > start < / code > and < code > end < / code > are not primary keys , they are indexes in the result set . Thus , < code > 0 < / code > refers to the first result in the set . Setting both < code > start < / code > and < code > end < / code > to { @ link QueryUtil # ALL _ POS } will return the full result set . If < code > orderByComparator < / code > is specified , then the query will include the given ORDER BY logic . If < code > orderByComparator < / code > is absent and pagination is required ( < code > start < / code > and < code > end < / code > are not { @ link QueryUtil # ALL _ POS } ) , then the query will include the default ORDER BY logic from { @ link CommerceWishListItemModelImpl } . If both < code > orderByComparator < / code > and pagination are absent , for performance reasons , the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order .
* @ param commerceWishListId the commerce wish list ID
* @ param CProductId the c product ID
* @ param start the lower bound of the range of commerce wish list items
* @ param end the upper bound of the range of commerce wish list items ( not inclusive )
* @ param orderByComparator the comparator to order the results by ( optionally < code > null < / code > )
* @ return the ordered range of matching commerce wish list items */
public static List < CommerceWishListItem > findByCW_CP ( long commerceWishListId , long CProductId , int start , int end , OrderByComparator < CommerceWishListItem > orderByComparator ) { } } | return getPersistence ( ) . findByCW_CP ( commerceWishListId , CProductId , start , end , orderByComparator ) ; |
public class ClassDelegate { /** * Subprocess activityBehaviour */
@ Override public void completing ( DelegateExecution execution , DelegateExecution subProcessInstance ) throws Exception { } } | if ( activityBehaviorInstance == null ) { activityBehaviorInstance = getActivityBehaviorInstance ( ) ; } if ( activityBehaviorInstance instanceof SubProcessActivityBehavior ) { ( ( SubProcessActivityBehavior ) activityBehaviorInstance ) . completing ( execution , subProcessInstance ) ; } else { throw new ActivitiException ( "completing() can only be called on a " + SubProcessActivityBehavior . class . getName ( ) + " instance" ) ; } |
public class EnumConverter { /** * Converts an { @ link Object } of { @ link Class type S } into an { @ link Object } of { @ link Class type T } .
* @ param value { @ link Object } of { @ link Class type S } to convert .
* @ return the converted { @ link Object } of { @ link Class type T } .
* @ throws ConversionException if the { @ link Object } cannot be converted .
* @ see org . cp . elements . data . conversion . ConversionService # convert ( Object , Class )
* @ see # convert ( Object , Class ) */
@ Override @ SuppressWarnings ( "unchecked" ) public < QT extends Enum > QT convert ( String value , Class < QT > enumType ) { } } | try { Enum enumInstance = Enum . valueOf ( enumType , value ) ; return enumType . cast ( enumInstance ) ; } catch ( Exception cause ) { throw newConversionException ( cause , "[%1$s] is not a valid enumerated value of Enum [%2$s]" , value , enumType . getName ( ) ) ; } |
public class ConverterRegistry { /** * 转换值为指定类型
* @ param < T > 转换的目标类型 ( 转换器转换到的类型 )
* @ param type 类型目标
* @ param value 被转换值
* @ param defaultValue 默认值
* @ param isCustomFirst 是否自定义转换器优先
* @ return 转换后的值
* @ throws ConvertException 转换器不存在 */
@ SuppressWarnings ( "unchecked" ) public < T > T convert ( Type type , Object value , T defaultValue , boolean isCustomFirst ) throws ConvertException { } } | if ( TypeUtil . isUnknow ( type ) && null == defaultValue ) { // 对于用户不指定目标类型的情况 , 返回原值
return ( T ) value ; } if ( ObjectUtil . isNull ( value ) ) { return defaultValue ; } if ( TypeUtil . isUnknow ( type ) ) { type = defaultValue . getClass ( ) ; } // 标准转换器
final Converter < T > converter = getConverter ( type , isCustomFirst ) ; if ( null != converter ) { return converter . convert ( value , defaultValue ) ; } Class < T > rowType = ( Class < T > ) TypeUtil . getClass ( type ) ; if ( null == rowType ) { if ( null != defaultValue ) { rowType = ( Class < T > ) defaultValue . getClass ( ) ; } else { // 无法识别的泛型类型 , 按照Object处理
return ( T ) value ; } } // 特殊类型转换 , 包括Collection 、 Map 、 强转 、 Array等
final T result = convertSpecial ( type , rowType , value , defaultValue ) ; if ( null != result ) { return result ; } // 尝试转Bean
if ( BeanUtil . isBean ( rowType ) ) { return new BeanConverter < T > ( type ) . convert ( value , defaultValue ) ; } // 无法转换
throw new ConvertException ( "No Converter for type [{}]" , rowType . getName ( ) ) ; |
public class PDFBoxTree { /** * Transforms a position according to the current transformation matrix and current page transformation .
* @ param x
* @ param y
* @ return */
protected float [ ] transformPosition ( float x , float y ) { } } | Point2D . Float point = super . transformedPoint ( x , y ) ; AffineTransform pageTransform = createCurrentPageTransformation ( ) ; Point2D . Float transformedPoint = ( Point2D . Float ) pageTransform . transform ( point , null ) ; return new float [ ] { ( float ) transformedPoint . getX ( ) , ( float ) transformedPoint . getY ( ) } ; |
public class WrappedFuture { /** * { @ inheritDoc } */
@ Override public Object get ( ) throws InterruptedException , ExecutionException { } } | Future < ? > wrapped = ( Future < ? > ) future . get ( ) ; return wrapped . get ( ) ; |
public class Expressions { /** * Create a new Template expression
* @ param cl type of expression
* @ param template template
* @ param args template parameters
* @ return template expression */
public static < T > DslTemplate < T > dslTemplate ( Class < ? extends T > cl , String template , List < ? > args ) { } } | return dslTemplate ( cl , createTemplate ( template ) , args ) ; |
public class CommerceWishListItemPersistenceImpl { /** * Returns the last commerce wish list item in the ordered set where commerceWishListId = & # 63 ; and CProductId = & # 63 ; .
* @ param commerceWishListId the commerce wish list ID
* @ param CProductId the c product ID
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the last matching commerce wish list item
* @ throws NoSuchWishListItemException if a matching commerce wish list item could not be found */
@ Override public CommerceWishListItem findByCW_CP_Last ( long commerceWishListId , long CProductId , OrderByComparator < CommerceWishListItem > orderByComparator ) throws NoSuchWishListItemException { } } | CommerceWishListItem commerceWishListItem = fetchByCW_CP_Last ( commerceWishListId , CProductId , orderByComparator ) ; if ( commerceWishListItem != null ) { return commerceWishListItem ; } StringBundler msg = new StringBundler ( 6 ) ; msg . append ( _NO_SUCH_ENTITY_WITH_KEY ) ; msg . append ( "commerceWishListId=" ) ; msg . append ( commerceWishListId ) ; msg . append ( ", CProductId=" ) ; msg . append ( CProductId ) ; msg . append ( "}" ) ; throw new NoSuchWishListItemException ( msg . toString ( ) ) ; |
public class JSEnum { /** * Format for printing . */
public void format ( StringBuffer fmt , Set done , Set todo , int indent ) { } } | formatName ( fmt , indent ) ; fmt . append ( "Enum" ) ; if ( enumerators != null ) { fmt . append ( "{{" ) ; String delim = "" ; for ( int i = 0 ; i < enumerators . length ; i ++ ) { fmt . append ( delim ) . append ( enumerators [ i ] ) ; delim = "," ; } fmt . append ( "}}" ) ; } |
public class EndpointHelpDto { /** * Creates an endpoint help DTO from a resource class .
* @ param resourceClass The resource class .
* @ return The endpoint help DTO . */
public static EndpointHelpDto fromResourceClass ( Class < ? extends AbstractResource > resourceClass ) { } } | Path path = resourceClass . getAnnotation ( Path . class ) ; Description description = resourceClass . getAnnotation ( Description . class ) ; if ( path != null && description != null ) { EndpointHelpDto result = new EndpointHelpDto ( ) ; result . setDescription ( description . value ( ) ) ; result . setEndpoint ( path . value ( ) ) ; return result ; } else { return null ; } |
public class RowBuilder { /** * identity valued column .
* @ param name the column name */
public RowBuilder identityCol ( String name ) { } } | Column column = new ColumnIdentity ( _columns . size ( ) , name , _offset ) ; _offset += column . length ( ) ; _columns . add ( column ) ; return this ; |
public class OutputConfigMarshaller { /** * Marshall the given parameter object . */
public void marshall ( OutputConfig outputConfig , ProtocolMarshaller protocolMarshaller ) { } } | if ( outputConfig == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( outputConfig . getS3OutputLocation ( ) , S3OUTPUTLOCATION_BINDING ) ; protocolMarshaller . marshall ( outputConfig . getTargetDevice ( ) , TARGETDEVICE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class FilesImpl { /** * Returns the content of the specified task file .
* @ param jobId The ID of the job that contains the task .
* @ param taskId The ID of the task whose file you want to retrieve .
* @ param filePath The path to the task file that you want to get the content of .
* @ param fileGetFromTaskOptions Additional parameters for the operation
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the InputStream object */
public Observable < InputStream > getFromTaskAsync ( String jobId , String taskId , String filePath , FileGetFromTaskOptions fileGetFromTaskOptions ) { } } | return getFromTaskWithServiceResponseAsync ( jobId , taskId , filePath , fileGetFromTaskOptions ) . map ( new Func1 < ServiceResponseWithHeaders < InputStream , FileGetFromTaskHeaders > , InputStream > ( ) { @ Override public InputStream call ( ServiceResponseWithHeaders < InputStream , FileGetFromTaskHeaders > response ) { return response . body ( ) ; } } ) ; |
public class SearchResult { /** * The requested facet information .
* @ return The requested facet information . */
public java . util . Map < String , BucketInfo > getFacets ( ) { } } | if ( facets == null ) { facets = new com . amazonaws . internal . SdkInternalMap < String , BucketInfo > ( ) ; } return facets ; |
public class MutableViewData { /** * Constructs a new { @ link MutableViewData } .
* @ param view the { @ code View } linked with this { @ code MutableViewData } .
* @ param start the start { @ code Timestamp } .
* @ return a { @ code MutableViewData } . */
static MutableViewData create ( final View view , final Timestamp start ) { } } | return view . getWindow ( ) . match ( new CreateCumulative ( view , start ) , new CreateInterval ( view , start ) , Functions . < MutableViewData > throwAssertionError ( ) ) ; |
public class BeanRepository { /** * Returns a new created Object with the given { @ code creator } . This equates to a { @ code prototype } Bean . It is
* not required to configure a { @ code prototype } Bean in the BeanRepository before . This Method can be used
* to pass Parameters to the Constructor of an Object . It is also possible to provide References to other
* Beans in the Constructor , because a { @ link BeanAccessor } is provided . The Method
* { @ link PostConstructible # onPostConstruct ( BeanRepository ) } is executed for every Call of this Method .
* @ param creator The Code to create the new Object
* @ param < T > The Type of the Bean
* @ see BeanAccessor
* @ see PostConstructible
* @ return a new created Object */
public < T > T getPrototypeBean ( final Function < BeanAccessor , T > creator ) { } } | final PrototypeProvider provider = new PrototypeProvider ( name , creator ) ; return provider . getBean ( this , dryRun ) ; |
public class BatchListObjectPoliciesResponse { /** * A list of policy < code > ObjectIdentifiers < / code > , that are attached to the object .
* @ param attachedPolicyIds
* A list of policy < code > ObjectIdentifiers < / code > , that are attached to the object . */
public void setAttachedPolicyIds ( java . util . Collection < String > attachedPolicyIds ) { } } | if ( attachedPolicyIds == null ) { this . attachedPolicyIds = null ; return ; } this . attachedPolicyIds = new java . util . ArrayList < String > ( attachedPolicyIds ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.