signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class MultiLayerConfiguration { /** * Create a neural net configuration from json
* @ param json the neural net configuration from json
* @ return { @ link MultiLayerConfiguration } */
public static MultiLayerConfiguration fromJson ( String json ) { } } | MultiLayerConfiguration conf ; ObjectMapper mapper = NeuralNetConfiguration . mapper ( ) ; try { conf = mapper . readValue ( json , MultiLayerConfiguration . class ) ; } catch ( IOException e ) { // Check if this exception came from legacy deserializer . . .
String msg = e . getMessage ( ) ; if ( msg != null && msg . contains ( "legacy" ) ) { throw new RuntimeException ( "Error deserializing MultiLayerConfiguration - configuration may have a custom " + "layer, vertex or preprocessor, in pre version 1.0.0-alpha JSON format. These layers can be " + "deserialized by first registering them with NeuralNetConfiguration.registerLegacyCustomClassesForJSON(Class...)" , e ) ; } throw new RuntimeException ( e ) ; } // To maintain backward compatibility after loss function refactoring ( configs generated with v0.5.0 or earlier )
// Previously : enumeration used for loss functions . Now : use classes
// IN the past , could have only been an OutputLayer or RnnOutputLayer using these enums
int layerCount = 0 ; JsonNode confs = null ; for ( NeuralNetConfiguration nnc : conf . getConfs ( ) ) { Layer l = nnc . getLayer ( ) ; if ( l instanceof BaseOutputLayer && ( ( BaseOutputLayer ) l ) . getLossFn ( ) == null ) { // lossFn field null - > may be an old config format , with lossFunction field being for the enum
// if so , try walking the JSON graph to extract out the appropriate enum value
BaseOutputLayer ol = ( BaseOutputLayer ) l ; try { JsonNode jsonNode = mapper . readTree ( json ) ; if ( confs == null ) { confs = jsonNode . get ( "confs" ) ; } if ( confs instanceof ArrayNode ) { ArrayNode layerConfs = ( ArrayNode ) confs ; JsonNode outputLayerNNCNode = layerConfs . get ( layerCount ) ; if ( outputLayerNNCNode == null ) return conf ; // Should never happen . . .
JsonNode outputLayerNode = outputLayerNNCNode . get ( "layer" ) ; JsonNode lossFunctionNode = null ; if ( outputLayerNode . has ( "output" ) ) { lossFunctionNode = outputLayerNode . get ( "output" ) . get ( "lossFunction" ) ; } else if ( outputLayerNode . has ( "rnnoutput" ) ) { lossFunctionNode = outputLayerNode . get ( "rnnoutput" ) . get ( "lossFunction" ) ; } if ( lossFunctionNode != null ) { String lossFunctionEnumStr = lossFunctionNode . asText ( ) ; LossFunctions . LossFunction lossFunction = null ; try { lossFunction = LossFunctions . LossFunction . valueOf ( lossFunctionEnumStr ) ; } catch ( Exception e ) { log . warn ( "OutputLayer with null LossFunction or pre-0.6.0 loss function configuration detected: could not parse JSON" , e ) ; } if ( lossFunction != null ) { switch ( lossFunction ) { case MSE : ol . setLossFn ( new LossMSE ( ) ) ; break ; case XENT : ol . setLossFn ( new LossBinaryXENT ( ) ) ; break ; case NEGATIVELOGLIKELIHOOD : ol . setLossFn ( new LossNegativeLogLikelihood ( ) ) ; break ; case MCXENT : ol . setLossFn ( new LossMCXENT ( ) ) ; break ; // Remaining : TODO
case EXPLL : case RMSE_XENT : case SQUARED_LOSS : case RECONSTRUCTION_CROSSENTROPY : case CUSTOM : default : log . warn ( "OutputLayer with null LossFunction or pre-0.6.0 loss function configuration detected: could not set loss function for {}" , lossFunction ) ; break ; } } } } else { log . warn ( "OutputLayer with null LossFunction or pre-0.6.0 loss function configuration detected: could not parse JSON: layer 'confs' field is not an ArrayNode (is: {})" , ( confs != null ? confs . getClass ( ) : null ) ) ; } } catch ( IOException e ) { log . warn ( "OutputLayer with null LossFunction or pre-0.6.0 loss function configuration detected: could not parse JSON" , e ) ; break ; } } // Also , pre 0.7.2 : activation functions were Strings ( " activationFunction " field ) , not classes ( " activationFn " )
// Try to load the old format if necessary , and create the appropriate IActivation instance
if ( ( l instanceof BaseLayer ) && ( ( BaseLayer ) l ) . getActivationFn ( ) == null ) { try { JsonNode jsonNode = mapper . readTree ( json ) ; if ( confs == null ) { confs = jsonNode . get ( "confs" ) ; } if ( confs instanceof ArrayNode ) { ArrayNode layerConfs = ( ArrayNode ) confs ; JsonNode outputLayerNNCNode = layerConfs . get ( layerCount ) ; if ( outputLayerNNCNode == null ) return conf ; // Should never happen . . .
JsonNode layerWrapperNode = outputLayerNNCNode . get ( "layer" ) ; if ( layerWrapperNode == null || layerWrapperNode . size ( ) != 1 ) { continue ; } JsonNode layerNode = layerWrapperNode . elements ( ) . next ( ) ; JsonNode activationFunction = layerNode . get ( "activationFunction" ) ; // Should only have 1 element : " dense " , " output " , etc
if ( activationFunction != null ) { IActivation ia = Activation . fromString ( activationFunction . asText ( ) ) . getActivationFunction ( ) ; ( ( BaseLayer ) l ) . setActivationFn ( ia ) ; } } } catch ( IOException e ) { log . warn ( "Layer with null ActivationFn field or pre-0.7.2 activation function detected: could not parse JSON" , e ) ; } } if ( ! handleLegacyWeightInitFromJson ( json , l , mapper , confs , layerCount ) ) { return conf ; } layerCount ++ ; } return conf ; |
public class DatagramSocketFactory { /** * Validates that the socket is good . */
@ Override public boolean validateObject ( SocketAddress key , DatagramSocket socket ) { } } | return socket . isBound ( ) && ! socket . isClosed ( ) && socket . isConnected ( ) ; |
public class HttpResponseMessageImpl { /** * Initialize the response version to either match the request version or
* to the lower 1.0 version based on the channel configuration . */
private void initVersion ( ) { } } | VersionValues ver = getServiceContext ( ) . getRequestVersion ( ) ; VersionValues configVer = getServiceContext ( ) . getHttpConfig ( ) . getOutgoingVersion ( ) ; if ( VersionValues . V10 . equals ( configVer ) && VersionValues . V11 . equals ( ver ) ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( tc , "Configuration forcing 1.0 instead of 1.1" ) ; } setVersion ( configVer ) ; } else { setVersion ( ver ) ; } |
public class VoiceApi { /** * Set the agent state to Not Ready
* Set the current agent & # 39 ; s state to Not Ready on the voice channel .
* @ param notReadyData ( optional )
* @ return ApiResponse & lt ; ApiSuccessResponse & gt ;
* @ throws ApiException If fail to call the API , e . g . server error or cannot deserialize the response body */
public ApiResponse < ApiSuccessResponse > setAgentStateNotReadyWithHttpInfo ( NotReadyData notReadyData ) throws ApiException { } } | com . squareup . okhttp . Call call = setAgentStateNotReadyValidateBeforeCall ( notReadyData , null , null ) ; Type localVarReturnType = new TypeToken < ApiSuccessResponse > ( ) { } . getType ( ) ; return apiClient . execute ( call , localVarReturnType ) ; |
public class CProductUtil { /** * Returns the last c product in the ordered set where groupId = & # 63 ; .
* @ param groupId the group ID
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the last matching c product , or < code > null < / code > if a matching c product could not be found */
public static CProduct fetchByGroupId_Last ( long groupId , OrderByComparator < CProduct > orderByComparator ) { } } | return getPersistence ( ) . fetchByGroupId_Last ( groupId , orderByComparator ) ; |
public class LTPAKeyFileCreatorImpl { /** * { @ inheritDoc } */
@ Override public Properties createLTPAKeysFile ( WsLocationAdmin locService , String keyFile , @ Sensitive byte [ ] keyPasswordBytes ) throws Exception { } } | Properties ltpaProps = generateLTPAKeys ( keyPasswordBytes , getRealmName ( ) ) ; addLTPAKeysToFile ( getOutputStream ( locService , keyFile ) , ltpaProps ) ; return ltpaProps ; |
public class CollectionHelper { /** * list to imuteable set .
* @ param set set to convert
* @ return imuteable set */
public static < T > Set < T > toImmutableSet ( final Set < ? extends T > set ) { } } | switch ( set . size ( ) ) { case 0 : return Collections . emptySet ( ) ; case 1 : return Collections . singleton ( set . iterator ( ) . next ( ) ) ; default : return Collections . unmodifiableSet ( set ) ; } |
public class MicroXaDataSource { /** * 获取一个数据库连接
* @ return 一个数据库连接
* @ throws SQLException */
public Connection getConnection ( ) throws SQLException { } } | MicroPooledConnection microConn = null ; String xGroupId = getXGroupIdByLocal ( ) ; String xBranchId = getXBranchIdByLocal ( ) ; if ( xGroupId == null || "" . equals ( xGroupId ) ) { log . error ( "getConnection error xid is null" ) ; throw new RuntimeException ( "getConnection error xid is null" ) ; } Connection conn = getConnByGbId ( xGroupId , xBranchId ) ; if ( conn != null ) { log . debug ( "get conn from holdermap xid=" + getStr4XidLocal ( ) ) ; if ( checkConn ( conn ) == false ) { Connection reconn = recreateConn ( conn ) ; microConn = new MicroPooledConnection ( reconn ) ; } else { microConn = new MicroPooledConnection ( conn ) ; } putConnByGbId ( xGroupId , xBranchId , microConn ) ; return microConn ; } int totalSize = getConnCount ( ) ; if ( totalSize >= maxSize ) { throw new RuntimeException ( "getConnection error totalsize > maxsize" ) ; } // synchronized ( pool ) {
if ( pool . isEmpty ( ) == false ) { conn = pool . poll ( ) ; log . debug ( "get conn from pool xid=" + getStr4XidLocal ( ) ) ; if ( checkConn ( conn ) == false ) { Connection reconn = recreateConn ( conn ) ; microConn = new MicroPooledConnection ( reconn ) ; } else { microConn = new MicroPooledConnection ( conn ) ; } } else { log . debug ( "create conn in pool xid=" + getStr4XidLocal ( ) ) ; Connection nconn = DriverManager . getConnection ( url , username , password ) ; nconn . setAutoCommit ( false ) ; nconn . setTransactionIsolation ( level ) ; microConn = new MicroPooledConnection ( nconn ) ; } putConnByGbId ( xGroupId , xBranchId , microConn ) ; return microConn ; |
public class HttpRequestExecutor { /** * Performs a HTTP POST request to the given < tt > path < / tt >
* relative to the internal target hostname .
* @ param path Relative server path to perform request to .
* @ param content POST content that will be sent .
* @ return Response content of the performed request .
* @ throws IOException If any error occurs while performing request . */
public String post ( final String path , final HttpContent content ) throws IOException { } } | final GenericUrl url = getURL ( path ) ; final HttpRequest request = requestFactory . buildPostRequest ( url , content ) ; final HttpResponse response = request . execute ( ) ; return response . parseAsString ( ) ; |
public class FunctionUtils { /** * Search for functions in string and replace with respective function result .
* @ param stringValue to parse .
* @ param enableQuoting enables quoting of function results .
* @ return parsed string result . */
public static String replaceFunctionsInString ( final String stringValue , TestContext context , boolean enableQuoting ) { } } | // make sure given string expression meets requirements for having a function
if ( ! StringUtils . hasText ( stringValue ) || ( stringValue . indexOf ( ':' ) < 0 ) || ( stringValue . indexOf ( '(' ) < 0 ) || ( stringValue . indexOf ( ')' ) < 0 ) ) { // it is not a function , as it is defined as ' prefix : methodName ( arguments ) '
return stringValue ; } String newString = stringValue ; StringBuffer strBuffer = new StringBuffer ( ) ; boolean isVarComplete = false ; StringBuffer variableNameBuf = new StringBuffer ( ) ; int startIndex = 0 ; int curIndex ; int searchIndex ; for ( FunctionLibrary library : context . getFunctionRegistry ( ) . getFunctionLibraries ( ) ) { startIndex = 0 ; while ( ( searchIndex = newString . indexOf ( library . getPrefix ( ) , startIndex ) ) != - 1 ) { int control = - 1 ; isVarComplete = false ; curIndex = searchIndex ; while ( curIndex < newString . length ( ) && ! isVarComplete ) { if ( newString . indexOf ( '(' , curIndex ) == curIndex ) { control ++ ; } if ( newString . charAt ( curIndex ) == ')' || curIndex == newString . length ( ) - 1 ) { if ( control == 0 ) { isVarComplete = true ; } else { control -- ; } } variableNameBuf . append ( newString . charAt ( curIndex ) ) ; curIndex ++ ; } final String value = resolveFunction ( variableNameBuf . toString ( ) , context ) ; strBuffer . append ( newString . substring ( startIndex , searchIndex ) ) ; if ( enableQuoting ) { strBuffer . append ( "'" + value + "'" ) ; } else { strBuffer . append ( value ) ; } startIndex = curIndex ; variableNameBuf = new StringBuffer ( ) ; isVarComplete = false ; } strBuffer . append ( newString . substring ( startIndex ) ) ; newString = strBuffer . toString ( ) ; strBuffer = new StringBuffer ( ) ; } return newString ; |
public class Page { /** * Write HTML page head tags .
* Write tags & ltHTML & gt & lthead & gt . . . . & lt / head & gt */
public void writeHtmlHead ( Writer out ) throws IOException { } } | if ( ! writtenHtmlHead ) { writtenHtmlHead = true ; completeSections ( ) ; out . write ( "<html><head>" ) ; String title = ( String ) properties . get ( Title ) ; if ( title != null && title . length ( ) > 0 && ! title . equals ( NoTitle ) ) out . write ( "<title>" + title + "</title>" ) ; head . write ( out ) ; out . write ( base ) ; out . write ( "\n</head>\n" ) ; } |
public class UserHandlerImpl { /** * Remove user and related entities from cache . */
private void removeAllRelatedFromCache ( String userName ) { } } | cache . remove ( userName , CacheType . USER_PROFILE ) ; cache . remove ( CacheHandler . USER_PREFIX + userName , CacheType . MEMBERSHIP ) ; |
public class HttpServerExchange { /** * Force the codec to treat the request as fully read . Should only be invoked by handlers which downgrade
* the socket or implement a transfer coding . */
void terminateRequest ( ) { } } | int oldVal = state ; if ( allAreSet ( oldVal , FLAG_REQUEST_TERMINATED ) ) { // idempotent
return ; } if ( requestChannel != null ) { requestChannel . requestDone ( ) ; } this . state = oldVal | FLAG_REQUEST_TERMINATED ; if ( anyAreSet ( oldVal , FLAG_RESPONSE_TERMINATED ) ) { invokeExchangeCompleteListeners ( ) ; } |
public class CheckBase { /** * If called in one of the { @ code doVisit * ( ) } methods , this method will push the elements along with some
* contextual
* data onto an internal stack .
* < p > You can then retrieve the contents on the top of the stack in your { @ link # doEnd ( ) } override by calling the
* { @ link # popIfActive ( ) } method .
* @ param oldElement the old API element
* @ param newElement the new API element
* @ param context optional contextual data
* @ param < T > the type of the elements */
protected final < T extends JavaElement > void pushActive ( @ Nullable T oldElement , @ Nullable T newElement , Object ... context ) { } } | ActiveElements < T > r = new ActiveElements < > ( depth , oldElement , newElement , activations . peek ( ) , context ) ; activations . push ( r ) ; |
public class GeneralSubsetMove { /** * Apply this move to a given subset solution . The move can only be applied to a solution
* for which none of the added IDs are currently already selected and none of the removed
* IDs are currently not selected . This guarantees that calling { @ link # undo ( SubsetSolution ) }
* will correctly undo the move .
* @ throws SolutionModificationException if some added ID is already selected , some removed ID is currently
* not selected , or any ID does not correspond to an underlying entity
* @ param solution solution to which to move will be applied */
@ Override public void apply ( SubsetSolution solution ) { } } | // add IDs
for ( int ID : add ) { if ( ! solution . select ( ID ) ) { throw new SolutionModificationException ( "Cannot add ID " + ID + " to selection (already selected)." , solution ) ; } } // remove IDs
for ( int ID : delete ) { if ( ! solution . deselect ( ID ) ) { throw new SolutionModificationException ( "Cannot remove ID " + ID + " from selection (currently not selected)." , solution ) ; } } |
public class PathNormalizer { /** * Normalizes two paths and joins them as a single path .
* @ param prefix
* @ param path
* @ param generatorRegistry
* the generator registry
* @ return the joined path */
public static String joinPaths ( String prefix , String path , GeneratorRegistry generatorRegistry ) { } } | return joinPaths ( prefix , path , generatorRegistry . isPathGenerated ( prefix ) ) ; |
public class ClassWriterImpl { /** * Get the class helper tree for the given class .
* @ param type the class to print the helper for
* @ return a content tree for class helper */
private Content getTreeForClassHelper ( TypeMirror type ) { } } | Content li = new HtmlTree ( HtmlTag . LI ) ; if ( type . equals ( typeElement . asType ( ) ) ) { Content typeParameters = getTypeParameterLinks ( new LinkInfoImpl ( configuration , LinkInfoImpl . Kind . TREE , typeElement ) ) ; if ( configuration . shouldExcludeQualifier ( utils . containingPackage ( typeElement ) . toString ( ) ) ) { li . addContent ( utils . asTypeElement ( type ) . getSimpleName ( ) ) ; li . addContent ( typeParameters ) ; } else { li . addContent ( utils . asTypeElement ( type ) . getQualifiedName ( ) ) ; li . addContent ( typeParameters ) ; } } else { Content link = getLink ( new LinkInfoImpl ( configuration , LinkInfoImpl . Kind . CLASS_TREE_PARENT , type ) . label ( configuration . getClassName ( utils . asTypeElement ( type ) ) ) ) ; li . addContent ( link ) ; } return li ; |
public class LaunchAppropriateUI { /** * Launch the appropriate UI .
* @ throws java . lang . Exception */
public void launch ( ) throws Exception { } } | // Sanity - check the loaded BCEL classes
if ( ! CheckBcel . check ( ) ) { System . exit ( 1 ) ; } int launchProperty = getLaunchProperty ( ) ; if ( GraphicsEnvironment . isHeadless ( ) || launchProperty == TEXTUI ) { FindBugs2 . main ( args ) ; } else if ( launchProperty == SHOW_HELP ) { ShowHelp . main ( args ) ; } else if ( launchProperty == SHOW_VERSION ) { Version . main ( new String [ ] { "-release" } ) ; } else { Class < ? > launchClass = Class . forName ( "edu.umd.cs.findbugs.gui2.Driver" ) ; Method mainMethod = launchClass . getMethod ( "main" , args . getClass ( ) ) ; mainMethod . invoke ( null , ( Object ) args ) ; } |
public class Scopes { /** * Returns true if { @ code binding } has the given scope . If the binding is a { @ link
* com . google . inject . spi . LinkedKeyBinding linked key binding } and belongs to an injector ( ie . it
* was retrieved via { @ link Injector # getBinding Injector . getBinding ( ) } ) , then this method will
* also true if the target binding has the given scope .
* @ param binding binding to check
* @ param scope scope implementation instance
* @ param scopeAnnotation scope annotation class
* @ since 4.0 */
public static boolean isScoped ( Binding < ? > binding , final Scope scope , final Class < ? extends Annotation > scopeAnnotation ) { } } | do { boolean matches = binding . acceptScopingVisitor ( new BindingScopingVisitor < Boolean > ( ) { @ Override public Boolean visitNoScoping ( ) { return false ; } @ Override public Boolean visitScopeAnnotation ( Class < ? extends Annotation > visitedAnnotation ) { return visitedAnnotation == scopeAnnotation ; } @ Override public Boolean visitScope ( Scope visitedScope ) { return visitedScope == scope ; } @ Override public Boolean visitEagerSingleton ( ) { return false ; } } ) ; if ( matches ) { return true ; } if ( binding instanceof LinkedBindingImpl ) { LinkedBindingImpl < ? > linkedBinding = ( LinkedBindingImpl ) binding ; Injector injector = linkedBinding . getInjector ( ) ; if ( injector != null ) { binding = injector . getBinding ( linkedBinding . getLinkedKey ( ) ) ; continue ; } } else if ( binding instanceof ExposedBinding ) { ExposedBinding < ? > exposedBinding = ( ExposedBinding ) binding ; Injector injector = exposedBinding . getPrivateElements ( ) . getInjector ( ) ; if ( injector != null ) { binding = injector . getBinding ( exposedBinding . getKey ( ) ) ; continue ; } } return false ; } while ( true ) ; |
public class ExpandableAdapter { /** * Collapse parent .
* @ param parentPosition position of parent item . */
public final void collapseParent ( int parentPosition ) { } } | if ( isExpanded ( parentPosition ) ) { mExpandItemArray . append ( parentPosition , false ) ; int position = positionFromParentPosition ( parentPosition ) ; int childCount = childItemCount ( parentPosition ) ; notifyItemRangeRemoved ( position + 1 , childCount ) ; } |
public class CmsVaadinUtils { /** * Builds a container for use in combo boxes from a map of key / value pairs , where the keys are options and the values are captions . < p >
* @ param captionProperty the property name to use for captions
* @ param map the map
* @ return the new container */
public static IndexedContainer buildContainerFromMap ( String captionProperty , Map < String , String > map ) { } } | IndexedContainer container = new IndexedContainer ( ) ; for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { container . addItem ( entry . getKey ( ) ) . getItemProperty ( captionProperty ) . setValue ( entry . getValue ( ) ) ; } return container ; |
public class AmazonSimpleDBUtil { /** * Unsed to encode a Not Integer { @ link Number } . */
public static String encodeAsRealNumber ( Object ob ) { } } | if ( AmazonSimpleDBUtil . isNaN ( ob ) || AmazonSimpleDBUtil . isInfinite ( ob ) ) { throw new MappingException ( "Could not serialize NaN or Infinity values" ) ; } BigDecimal realBigDecimal = AmazonSimpleDBUtil . tryToStoreAsRealBigDecimal ( ob ) ; if ( realBigDecimal != null ) { return AmazonSimpleDBUtil . encodeRealNumberRange ( realBigDecimal , AmazonSimpleDBUtil . LONG_DIGITS , AmazonSimpleDBUtil . LONG_DIGITS , OFFSET_VALUE ) ; } return null ; |
public class SessionIdGenerator { /** * Generate and return a new session identifier . */
public String generateSessionId ( ) { } } | byte random [ ] = new byte [ 16 ] ; // Render the result as a String of hexadecimal digits
StringBuilder buffer = new StringBuilder ( ) ; int resultLenBytes = 0 ; while ( resultLenBytes < sessionIdLength ) { getRandomBytes ( random ) ; for ( int j = 0 ; j < random . length && resultLenBytes < sessionIdLength ; j ++ ) { byte b1 = ( byte ) ( ( random [ j ] & 0xf0 ) >> 4 ) ; byte b2 = ( byte ) ( random [ j ] & 0x0f ) ; if ( b1 < 10 ) { buffer . append ( ( char ) ( '0' + b1 ) ) ; } else { buffer . append ( ( char ) ( 'A' + ( b1 - 10 ) ) ) ; } if ( b2 < 10 ) { buffer . append ( ( char ) ( '0' + b2 ) ) ; } else { buffer . append ( ( char ) ( 'A' + ( b2 - 10 ) ) ) ; } resultLenBytes ++ ; } } if ( jvmRoute != null && jvmRoute . length ( ) > 0 ) { buffer . append ( '.' ) . append ( jvmRoute ) ; } return buffer . toString ( ) ; |
public class cmpaction { /** * Use this API to add cmpaction resources . */
public static base_responses add ( nitro_service client , cmpaction resources [ ] ) throws Exception { } } | base_responses result = null ; if ( resources != null && resources . length > 0 ) { cmpaction addresources [ ] = new cmpaction [ resources . length ] ; for ( int i = 0 ; i < resources . length ; i ++ ) { addresources [ i ] = new cmpaction ( ) ; addresources [ i ] . name = resources [ i ] . name ; addresources [ i ] . cmptype = resources [ i ] . cmptype ; addresources [ i ] . deltatype = resources [ i ] . deltatype ; } result = add_bulk_request ( client , addresources ) ; } return result ; |
public class WorkbooksInner { /** * Updates a workbook that has already been added .
* @ param resourceGroupName The name of the resource group .
* @ param resourceName The name of the Application Insights component resource .
* @ param workbookProperties Properties that need to be specified to create a new workbook .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws WorkbookErrorException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the WorkbookInner object if successful . */
public WorkbookInner update ( String resourceGroupName , String resourceName , WorkbookInner workbookProperties ) { } } | return updateWithServiceResponseAsync ( resourceGroupName , resourceName , workbookProperties ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class TransliteratorIDParser { /** * Parse an ID into pieces . Take IDs of the form T , T / V , S - T ,
* S - T / V , or S / V - T . If the source is missing , return a source of
* ANY .
* @ param id the id string , in any of several forms
* @ return an array of 4 strings : source , target , variant , and
* isSourcePresent . If the source is not present , ANY will be
* given as the source , and isSourcePresent will be null . Otherwise
* isSourcePresent will be non - null . The target may be empty if the
* id is not well - formed . The variant may be empty . */
public static String [ ] IDtoSTV ( String id ) { } } | String source = ANY ; String target = null ; String variant = "" ; int sep = id . indexOf ( TARGET_SEP ) ; int var = id . indexOf ( VARIANT_SEP ) ; if ( var < 0 ) { var = id . length ( ) ; } boolean isSourcePresent = false ; if ( sep < 0 ) { // Form : T / V or T ( or / V )
target = id . substring ( 0 , var ) ; variant = id . substring ( var ) ; } else if ( sep < var ) { // Form : S - T / V or S - T ( or - T / V or - T )
if ( sep > 0 ) { source = id . substring ( 0 , sep ) ; isSourcePresent = true ; } target = id . substring ( ++ sep , var ) ; variant = id . substring ( var ) ; } else { // Form : ( S / V - T or / V - T )
if ( var > 0 ) { source = id . substring ( 0 , var ) ; isSourcePresent = true ; } variant = id . substring ( var , sep ++ ) ; target = id . substring ( sep ) ; } if ( variant . length ( ) > 0 ) { variant = variant . substring ( 1 ) ; } return new String [ ] { source , target , variant , isSourcePresent ? "" : null } ; |
public class Fonts { /** * Applies font to provided TextView . < br / >
* Note : this class will only accept fonts under < code > fonts / < / code > directory
* and fonts starting with < code > font : < / code > prefix . */
public static void apply ( @ NonNull TextView textView , @ NonNull String fontPath ) { } } | if ( ! textView . isInEditMode ( ) ) { setTypeface ( textView , getFontFromString ( textView . getContext ( ) . getAssets ( ) , fontPath , true ) ) ; } |
public class CommandFactory { /** * Changes the view parameters of the player . The amount and detail returned
* by the visual sensor depends on the width of view and the quality . But
* note that the frequency of sending information also depends on these
* parameters . ( eg . If you change the quality from high to low , the
* frequency doubles , and the time between the two see sensors will be
* cut in half ) .
* @ param angle Between NARROW , NORMAL or WIDE .
* @ param quality Between HIGH or LOW . */
public void addChangeViewCommand ( ViewAngle angle , ViewQuality quality ) { } } | StringBuilder buf = new StringBuilder ( ) ; buf . append ( "(change_view " ) ; switch ( angle ) { case NARROW : switch ( quality ) { case HIGH : buf . append ( "narrow high)" ) ; break ; case LOW : buf . append ( "narrow low)" ) ; break ; } break ; case NORMAL : switch ( quality ) { case HIGH : buf . append ( "normal high)" ) ; break ; case LOW : buf . append ( "normal low)" ) ; break ; } break ; case WIDE : switch ( quality ) { case HIGH : buf . append ( "wide high)" ) ; break ; case LOW : buf . append ( "wide low)" ) ; break ; } break ; } fifo . add ( fifo . size ( ) , buf . toString ( ) ) ; |
public class StridedIndexTypeCollection { /** * Returns the given field of the element . */
int getField ( int element , int field ) { } } | assert ( m_buffer [ element >> m_blockPower ] [ ( element & m_blockMask ) + 1 ] != - 0x7eadbeed ) ; return m_buffer [ element >> m_blockPower ] [ ( element & m_blockMask ) + field ] ; |
public class DateTimeService { /** * This operation converts the date input value from one date / time format ( specified by dateFormat )
* to another date / time format ( specified by outFormat ) using locale settings ( language and country ) .
* You can use the flow " Get Current Date and Time " to check upon the default date / time format from
* the Java environment .
* @ param date the date to parse / convert
* @ param dateFormat the format of the input date
* @ param dateLocaleLang the locale language for input dateFormat string . It will be ignored if
* dateFormat is empty . default locale language from the Java environment
* ( which is dependent on the OS locale language )
* @ param dateLocaleCountry the locale country for input dateFormat string . It will be ignored
* if dateFormat is empty or dateLocaleLang is empty . Default locale country
* from the Java environment ( which is dependent on the OS locale country )
* @ param outFormat The format of the output date / time . Default date / time format from the Java
* environment ( which is dependent on the OS date / time format )
* @ param outLocaleLang The locale language for output string . It will be ignored if outFormat is
* empty .
* @ param outLocaleCountry The locale country for output string . It will be ignored if outFormat
* is empty or outLocaleLang is empty .
* @ return The date in the new format */
public static String parseDate ( final String date , final String dateFormat , final String dateLocaleLang , final String dateLocaleCountry , final String outFormat , final String outLocaleLang , final String outLocaleCountry ) throws Exception { } } | if ( StringUtils . isBlank ( date ) ) { throw new RuntimeException ( Constants . ErrorMessages . DATE_NULL_OR_EMPTY ) ; } DateTimeZone timeZone = DateTimeZone . forID ( Constants . Miscellaneous . GMT ) ; DateTime inputDateTime = parseInputDate ( date , dateFormat , dateLocaleLang , dateLocaleCountry , timeZone ) ; return changeFormatForDateTime ( inputDateTime , outFormat , outLocaleLang , outLocaleCountry ) ; |
public class OutboundFlowController { /** * Writes as much data for all the streams as possible given the current flow control windows .
* < p > Must be called with holding transport lock . */
void writeStreams ( ) { } } | OkHttpClientStream [ ] streams = transport . getActiveStreams ( ) ; int connectionWindow = connectionState . window ( ) ; for ( int numStreams = streams . length ; numStreams > 0 && connectionWindow > 0 ; ) { int nextNumStreams = 0 ; int windowSlice = ( int ) ceil ( connectionWindow / ( float ) numStreams ) ; for ( int index = 0 ; index < numStreams && connectionWindow > 0 ; ++ index ) { OkHttpClientStream stream = streams [ index ] ; OutboundFlowState state = state ( stream ) ; int bytesForStream = min ( connectionWindow , min ( state . unallocatedBytes ( ) , windowSlice ) ) ; if ( bytesForStream > 0 ) { state . allocateBytes ( bytesForStream ) ; connectionWindow -= bytesForStream ; } if ( state . unallocatedBytes ( ) > 0 ) { // There is more data to process for this stream . Add it to the next
// pass .
streams [ nextNumStreams ++ ] = stream ; } } numStreams = nextNumStreams ; } // Now take one last pass through all of the streams and write any allocated bytes .
WriteStatus writeStatus = new WriteStatus ( ) ; for ( OkHttpClientStream stream : transport . getActiveStreams ( ) ) { OutboundFlowState state = state ( stream ) ; state . writeBytes ( state . allocatedBytes ( ) , writeStatus ) ; state . clearAllocatedBytes ( ) ; } if ( writeStatus . hasWritten ( ) ) { flush ( ) ; } |
public class ResourceTypeUtil { /** * Iterates over the { @ link Resources } and
* returns either the resource with specified < code > resourceType < / code > or < code > null < / code > . */
public static Resource getResourceByType ( int resourceType ) { } } | for ( Resource resource : Resources . values ( ) ) { if ( resource . resourceType ( ) == resourceType ) { return resource ; } } return null ; |
public class XMLSocketReceiver { /** * Called when the receiver should be stopped . Closes the
* server socket and all of the open sockets . */
public synchronized void shutdown ( ) { } } | // mark this as no longer running
active = false ; if ( rThread != null ) { rThread . interrupt ( ) ; rThread = null ; } doShutdown ( ) ; |
public class AWSCodePipelineClient { /** * Resumes the pipeline execution by retrying the last failed actions in a stage .
* @ param retryStageExecutionRequest
* Represents the input of a RetryStageExecution action .
* @ return Result of the RetryStageExecution operation returned by the service .
* @ throws ValidationException
* The validation was specified in an invalid format .
* @ throws PipelineNotFoundException
* The specified pipeline was specified in an invalid format or cannot be found .
* @ throws StageNotFoundException
* The specified stage was specified in an invalid format or cannot be found .
* @ throws StageNotRetryableException
* The specified stage can ' t be retried because the pipeline structure or stage state changed after the
* stage was not completed ; the stage contains no failed actions ; one or more actions are still in progress ;
* or another retry attempt is already in progress .
* @ throws NotLatestPipelineExecutionException
* The stage has failed in a later run of the pipeline and the pipelineExecutionId associated with the
* request is out of date .
* @ sample AWSCodePipeline . RetryStageExecution
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / codepipeline - 2015-07-09 / RetryStageExecution "
* target = " _ top " > AWS API Documentation < / a > */
@ Override public RetryStageExecutionResult retryStageExecution ( RetryStageExecutionRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeRetryStageExecution ( request ) ; |
public class Auth { /** * 下载签名
* @ param baseUrl 待签名文件url , 如 http : / / img . domain . com / u / 3 . jpg 、
* http : / / img . domain . com / u / 3 . jpg ? imageView2/1 / w / 120
* @ param expires 有效时长 , 单位秒 。 默认3600s
* @ return */
public String privateDownloadUrl ( String baseUrl , long expires ) { } } | long deadline = System . currentTimeMillis ( ) / 1000 + expires ; return privateDownloadUrlWithDeadline ( baseUrl , deadline ) ; |
public class Searcher { /** * Search .
* @ param _ query the query
* @ return the search result
* @ throws EFapsException on error */
public static SearchResult search ( final String _query ) throws EFapsException { } } | final ISearch searchDef = Index . getSearch ( ) ; searchDef . setQuery ( _query ) ; return search ( searchDef ) ; |
public class ArabicShaping { /** * Name : deShapeUnicode
* Function : Converts an Arabic Unicode buffer in FExx Range into unshaped
* arabic Unicode buffer in 06xx Range */
private int deShapeUnicode ( char [ ] dest , int start , int length , int destSize ) throws ArabicShapingException { } } | int lamalef_count = deshapeNormalize ( dest , start , length ) ; // If there was a lamalef in the buffer call expandLamAlef
if ( lamalef_count != 0 ) { // need to adjust dest to fit expanded buffer . . . ! ! !
destSize = expandCompositChar ( dest , start , length , lamalef_count , DESHAPE_MODE ) ; } else { destSize = length ; } return destSize ; |
public class JdbcCpoAdapter { /** * DOCUMENT ME !
* @ param obj DOCUMENT ME !
* @ param groupName DOCUMENT ME !
* @ param con DOCUMENT ME !
* @ return DOCUMENT ME !
* @ throws CpoException DOCUMENT ME ! */
protected < T > T processSelectGroup ( T obj , String groupName , Collection < CpoWhere > wheres , Collection < CpoOrderBy > orderBy , Collection < CpoNativeFunction > nativeExpressions , Connection con ) throws CpoException { } } | PreparedStatement ps = null ; ResultSet rs = null ; ResultSetMetaData rsmd ; CpoClass cpoClass ; JdbcCpoAttribute attribute ; T criteriaObj = obj ; boolean recordsExist = false ; Logger localLogger = obj == null ? logger : LoggerFactory . getLogger ( obj . getClass ( ) ) ; int recordCount = 0 ; int attributesSet = 0 ; int k ; T rObj = null ; if ( obj == null ) { throw new CpoException ( "NULL Object passed into retrieveBean" ) ; } try { cpoClass = metaDescriptor . getMetaClass ( criteriaObj ) ; List < CpoFunction > functions = cpoClass . getFunctionGroup ( JdbcCpoAdapter . RETRIEVE_GROUP , groupName ) . getFunctions ( ) ; localLogger . info ( "=================== Class=<" + criteriaObj . getClass ( ) + "> Type=<" + JdbcCpoAdapter . RETRIEVE_GROUP + "> Name=<" + groupName + "> =========================" ) ; try { rObj = ( T ) obj . getClass ( ) . newInstance ( ) ; } catch ( IllegalAccessException iae ) { localLogger . error ( "=================== Could not access default constructor for Class=<" + obj . getClass ( ) + "> ==================" ) ; throw new CpoException ( "Unable to access the constructor of the Return Object" , iae ) ; } catch ( InstantiationException iae ) { throw new CpoException ( "Unable to instantiate Return Object" , iae ) ; } for ( CpoFunction cpoFunction : functions ) { JdbcPreparedStatementFactory jpsf = new JdbcPreparedStatementFactory ( con , this , cpoClass , cpoFunction , criteriaObj , wheres , orderBy , nativeExpressions ) ; ps = jpsf . getPreparedStatement ( ) ; // insertions on
// selectgroup
rs = ps . executeQuery ( ) ; jpsf . release ( ) ; if ( rs . isBeforeFirst ( ) ) { rsmd = rs . getMetaData ( ) ; if ( ( rsmd . getColumnCount ( ) == 2 ) && "CPO_ATTRIBUTE" . equalsIgnoreCase ( rsmd . getColumnLabel ( 1 ) ) && "CPO_VALUE" . equalsIgnoreCase ( rsmd . getColumnLabel ( 2 ) ) ) { while ( rs . next ( ) ) { recordsExist = true ; recordCount ++ ; attribute = ( JdbcCpoAttribute ) cpoClass . getAttributeData ( rs . getString ( 1 ) ) ; if ( attribute != null ) { attribute . invokeSetter ( rObj , new ResultSetCpoData ( JdbcMethodMapper . getMethodMapper ( ) , rs , attribute , 2 ) ) ; attributesSet ++ ; } } } else if ( rs . next ( ) ) { recordsExist = true ; recordCount ++ ; for ( k = 1 ; k <= rsmd . getColumnCount ( ) ; k ++ ) { attribute = ( JdbcCpoAttribute ) cpoClass . getAttributeData ( rsmd . getColumnLabel ( k ) ) ; if ( attribute != null ) { attribute . invokeSetter ( rObj , new ResultSetCpoData ( JdbcMethodMapper . getMethodMapper ( ) , rs , attribute , k ) ) ; attributesSet ++ ; } } if ( rs . next ( ) ) { String msg = "ProcessSelectGroup(Object, String) failed: Multiple Records Returned" ; localLogger . error ( msg ) ; throw new CpoException ( msg ) ; } } criteriaObj = rObj ; } rs . close ( ) ; rs = null ; ps . close ( ) ; ps = null ; } if ( ! recordsExist ) { rObj = null ; localLogger . info ( "=================== 0 Records - 0 Attributes - Class=<" + criteriaObj . getClass ( ) + "> Type=<" + JdbcCpoAdapter . RETRIEVE_GROUP + "> Name=<" + groupName + "> =========================" ) ; } else { localLogger . info ( "=================== " + recordCount + " Records - " + attributesSet + " Attributes - Class=<" + criteriaObj . getClass ( ) + "> Type=<" + JdbcCpoAdapter . RETRIEVE_GROUP + "> Name=<" + groupName + "> =========================" ) ; } } catch ( Throwable t ) { String msg = "ProcessSeclectGroup(Object) failed: " + ExceptionHelper . getLocalizedMessage ( t ) ; localLogger . error ( msg , t ) ; rObj = null ; throw new CpoException ( msg , t ) ; } finally { resultSetClose ( rs ) ; statementClose ( ps ) ; } return rObj ; |
public class ValidateEnv { /** * validates environment on remote node */
private static boolean validateRemote ( String node , String target , String name , CommandLine cmd ) throws InterruptedException { } } | System . out . format ( "Validating %s environment on %s...%n" , target , node ) ; if ( ! Utils . isAddressReachable ( node , 22 ) ) { System . err . format ( "Unable to reach ssh port 22 on node %s.%n" , node ) ; return false ; } // args is not null .
String argStr = String . join ( " " , cmd . getArgs ( ) ) ; String homeDir = ServerConfiguration . get ( PropertyKey . HOME ) ; String remoteCommand = String . format ( "%s/bin/alluxio validateEnv %s %s %s" , homeDir , target , name == null ? "" : name , argStr ) ; String localCommand = String . format ( "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"" , node , remoteCommand ) ; String [ ] command = { "bash" , "-c" , localCommand } ; try { ProcessBuilder builder = new ProcessBuilder ( command ) ; builder . redirectErrorStream ( true ) ; builder . redirectOutput ( ProcessBuilder . Redirect . INHERIT ) ; builder . redirectInput ( ProcessBuilder . Redirect . INHERIT ) ; Process process = builder . start ( ) ; process . waitFor ( ) ; return process . exitValue ( ) == 0 ; } catch ( IOException e ) { System . err . format ( "Unable to validate on node %s: %s.%n" , node , e . getMessage ( ) ) ; return false ; } |
public class Polynomial { /** * Computes the polynomials output given the variable value Can handle infinite numbers
* @ return Output */
public double evaluate ( double variable ) { } } | if ( size == 0 ) { return 0 ; } else if ( size == 1 ) { return c [ 0 ] ; } else if ( Double . isInfinite ( variable ) ) { // Only the largest power with a non - zero coefficient needs to be evaluated
int degree = computeDegree ( ) ; if ( degree % 2 == 0 ) variable = Double . POSITIVE_INFINITY ; if ( c [ degree ] < 0 ) variable = variable == Double . POSITIVE_INFINITY ? Double . NEGATIVE_INFINITY : Double . POSITIVE_INFINITY ; return variable ; } // Evaluate using Horner ' s Method .
// This formulation produces more accurate results than the straight forward one and has fewer
// multiplications
double total = c [ size - 1 ] ; for ( int i = size - 2 ; i >= 0 ; i -- ) { total = c [ i ] + total * variable ; } return total ; |
public class CommerceAccountPersistenceImpl { /** * Returns the last commerce account in the ordered set where userId = & # 63 ; and type = & # 63 ; .
* @ param userId the user ID
* @ param type the type
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the last matching commerce account , or < code > null < / code > if a matching commerce account could not be found */
@ Override public CommerceAccount fetchByU_T_Last ( long userId , int type , OrderByComparator < CommerceAccount > orderByComparator ) { } } | int count = countByU_T ( userId , type ) ; if ( count == 0 ) { return null ; } List < CommerceAccount > list = findByU_T ( userId , type , count - 1 , count , orderByComparator ) ; if ( ! list . isEmpty ( ) ) { return list . get ( 0 ) ; } return null ; |
public class PMode { /** * < code > required . alluxio . grpc . Bits otherBits = 3 ; < / code > */
public alluxio . grpc . Bits getOtherBits ( ) { } } | alluxio . grpc . Bits result = alluxio . grpc . Bits . valueOf ( otherBits_ ) ; return result == null ? alluxio . grpc . Bits . NONE : result ; |
public class ReqUtil { /** * Get a multi - valued request parameter stripped of white space .
* Return null for zero length .
* @ param name name of parameter
* @ return List < String > or null
* @ throws Throwable */
public List < String > getReqPars ( final String name ) throws Throwable { } } | String [ ] s = request . getParameterValues ( name ) ; ArrayList < String > res = null ; if ( ( s == null ) || ( s . length == 0 ) ) { return null ; } for ( String par : s ) { par = Util . checkNull ( par ) ; if ( par != null ) { if ( res == null ) { res = new ArrayList < > ( ) ; } res . add ( par ) ; } } return res ; |
public class ApiOvhMe { /** * Return main data about the object the processing of the order generated
* REST : GET / me / order / { orderId } / associatedObject
* @ param orderId [ required ] */
public OvhAssociatedObject order_orderId_associatedObject_GET ( Long orderId ) throws IOException { } } | String qPath = "/me/order/{orderId}/associatedObject" ; StringBuilder sb = path ( qPath , orderId ) ; String resp = exec ( qPath , "GET" , sb . toString ( ) , null ) ; return convertTo ( resp , OvhAssociatedObject . class ) ; |
public class GoogleCodingConvention { /** * { @ inheritDoc }
* < p > In Google code , any global name starting with an underscore is
* considered exported . */
@ Override public boolean isExported ( String name , boolean local ) { } } | return super . isExported ( name , local ) || ( ! local && name . startsWith ( "_" ) ) ; |
public class JumboEnumSet { /** * Removes the specified element from this set if it is present .
* @ param e element to be removed from this set , if present
* @ return < tt > true < / tt > if the set contained the specified element */
public boolean remove ( Object e ) { } } | if ( e == null ) return false ; Class < ? > eClass = e . getClass ( ) ; if ( eClass != elementType && eClass . getSuperclass ( ) != elementType ) return false ; int eOrdinal = ( ( Enum < ? > ) e ) . ordinal ( ) ; int eWordNum = eOrdinal >>> 6 ; long oldElements = elements [ eWordNum ] ; elements [ eWordNum ] &= ~ ( 1L << eOrdinal ) ; boolean result = ( elements [ eWordNum ] != oldElements ) ; if ( result ) size -- ; return result ; |
public class BeanQuery { /** * Create a BeanQuery instance with multiple Selectors .
* @ param selectors */
public static BeanQuery < Map < String , Object > > select ( KeyValueMapSelector ... selectors ) { } } | return new BeanQuery < Map < String , Object > > ( new CompositeSelector ( selectors ) ) ; |
public class CmsSerialDateValue { /** * Validates the wrapped value and returns a localized error message in case of invalid values .
* @ return < code > null < / code > if the value is valid , a suitable localized error message otherwise . */
public CmsMessageContainer validateWithMessage ( ) { } } | if ( m_parsingFailed ) { return Messages . get ( ) . container ( Messages . ERR_SERIALDATE_INVALID_VALUE_0 ) ; } if ( ! isStartSet ( ) ) { return Messages . get ( ) . container ( Messages . ERR_SERIALDATE_START_MISSING_0 ) ; } if ( ! isEndValid ( ) ) { return Messages . get ( ) . container ( Messages . ERR_SERIALDATE_END_BEFORE_START_0 ) ; } String key = validatePattern ( ) ; if ( null != key ) { return Messages . get ( ) . container ( key ) ; } key = validateDuration ( ) ; if ( null != key ) { return Messages . get ( ) . container ( key ) ; } if ( hasTooManyEvents ( ) ) { return Messages . get ( ) . container ( Messages . ERR_SERIALDATE_TOO_MANY_EVENTS_1 , Integer . valueOf ( CmsSerialDateUtil . getMaxEvents ( ) ) ) ; } return null ; |
public class LazyObject { /** * Returns the JSON array stored in this object for the given key or null if the key doesn ' t exist .
* @ param key the name of the field on this object
* @ return an array value or null if the key doesn ' t exist
* @ throws LazyException if the value for the given key was not an array . */
public LazyArray optJSONArray ( String key ) throws LazyException { } } | LazyNode token = getOptionalFieldToken ( key ) ; if ( token == null ) return null ; if ( token . type == LazyNode . VALUE_NULL ) return null ; if ( token . type != LazyNode . ARRAY ) return null ; LazyArray arr = new LazyArray ( token ) ; arr . parent = this ; return arr ; |
public class MentsuComp { /** * 対子も含めて全ての面子をリストにして返します
* @ return 構成する全ての面子のリスト */
public List < Mentsu > getAllMentsu ( ) { } } | List < Mentsu > allMentsu = new ArrayList < > ( 7 ) ; allMentsu . addAll ( getToitsuList ( ) ) ; allMentsu . addAll ( getShuntsuList ( ) ) ; allMentsu . addAll ( getKotsuList ( ) ) ; allMentsu . addAll ( getKantsuList ( ) ) ; return allMentsu ; |
public class MessageLogger { /** * Logs a message by the provided key to the provided { @ link Logger } at debug level after substituting the parameters in the message by the provided objects .
* @ param logger the logger to log to
* @ param messageKey the key of the message in the bundle
* @ param objects the substitution parameters */
public final void logDebug ( final Logger logger , final String messageKey , final Object ... objects ) { } } | logger . debug ( getMessage ( messageKey , objects ) ) ; |
public class FraggleManager { /** * Configures the way to add the Fragment into the transaction . It can vary from adding a new fragment ,
* to using a previous instance and refresh it , or replacing the last one .
* @ param frag Fragment to add
* @ param flags Added flags to the Fragment configuration
* @ param ft Transaction to add the fragment
* @ param containerId Target container ID */
protected void configureAdditionMode ( Fragment frag , int flags , FragmentTransaction ft , int containerId ) { } } | if ( ( flags & DO_NOT_REPLACE_FRAGMENT ) != DO_NOT_REPLACE_FRAGMENT ) { ft . replace ( containerId , frag , ( ( FraggleFragment ) frag ) . getFragmentTag ( ) ) ; } else { ft . add ( containerId , frag , ( ( FraggleFragment ) frag ) . getFragmentTag ( ) ) ; peek ( ) . onFragmentNotVisible ( ) ; } |
public class BeanMetaData { /** * Gets the index of the remote business interface . This will also
* try to match the interface class passed in to a super type of a
* known interface of an EJB . < p >
* Note : this should only be used if necessary , as this is an expensive
* check . The getRemoteBusinessInterfaceIndex method should be used
* if this specialized check is not needed .
* @ param target the class that needs to be matched to an interface
* @ return the index of the found matching interface */
public int getAssignableRemoteBusinessInterfaceIndex ( Class < ? > target ) { } } | if ( ivBusinessRemoteInterfaceClasses != null ) { for ( int i = 0 ; i < ivBusinessRemoteInterfaceClasses . length ; i ++ ) { Class < ? > bInterface = ivBusinessRemoteInterfaceClasses [ i ] ; if ( target . isAssignableFrom ( bInterface ) ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) Tr . debug ( tc , "getAssignableRemoteBusinessInterfaceIndex : " + bInterface . getName ( ) + " at index " + i ) ; return i ; } } } return - 1 ; |
public class MetatagsRecord { /** * Returns an unmodifiable collection of metatags associated with the metric .
* @ return The metatags for a metric . Will never be null but may be empty . */
public Map < String , String > getMetatags ( ) { } } | Map < String , String > result = new HashMap < > ( ) ; for ( Map . Entry < String , String > entry : _metatags . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( ! ReservedField . isReservedField ( key ) ) { result . put ( key , entry . getValue ( ) ) ; } } return Collections . unmodifiableMap ( result ) ; |
public class Vector2d { /** * Replies the orientation vector , which is corresponding
* to the given angle on a trigonometric circle .
* @ param angle is the angle in radians to translate .
* @ return the orientation vector which is corresponding to the given angle . */
@ Pure @ Inline ( value = "new Vector2d(Math.cos($1), Math.sin($1))" , imported = { } } | Vector2d . class , Math . class } ) public static Vector2d toOrientationVector ( double angle ) { return new Vector2d ( Math . cos ( angle ) , Math . sin ( angle ) ) ; |
public class XTypeLiteralImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public Object eGet ( int featureID , boolean resolve , boolean coreType ) { } } | switch ( featureID ) { case XbasePackage . XTYPE_LITERAL__TYPE : if ( resolve ) return getType ( ) ; return basicGetType ( ) ; case XbasePackage . XTYPE_LITERAL__ARRAY_DIMENSIONS : return getArrayDimensions ( ) ; } return super . eGet ( featureID , resolve , coreType ) ; |
public class ProjectCalendarContainer { /** * Retrieves the named calendar . This method will return
* null if the named calendar is not located .
* @ param calendarName name of the required calendar
* @ return ProjectCalendar instance */
public ProjectCalendar getByName ( String calendarName ) { } } | ProjectCalendar calendar = null ; if ( calendarName != null && calendarName . length ( ) != 0 ) { Iterator < ProjectCalendar > iter = iterator ( ) ; while ( iter . hasNext ( ) == true ) { calendar = iter . next ( ) ; String name = calendar . getName ( ) ; if ( ( name != null ) && ( name . equalsIgnoreCase ( calendarName ) == true ) ) { break ; } calendar = null ; } } return ( calendar ) ; |
public class KunderaJTAUserTransaction { /** * ( non - Javadoc )
* @ see javax . transaction . UserTransaction # begin ( ) */
@ Override public void begin ( ) throws NotSupportedException , SystemException { } } | if ( log . isDebugEnabled ( ) ) log . info ( "beginning JTA transaction" ) ; Transaction tx = threadLocal . get ( ) ; if ( tx != null ) { if ( ( tx . getStatus ( ) == Status . STATUS_MARKED_ROLLBACK ) ) { throw new NotSupportedException ( "Nested Transaction not supported!" ) ; } } Integer timer = timerThead . get ( ) ; threadLocal . set ( new KunderaTransaction ( timer != null ? timer : DEFAULT_TIME_OUT ) ) ; |
public class Retryer { /** * Sets the stop strategy used to decide when to stop retrying . The default strategy is never stop
* @ param stopStrategy
* @ return */
public Retryer < R > withStopStrategy ( StopStrategy stopStrategy ) { } } | checkState ( this . stopStrategy == null , "A stop strategy has already been set %s" , this . stopStrategy ) ; this . stopStrategy = checkNotNull ( stopStrategy , "StopStrategy cannot be null" ) ; return this ; |
public class CommerceWarehouseUtil { /** * Returns the first commerce warehouse in the ordered set where groupId = & # 63 ; and active = & # 63 ; .
* @ param groupId the group ID
* @ param active the active
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the first matching commerce warehouse , or < code > null < / code > if a matching commerce warehouse could not be found */
public static CommerceWarehouse fetchByG_A_First ( long groupId , boolean active , OrderByComparator < CommerceWarehouse > orderByComparator ) { } } | return getPersistence ( ) . fetchByG_A_First ( groupId , active , orderByComparator ) ; |
public class RowLevelPolicyChecker { /** * Get final state for this object , obtained by merging the final states of the
* { @ link org . apache . gobblin . qualitychecker . row . RowLevelPolicy } s used by this object .
* @ return Merged { @ link org . apache . gobblin . configuration . State } of final states for
* { @ link org . apache . gobblin . qualitychecker . row . RowLevelPolicy } used by this checker . */
@ Override public State getFinalState ( ) { } } | State state = new State ( ) ; for ( RowLevelPolicy policy : this . list ) { state . addAll ( policy . getFinalState ( ) ) ; } return state ; |
public class UserRepository { /** * Updates a user that was previously fetched from the repository . Only fields that have been
* modified since it was loaded will be written to the database and those fields will
* subsequently be marked clean once again .
* @ return true if the record was updated , false if the update was skipped because no fields in
* the user record were modified . */
public boolean updateUser ( final User user ) throws PersistenceException { } } | if ( ! user . getDirtyMask ( ) . isModified ( ) ) { // nothing doing !
return false ; } update ( _utable , user , user . getDirtyMask ( ) ) ; return true ; |
public class URIDestinationCreator { /** * Remove ' \ ' characters from input String when they precede
* specified character .
* @ param input The string to be processed
* @ param c The character that should be unescaped
* @ return The modified String */
private String unescape ( String input , char c ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "unescape" , new Object [ ] { input , c } ) ; String result = input ; // if there are no instances of c in the String we can just return the original
if ( input . indexOf ( c ) != - 1 ) { int startValue = 0 ; StringBuffer temp = new StringBuffer ( input ) ; String cStr = new String ( new char [ ] { c } ) ; while ( ( startValue = temp . indexOf ( cStr , startValue ) ) != - 1 ) { if ( startValue > 0 && temp . charAt ( startValue - 1 ) == '\\' ) { // remove the preceding slash to leave the escaped character
temp . deleteCharAt ( startValue - 1 ) ; } else { startValue ++ ; } } result = temp . toString ( ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "unescape" , result ) ; return result ; |
public class VariantMetadataManager { /** * Remove a variant file metadata of a given variant study metadata ( from study ID ) .
* @ param file File
* @ param studyId Study ID */
public void removeFile ( VariantFileMetadata file , String studyId ) { } } | // Sanity check
if ( file == null ) { logger . error ( "Variant file metadata is null." ) ; return ; } removeFile ( file . getId ( ) , studyId ) ; |
public class ComparableProperty { /** * Creates a { @ code Filter } to indicate whether this property is less than
* the specified value or not ( & lt ; ) .
* @ param value The value to be evaluated .
* @ return The { @ code Filter } to indicate whether this property is less than
* the specified value or not . */
public Filter < T > lessThan ( T value ) { } } | return new ComparableFilter < T > ( this , value , Operator . LESS_THAN ) ; |
public class XMLChar { /** * Returns true if the specified character is a extender as defined by production [ 89 ] in the XML
* 1.0 specification .
* @ param ch
* The character to check . */
public static boolean isExtender ( int ch ) { } } | return 0x00B7 == ch || 0x02D0 == ch || 0x02D1 == ch || 0x0387 == ch || 0x0640 == ch || 0x0E46 == ch || 0x0EC6 == ch || 0x3005 == ch || ( 0x3031 <= ch && ch <= 0x3035 ) || ( 0x309D <= ch && ch <= 0x309E ) || ( 0x30FC <= ch && ch <= 0x30FE ) ; |
public class LoadLibs { /** * Copies resources from WAR to target folder .
* @ param virtualFileOrFolder
* @ param targetFolder
* @ throws IOException */
static void copyFromWarToFolder ( VirtualFile virtualFileOrFolder , File targetFolder ) throws IOException { } } | if ( virtualFileOrFolder . isDirectory ( ) && ! virtualFileOrFolder . getName ( ) . contains ( "." ) ) { if ( targetFolder . getName ( ) . equalsIgnoreCase ( virtualFileOrFolder . getName ( ) ) ) { for ( VirtualFile innerFileOrFolder : virtualFileOrFolder . getChildren ( ) ) { copyFromWarToFolder ( innerFileOrFolder , targetFolder ) ; } } else { File innerTargetFolder = new File ( targetFolder , virtualFileOrFolder . getName ( ) ) ; innerTargetFolder . mkdir ( ) ; for ( VirtualFile innerFileOrFolder : virtualFileOrFolder . getChildren ( ) ) { copyFromWarToFolder ( innerFileOrFolder , innerTargetFolder ) ; } } } else { File targetFile = new File ( targetFolder , virtualFileOrFolder . getName ( ) ) ; if ( ! targetFile . exists ( ) || targetFile . length ( ) != virtualFileOrFolder . getSize ( ) ) { FileUtils . copyURLToFile ( virtualFileOrFolder . asFileURL ( ) , targetFile ) ; } } |
public class Ifc4PackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public EClass getIfcRelDefinesByType ( ) { } } | if ( ifcRelDefinesByTypeEClass == null ) { ifcRelDefinesByTypeEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( Ifc4Package . eNS_URI ) . getEClassifiers ( ) . get ( 551 ) ; } return ifcRelDefinesByTypeEClass ; |
public class AssetUtil { /** * Helper to extract a ClassloaderResources name . < br / >
* < br / >
* ie : / user / test / file . properties = file . properties
* @ param resourceName
* The name of the resource
* @ return The name of the given resource */
public static String getNameForClassloaderResource ( String resourceName ) { } } | String fileName = resourceName ; if ( resourceName . indexOf ( '/' ) != - 1 ) { fileName = resourceName . substring ( resourceName . lastIndexOf ( '/' ) + 1 , resourceName . length ( ) ) ; } return fileName ; |
public class FlowController { /** * Call an action and return the result URI .
* @ param actionName the name of the action to run .
* @ param form the form bean instance to pass to the action , or < code > null < / code > if none should be passed .
* @ return the result webapp - relative URI , as a String .
* @ throws ActionNotFoundException when the given action does not exist in this FlowController .
* @ throws Exception if the action method throws an Exception . */
public String resolveAction ( String actionName , Object form , HttpServletRequest request , HttpServletResponse response ) throws Exception { } } | ActionMapping mapping = ( ActionMapping ) getModuleConfig ( ) . findActionConfig ( '/' + actionName ) ; if ( mapping == null ) { InternalUtils . throwPageFlowException ( new ActionNotFoundException ( actionName , this , form ) , request ) ; } ActionForward fwd = getActionMethodForward ( actionName , form , request , response , mapping ) ; if ( fwd instanceof Forward ) { ( ( Forward ) fwd ) . initialize ( mapping , this , request ) ; } String path = fwd . getPath ( ) ; if ( fwd . getContextRelative ( ) || FileUtils . isAbsoluteURI ( path ) ) { return path ; } else { return getModulePath ( ) + path ; } |
public class RedefinableXmlLaContainerBuilder { protected void mergeContainers ( LaContainer container , String path , boolean addToTail ) { } } | final Set < URL > additionalURLSet = gatherAdditionalDiconURLs ( path , addToTail ) ; for ( Iterator < URL > itr = additionalURLSet . iterator ( ) ; itr . hasNext ( ) ; ) { final String url = itr . next ( ) . toExternalForm ( ) ; if ( LaContainerBuilderUtils . resourceExists ( url , this ) ) { LaContainerBuilderUtils . mergeContainer ( container , LaContainerFactory . create ( url ) ) ; } } |
public class NewChunk { /** * Heuristic to decide the basic type of a column */
public byte type ( ) { } } | if ( _naCnt == - 1 ) { // No rollups yet ?
int nas = 0 , ss = 0 , nzs = 0 ; if ( _ds != null && _ls != null ) { // UUID ?
for ( int i = 0 ; i < _sparseLen ; i ++ ) if ( _xs != null && _xs [ i ] == Integer . MIN_VALUE ) nas ++ ; else if ( _ds [ i ] != 0 || _ls [ i ] != 0 ) nzs ++ ; _uuidCnt = _len - nas ; } else if ( _ds != null ) { // Doubles ?
assert _xs == null ; for ( int i = 0 ; i < _sparseLen ; ++ i ) if ( Double . isNaN ( _ds [ i ] ) ) nas ++ ; else if ( _ds [ i ] != 0 ) nzs ++ ; } else { // Longs and enums ?
if ( _ls != null ) for ( int i = 0 ; i < _sparseLen ; i ++ ) if ( isNA2 ( i ) ) nas ++ ; else { if ( isEnum2 ( i ) ) ss ++ ; if ( _ls [ i ] != 0 ) nzs ++ ; } } _nzCnt = nzs ; _strCnt = ss ; _naCnt = nas ; } // Now run heuristic for type
if ( _naCnt == _len ) // All NAs = = > NA Chunk
return AppendableVec . NA ; if ( _strCnt > 0 && _strCnt + _naCnt == _len ) return AppendableVec . ENUM ; // All are Strings + NAs = = > Enum Chunk
// UUIDs ?
if ( _uuidCnt > 0 ) return AppendableVec . UUID ; // Larger of time & numbers
int timCnt = 0 ; for ( int t : _timCnt ) timCnt += t ; int nums = _len - _naCnt - timCnt ; return timCnt >= nums ? AppendableVec . TIME : AppendableVec . NUMBER ; |
public class URITemplate { /** * Liberty Change end */
public static int compareTemplates ( URITemplate t1 , URITemplate t2 ) { } } | int l1 = t1 . getLiteralChars ( ) . length ( ) ; int l2 = t2 . getLiteralChars ( ) . length ( ) ; // descending order
int result = l1 < l2 ? 1 : l1 > l2 ? - 1 : 0 ; if ( result == 0 ) { int g1 = t1 . getVariables ( ) . size ( ) ; int g2 = t2 . getVariables ( ) . size ( ) ; // descending order
result = g1 < g2 ? 1 : g1 > g2 ? - 1 : 0 ; if ( result == 0 ) { int gCustom1 = t1 . getCustomVariables ( ) . size ( ) ; int gCustom2 = t2 . getCustomVariables ( ) . size ( ) ; result = gCustom1 < gCustom2 ? 1 : gCustom1 > gCustom2 ? - 1 : 0 ; if ( result == 0 ) { result = t1 . getPatternValue ( ) . compareTo ( t2 . getPatternValue ( ) ) ; } } } return result ; |
public class MurmurHash3v2 { /** * Returns a 128 - bit hash of the input .
* Note the entropy of the resulting hash cannot be more than 64 bits .
* @ param in a long
* @ param seed A long valued seed .
* @ param hashOut A long array of size 2
* @ return the hash */
public static long [ ] hash ( final long in , final long seed , final long [ ] hashOut ) { } } | final long h1 = seed ^ mixK1 ( in ) ; final long h2 = seed ; return finalMix128 ( h1 , h2 , 8 , hashOut ) ; |
public class AipImageSearch { /** * 相同图检索 — 删除接口
* * * 删除图库中的图片 , 支持批量删除 , 批量删除时请传cont _ sign参数 , 勿传image , 最多支持1000个cont _ sign * *
* @ param url - 图片完整URL , URL长度不超过1024字节 , URL对应的图片base64编码后大小不超过4M , 最短边至少15px , 最长边最大4096px , 支持jpg / png / bmp格式 , 当image字段存在时url字段失效
* @ param options - 可选参数对象 , key : value都为string类型
* options - options列表 :
* @ return JSONObject */
public JSONObject sameHqDeleteByUrl ( String url , HashMap < String , String > options ) { } } | AipRequest request = new AipRequest ( ) ; preOperation ( request ) ; request . addBody ( "url" , url ) ; if ( options != null ) { request . addBody ( options ) ; } request . setUri ( ImageSearchConsts . SAME_HQ_DELETE ) ; postOperation ( request ) ; return requestServer ( request ) ; |
public class FileTools { /** * Load a collection of properties files into the same Map , supports multiple lines values .
* @ param sources
* the list of properties files to load .
* @ param encoding
* the encoding of the files .
* @ param newline
* the sequence to use as a line separator for multiple line values .
* @ return the properties , merged following the rules " the last speaker is right " .
* @ throws IOException
* if there is a problem to deal with , especially if one of the URL points to nothing .
* @ throws SyntaxErrorException
* if there is a problem to deal with .
* @ see LineByLinePropertyParser
* @ since 16.08.02 */
public static Map < String , String > loadBundle ( List < URL > sources , Encoding encoding , String newline ) throws IOException , SyntaxErrorException { } } | Map < String , String > _result = new HashMap < String , String > ( ) ; for ( URL _source : sources ) { Map < String , String > _properties = loadProperties ( _source . openStream ( ) , encoding , newline ) ; _result . putAll ( _properties ) ; } return _result ; |
public class PerceptronClassifier { /** * Do a prediction .
* @ param predict predict tuple .
* @ return Map ' s key is the actual label , Value is probability , the probability is random depends on the order of training
* sample . */
@ Override public Map < String , Double > predict ( Tuple predict ) { } } | Map < Integer , Double > indexResult = predict ( predict . vector . getVector ( ) ) ; return indexResult . entrySet ( ) . stream ( ) . map ( e -> new ImmutablePair < > ( model . labelIndexer . getLabel ( e . getKey ( ) ) , VectorUtils . sigmoid . apply ( e . getValue ( ) ) ) ) // Only do sigmoid here !
. collect ( Collectors . toMap ( ImmutablePair :: getLeft , ImmutablePair :: getRight ) ) ; |
public class RepositoryTrigger { /** * The repository events that will cause the trigger to run actions in another service , such as sending a
* notification through Amazon Simple Notification Service ( SNS ) .
* < note >
* The valid value " all " cannot be used with any other values .
* < / note >
* @ param events
* The repository events that will cause the trigger to run actions in another service , such as sending a
* notification through Amazon Simple Notification Service ( SNS ) . < / p > < note >
* The valid value " all " cannot be used with any other values .
* @ return Returns a reference to this object so that method calls can be chained together .
* @ see RepositoryTriggerEventEnum */
public RepositoryTrigger withEvents ( RepositoryTriggerEventEnum ... events ) { } } | java . util . ArrayList < String > eventsCopy = new java . util . ArrayList < String > ( events . length ) ; for ( RepositoryTriggerEventEnum value : events ) { eventsCopy . add ( value . toString ( ) ) ; } if ( getEvents ( ) == null ) { setEvents ( eventsCopy ) ; } else { getEvents ( ) . addAll ( eventsCopy ) ; } return this ; |
public class MockRequest { /** * { @ inheritDoc } */
@ Override public void setSessionAttribute ( final String key , final Serializable value ) { } } | sessionAttributes . put ( key , value ) ; |
public class JcrService { /** * - - - - - < repository service > - - - */
@ Override public RepositoryInfo getRepositoryInfo ( String repositoryId , ExtensionsData extension ) { } } | LOGGER . debug ( "-- getting repository info" ) ; RepositoryInfo info = jcrRepository ( repositoryId ) . getRepositoryInfo ( login ( repositoryId ) ) ; return new RepositoryInfoLocal ( repositoryId , info ) ; |
public class Gram { /** * - - - - - JOB MANAGER CALLS - - - - - */
private static GatekeeperReply jmConnect ( GSSCredential cred , GlobusURL jobURL , String msg ) throws GramException , GSSException { } } | GSSManager manager = ExtendedGSSManager . getInstance ( ) ; GatekeeperReply reply = null ; GssSocket socket = null ; try { ExtendedGSSContext context = ( ExtendedGSSContext ) manager . createContext ( null , GSSConstants . MECH_OID , cred , GSSContext . DEFAULT_LIFETIME ) ; context . setOption ( GSSConstants . GSS_MODE , GSIConstants . MODE_SSL ) ; GssSocketFactory factory = GssSocketFactory . getDefault ( ) ; socket = ( GssSocket ) factory . createSocket ( jobURL . getHost ( ) , jobURL . getPort ( ) , context ) ; socket . setAuthorization ( SelfAuthorization . getInstance ( ) ) ; OutputStream out = socket . getOutputStream ( ) ; InputStream in = socket . getInputStream ( ) ; out . write ( msg . getBytes ( ) ) ; out . flush ( ) ; debug ( "JM SENT:" , msg ) ; reply = new GatekeeperReply ( in ) ; } catch ( IOException e ) { throw new GramException ( GramException . ERROR_CONNECTION_FAILED , e ) ; } finally { if ( socket != null ) { try { socket . close ( ) ; } catch ( Exception e ) { } } } debug ( "JM RECEIVED:" , reply ) ; // must be 200 otherwise throw exception
checkHttpReply ( reply . httpCode ) ; // protocol version must match
checkProtocolVersion ( reply . protocolVersion ) ; return reply ; |
public class CellMaskedMatrix { /** * { @ inheritDoc } */
public DoubleVector getColumnVector ( int column ) { } } | column = getIndexFromMap ( colMaskMap , column ) ; DoubleVector v = matrix . getColumnVector ( column ) ; return new MaskedDoubleVectorView ( v , rowMaskMap ) ; |
public class KodoClient { /** * Deletes Object in Qiniu kodo .
* @ param key Object key */
public void deleteObject ( String key ) throws QiniuException { } } | com . qiniu . http . Response response = mBucketManager . delete ( mBucketName , key ) ; response . close ( ) ; |
public class EbeanQueryLookupStrategy { /** * Creates a { @ link QueryLookupStrategy } for the given { @ link EbeanServer } and { @ link Key } .
* @ param ebeanServer must not be { @ literal null } .
* @ param key may be { @ literal null } .
* @ param evaluationContextProvider must not be { @ literal null } .
* @ return */
public static QueryLookupStrategy create ( EbeanServer ebeanServer , Key key , QueryMethodEvaluationContextProvider evaluationContextProvider ) { } } | Assert . notNull ( ebeanServer , "EbeanServer must not be null!" ) ; Assert . notNull ( evaluationContextProvider , "EvaluationContextProvider must not be null!" ) ; switch ( key != null ? key : Key . CREATE_IF_NOT_FOUND ) { case CREATE : return new CreateQueryLookupStrategy ( ebeanServer ) ; case USE_DECLARED_QUERY : return new DeclaredQueryLookupStrategy ( ebeanServer , evaluationContextProvider ) ; case CREATE_IF_NOT_FOUND : return new CreateIfNotFoundQueryLookupStrategy ( ebeanServer , new CreateQueryLookupStrategy ( ebeanServer ) , new DeclaredQueryLookupStrategy ( ebeanServer , evaluationContextProvider ) ) ; default : throw new IllegalArgumentException ( String . format ( "Unsupported query lookup strategy %s!" , key ) ) ; } |
public class MultilineRecursiveToStringStyle { /** * Creates a StringBuilder responsible for the indenting .
* @ param spaces how far to indent
* @ return a StringBuilder with { spaces } leading space characters . */
private StringBuilder spacer ( final int spaces ) { } } | final StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < spaces ; i ++ ) { sb . append ( " " ) ; } return sb ; |
public class AResource { /** * Extracts and returns query parameters from the specified map . If a
* parameter is specified multiple times , its values will be separated with
* tab characters .
* @ param uri
* uri info with query parameters
* @ param jaxrx
* JAX - RX implementation
* @ return The parameters as { @ link Map } . */
protected Map < QueryParameter , String > getParameters ( final UriInfo uri , final JaxRx jaxrx ) { } } | final MultivaluedMap < String , String > params = uri . getQueryParameters ( ) ; final Map < QueryParameter , String > newParam = createMap ( ) ; final Set < QueryParameter > impl = jaxrx . getParameters ( ) ; for ( final String key : params . keySet ( ) ) { for ( final String s : params . get ( key ) ) { addParameter ( key , s , newParam , impl ) ; } } return newParam ; |
public class DefaultBeanContext { /** * Get provided beans of the given type .
* @ param resolutionContext The bean resolution context
* @ param beanType The bean type
* @ param < T > The bean type parameter
* @ return The found beans */
protected @ Nonnull < T > Provider < T > getBeanProvider ( @ Nullable BeanResolutionContext resolutionContext , @ Nonnull Class < T > beanType ) { } } | return getBeanProvider ( resolutionContext , beanType , null ) ; |
public class CmsWorkplaceAppManager { /** * Returns the editor for the given resource type . < p >
* @ param type the resource type to edit
* @ param plainText if plain text editing is required
* @ return the editor */
public I_CmsEditor getEditorForType ( I_CmsResourceType type , boolean plainText ) { } } | List < I_CmsEditor > editors = new ArrayList < I_CmsEditor > ( ) ; for ( int i = 0 ; i < EDITORS . length ; i ++ ) { if ( EDITORS [ i ] . matchesType ( type , plainText ) ) { editors . add ( EDITORS [ i ] ) ; } } I_CmsEditor result = null ; if ( editors . size ( ) == 1 ) { result = editors . get ( 0 ) ; } else if ( editors . size ( ) > 1 ) { Collections . sort ( editors , new Comparator < I_CmsEditor > ( ) { public int compare ( I_CmsEditor o1 , I_CmsEditor o2 ) { return o1 . getPriority ( ) > o2 . getPriority ( ) ? - 1 : 1 ; } } ) ; result = editors . get ( 0 ) ; } return result ; |
public class AccessibilityNodeInfoUtils { /** * Returns the { @ code node } if it matches the { @ code filter } , or the first
* matching ancestor . Returns { @ code null } if no nodes match . */
public static AccessibilityNodeInfoCompat getSelfOrMatchingAncestor ( Context context , AccessibilityNodeInfoCompat node , NodeFilter filter ) { } } | if ( node == null ) { return null ; } if ( filter . accept ( context , node ) ) { return AccessibilityNodeInfoCompat . obtain ( node ) ; } return getMatchingAncestor ( context , node , filter ) ; |
public class LifecycleManager { /** * Binds the current { @ link LifecycleManager } with given object of given class .
* @ param clazz the class to be bound
* @ param object the object to be bound
* @ throws ObjectAlreadyAssociatedException when there is already object bound with { @ link LifecycleManager } for given
* class . */
public final < T > void bindTo ( Class < T > clazz , T object ) throws ObjectAlreadyAssociatedException { } } | LifecycleManagerStore . getCurrentStore ( ) . bind ( this , clazz , object ) ; |
public class MultiUserChat { /** * Fires notification events if the affiliation of a room occupant has changed . If the
* occupant that changed his affiliation is your occupant then the
* < code > UserStatusListeners < / code > added to this < code > MultiUserChat < / code > will be fired .
* On the other hand , if the occupant that changed his affiliation is not yours then the
* < code > ParticipantStatusListeners < / code > added to this < code > MultiUserChat < / code > will be
* fired . The following table shows the events that will be fired depending on the previous
* and new affiliation of the occupant .
* < pre >
* < table border = " 1 " >
* < tr > < td > < b > Old < / b > < / td > < td > < b > New < / b > < / td > < td > < b > Events < / b > < / td > < / tr >
* < tr > < td > None < / td > < td > Member < / td > < td > membershipGranted < / td > < / tr >
* < tr > < td > Member < / td > < td > Admin < / td > < td > membershipRevoked + adminGranted < / td > < / tr >
* < tr > < td > Admin < / td > < td > Owner < / td > < td > adminRevoked + ownershipGranted < / td > < / tr >
* < tr > < td > None < / td > < td > Admin < / td > < td > adminGranted < / td > < / tr >
* < tr > < td > None < / td > < td > Owner < / td > < td > ownershipGranted < / td > < / tr >
* < tr > < td > Member < / td > < td > Owner < / td > < td > membershipRevoked + ownershipGranted < / td > < / tr >
* < tr > < td > Owner < / td > < td > Admin < / td > < td > ownershipRevoked + adminGranted < / td > < / tr >
* < tr > < td > Admin < / td > < td > Member < / td > < td > adminRevoked + membershipGranted < / td > < / tr >
* < tr > < td > Member < / td > < td > None < / td > < td > membershipRevoked < / td > < / tr >
* < tr > < td > Owner < / td > < td > Member < / td > < td > ownershipRevoked + membershipGranted < / td > < / tr >
* < tr > < td > Owner < / td > < td > None < / td > < td > ownershipRevoked < / td > < / tr >
* < tr > < td > Admin < / td > < td > None < / td > < td > adminRevoked < / td > < / tr >
* < tr > < td > < i > Anyone < / i > < / td > < td > Outcast < / td > < td > banned < / td > < / tr >
* < / table >
* < / pre >
* @ param oldAffiliation the previous affiliation of the user in the room before receiving the
* new presence
* @ param newAffiliation the new affiliation of the user in the room after receiving the new
* presence
* @ param isUserModification whether the received presence is about your user in the room or not
* @ param from the occupant whose role in the room has changed
* ( e . g . room @ conference . jabber . org / nick ) . */
private void checkAffiliationModifications ( MUCAffiliation oldAffiliation , MUCAffiliation newAffiliation , boolean isUserModification , EntityFullJid from ) { } } | // First check for revoked affiliation and then for granted affiliations . The idea is to
// first fire the " revoke " events and then fire the " grant " events .
// The user ' s ownership to the room was revoked
if ( MUCAffiliation . owner . equals ( oldAffiliation ) && ! MUCAffiliation . owner . equals ( newAffiliation ) ) { if ( isUserModification ) { for ( UserStatusListener listener : userStatusListeners ) { listener . ownershipRevoked ( ) ; } } else { for ( ParticipantStatusListener listener : participantStatusListeners ) { listener . ownershipRevoked ( from ) ; } } } // The user ' s administrative privileges to the room were revoked
else if ( MUCAffiliation . admin . equals ( oldAffiliation ) && ! MUCAffiliation . admin . equals ( newAffiliation ) ) { if ( isUserModification ) { for ( UserStatusListener listener : userStatusListeners ) { listener . adminRevoked ( ) ; } } else { for ( ParticipantStatusListener listener : participantStatusListeners ) { listener . adminRevoked ( from ) ; } } } // The user ' s membership to the room was revoked
else if ( MUCAffiliation . member . equals ( oldAffiliation ) && ! MUCAffiliation . member . equals ( newAffiliation ) ) { if ( isUserModification ) { for ( UserStatusListener listener : userStatusListeners ) { listener . membershipRevoked ( ) ; } } else { for ( ParticipantStatusListener listener : participantStatusListeners ) { listener . membershipRevoked ( from ) ; } } } // The user was granted ownership to the room
if ( ! MUCAffiliation . owner . equals ( oldAffiliation ) && MUCAffiliation . owner . equals ( newAffiliation ) ) { if ( isUserModification ) { for ( UserStatusListener listener : userStatusListeners ) { listener . ownershipGranted ( ) ; } } else { for ( ParticipantStatusListener listener : participantStatusListeners ) { listener . ownershipGranted ( from ) ; } } } // The user was granted administrative privileges to the room
else if ( ! MUCAffiliation . admin . equals ( oldAffiliation ) && MUCAffiliation . admin . equals ( newAffiliation ) ) { if ( isUserModification ) { for ( UserStatusListener listener : userStatusListeners ) { listener . adminGranted ( ) ; } } else { for ( ParticipantStatusListener listener : participantStatusListeners ) { listener . adminGranted ( from ) ; } } } // The user was granted membership to the room
else if ( ! MUCAffiliation . member . equals ( oldAffiliation ) && MUCAffiliation . member . equals ( newAffiliation ) ) { if ( isUserModification ) { for ( UserStatusListener listener : userStatusListeners ) { listener . membershipGranted ( ) ; } } else { for ( ParticipantStatusListener listener : participantStatusListeners ) { listener . membershipGranted ( from ) ; } } } |
public class ToolchainSourceMarshaller { /** * Marshall the given parameter object . */
public void marshall ( ToolchainSource toolchainSource , ProtocolMarshaller protocolMarshaller ) { } } | if ( toolchainSource == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( toolchainSource . getS3 ( ) , S3_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class IOUtils { /** * Create a new file , if the file exists , delete and create again .
* @ param filePath file path .
* @ return True : success , or false : failure . */
public static boolean createNewFile ( String filePath ) { } } | if ( ! StringUtils . isEmpty ( filePath ) ) { File file = new File ( filePath ) ; return createNewFile ( file ) ; } return false ; |
public class OperationValidator { /** * Throws an exception or logs a message
* @ param message The message for the exception or the log message . Must be internationalized */
private void throwOrWarnAboutDescriptorProblem ( String message ) { } } | if ( validateDescriptions ) { throw new IllegalArgumentException ( message ) ; } ControllerLogger . ROOT_LOGGER . warn ( message ) ; |
public class CaptureActivityIntents { /** * Set barcode formats to scan for onto { @ code Intent } .
* @ param intent Target intent .
* @ param scanMode Mode which specify set of barcode formats to scan for . Use one of
* { @ link Intents . Scan # PRODUCT _ MODE } , { @ link Intents . Scan # ONE _ D _ MODE } ,
* { @ link Intents . Scan # QR _ CODE _ MODE } , { @ link Intents . Scan # DATA _ MATRIX _ MODE } . */
public static void setDecodeMode ( Intent intent , String scanMode ) { } } | intent . putExtra ( Intents . Scan . MODE , scanMode ) ; |
public class MemoryOutputJavaFileObject { /** * Opens an input stream to the file data . If the file has never
* been written the input stream will contain no data ( i . e . length = 0 ) .
* @ return an input stream .
* @ throws IOException if an I / O error occurs . */
@ Override public InputStream openInputStream ( ) throws IOException { } } | if ( outputStream != null ) { return new ByteArrayInputStream ( outputStream . toByteArray ( ) ) ; } else { return new ByteArrayInputStream ( new byte [ 0 ] ) ; } |
public class DateRangePicker { /** * Searches for a comboitem that has a date range equivalent to the specified range .
* @ param range The date range to locate .
* @ return A comboitem containing the date range , or null if not found . */
public Dateitem findMatchingItem ( DateRange range ) { } } | for ( BaseComponent item : getChildren ( ) ) { if ( range . equals ( item . getData ( ) ) ) { return ( Dateitem ) item ; } } return null ; |
public class EventBus { /** * Registers the given method to the event bus . The object is assumed to be
* of the class that contains the given method .
* < p > The method parameters are
* checked and added to the event queue corresponding to the { @ link Event }
* used as the first method parameter . In other words , if passed a reference
* to the following method : < / p >
* < p > < code >
* public void xyzHandler ( XYZEvent event ) { . . . }
* < / code > < / p >
* < p > . . . < code > xyzHandler < / code > will be added to the event queue for
* { @ code XYZEvent } assuming that { @ code XYZEvent } extends { @ link Event } and
* an event queue has been created for that event type . < / p >
* @ param o an instance of the class containing the method < code > m < / code >
* @ param m the method to register
* @ param priority the event priority
* @ param vetoable vetoable flag */
protected void registerMethod ( Object o , Method m , int priority , boolean vetoable ) { } } | // check the parameter types , and attempt to resolve the event
// type
if ( m . getParameterTypes ( ) . length != 1 ) { log . warn ( "Skipping invalid event handler definition: " + m ) ; return ; } // make sure the parameter is an Event
// this additional / technically unneeded check should cut down on the
// time required to process the loop over the definitions for methods
// that don ' t match
Class < ? > param = m . getParameterTypes ( ) [ 0 ] ; if ( ! Event . class . isAssignableFrom ( param ) ) { log . warn ( "Skipping event handler without an Event parameter: " + m ) ; return ; } // add the method to all assignable definitions .
// this may result in the method being added to multiple queues ,
// that is , the queues for each superclass .
// ( this is intended and is fundamentally what makes subclassed events
// work as expected )
for ( EventQueueDefinition d : definitions ) { if ( param . isAssignableFrom ( d . getEventType ( ) ) ) { d . add ( new EventQueueEntry ( o , m , priority , vetoable ) ) ; log . debug ( "Added {} to queue {}" , m , d . getEventType ( ) ) ; } } |
public class EffectUtils { /** * Create a Gaussian kernel for the transformation .
* @ param radius the kernel radius .
* @ return the Gaussian kernel . */
protected static float [ ] createGaussianKernel ( int radius ) { } } | if ( radius < 1 ) { throw new IllegalArgumentException ( "Radius must be >= 1" ) ; } float [ ] data = new float [ radius * 2 + 1 ] ; float sigma = radius / 3.0f ; float twoSigmaSquare = 2.0f * sigma * sigma ; float sigmaRoot = ( float ) Math . sqrt ( twoSigmaSquare * Math . PI ) ; float total = 0.0f ; for ( int i = - radius ; i <= radius ; i ++ ) { float distance = i * i ; int index = i + radius ; data [ index ] = ( float ) Math . exp ( - distance / twoSigmaSquare ) / sigmaRoot ; total += data [ index ] ; } for ( int i = 0 ; i < data . length ; i ++ ) { data [ i ] /= total ; } return data ; |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < }
* { @ link CmisExtensionType } { @ code > } */
@ XmlElementDecl ( namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/" , name = "extension" , scope = DeleteTypeResponse . class ) public JAXBElement < CmisExtensionType > createDeleteTypeResponseExtension ( CmisExtensionType value ) { } } | return new JAXBElement < CmisExtensionType > ( _GetPropertiesExtension_QNAME , CmisExtensionType . class , DeleteTypeResponse . class , value ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.