signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class JolokiaMBeanServer { /** * Extract convert options from annotation */
private JsonConvertOptions getJsonConverterOptions ( JsonMBean pAnno ) { } } | // Extract conversion options from the annotation
if ( pAnno == null ) { return JsonConvertOptions . DEFAULT ; } else { ValueFaultHandler faultHandler = pAnno . faultHandling ( ) == JsonMBean . FaultHandler . IGNORE_ERRORS ? ValueFaultHandler . IGNORING_VALUE_FAULT_HANDLER : ValueFaultHandler . THROWING_VALUE_FAULT_HANDLER ; return new JsonConvertOptions . Builder ( ) . maxCollectionSize ( pAnno . maxCollectionSize ( ) ) . maxDepth ( pAnno . maxDepth ( ) ) . maxObjects ( pAnno . maxObjects ( ) ) . faultHandler ( faultHandler ) . build ( ) ; } |
public class Cluster { /** * Starts up a work unit that this node has claimed .
* If " smart rebalancing " is enabled , hand the listener a meter to mark load .
* Otherwise , just call " startWork " on the listener and let the client have at it .
* TODO : Refactor to remove check and cast . */
public void startWork ( String workUnit ) throws InterruptedException { } } | if ( waitInProgress . get ( ) ) LOG . warn ( "Claiming work during wait!" ) ; LOG . info ( "Successfully claimed {}: {}. Starting..." , config . workUnitName , workUnit ) ; final boolean added = myWorkUnits . add ( workUnit ) ; if ( added ) { if ( balancingPolicy instanceof MeteredBalancingPolicy ) { MeteredBalancingPolicy mbp = ( MeteredBalancingPolicy ) balancingPolicy ; Meter meter = mbp . findOrCreateMetrics ( workUnit ) ; ( ( SmartListener ) listener ) . startWork ( workUnit , meter ) ; } else { ( ( ClusterListener ) listener ) . startWork ( workUnit ) ; } } else { LOG . warn ( "Detected that %s is already a member of my work units; not starting twice!" , workUnit ) ; } |
public class LexTokenReader { /** * Check the next character is as expected . If the character is not as expected , throw the message as a
* { @ link LexException } .
* @ param c
* The expected next character .
* @ param number
* The number of the error message .
* @ param message
* The error message .
* @ throws LexException */
private void checkFor ( char c , int number , String message ) throws LexException { } } | if ( ch == c ) { rdCh ( ) ; } else { throwMessage ( number , message ) ; } |
public class FileLocator { /** * Get a list of Files from the given path that match the provided filter ;
* not recursive .
* @ param root
* base directory to look for files
* @ param filterExpr
* the regular expression to match , may be null
* @ return List of File objects ; List will be empty if root is null */
public static List < File > getMatchingFiles ( File root , String filterExpr ) { } } | if ( root == null ) return Collections . emptyList ( ) ; File fileList [ ] ; FileFilter filter ; if ( filterExpr == null ) filter = new FilesOnly ( ) ; else filter = new FilesOnlyFilter ( filterExpr ) ; fileList = root . listFiles ( filter ) ; if ( fileList == null ) return Collections . emptyList ( ) ; else { if ( fileList . length > 1 ) { Arrays . sort ( fileList , new SortByFileName ( ) ) ; } return Arrays . asList ( fileList ) ; } |
public class LayersFactory { /** * Load the available layers .
* @ param image the installed image
* @ param productConfig the product config to establish the identity
* @ param moduleRoots the module roots
* @ param bundleRoots the bundle roots
* @ return the layers
* @ throws IOException */
static InstalledIdentity load ( final InstalledImage image , final ProductConfig productConfig , final List < File > moduleRoots , final List < File > bundleRoots ) throws IOException { } } | // build the identity information
final String productVersion = productConfig . resolveVersion ( ) ; final String productName = productConfig . resolveName ( ) ; final Identity identity = new AbstractLazyIdentity ( ) { @ Override public String getName ( ) { return productName ; } @ Override public String getVersion ( ) { return productVersion ; } @ Override public InstalledImage getInstalledImage ( ) { return image ; } } ; final Properties properties = PatchUtils . loadProperties ( identity . getDirectoryStructure ( ) . getInstallationInfo ( ) ) ; final List < String > allPatches = PatchUtils . readRefs ( properties , Constants . ALL_PATCHES ) ; // Step 1 - gather the installed layers data
final InstalledConfiguration conf = createInstalledConfig ( image ) ; // Step 2 - process the actual module and bundle roots
final ProcessedLayers processedLayers = process ( conf , moduleRoots , bundleRoots ) ; final InstalledConfiguration config = processedLayers . getConf ( ) ; // Step 3 - create the actual config objects
// Process layers
final InstalledIdentityImpl installedIdentity = new InstalledIdentityImpl ( identity , allPatches , image ) ; for ( final LayerPathConfig layer : processedLayers . getLayers ( ) . values ( ) ) { final String name = layer . name ; installedIdentity . putLayer ( name , createPatchableTarget ( name , layer , config . getLayerMetadataDir ( name ) , image ) ) ; } // Process add - ons
for ( final LayerPathConfig addOn : processedLayers . getAddOns ( ) . values ( ) ) { final String name = addOn . name ; installedIdentity . putAddOn ( name , createPatchableTarget ( name , addOn , config . getAddOnMetadataDir ( name ) , image ) ) ; } return installedIdentity ; |
public class RpcProtocol { /** * Url - encodes a string . */
static String urlencode ( final String s ) { } } | try { return URLEncoder . encode ( s , CHARSET_NAME ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } |
import java . util . * ; class Main { /** * Extract the index at which the minimum value is found from a list of tuples .
* @ param inputList A list of tuples , each containing a string and an integer .
* @ return The string from the tuple in the input list which has the minimum integer value . */
public static String getMinimumIndex ( List < Tuple > inputList ) { } class Tuple { private String x ; private int y ; public Tuple ( String x , int y ) { this . x = x ; this . y = y ; } public String getX ( ) { return x ; } public int getY ( ) { return y ; } } } | Tuple minTuple = Collections . min ( inputList , new Comparator < Tuple > ( ) { @ Override public int compare ( Tuple o1 , Tuple o2 ) { return o1 . getY ( ) - o2 . getY ( ) ; } } ) ; return minTuple . getX ( ) ; |
public class RegexParser { /** * regex : : = term ( ` | ` term ) *
* term : : = factor +
* factor : : = ( ' ^ ' | ' $ ' | ' \ A ' | ' \ Z ' | ' \ z ' | ' \ b ' | ' \ B ' | ' \ < ' | ' \ > '
* | atom ( ( ' * ' | ' + ' | ' ? ' | minmax ) ' ? ' ? ) ? )
* | ' ( ? = ' regex ' ) ' | ' ( ? ! ' regex ' ) ' | ' ( ? & lt ; = ' regex ' ) ' | ' ( ? & lt ; ! ' regex ' ) '
* atom : : = char | ' . ' | range | ' ( ' regex ' ) ' | ' ( ? : ' regex ' ) ' | ' \ ' [ 0-9]
* | ' \ w ' | ' \ W ' | ' \ d ' | ' \ D ' | ' \ s ' | ' \ S ' | category - block */
Token parseRegex ( ) throws ParseException { } } | Token tok = this . parseTerm ( ) ; Token parent = null ; while ( this . read ( ) == T_OR ) { this . next ( ) ; if ( parent == null ) { parent = Token . createUnion ( ) ; parent . addChild ( tok ) ; tok = parent ; } tok . addChild ( this . parseTerm ( ) ) ; } return tok ; |
public class ModeledObjectPermissionService { /** * Determines whether the current user has permission to update the given
* target entity , adding or removing the given permissions . Such permission
* depends on whether the current user is a system administrator , whether
* they have explicit UPDATE permission on the target entity , and whether
* they have explicit ADMINISTER permission on all affected objects .
* Permission inheritance via user groups is taken into account .
* @ param user
* The user who is changing permissions .
* @ param targetEntity
* The entity whose permissions are being changed .
* @ param permissions
* The permissions that are being added or removed from the target
* entity .
* @ return
* true if the user has permission to change the target entity ' s
* permissions as specified , false otherwise .
* @ throws GuacamoleException
* If an error occurs while checking permission status , or if
* permission is denied to read the current user ' s permissions . */
protected boolean canAlterPermissions ( ModeledAuthenticatedUser user , ModeledPermissions < ? extends EntityModel > targetEntity , Collection < ObjectPermission > permissions ) throws GuacamoleException { } } | // A system adminstrator can do anything
if ( user . getUser ( ) . isAdministrator ( ) ) return true ; // Verify user has update permission on the target entity
ObjectPermissionSet permissionSet = getRelevantPermissionSet ( user . getUser ( ) , targetEntity ) ; if ( ! permissionSet . hasPermission ( ObjectPermission . Type . UPDATE , targetEntity . getIdentifier ( ) ) ) return false ; // Produce collection of affected identifiers
Collection < String > affectedIdentifiers = new HashSet < String > ( permissions . size ( ) ) ; for ( ObjectPermission permission : permissions ) affectedIdentifiers . add ( permission . getObjectIdentifier ( ) ) ; // Determine subset of affected identifiers that we have admin access to
ObjectPermissionSet affectedPermissionSet = getPermissionSet ( user , user . getUser ( ) , user . getEffectiveUserGroups ( ) ) ; Collection < String > allowedSubset = affectedPermissionSet . getAccessibleObjects ( Collections . singleton ( ObjectPermission . Type . ADMINISTER ) , affectedIdentifiers ) ; // The permissions can be altered if and only if the set of objects we
// are allowed to administer is equal to the set of objects we will be
// affecting .
return affectedIdentifiers . size ( ) == allowedSubset . size ( ) ; |
public class XSLTAttributeDef { /** * Process an attribute string of type T _ AVT into
* a AVT value .
* @ param handler non - null reference to current StylesheetHandler that is constructing the Templates .
* @ param uri The Namespace URI , or an empty string .
* @ param name The local name ( without prefix ) , or empty string if not namespace processing .
* @ param rawName The qualified name ( with prefix ) .
* @ param value Should be an Attribute Value Template string .
* @ return An AVT object that may be used to evaluate the Attribute Value Template .
* @ throws org . xml . sax . SAXException which will wrap a
* { @ link javax . xml . transform . TransformerException } , if there is a syntax error
* in the attribute value template string . */
AVT processAVT ( StylesheetHandler handler , String uri , String name , String rawName , String value , ElemTemplateElement owner ) throws org . xml . sax . SAXException { } } | try { AVT avt = new AVT ( handler , uri , name , rawName , value , owner ) ; return avt ; } catch ( TransformerException te ) { throw new org . xml . sax . SAXException ( te ) ; } |
public class ProductUrl { /** * Get Resource Url for GetProduct
* @ param acceptVariantProductCode Specifies whether to accept a product variant ' s code as the . When you set this parameter to , you can pass in a product variant ' s code in the GetProduct call to retrieve the product variant details that are associated with the base product .
* @ param allowInactive If true , allow inactive categories to be retrieved in the category list response . If false , the categories retrieved will not include ones marked inactive .
* @ param productCode The unique , user - defined product code of a product , used throughout to reference and associate to a product .
* @ param purchaseLocation The location where the order item ( s ) was purchased .
* @ param quantity The number of cart items in the shopper ' s active cart .
* @ param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object . This parameter should only be used to retrieve data . Attempting to update data using this parameter may cause data loss .
* @ param skipInventoryCheck If true , skip the process to validate inventory when creating this product reservation .
* @ param supressOutOfStock404 Specifies whether to supress the 404 error when the product is out of stock .
* @ param variationProductCode Merchant - created code associated with a specific product variation . Variation product codes maintain an association with the base product code .
* @ param variationProductCodeFilter
* @ return String Resource Url */
public static MozuUrl getProductUrl ( Boolean acceptVariantProductCode , Boolean allowInactive , String productCode , String purchaseLocation , Integer quantity , String responseFields , Boolean skipInventoryCheck , Boolean supressOutOfStock404 , String variationProductCode , String variationProductCodeFilter ) { } } | UrlFormatter formatter = new UrlFormatter ( "/api/commerce/catalog/storefront/products/{productCode}?variationProductCode={variationProductCode}&allowInactive={allowInactive}&skipInventoryCheck={skipInventoryCheck}&supressOutOfStock404={supressOutOfStock404}&quantity={quantity}&acceptVariantProductCode={acceptVariantProductCode}&purchaseLocation={purchaseLocation}&variationProductCodeFilter={variationProductCodeFilter}&responseFields={responseFields}" ) ; formatter . formatUrl ( "acceptVariantProductCode" , acceptVariantProductCode ) ; formatter . formatUrl ( "allowInactive" , allowInactive ) ; formatter . formatUrl ( "productCode" , productCode ) ; formatter . formatUrl ( "purchaseLocation" , purchaseLocation ) ; formatter . formatUrl ( "quantity" , quantity ) ; formatter . formatUrl ( "responseFields" , responseFields ) ; formatter . formatUrl ( "skipInventoryCheck" , skipInventoryCheck ) ; formatter . formatUrl ( "supressOutOfStock404" , supressOutOfStock404 ) ; formatter . formatUrl ( "variationProductCode" , variationProductCode ) ; formatter . formatUrl ( "variationProductCodeFilter" , variationProductCodeFilter ) ; return new MozuUrl ( formatter . getResourceUrl ( ) , MozuUrl . UrlLocation . TENANT_POD ) ; |
public class TapeRecoveryPointInfoMarshaller { /** * Marshall the given parameter object . */
public void marshall ( TapeRecoveryPointInfo tapeRecoveryPointInfo , ProtocolMarshaller protocolMarshaller ) { } } | if ( tapeRecoveryPointInfo == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( tapeRecoveryPointInfo . getTapeARN ( ) , TAPEARN_BINDING ) ; protocolMarshaller . marshall ( tapeRecoveryPointInfo . getTapeRecoveryPointTime ( ) , TAPERECOVERYPOINTTIME_BINDING ) ; protocolMarshaller . marshall ( tapeRecoveryPointInfo . getTapeSizeInBytes ( ) , TAPESIZEINBYTES_BINDING ) ; protocolMarshaller . marshall ( tapeRecoveryPointInfo . getTapeStatus ( ) , TAPESTATUS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class CSSHTMLBundleLinkRenderer { /** * Returns true if the renderer must render a CSS bundle link even in debug
* mode
* @ param ctx
* the context
* @ param debugOn
* the debug flag
* @ return true if the renderer must render a CSS bundle link even in debug
* mode */
private boolean isForcedToRenderIeCssBundleInDebug ( BundleRendererContext ctx , boolean debugOn ) { } } | return debugOn && getResourceType ( ) . equals ( JawrConstant . CSS_TYPE ) && bundler . getConfig ( ) . isForceCssBundleInDebugForIEOn ( ) && RendererRequestUtils . isIE ( ctx . getRequest ( ) ) ; |
public class SeGoodsSpecifics { /** * < p > Setter for specifics . < / p >
* @ param pSpecifics reference */
@ Override public final void setSpecifics ( final SpecificsOfItem pSpecifics ) { } } | this . specifics = pSpecifics ; if ( this . itsId == null ) { this . itsId = new SeGoodsSpecificsId ( ) ; } this . itsId . setSpecifics ( this . specifics ) ; |
public class TarArchive { /** * Set the debugging flag .
* @ param debugF
* The new debug setting . */
public void setDebug ( boolean debugF ) { } } | this . debug = debugF ; if ( this . tarIn != null ) { this . tarIn . setDebug ( debugF ) ; } else if ( this . tarOut != null ) { this . tarOut . setDebug ( debugF ) ; } |
public class WsLogger { /** * @ see java . util . logging . Logger # fine ( java . lang . String ) */
@ Override public void fine ( String msg ) { } } | if ( isLoggable ( Level . FINE ) ) { log ( Level . FINE , msg ) ; } |
public class RegistriesInner { /** * Updates a container registry with the specified parameters .
* @ param resourceGroupName The name of the resource group to which the container registry belongs .
* @ param registryName The name of the container registry .
* @ param registryUpdateParameters The parameters for updating a container registry .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws CloudException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the RegistryInner object if successful . */
public RegistryInner beginUpdate ( String resourceGroupName , String registryName , RegistryUpdateParameters registryUpdateParameters ) { } } | return beginUpdateWithServiceResponseAsync ( resourceGroupName , registryName , registryUpdateParameters ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class Util { /** * Create a HttpCarbonMessage using the netty inbound http request .
* @ param httpRequestHeaders of inbound request
* @ param ctx of the inbound request
* @ param sourceHandler instance which handled the particular request
* @ return HttpCarbon message */
public static HttpCarbonMessage createInboundReqCarbonMsg ( HttpRequest httpRequestHeaders , ChannelHandlerContext ctx , SourceHandler sourceHandler ) { } } | HttpCarbonMessage inboundRequestMsg = new HttpCarbonRequest ( httpRequestHeaders , new DefaultListener ( ctx ) ) ; inboundRequestMsg . setProperty ( Constants . POOLED_BYTE_BUFFER_FACTORY , new PooledDataStreamerFactory ( ctx . alloc ( ) ) ) ; inboundRequestMsg . setProperty ( Constants . CHNL_HNDLR_CTX , ctx ) ; inboundRequestMsg . setProperty ( Constants . SRC_HANDLER , sourceHandler ) ; HttpVersion protocolVersion = httpRequestHeaders . protocolVersion ( ) ; inboundRequestMsg . setProperty ( Constants . HTTP_VERSION , protocolVersion . majorVersion ( ) + "." + protocolVersion . minorVersion ( ) ) ; inboundRequestMsg . setProperty ( Constants . HTTP_METHOD , httpRequestHeaders . method ( ) . name ( ) ) ; InetSocketAddress localAddress = null ; // This check was added because in case of netty embedded channel , this could be of type ' EmbeddedSocketAddress ' .
if ( ctx . channel ( ) . localAddress ( ) instanceof InetSocketAddress ) { localAddress = ( InetSocketAddress ) ctx . channel ( ) . localAddress ( ) ; } inboundRequestMsg . setProperty ( Constants . LISTENER_PORT , localAddress != null ? localAddress . getPort ( ) : null ) ; inboundRequestMsg . setProperty ( Constants . LISTENER_INTERFACE_ID , sourceHandler . getInterfaceId ( ) ) ; inboundRequestMsg . setProperty ( Constants . PROTOCOL , Constants . HTTP_SCHEME ) ; boolean isSecuredConnection = false ; if ( ctx . channel ( ) . pipeline ( ) . get ( Constants . SSL_HANDLER ) != null ) { isSecuredConnection = true ; } inboundRequestMsg . setProperty ( Constants . IS_SECURED_CONNECTION , isSecuredConnection ) ; inboundRequestMsg . setProperty ( Constants . LOCAL_ADDRESS , ctx . channel ( ) . localAddress ( ) ) ; inboundRequestMsg . setProperty ( Constants . REMOTE_ADDRESS , sourceHandler . getRemoteAddress ( ) ) ; inboundRequestMsg . setProperty ( Constants . REQUEST_URL , httpRequestHeaders . uri ( ) ) ; inboundRequestMsg . setProperty ( Constants . TO , httpRequestHeaders . uri ( ) ) ; inboundRequestMsg . setProperty ( MUTUAL_SSL_HANDSHAKE_RESULT , ctx . channel ( ) . attr ( Constants . MUTUAL_SSL_RESULT_ATTRIBUTE ) . get ( ) ) ; return inboundRequestMsg ; |
public class WaitSet { /** * executed with an unpark for the same key . */
public void unpark ( Notifier notifier , WaitNotifyKey key ) { } } | WaitSetEntry entry = queue . peek ( ) ; while ( entry != null ) { Operation op = entry . getOperation ( ) ; if ( notifier == op ) { throw new IllegalStateException ( "Found cyclic wait-notify! -> " + notifier ) ; } if ( entry . isValid ( ) ) { if ( entry . isExpired ( ) ) { // expired
entry . onExpire ( ) ; } else if ( entry . isCancelled ( ) ) { entry . onCancel ( ) ; } else { if ( entry . shouldWait ( ) ) { return ; } OperationService operationService = nodeEngine . getOperationService ( ) ; operationService . run ( op ) ; } entry . setValid ( false ) ; } // consume
queue . poll ( ) ; entry = queue . peek ( ) ; // If parkQueue . peek ( ) returns null , we should deregister this specific
// key to avoid memory leak . By contract we know that park ( ) and unpark ( )
// cannot be called in parallel .
// We can safely remove this queue from registration map here .
if ( entry == null ) { waitSetMap . remove ( key ) ; } } |
public class InstanceCheck { /** * Creates a new instance check .
* @ param typeDescription The type to apply the instance check against .
* @ return An appropriate stack manipulation . */
public static StackManipulation of ( TypeDescription typeDescription ) { } } | if ( typeDescription . isPrimitive ( ) ) { throw new IllegalArgumentException ( "Cannot check an instance against a primitive type: " + typeDescription ) ; } return new InstanceCheck ( typeDescription ) ; |
public class InvocationProxyFactory { /** * Add a interface type that should be implemented by the resulting invocation proxy .
* @ param ifc must not be { @ literal null } and must be an interface type . */
public void addInterface ( Class < ? > ifc ) { } } | LettuceAssert . notNull ( ifc , "Interface type must not be null" ) ; LettuceAssert . isTrue ( ifc . isInterface ( ) , "Type must be an interface" ) ; this . interfaces . add ( ifc ) ; |
public class MultiPolygon { /** * Creates a MultiPolygon from the given { @ link Polygon } sequence .
* @ param polygons The { @ link Polygon } Iterable .
* @ return MultiPolygon */
public static MultiPolygon of ( Iterable < Polygon > polygons ) { } } | MultiDimensionalPositions . Builder positionsBuilder = MultiDimensionalPositions . builder ( ) ; for ( Polygon polygon : polygons ) { positionsBuilder . addAreaPosition ( polygon . positions ( ) ) ; } return new MultiPolygon ( positionsBuilder . build ( ) ) ; |
public class SparseHashMatrix { /** * Checks that the indices are within the bounds of this matrix or throws an
* { @ link IndexOutOfBoundsException } if not . */
private void checkIndices ( int row , int col ) { } } | if ( row < 0 || col < 0 || row >= rows || col >= columns ) { throw new IndexOutOfBoundsException ( ) ; } |
public class Camera { /** * Sets the eye position , the center of the scene and which axis is facing upward .
* @ param eyeX
* The x - coordinate for the eye .
* @ param eyeY
* The y - coordinate for the eye .
* @ param eyeZ
* The z - coordinate for the eye .
* @ param centerX
* The x - coordinate for the center of the scene .
* @ param centerY
* The y - coordinate for the center of the scene .
* @ param centerZ
* The z - coordinate for the center of the scene .
* @ param upX
* Setting which axis is facing upward ; usually 0.0 , 1.0 , or - 1.0.
* @ param upY
* Setting which axis is facing upward ; usually 0.0 , 1.0 , or - 1.0.
* @ param upZ
* Setting which axis is facing upward ; usually 0.0 , 1.0 , or - 1.0. */
public void set ( double eyeX , double eyeY , double eyeZ , double centerX , double centerY , double centerZ , double upX , double upY , double upZ ) { } } | this . eyeX = eyeX ; this . eyeY = eyeY ; this . eyeZ = eyeZ ; this . centerX = centerX ; this . centerY = centerY ; this . centerZ = centerZ ; this . upX = upX ; this . upY = upY ; this . upZ = upZ ; |
public class AjaxBehavior { /** * < p class = " changed _ added _ 2_2 " >
* Return the resetValues status of this behavior . < / p >
* @ since 2.2 */
public boolean isResetValues ( ) { } } | Boolean result = ( Boolean ) eval ( RESET_VALUES , resetValues ) ; return ( ( result != null ) ? result : false ) ; |
public class MapConstraints { /** * Returns a constrained view of the specified bimap , using the specified
* constraint . Any operations that modify the bimap will have the associated
* keys and values verified with the constraint .
* < p > The returned bimap is not serializable .
* @ param map the bimap to constrain
* @ param constraint the constraint that validates added entries
* @ return a constrained view of the specified bimap */
public static < K , V > BiMap < K , V > constrainedBiMap ( BiMap < K , V > map , MapConstraint < ? super K , ? super V > constraint ) { } } | return new ConstrainedBiMap < K , V > ( map , null , constraint ) ; |
public class SparkSaslClient { /** * Disposes of any system resources or security - sensitive information the
* SaslClient might be using . */
@ Override public synchronized void dispose ( ) { } } | if ( saslClient != null ) { try { saslClient . dispose ( ) ; } catch ( SaslException e ) { // ignore
} finally { saslClient = null ; } } |
public class AmazonRoute53DomainsClient { /** * This operation removes the transfer lock on the domain ( specifically the < code > clientTransferProhibited < / code >
* status ) to allow domain transfers . We recommend you refrain from performing this action unless you intend to
* transfer the domain to a different registrar . Successful submission returns an operation ID that you can use to
* track the progress and completion of the action . If the request is not completed successfully , the domain
* registrant will be notified by email .
* @ param disableDomainTransferLockRequest
* The DisableDomainTransferLock request includes the following element .
* @ return Result of the DisableDomainTransferLock operation returned by the service .
* @ throws InvalidInputException
* The requested item is not acceptable . For example , for an OperationId it might refer to the ID of an
* operation that is already completed . For a domain name , it might not be a valid domain name or belong to
* the requester account .
* @ throws DuplicateRequestException
* The request is already in progress for the domain .
* @ throws TLDRulesViolationException
* The top - level domain does not support this operation .
* @ throws OperationLimitExceededException
* The number of operations or jobs running exceeded the allowed threshold for the account .
* @ throws UnsupportedTLDException
* Amazon Route 53 does not support this top - level domain ( TLD ) .
* @ sample AmazonRoute53Domains . DisableDomainTransferLock
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / route53domains - 2014-05-15 / DisableDomainTransferLock "
* target = " _ top " > AWS API Documentation < / a > */
@ Override public DisableDomainTransferLockResult disableDomainTransferLock ( DisableDomainTransferLockRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeDisableDomainTransferLock ( request ) ; |
public class CmsPermissionView { /** * Returns a String array with the possible entry types . < p >
* @ param all to include all types , or just user , groups and roles
* @ return the possible types */
protected String [ ] getTypes ( boolean all ) { } } | if ( ! all ) { String [ ] array = new String [ 3 ] ; return Arrays . asList ( CmsPermissionDialog . PRINCIPAL_TYPES ) . subList ( 0 , 3 ) . toArray ( array ) ; } return CmsPermissionDialog . PRINCIPAL_TYPES ; |
public class SceneStructureMetric { /** * Counts the total number of unknown camera parameters that will be optimized /
* @ return Number of parameters */
public int getUnknownCameraParameterCount ( ) { } } | int total = 0 ; for ( int i = 0 ; i < cameras . length ; i ++ ) { if ( ! cameras [ i ] . known ) { total += cameras [ i ] . model . getIntrinsicCount ( ) ; } } return total ; |
public class VirtualNetworkGatewayConnectionsInner { /** * Gets the specified virtual network gateway connection by resource group .
* @ param resourceGroupName The name of the resource group .
* @ param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws CloudException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the VirtualNetworkGatewayConnectionInner object if successful . */
public VirtualNetworkGatewayConnectionInner getByResourceGroup ( String resourceGroupName , String virtualNetworkGatewayConnectionName ) { } } | return getByResourceGroupWithServiceResponseAsync ( resourceGroupName , virtualNetworkGatewayConnectionName ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class VarTupleSet { /** * Returns a measure of the " used - ness " of the given binding . If < CODE > onceOnly < / CODE > is true , consider only once - only tuples .
* Returns a value between 0 and 1 ( exclusive ) - - a higher value means a binding is more used . */
private double getUsedScore ( VarBindingDef binding , boolean onceOnly ) { } } | // Since used tuples are in least - recently - used - first order , start from the end of the list and look
// for the first tuple that includes this binding . This is the most recent use of this binding .
// Return the distance of this tuple from the start of the list , as percentage of the size of the list .
int index ; int usedCount ; Tuple nextTuple ; for ( usedCount = used_ . size ( ) , index = usedCount - 1 ; index >= 0 && ( nextTuple = used_ . get ( index ) ) != null && ! ( ( ! onceOnly || nextTuple . isOnce ( ) ) && nextTuple . contains ( binding ) ) ; index -- ) ; return index < 0 ? 0.0 : ( double ) ( index + 1 ) / ( usedCount + 1 ) ; |
public class PrcSalRetLnCreate { /** * < p > Process entity request . < / p >
* @ param pReqVars additional param , e . g . return this line ' s
* document in " nextEntity " for farther process
* @ param pRequestData Request Data
* @ param pEntity Entity to process
* @ return Entity processed for farther process or null
* @ throws Exception - an exception */
@ Override public final SalesReturnLine process ( final Map < String , Object > pReqVars , final SalesReturnLine pEntityPb , final IRequestData pRequestData ) throws Exception { } } | SalesReturnLine entity = this . prcEntityCreate . process ( pReqVars , pEntityPb , pRequestData ) ; pReqVars . put ( "DebtorCreditortaxDestinationdeepLevel" , 2 ) ; Set < String > ndFlDc = new HashSet < String > ( ) ; ndFlDc . add ( "itsId" ) ; ndFlDc . add ( "isForeigner" ) ; ndFlDc . add ( "taxDestination" ) ; pReqVars . put ( "DebtorCreditorneededFields" , ndFlDc ) ; entity . setItsOwner ( this . prcEntityCreate . getSrvOrm ( ) . retrieveEntity ( pReqVars , entity . getItsOwner ( ) ) ) ; pReqVars . remove ( "DebtorCreditorneededFields" ) ; pReqVars . remove ( "DebtorCreditortaxDestinationdeepLevel" ) ; return entity ; |
public class Benchmark { /** * Closes this benchmark and calculates totals and times . */
public final void close ( ) { } } | while ( subChannel . size ( ) > 0 ) { subs . addSample ( subChannel . poll ( ) ) ; } while ( pubChannel . size ( ) > 0 ) { pubs . addSample ( pubChannel . poll ( ) ) ; } if ( subs . hasSamples ( ) ) { start = subs . getStart ( ) ; end = subs . getEnd ( ) ; if ( pubs . hasSamples ( ) ) { end = Math . min ( end , pubs . getEnd ( ) ) ; } } else { start = pubs . getStart ( ) ; end = pubs . getEnd ( ) ; } msgBytes = pubs . msgBytes + subs . msgBytes ; ioBytes = pubs . ioBytes + subs . ioBytes ; msgCnt = pubs . msgCnt + subs . msgCnt ; jobMsgCnt = pubs . jobMsgCnt + subs . jobMsgCnt ; |
public class AttributeTypeServiceImpl { /** * Returns an enriched AttributeType for when the value meets certain criteria i . e . if a string
* value is longer dan 255 characters , the type should be TEXT */
private AttributeType getEnrichedType ( AttributeType guess , Object value ) { } } | if ( guess == null || value == null ) { return guess ; } if ( guess . equals ( STRING ) ) { String stringValue = value . toString ( ) ; if ( stringValue . length ( ) > MAX_STRING_LENGTH ) { return TEXT ; } if ( canValueBeUsedAsDate ( value ) ) { return DATE ; } } else if ( guess . equals ( DECIMAL ) ) { if ( value instanceof Integer ) { return INT ; } else if ( value instanceof Long ) { Long longValue = ( Long ) value ; return longValue > Integer . MIN_VALUE && longValue < Integer . MAX_VALUE ? INT : LONG ; } else if ( value instanceof Double ) { Double doubleValue = ( Double ) value ; if ( doubleValue != Math . rint ( doubleValue ) ) { return DECIMAL ; } if ( doubleValue > Integer . MIN_VALUE && doubleValue < Integer . MAX_VALUE ) { return INT ; } if ( doubleValue > Long . MIN_VALUE && doubleValue < Long . MAX_VALUE ) { return LONG ; } } } return guess ; |
public class SynchronizeFXWebsocketChannel { /** * Informs this { @ link CommandTransferServer } that a client connection got closed .
* @ param connection The connection that was closed */
void connectionCloses ( final Session connection ) { } } | synchronized ( connections ) { final ExecutorService executorService = connectionThreads . get ( connection ) ; if ( executorService != null ) { executorService . shutdownNow ( ) ; } connectionThreads . remove ( connection ) ; connections . remove ( connection ) ; } |
public class BodyParserXML { /** * Invoke the parser and get back a Java object populated
* with the content of this request .
* MUST BE THREAD SAFE TO CALL !
* @ param context The context
* @ param classOfT The class we expect
* @ param genericType the generic type
* @ return The object instance populated with all values from raw request */
@ Override public < T > T invoke ( Context context , Class < T > classOfT , Type genericType ) { } } | T t = null ; try { final String content = context . body ( ) ; if ( content == null || content . length ( ) == 0 ) { return null ; } if ( classOfT . equals ( Document . class ) ) { return ( T ) parseXMLDocument ( content . getBytes ( Charsets . UTF_8 ) ) ; } if ( genericType != null ) { t = xml . xmlMapper ( ) . readValue ( content , xml . xmlMapper ( ) . constructType ( genericType ) ) ; } else { t = xml . xmlMapper ( ) . readValue ( content , classOfT ) ; } } catch ( IOException e ) { LOGGER . error ( ERROR , e ) ; } return t ; |
public class CmsModule { /** * Removes the resources not accessible with the provided { @ link CmsObject } .
* @ param cms the { @ link CmsObject } used to read the resources .
* @ param sitePaths site relative paths of the resources that should be checked for accessibility .
* @ return site paths of the accessible resources . */
private static List < String > removeNonAccessible ( CmsObject cms , List < String > sitePaths ) { } } | List < String > result = new ArrayList < String > ( sitePaths . size ( ) ) ; for ( String sitePath : sitePaths ) { if ( cms . existsResource ( sitePath , CmsResourceFilter . IGNORE_EXPIRATION ) ) { result . add ( sitePath ) ; } } return result ; |
public class ExtraLanguageFeatureNameConverter { /** * Replies the type of conversion for the given feature call .
* @ param featureCall the feature call .
* @ return the type of conversion . */
public ConversionType getConversionTypeFor ( XAbstractFeatureCall featureCall ) { } } | if ( this . conversions == null ) { this . conversions = initMapping ( ) ; } final List < Object > receiver = new ArrayList < > ( ) ; AbstractExpressionGenerator . buildCallReceiver ( featureCall , this . keywords . getThisKeywordLambda ( ) , this . referenceNameLambda , receiver ) ; final String simpleName = AbstractExpressionGenerator . getCallSimpleName ( featureCall , this . logicalContainerProvider , this . simpleNameProvider , this . keywords . getNullKeywordLambda ( ) , this . keywords . getThisKeywordLambda ( ) , this . keywords . getSuperKeywordLambda ( ) , this . referenceNameLambda2 ) ; final List < Pair < FeaturePattern , FeatureReplacement > > struct = this . conversions . get ( getKey ( simpleName ) ) ; if ( struct != null ) { final String replacementId = featureCall . getFeature ( ) . getIdentifier ( ) ; final FeatureReplacement replacement = matchFirstPattern ( struct , replacementId , simpleName , receiver ) ; if ( replacement != null ) { if ( replacement . hasReplacement ( ) ) { return ConversionType . EXPLICIT ; } return ConversionType . FORBIDDEN_CONVERSION ; } } return ConversionType . IMPLICIT ; |
public class StyleWrapper { /** * Swap two elements of the list .
* @ param src the position first element .
* @ param dest the position second element . */
public void swap ( int src , int dest ) { } } | List < FeatureTypeStyle > ftss = style . featureTypeStyles ( ) ; if ( src >= 0 && src < ftss . size ( ) && dest >= 0 && dest < ftss . size ( ) ) { Collections . swap ( ftss , src , dest ) ; Collections . swap ( featureTypeStylesWrapperList , src , dest ) ; } |
public class MonetaryFunctions { /** * Creates a the summary of MonetaryAmounts .
* @ param currencyUnit the target { @ link javax . money . CurrencyUnit }
* @ return the MonetarySummaryStatistics */
public static Collector < MonetaryAmount , MonetarySummaryStatistics , MonetarySummaryStatistics > summarizingMonetary ( CurrencyUnit currencyUnit ) { } } | Supplier < MonetarySummaryStatistics > supplier = ( ) -> new DefaultMonetarySummaryStatistics ( currencyUnit ) ; return Collector . of ( supplier , MonetarySummaryStatistics :: accept , MonetarySummaryStatistics :: combine ) ; |
public class VisitorPlugin { /** * The classes are sorted for test purposes only . This gives us a predictable order for our
* assertions on the generated code .
* @ param outline */
private Set < ClassOutline > sortClasses ( Outline outline ) { } } | Set < ClassOutline > sorted = new TreeSet < > ( ( aOne , aTwo ) -> { String one = aOne . implClass . fullName ( ) ; String two = aTwo . implClass . fullName ( ) ; return one . compareTo ( two ) ; } ) ; sorted . addAll ( outline . getClasses ( ) ) ; return sorted ; |
public class OrganizationService { /** * Attach a { @ link OrganizationModel } with the given organization to the provided { @ link ArchiveModel } . If an existing Model
* exists with the provided organization , that one will be used instead . */
public OrganizationModel attachOrganization ( ArchiveModel archiveModel , String organizationName ) { } } | OrganizationModel model = getUnique ( getQuery ( ) . traverse ( g -> g . has ( OrganizationModel . NAME , organizationName ) ) . getRawTraversal ( ) ) ; if ( model == null ) { model = create ( ) ; model . setName ( organizationName ) ; model . addArchiveModel ( archiveModel ) ; } else { return attachOrganization ( model , archiveModel ) ; } return model ; |
public class CmsDisableMenuEntry { /** * Checks if the entry is disabled . < p >
* @ return < code > true < / code > if the entry is disabled */
private boolean isEntryDisabled ( ) { } } | CmsClientSitemapEntry entry = getHoverbar ( ) . getEntry ( ) ; final CmsUUID id = entry . getId ( ) ; return getHoverbar ( ) . getController ( ) . isEditable ( ) && CmsSitemapView . getInstance ( ) . isDisabledModelPageEntry ( id ) ; |
public class WizardDialogDecorator { /** * Adapts the visibility of the dialog ' s buttons . */
private void adaptButtonBarVisibility ( ) { } } | if ( buttonBarContainer != null ) { buttonBarContainer . setVisibility ( buttonBarShown ? View . VISIBLE : View . GONE ) ; } |
public class Functions { /** * Runs create digest auth header function with arguments .
* @ return */
public static String digestAuthHeader ( String username , String password , String realm , String noncekey , String method , String uri , String opaque , String algorithm , TestContext context ) { } } | return new DigestAuthHeaderFunction ( ) . execute ( Arrays . asList ( username , password , realm , noncekey , method , uri , opaque , algorithm ) , context ) ; |
public class FlinkKafkaConsumerBase { /** * Specifies the consumer to start reading partitions from specific offsets , set independently for each partition .
* The specified offset should be the offset of the next record that will be read from partitions .
* This lets the consumer ignore any committed group offsets in Zookeeper / Kafka brokers .
* < p > If the provided map of offsets contains entries whose { @ link KafkaTopicPartition } is not subscribed by the
* consumer , the entry will be ignored . If the consumer subscribes to a partition that does not exist in the provided
* map of offsets , the consumer will fallback to the default group offset behaviour ( see
* { @ link FlinkKafkaConsumerBase # setStartFromGroupOffsets ( ) } ) for that particular partition .
* < p > If the specified offset for a partition is invalid , or the behaviour for that partition is defaulted to group
* offsets but still no group offset could be found for it , then the " auto . offset . reset " behaviour set in the
* configuration properties will be used for the partition
* < p > This method does not affect where partitions are read from when the consumer is restored
* from a checkpoint or savepoint . When the consumer is restored from a checkpoint or
* savepoint , only the offsets in the restored state will be used .
* @ return The consumer object , to allow function chaining . */
public FlinkKafkaConsumerBase < T > setStartFromSpecificOffsets ( Map < KafkaTopicPartition , Long > specificStartupOffsets ) { } } | this . startupMode = StartupMode . SPECIFIC_OFFSETS ; this . startupOffsetsTimestamp = null ; this . specificStartupOffsets = checkNotNull ( specificStartupOffsets ) ; return this ; |
public class HttpStatusCodeException { /** * Return the response body converted to the given class
* @ since 3.0.5 */
public < T > T getResponseBody ( Class < T > clazz ) { } } | final ByteBuf byteBuf = httpInputMessage . getBody ( ) ; if ( byteBuf . readableBytes ( ) == 0 || Void . class . isAssignableFrom ( clazz ) ) return null ; final MediaType mediaType = MediaType . parseMediaType ( httpInputMessage . getHeaders ( ) . get ( HttpHeaders . CONTENT_TYPE ) ) ; for ( HttpMessageConverter httpMessageConverter : httpMessageConverters ) { if ( httpMessageConverter . canRead ( clazz , mediaType ) ) { return ( T ) httpMessageConverter . read ( clazz , httpInputMessage ) ; } } return null ; |
public class Annotate { /** * TODO move to ixa - pipe - ml */
private static List < String > buildSegmentedSentences ( final BufferedReader breader ) { } } | String line ; List < String > sentences = new ArrayList < > ( ) ; try { while ( ( line = breader . readLine ( ) ) != null ) { sentences . add ( line ) ; } } catch ( final IOException e ) { LOG . error ( "IOException" , e ) ; } return sentences ; |
public class NextClient { /** * put params into url queries */
public NextResponse delete ( final String url , final Map < String , String > queries , final Map < String , String > headers ) throws IOException { } } | return request ( HttpMethod . DELETE , url , queries , null , headers ) ; |
public class MapBuilder { /** * Adds an entry to the map for this builder if the given value is present . */
public MapBuilder < K , V > putIf ( K key , Optional < V > value ) { } } | value . ifPresent ( v -> map_ . put ( key , v ) ) ; return this ; |
public class DomImplFF { /** * { @ inheritDoc } */
public void setTransformOrigin ( Element element , String origin ) { } } | DOM . setStyleAttribute ( element , "MozTransformOrigin" , origin ) ; // added for IE11
DOM . setStyleAttribute ( element , "transformOrigin" , origin ) ; |
public class NumberFeaturesTile { /** * { @ inheritDoc } */
@ Override public BufferedImage drawTile ( int tileWidth , int tileHeight , long tileFeatureCount , CloseableIterator < GeometryIndex > geometryIndexResults ) { } } | String featureText = String . valueOf ( tileFeatureCount ) ; BufferedImage image = drawTile ( tileWidth , tileHeight , featureText ) ; return image ; |
public class JSONUtils { /** * Finds out if n represents a Double .
* @ return true if n is instanceOf Double or the literal value can be
* evaluated as a Double . */
private static boolean isDouble ( Number n ) { } } | if ( n instanceof Double ) { return true ; } try { double d = Double . parseDouble ( String . valueOf ( n ) ) ; return ! Double . isInfinite ( d ) ; } catch ( NumberFormatException e ) { return false ; } |
public class QstatQueuesParser { /** * ( non - Javadoc )
* @ see com . tupilabs . pbs . parser . Parser # parse ( java . lang . Object ) */
@ Override public List < Queue > parse ( String text ) throws ParseException { } } | final List < Queue > queues ; if ( StringUtils . isNotBlank ( text ) ) { queues = new LinkedList < Queue > ( ) ; String separator = "\n" ; if ( text . indexOf ( "\r\n" ) > 0 ) { separator = "\r\n" ; } final String [ ] lines = text . split ( separator ) ; Queue queue = null ; for ( final String line : lines ) { Matcher matcher = PATTERN_QUEUE . matcher ( line ) ; if ( matcher . matches ( ) ) { if ( queue != null ) { queues . add ( queue ) ; } queue = new Queue ( ) ; final String name = matcher . group ( 1 ) ; queue . setName ( name ) ; } else if ( StringUtils . isNotBlank ( line ) ) { String [ ] temp = Utils . splitFirst ( line , CHAR_EQUALS ) ; if ( temp . length == 2 ) { final String key = temp [ 0 ] . trim ( ) . toLowerCase ( ) ; final String value = temp [ 1 ] . trim ( ) ; if ( "queue_type" . equals ( key ) ) { queue . setQueueType ( value ) ; } else if ( "priority" . equals ( key ) ) { try { queue . setPriority ( Integer . parseInt ( value ) ) ; } catch ( NumberFormatException nfe ) { LOGGER . log ( Level . WARNING , "Failed parsing queue priority: " + nfe . getMessage ( ) , nfe ) ; queue . setPriority ( - 1 ) ; } } else if ( "total_jobs" . equals ( key ) ) { try { queue . setTotalJobs ( Integer . parseInt ( value ) ) ; } catch ( NumberFormatException nfe ) { LOGGER . log ( Level . WARNING , "Failed parsing queue total jobs: " + nfe . getMessage ( ) , nfe ) ; queue . setPriority ( - 1 ) ; } } else if ( "state_count" . equals ( key ) ) { queue . setStateCount ( value ) ; } else if ( "mtime" . equals ( key ) ) { queue . setMtime ( value ) ; } else if ( "max_user_run" . equals ( key ) ) { try { queue . setMaxUserRun ( Integer . parseInt ( value ) ) ; } catch ( NumberFormatException nfe ) { LOGGER . log ( Level . WARNING , "Failed parsing queue max user run: " + nfe . getMessage ( ) , nfe ) ; queue . setPriority ( - 1 ) ; } } else if ( "enabled" . equals ( key ) ) { queue . setEnabled ( Boolean . parseBoolean ( value ) ) ; } else if ( "started" . equals ( key ) ) { queue . setStarted ( Boolean . parseBoolean ( value ) ) ; } else if ( key . startsWith ( "resources_max." ) ) { queue . getResourcesMax ( ) . put ( key , value ) ; } else if ( key . startsWith ( "resources_min." ) ) { queue . getResourcesMin ( ) . put ( key , value ) ; } else if ( key . startsWith ( "resources_assigned." ) ) { queue . getResourcesAssigned ( ) . put ( key , value ) ; } else if ( key . startsWith ( "resources_default." ) ) { queue . getResourcesDefault ( ) . put ( key , value ) ; } else { LOGGER . info ( "Unmmaped key, value: " + key + ", " + value ) ; } } } } if ( queue != null ) { queues . add ( queue ) ; } return queues ; } else { return Collections . emptyList ( ) ; } |
public class AVFirebaseMessagingService { /** * FCM 有两种消息 : 通知消息与数据消息 。
* 通知消息 - - 就是普通的通知栏消息 , 应用在后台的时候 , 通知消息会直接显示在通知栏 , 默认情况下 ,
* 用户点按通知即可打开应用启动器 ( 通知消息附带的参数在 Bundle 内 ) , 我们无法处理 。
* 数据消息 - - 类似于其他厂商的 「 透传消息 」 。 应用在前台的时候 , 数据消息直接发送到应用内 , 应用层通过这一接口进行响应 。
* @ param remoteMessage */
@ Override public void onMessageReceived ( RemoteMessage remoteMessage ) { } } | Map < String , String > data = remoteMessage . getData ( ) ; if ( null == data ) { return ; } LOGGER . d ( "received message from: " + remoteMessage . getFrom ( ) + ", payload: " + data . toString ( ) ) ; try { JSONObject jsonObject = JSON . parseObject ( data . get ( "payload" ) ) ; if ( null != jsonObject ) { String channel = jsonObject . getString ( "_channel" ) ; String action = jsonObject . getString ( "action" ) ; AndroidNotificationManager androidNotificationManager = AndroidNotificationManager . getInstance ( ) ; androidNotificationManager . processGcmMessage ( channel , action , jsonObject . toJSONString ( ) ) ; } } catch ( Exception ex ) { LOGGER . e ( "failed to parse push data." , ex ) ; } |
public class ChartRunner { /** * Set next chart object
* @ param chart next chart object */
public void setChart ( Chart chart ) { } } | this . chart = chart ; if ( this . chart . getReport ( ) . getQuery ( ) != null ) { this . chart . getReport ( ) . getQuery ( ) . setDialect ( dialect ) ; } |
public class GrailsParameterMap { /** * Builds up a multi dimensional hash structure from the parameters so that nested keys such as
* " book . author . name " can be addressed like params [ ' author ' ] . name
* This also allows data binding to occur for only a subset of the properties in the parameter map . */
private void processNestedKeys ( Map requestMap , String key , String nestedKey , Map nestedLevel ) { } } | final int nestedIndex = nestedKey . indexOf ( '.' ) ; if ( nestedIndex == - 1 ) { return ; } // We have at least one sub - key , so extract the first element
// of the nested key as the prfix . In other words , if we have
// ' nestedKey ' = = " a . b . c " , the prefix is " a " .
String nestedPrefix = nestedKey . substring ( 0 , nestedIndex ) ; boolean prefixedByUnderscore = false ; // Use the same prefix even if it starts with an ' _ '
if ( nestedPrefix . startsWith ( "_" ) ) { prefixedByUnderscore = true ; nestedPrefix = nestedPrefix . substring ( 1 ) ; } // Let ' s see if we already have a value in the current map for the prefix .
Object prefixValue = nestedLevel . get ( nestedPrefix ) ; if ( prefixValue == null ) { // No value . So , since there is at least one sub - key ,
// we create a sub - map for this prefix .
prefixValue = new GrailsParameterMap ( new LinkedHashMap ( ) , request ) ; nestedLevel . put ( nestedPrefix , prefixValue ) ; } // If the value against the prefix is a map , then we store the sub - keys in that map .
if ( ! ( prefixValue instanceof Map ) ) { return ; } Map nestedMap = ( Map ) prefixValue ; if ( nestedIndex < nestedKey . length ( ) - 1 ) { String remainderOfKey = nestedKey . substring ( nestedIndex + 1 , nestedKey . length ( ) ) ; // GRAILS - 2486 Cascade the ' _ ' prefix in order to bind checkboxes properly
if ( prefixedByUnderscore ) { remainderOfKey = '_' + remainderOfKey ; } nestedMap . put ( remainderOfKey , getParameterValue ( requestMap , key ) ) ; if ( ! ( nestedMap instanceof GrailsParameterMap ) && remainderOfKey . indexOf ( '.' ) > - 1 ) { processNestedKeys ( requestMap , remainderOfKey , remainderOfKey , nestedMap ) ; } } |
public class JwwfServer { /** * < p > Binds ServletHolder to URL , this allows creation of REST APIs , etc < / p >
* < p > PLUGINS : Plugin servlets should have url ' s like / _ _ jwwf / myplugin / stuff < / p >
* @ param servlet Servlet holder
* @ param url URL to bind servlet to
* @ return This JwwfServer */
public JwwfServer bindServlet ( Servlet servlet , String url ) { } } | context . addServlet ( new ServletHolder ( servlet ) , url ) ; return this ; |
public class PowerShell { /** * Initializes PowerShell console in which we will enter the commands */
private PowerShell initalize ( String powerShellExecutablePath ) throws PowerShellNotAvailableException { } } | String codePage = PowerShellCodepage . getIdentifierByCodePageName ( Charset . defaultCharset ( ) . name ( ) ) ; ProcessBuilder pb ; // Start powershell executable in process
if ( OSDetector . isWindows ( ) ) { pb = new ProcessBuilder ( "cmd.exe" , "/c" , "chcp" , codePage , ">" , "NUL" , "&" , powerShellExecutablePath , "-ExecutionPolicy" , "Bypass" , "-NoExit" , "-NoProfile" , "-Command" , "-" ) ; } else { pb = new ProcessBuilder ( powerShellExecutablePath , "-nologo" , "-noexit" , "-Command" , "-" ) ; } // Merge standard and error streams
pb . redirectErrorStream ( true ) ; try { // Launch process
p = pb . start ( ) ; if ( p . waitFor ( 5 , TimeUnit . SECONDS ) && ! p . isAlive ( ) ) { throw new PowerShellNotAvailableException ( "Cannot execute PowerShell. Please make sure that it is installed in your system. Errorcode:" + p . exitValue ( ) ) ; } } catch ( IOException | InterruptedException ex ) { throw new PowerShellNotAvailableException ( "Cannot execute PowerShell. Please make sure that it is installed in your system" , ex ) ; } // Prepare writer that will be used to send commands to powershell
this . commandWriter = new PrintWriter ( new OutputStreamWriter ( new BufferedOutputStream ( p . getOutputStream ( ) ) ) , true ) ; // Init thread pool . 2 threads are needed : one to write and read console and the other to close it
this . threadpool = Executors . newFixedThreadPool ( 2 ) ; // Get and store the PID of the process
this . pid = getPID ( ) ; return this ; |
public class AbstractSourceImporter { /** * Method to search the Instance which is imported .
* @ return Instance of the imported program
* @ throws InstallationException if search failed */
public Instance searchInstance ( ) throws InstallationException { } } | Instance instance = null ; try { // check if type exists . Necessary for first time installations
if ( getCiType ( ) . getType ( ) != null ) { final QueryBuilder queryBldr = new QueryBuilder ( getCiType ( ) ) ; queryBldr . addWhereAttrEqValue ( CIAdminProgram . Abstract . Name , this . programName ) ; final InstanceQuery query = queryBldr . getQuery ( ) ; query . executeWithoutAccessCheck ( ) ; if ( query . next ( ) ) { instance = query . getCurrentValue ( ) ; } } } catch ( final EFapsException e ) { throw new InstallationException ( "Could not find '" + getCiType ( ) + "' '" + this . programName + "'" , e ) ; } return instance ; |
public class UriCodec { /** * Throws if { @ code s } contains characters that are not letters , digits or
* in { @ code legal } . */
public static void validateSimple ( String s , String legal ) throws URISyntaxException { } } | for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char ch = s . charAt ( i ) ; if ( ! ( ( ch >= 'a' && ch <= 'z' ) || ( ch >= 'A' && ch <= 'Z' ) || ( ch >= '0' && ch <= '9' ) || legal . indexOf ( ch ) > - 1 ) ) { throw new URISyntaxException ( s , "Illegal character" , i ) ; } } |
public class ImageLoader { /** * Convert an input stream to an bgr spectrum image
* @ param file the file to convert
* @ return the input stream to convert */
public INDArray toBgr ( File file ) { } } | try { BufferedInputStream bis = new BufferedInputStream ( new FileInputStream ( file ) ) ; INDArray ret = toBgr ( bis ) ; bis . close ( ) ; return ret ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } |
public class PipeInMessage { /** * private InboxAmp getCallerInbox ( )
* return _ callerInbox ; */
@ Override public final void invokeQuery ( InboxAmp inbox , StubAmp actorDeliver ) { } } | try { MethodAmp method = method ( ) ; StubAmp actorMessage = serviceRef ( ) . stub ( ) ; StubStateAmp load = actorDeliver . load ( actorMessage , this ) ; load . inPipe ( actorDeliver , actorMessage , method , getHeaders ( ) , this , _args ) ; } catch ( Throwable e ) { fail ( e ) ; } |
public class Groups { /** * Indexes elements from the iterator using passed function . E . g :
* < code > indexBy ( [ 1,2,3,4 ] , id ) - > { 1:1 , 2:2 , 3:3 , 4:4 } < / code >
* @ param < K > the key type
* @ param < V > the value type
* @ param < M > the map type
* @ param groupies elements to be indexed
* @ param indexer the function used to index elements
* @ param mapProvider a supplier used to create the resulting map
* @ return indexed elements in a map */
public static < K , V , M extends Map < K , V > > Map < K , V > indexBy ( Iterator < V > groupies , Function < V , K > indexer , Supplier < M > mapProvider ) { } } | return new IndexBy < > ( indexer , mapProvider ) . apply ( groupies ) ; |
public class JavaUtils { /** * Determines the type which is least " specific " ( i . e . parametrized types are more " specific " than generic types ,
* types which are not { @ link Object } are less specific ) . If no exact statement can be made , the second type is chosen .
* @ param types The types
* @ return The most " specific " type
* @ see # determineMostSpecificType ( String . . . ) */
public static String determineLeastSpecificType ( final String ... types ) { } } | switch ( types . length ) { case 0 : throw new IllegalArgumentException ( "At least one type has to be provided" ) ; case 1 : return types [ 0 ] ; case 2 : return determineLeastSpecific ( types [ 0 ] , types [ 1 ] ) ; default : String currentLeastSpecific = determineLeastSpecific ( types [ 0 ] , types [ 1 ] ) ; for ( int i = 2 ; i < types . length ; i ++ ) { currentLeastSpecific = determineLeastSpecific ( currentLeastSpecific , types [ i ] ) ; } return currentLeastSpecific ; } |
public class SOAPHelper { /** * Create message from stream with headers
* @ param headers
* @ param is
* @ return */
public static SOAPMessage createSoapFromStream ( Map < String , String > headers , InputStream is ) { } } | return createSoapFromStream ( null , headers , is ) ; |
public class Matrix4d { /** * / * ( non - Javadoc )
* @ see org . joml . Matrix4dc # rotateTowardsXY ( double , double , org . joml . Matrix4d ) */
public Matrix4d rotateTowardsXY ( double dirX , double dirY , Matrix4d dest ) { } } | if ( ( properties & PROPERTY_IDENTITY ) != 0 ) return dest . rotationTowardsXY ( dirX , dirY ) ; double rm00 = dirY ; double rm01 = dirX ; double rm10 = - dirX ; double rm11 = dirY ; double nm00 = m00 * rm00 + m10 * rm01 ; double nm01 = m01 * rm00 + m11 * rm01 ; double nm02 = m02 * rm00 + m12 * rm01 ; double nm03 = m03 * rm00 + m13 * rm01 ; dest . m10 = m00 * rm10 + m10 * rm11 ; dest . m11 = m01 * rm10 + m11 * rm11 ; dest . m12 = m02 * rm10 + m12 * rm11 ; dest . m13 = m03 * rm10 + m13 * rm11 ; dest . m00 = nm00 ; dest . m01 = nm01 ; dest . m02 = nm02 ; dest . m03 = nm03 ; dest . m20 = m20 ; dest . m21 = m21 ; dest . m22 = m22 ; dest . m23 = m23 ; dest . m30 = m30 ; dest . m31 = m31 ; dest . m32 = m32 ; dest . m33 = m33 ; dest . properties = properties & ~ ( PROPERTY_PERSPECTIVE | PROPERTY_IDENTITY | PROPERTY_TRANSLATION ) ; return dest ; |
public class tmtrafficpolicy { /** * Use this API to fetch filtered set of tmtrafficpolicy resources .
* filter string should be in JSON format . eg : " port : 80 , servicetype : HTTP " . */
public static tmtrafficpolicy [ ] get_filtered ( nitro_service service , String filter ) throws Exception { } } | tmtrafficpolicy obj = new tmtrafficpolicy ( ) ; options option = new options ( ) ; option . set_filter ( filter ) ; tmtrafficpolicy [ ] response = ( tmtrafficpolicy [ ] ) obj . getfiltered ( service , option ) ; return response ; |
public class UnsafeExternalSorter { /** * Allocates more memory in order to insert an additional record . This will request additional
* memory from the memory manager and spill if the requested memory can not be obtained .
* @ param required the required space in the data page , in bytes , including space for storing
* the record size . This must be less than or equal to the page size ( records
* that exceed the page size are handled via a different code path which uses
* special overflow pages ) . */
private void acquireNewPageIfNecessary ( int required ) { } } | if ( currentPage == null || pageCursor + required > currentPage . getBaseOffset ( ) + currentPage . size ( ) ) { // TODO : try to find space on previous pages
currentPage = allocatePage ( required ) ; pageCursor = currentPage . getBaseOffset ( ) ; allocatedPages . add ( currentPage ) ; } |
public class CollectionUtil { /** * Creates a thin { @ link Iterator } wrapper around an array .
* @ param pArray the array to iterate
* @ param pStart the offset into the array
* @ param pLength the number of elements to include in the iterator
* @ return a new { @ link ListIterator }
* @ throws IllegalArgumentException if { @ code pArray } is { @ code null } ,
* { @ code pStart < 0 } , or
* { @ code pLength > pArray . length - pStart } */
public static < E > ListIterator < E > iterator ( final E [ ] pArray , final int pStart , final int pLength ) { } } | return new ArrayIterator < E > ( pArray , pStart , pLength ) ; |
public class AbstractVegetationObjectType { /** * Gets the value of the genericApplicationPropertyOfVegetationObject property .
* This accessor method returns a reference to the live list ,
* not a snapshot . Therefore any modification you make to the
* returned list will be present inside the JAXB object .
* This is why there is not a < CODE > set < / CODE > method for the genericApplicationPropertyOfVegetationObject property .
* For example , to add a new item , do as follows :
* < pre >
* get _ GenericApplicationPropertyOfVegetationObject ( ) . add ( newItem ) ;
* < / pre >
* Objects of the following type ( s ) are allowed in the list
* { @ link JAXBElement } { @ code < } { @ link Object } { @ code > }
* { @ link JAXBElement } { @ code < } { @ link Object } { @ code > } */
public List < JAXBElement < Object > > get_GenericApplicationPropertyOfVegetationObject ( ) { } } | if ( _GenericApplicationPropertyOfVegetationObject == null ) { _GenericApplicationPropertyOfVegetationObject = new ArrayList < JAXBElement < Object > > ( ) ; } return this . _GenericApplicationPropertyOfVegetationObject ; |
public class StructureSequenceMatcher { /** * Get a substructure of { @ code wholeStructure } containing only the { @ link Group Groups } that are included in
* { @ code sequence } . The resulting structure will contain only { @ code ATOM } residues ; the SEQ - RES will be empty .
* The { @ link Chain Chains } of the Structure will be new instances ( cloned ) , but the { @ link Group Groups } will not .
* @ param sequence The input protein sequence
* @ param wholeStructure The structure from which to take a substructure
* @ return The resulting structure
* @ throws StructureException
* @ see { @ link # matchSequenceToStructure ( ProteinSequence , Structure ) } */
public static Structure getSubstructureMatchingProteinSequence ( ProteinSequence sequence , Structure wholeStructure ) { } } | ResidueNumber [ ] rns = matchSequenceToStructure ( sequence , wholeStructure ) ; Structure structure = wholeStructure . clone ( ) ; structure . setChains ( new ArrayList < > ( ) ) ; // structure . getHetGroups ( ) . clear ( ) ;
Chain currentChain = null ; for ( ResidueNumber rn : rns ) { if ( rn == null ) continue ; Group group ; // note that we don ' t clone
try { group = StructureTools . getGroupByPDBResidueNumber ( wholeStructure , rn ) ; } catch ( StructureException e ) { throw new IllegalArgumentException ( "Could not find residue " + rn + " in structure" , e ) ; } Chain chain = new ChainImpl ( ) ; chain . setName ( group . getChain ( ) . getName ( ) ) ; chain . setId ( group . getChain ( ) . getId ( ) ) ; if ( currentChain == null || ! currentChain . getId ( ) . equals ( chain . getId ( ) ) ) { structure . addChain ( chain ) ; chain . setEntityInfo ( group . getChain ( ) . getEntityInfo ( ) ) ; chain . setStructure ( structure ) ; chain . setSwissprotId ( group . getChain ( ) . getSwissprotId ( ) ) ; chain . setId ( group . getChain ( ) . getId ( ) ) ; chain . setName ( group . getChain ( ) . getName ( ) ) ; currentChain = chain ; } currentChain . addGroup ( group ) ; } return structure ; |
public class AllConnectConnectionHolder { /** * Add alive .
* @ param providerInfo the provider
* @ param transport the transport */
protected void addAlive ( ProviderInfo providerInfo , ClientTransport transport ) { } } | if ( checkState ( providerInfo , transport ) ) { aliveConnections . put ( providerInfo , transport ) ; } |
public class TimePickerDialog { /** * Update the hours , minutes , seconds and AM / PM displays with the typed times . If the typedTimes
* is empty , either show an empty display ( filled with the placeholder text ) , or update from the
* timepicker ' s values .
* @ param allowEmptyDisplay if true , then if the typedTimes is empty , use the placeholder text .
* Otherwise , revert to the timepicker ' s values . */
private void updateDisplay ( boolean allowEmptyDisplay ) { } } | if ( ! allowEmptyDisplay && mTypedTimes . isEmpty ( ) ) { int hour = mTimePicker . getHours ( ) ; int minute = mTimePicker . getMinutes ( ) ; int second = mTimePicker . getSeconds ( ) ; setHour ( hour , true ) ; setMinute ( minute ) ; setSecond ( second ) ; if ( ! mIs24HourMode ) { updateAmPmDisplay ( hour < 12 ? AM : PM ) ; } setCurrentItemShowing ( mTimePicker . getCurrentItemShowing ( ) , true , true , true ) ; mOkButton . setEnabled ( true ) ; } else { Boolean [ ] enteredZeros = { false , false , false } ; int [ ] values = getEnteredTime ( enteredZeros ) ; String hourFormat = enteredZeros [ 0 ] ? "%02d" : "%2d" ; String minuteFormat = ( enteredZeros [ 1 ] ) ? "%02d" : "%2d" ; String secondFormat = ( enteredZeros [ 1 ] ) ? "%02d" : "%2d" ; String hourStr = ( values [ 0 ] == - 1 ) ? mDoublePlaceholderText : String . format ( hourFormat , values [ 0 ] ) . replace ( ' ' , mPlaceholderText ) ; String minuteStr = ( values [ 1 ] == - 1 ) ? mDoublePlaceholderText : String . format ( minuteFormat , values [ 1 ] ) . replace ( ' ' , mPlaceholderText ) ; String secondStr = ( values [ 2 ] == - 1 ) ? mDoublePlaceholderText : String . format ( secondFormat , values [ 1 ] ) . replace ( ' ' , mPlaceholderText ) ; mHourView . setText ( hourStr ) ; mHourSpaceView . setText ( hourStr ) ; mHourView . setTextColor ( mUnselectedColor ) ; mMinuteView . setText ( minuteStr ) ; mMinuteSpaceView . setText ( minuteStr ) ; mMinuteView . setTextColor ( mUnselectedColor ) ; mSecondView . setText ( secondStr ) ; mSecondSpaceView . setText ( secondStr ) ; mSecondView . setTextColor ( mUnselectedColor ) ; if ( ! mIs24HourMode ) { updateAmPmDisplay ( values [ 3 ] ) ; } } |
public class UrlStartWithMatcher { /** * 将URL拆成两块 : 反序后的斜线前面的主机 、 端口和帐号 ; 斜线后面的路径和参数 。
* 比如对于http : / / www . news . com / read / daily / headline . html , 返回的是 :
* moc . swen . www和read / daily / headline . html两项 。
* @ param urlURL , 可以带http : / / , 也可不带
* @ return第一项是反序后的斜线前面的 , 第二项是斜线后面的 。 而且已经被转为小写 。 */
static protected String [ ] splitURL ( String url ) { } } | String beforePart ; String afterPart ; String [ ] l = new String [ 2 ] ; int protocolEnd = url . indexOf ( "://" ) ; if ( protocolEnd == - 1 ) { // 如果没有协议信息
protocolEnd = - 3 ; } int pathStart = url . indexOf ( "/" , protocolEnd + 3 ) ; if ( pathStart == - 1 ) { // 没路径信息
pathStart = url . length ( ) ; afterPart = "" ; } else { afterPart = url . substring ( pathStart + 1 ) . toLowerCase ( ) ; // 斜线后的路径和参数
} beforePart = url . substring ( protocolEnd + 3 , pathStart ) . toLowerCase ( ) ; // 斜线前的主机 、 端口和帐号
String reversedBeforePart = new StringBuffer ( beforePart ) . reverse ( ) . toString ( ) ; l [ 0 ] = reversedBeforePart ; l [ 1 ] = afterPart ; return l ; |
public class DescribeAnalysisSchemesRequest { /** * The analysis schemes you want to describe .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setAnalysisSchemeNames ( java . util . Collection ) } or { @ link # withAnalysisSchemeNames ( java . util . Collection ) }
* if you want to override the existing values .
* @ param analysisSchemeNames
* The analysis schemes you want to describe .
* @ return Returns a reference to this object so that method calls can be chained together . */
public DescribeAnalysisSchemesRequest withAnalysisSchemeNames ( String ... analysisSchemeNames ) { } } | if ( this . analysisSchemeNames == null ) { setAnalysisSchemeNames ( new com . amazonaws . internal . SdkInternalList < String > ( analysisSchemeNames . length ) ) ; } for ( String ele : analysisSchemeNames ) { this . analysisSchemeNames . add ( ele ) ; } return this ; |
public class GoogleImageDAO { /** * Updates GoogleImage name . This method does not update lastModifier and lastModified fields and thus should
* be called only by system operations ( e . g . scheduler )
* @ param googleImage GoogleImage entity
* @ param name new resource name
* @ param urlName new resource urlName
* @ return Updated GoogleImage */
public GoogleImage updateName ( GoogleImage googleImage , String name , String urlName ) { } } | googleImage . setName ( name ) ; googleImage . setUrlName ( urlName ) ; getEntityManager ( ) . persist ( googleImage ) ; return googleImage ; |
public class CEMILDataEx { /** * Returns additional information data corresponding to the supplied type ID , if it is
* contained in the message .
* @ param infoType type ID of the request additional information
* @ return additional information data or < code > null < / code > if no such information
* is available */
public synchronized byte [ ] getAdditionalInfo ( int infoType ) { } } | if ( infoType < addInfo . length && addInfo [ infoType ] != null ) return ( byte [ ] ) addInfo [ infoType ] . clone ( ) ; return null ; |
public class RedisIndexer { /** * ( non - Javadoc )
* @ see com . impetus . kundera . index . Indexer # search ( java . lang . Class ,
* java . lang . String , int , int ) */
@ Override public Map < String , Object > search ( Class < ? > clazz , EntityMetadata m , String queryString , int start , int count ) { } } | // TODO Auto - generated method stub
return null ; |
public class ShowcaseAd { /** * Gets the collapsedImage value for this ShowcaseAd .
* @ return collapsedImage * Image displayed in the collapsed view of the Showcase shopping
* ad .
* < p > The format of the image must be either JPEG
* or PNG and the size of the image must be
* 270x270 px . */
public com . google . api . ads . adwords . axis . v201809 . cm . Image getCollapsedImage ( ) { } } | return collapsedImage ; |
public class FunctionWriter { /** * @ param writer
* @ throws IOException */
public void writeCloseFunction ( Writer writer ) throws IOException { } } | writer . append ( TAB ) . append ( CLOSEBRACE ) . append ( CR ) ; |
public class Parser { /** * Pattern : : = " { " ( Field ( " , " Field ) * " , " ? ) ? " } " | . . . */
private ParseTree parseObjectPattern ( PatternKind kind ) { } } | SourcePosition start = getTreeStartLocation ( ) ; ImmutableList . Builder < ParseTree > fields = ImmutableList . builder ( ) ; eat ( TokenType . OPEN_CURLY ) ; while ( peekObjectPatternField ( ) ) { fields . add ( parseObjectPatternField ( kind ) ) ; if ( peek ( TokenType . COMMA ) ) { // Consume the comma separator
eat ( TokenType . COMMA ) ; } else { // Otherwise we must be done
break ; } } if ( peek ( TokenType . SPREAD ) ) { recordFeatureUsed ( Feature . OBJECT_PATTERN_REST ) ; fields . add ( parsePatternRest ( kind ) ) ; } eat ( TokenType . CLOSE_CURLY ) ; return new ObjectPatternTree ( getTreeLocation ( start ) , fields . build ( ) ) ; |
public class EurekaClinicalClient { /** * Submits a multi - part form .
* @ param path the API to call .
* @ param formDataMultiPart the multi - part form content .
* @ param headers any headers to add . If no Content Type header is provided ,
* this method adds a Content Type header for multi - part forms data .
* @ throws ClientException if a status code other than 200 ( OK ) and 204 ( No
* Content ) is returned . */
public void doPostMultipart ( String path , FormDataMultiPart formDataMultiPart , MultivaluedMap < String , String > headers ) throws ClientException { } } | this . readLock . lock ( ) ; try { WebResource . Builder requestBuilder = getResourceWrapper ( ) . rewritten ( path , HttpMethod . POST ) . getRequestBuilder ( ) ; requestBuilder = ensurePostMultipartHeaders ( headers , requestBuilder ) ; ClientResponse response = requestBuilder . post ( ClientResponse . class , formDataMultiPart ) ; errorIfStatusNotEqualTo ( response , ClientResponse . Status . OK , ClientResponse . Status . NO_CONTENT ) ; response . close ( ) ; } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } |
public class ClassLoaderUtil { /** * This method returns a method ( public , protected or private ) which appears
* in the selected class or any of its parent ( interface or superclass ) or
* container classes ( when the selected class is an inner class ) which
* matches with the name and whose parameters are compatible with the
* selected typeArgs .
* @ param clazz
* Class to scan
* @ param methodName
* Method name
* @ param typeArgs
* Method arguments
* @ return Method instance */
public Method getMethod ( Class < ? > clazz , String methodName , Class < ? > ... typeArgs ) { } } | int numParams = typeArgs == null ? 0 : typeArgs . length ; Method [ ] classMethods = clazz . getMethods ( ) ; for ( Method method : classMethods ) { if ( method . getName ( ) . equals ( methodName ) ) { if ( method . getParameterTypes ( ) . length == numParams ) { boolean isCompatible = true ; Class < ? > [ ] methodParameterTypes = method . getParameterTypes ( ) ; for ( int i = 0 ; i < methodParameterTypes . length ; i ++ ) { isCompatible = isCompatible ( typeArgs [ i ] , methodParameterTypes [ i ] ) ; if ( ! isCompatible ) break ; } if ( isCompatible ) { return method ; } } } } classMethods = clazz . getDeclaredMethods ( ) ; for ( Method method : classMethods ) { if ( method . getName ( ) . equals ( methodName ) ) { if ( method . getParameterTypes ( ) . length == numParams ) { boolean isCompatible = true ; Class < ? > [ ] methodParameterTypes = method . getParameterTypes ( ) ; for ( int i = 0 ; i < methodParameterTypes . length ; i ++ ) { isCompatible = isCompatible ( typeArgs [ i ] , methodParameterTypes [ i ] ) ; if ( ! isCompatible ) break ; } if ( isCompatible ) { return method ; } } } } Method result = null ; if ( clazz . isMemberClass ( ) ) { result = getMethod ( clazz . getEnclosingClass ( ) , methodName , typeArgs ) ; } if ( result == null && clazz . getSuperclass ( ) != null ) { return getMethod ( clazz . getSuperclass ( ) , methodName , typeArgs ) ; } return result ; |
public class BatchPutScheduledUpdateGroupActionRequest { /** * One or more scheduled actions . The maximum number allowed is 50.
* @ param scheduledUpdateGroupActions
* One or more scheduled actions . The maximum number allowed is 50. */
public void setScheduledUpdateGroupActions ( java . util . Collection < ScheduledUpdateGroupActionRequest > scheduledUpdateGroupActions ) { } } | if ( scheduledUpdateGroupActions == null ) { this . scheduledUpdateGroupActions = null ; return ; } this . scheduledUpdateGroupActions = new com . amazonaws . internal . SdkInternalList < ScheduledUpdateGroupActionRequest > ( scheduledUpdateGroupActions ) ; |
public class BufferedIterator { /** * Advances the specified number of tokens in the stream and places them in
* the buffer .
* @ param tokens the number of tokens to advance
* @ return { @ true } if the stream contained at least that many tokens , { @ code
* false } if the stream contained fewer */
private boolean advance ( int tokens ) { } } | while ( buffer . size ( ) < tokens && tokenizer . hasNext ( ) ) buffer . add ( tokenizer . next ( ) ) ; return buffer . size ( ) >= tokens ; |
public class ApiClient { /** * Encode the given form parameters as request body . */
private String getXWWWFormUrlencodedParams ( Map < String , Object > formParams ) { } } | StringBuilder formParamBuilder = new StringBuilder ( ) ; for ( Entry < String , Object > param : formParams . entrySet ( ) ) { String valueStr = parameterToString ( param . getValue ( ) ) ; try { formParamBuilder . append ( URLEncoder . encode ( param . getKey ( ) , "utf8" ) ) . append ( "=" ) . append ( URLEncoder . encode ( valueStr , "utf8" ) ) ; formParamBuilder . append ( "&" ) ; } catch ( UnsupportedEncodingException e ) { // move on to next
} } String encodedFormParams = formParamBuilder . toString ( ) ; if ( encodedFormParams . endsWith ( "&" ) ) { encodedFormParams = encodedFormParams . substring ( 0 , encodedFormParams . length ( ) - 1 ) ; } return encodedFormParams ; |
public class GraphIOUtil { /** * Merges the { @ code message } from the { @ link InputStream } using the given { @ code schema } .
* The { @ code buffer } ' s internal byte array will be used for reading the message . */
public static < T > void mergeFrom ( InputStream in , T message , Schema < T > schema , LinkedBuffer buffer ) throws IOException { } } | final CodedInput input = new CodedInput ( in , buffer . buffer , true ) ; final GraphCodedInput graphInput = new GraphCodedInput ( input ) ; schema . mergeFrom ( graphInput , message ) ; input . checkLastTagWas ( 0 ) ; |
public class Dklu_kernel { /** * Computes the numerical values of x , for the solution of Lx = b . Note that x
* may include explicit zeros if numerical cancelation occurs . L is assumed
* to be unit - diagonal , with possibly unsorted columns ( but the first entry in
* the column must always be the diagonal entry ) .
* @ param Pinv Pinv [ i ] = k if i is kth pivot row , or EMPTY if row i
* is not yet pivotal .
* @ param LU LU factors ( pattern and values )
* @ param Stack stack for dfs
* @ param Lip size n , Lip [ k ] is position in LU of column k of L
* @ param top top of stack on input
* @ param n A is n - by - n
* @ param Llen size n , Llen [ k ] = # nonzeros in column k of L
* @ param X size n , initially zero . On output ,
* X [ Ui [ up1 . . up - 1 ] ] and X [ Li [ lp1 . . lp - 1 ] ] contains the solution . */
public static void lsolve_numeric ( int [ ] Pinv , double [ ] LU , int [ ] Stack , int [ ] Lip , int Lip_offset , int top , int n , int [ ] Llen , int Llen_offset , double [ ] X ) { } } | double xj ; double [ ] Lx ; /* int [ ] */
double [ ] Li ; int p , s , j , jnew ; int [ ] len = new int [ 1 ] ; int [ ] Li_offset = new int [ 1 ] ; int [ ] Lx_offset = new int [ 1 ] ; /* solve Lx = b */
for ( s = top ; s < n ; s ++ ) { /* forward solve with column j of L */
j = Stack [ s ] ; jnew = Pinv [ j ] ; ASSERT ( jnew >= 0 ) ; xj = X [ j ] ; Li = Lx = GET_POINTER ( LU , Lip , Lip_offset , Llen , Llen_offset , Li_offset , Lx_offset , jnew , len ) ; ASSERT ( Lip [ Lip_offset + jnew ] <= Lip [ Lip_offset + jnew + 1 ] ) ; for ( p = 0 ; p < len [ 0 ] ; p ++ ) { // MULT _ SUB ( X [ Li [ p ] ] , Lx [ p ] , xj ) ;
X [ ( int ) Li [ Li_offset [ 0 ] + p ] ] -= Lx [ Lx_offset [ 0 ] + p ] * xj ; } } |
public class EmbeddedJmxTransFactory { /** * Computes the last modified date of all configuration files .
* @ param configurations the list of available configurations as Spring resources
* @ return */
private long computeConfigurationLastModified ( List < Resource > configurations ) { } } | long result = 0 ; for ( Resource configuration : configurations ) { try { long currentConfigurationLastModified = configuration . lastModified ( ) ; if ( currentConfigurationLastModified > result ) { result = currentConfigurationLastModified ; } } catch ( IOException ioex ) { logger . warn ( "Error while reading last configuration modification date." , ioex ) ; } } return result ; |
public class Table { /** * Add cell nesting factory .
* Set the CompositeFactory for this thread . Each new cell in the
* table added by this thread will have a new Composite from this
* factory nested in the Cell .
* @ param factory The factory for this Thread . If null clear this
* threads factory .
* @ deprecated Use setNestingFactory or setThreadNestingFactory */
public static void setCellNestingFactory ( CompositeFactory factory ) { } } | if ( threadNestingMap == null ) threadNestingMap = new Hashtable ( ) ; if ( factory == null ) threadNestingMap . remove ( Thread . currentThread ( ) ) ; else threadNestingMap . put ( Thread . currentThread ( ) , factory ) ; |
public class ParameterUtil { /** * Get values for a dependent parameter sql
* All parent parameters must have the values in the map .
* @ param con database connection
* @ param qp parameter
* @ param map report map of parameters
* @ param vals map of parameter values
* @ return values for parameter with sql source
* @ throws Exception if an exception occurs */
public static List < IdName > getParameterValues ( Connection con , QueryParameter qp , Map < String , QueryParameter > map , Map < String , Serializable > vals ) throws Exception { } } | Map < String , Object > objVals = new HashMap < String , Object > ( ) ; for ( String key : vals . keySet ( ) ) { Serializable s = vals . get ( key ) ; if ( s instanceof Serializable [ ] ) { Serializable [ ] array = ( Serializable [ ] ) s ; Object [ ] objArray = new Object [ array . length ] ; for ( int i = 0 , size = array . length ; i < size ; i ++ ) { objArray [ i ] = array [ i ] ; } s = objArray ; } objVals . put ( key , s ) ; } QueryExecutor executor = null ; try { List < IdName > values = new ArrayList < IdName > ( ) ; Query query = new Query ( qp . getSource ( ) ) ; executor = new QueryExecutor ( query , map , objVals , con , false , false , false ) ; executor . setTimeout ( 10000 ) ; executor . setMaxRows ( 0 ) ; QueryResult qr = executor . execute ( ) ; // int count = qr . getRowCount ( ) ;
// one or two columns in manual select source
// for ( int i = 0 ; i < count ; i + + ) {
while ( qr . hasNext ( ) ) { IdName in = new IdName ( ) ; in . setId ( ( Serializable ) qr . nextValue ( 0 ) ) ; if ( qr . getColumnCount ( ) == 1 ) { in . setName ( ( Serializable ) qr . nextValue ( 0 ) ) ; } else { in . setName ( ( Serializable ) qr . nextValue ( 1 ) ) ; } values . add ( in ) ; } return values ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; throw new Exception ( ex ) ; } finally { if ( executor != null ) { executor . close ( ) ; } } |
public class ClientManager { /** * Renames a currently connected client from < code > oldname < / code > to < code > newname < / code > .
* @ return true if the client was found and renamed . */
protected boolean renameClientObject ( Name oldname , Name newname ) { } } | ClientObject clobj = _objmap . remove ( oldname ) ; if ( clobj == null ) { log . warning ( "Requested to rename unmapped client object" , "username" , oldname , new Exception ( ) ) ; return false ; } _objmap . put ( newname , clobj ) ; return true ; |
public class SQLUtils { /** * 拼凑select的field的语句
* @ param fields
* @ param sep
* @ param fieldPrefix
* @ return */
private static String join ( List < Field > fields , String sep , String fieldPrefix ) { } } | return joinAndGetValueForSelect ( fields , sep , fieldPrefix ) ; |
public class PageContextImpl { /** * called by generated bytecode */
public Tag use ( String tagClassName , String fullname , int attrType ) throws PageException { } } | return use ( tagClassName , null , null , fullname , attrType , null ) ; |
public class CharOperation { /** * Answers the first index in the array for which the corresponding character is equal to toBeFound starting the
* search at index start . Answers - 1 if no occurrence of this character is found . < br >
* < br >
* For example :
* < ol >
* < li >
* < pre >
* toBeFound = ' c '
* array = { ' a ' , ' b ' , ' c ' , ' d ' }
* start = 2
* result = & gt ; 2
* < / pre >
* < / li >
* < li >
* < pre >
* toBeFound = ' c '
* array = { ' a ' , ' b ' , ' c ' , ' d ' }
* start = 3
* result = & gt ; - 1
* < / pre >
* < / li >
* < li >
* < pre >
* toBeFound = ' e '
* array = { ' a ' , ' b ' , ' c ' , ' d ' }
* start = 1
* result = & gt ; - 1
* < / pre >
* < / li >
* < / ol >
* @ param toBeFound
* the character to search
* @ param array
* the array to be searched
* @ param start
* the starting index
* @ return the first index in the array for which the corresponding character is equal to toBeFound , - 1 otherwise
* @ throws NullPointerException
* if array is null
* @ throws ArrayIndexOutOfBoundsException
* if start is lower than 0 */
public static final int indexOf ( char toBeFound , char [ ] array , int start ) { } } | for ( int i = start ; i < array . length ; i ++ ) { if ( toBeFound == array [ i ] ) { return i ; } } return - 1 ; |
public class ArtifactResource { /** * Add a license to an artifact
* @ param credential DbCredential
* @ param gavc String
* @ param licenseId String
* @ return Response */
@ POST @ Path ( "/{gavc}" + ServerAPI . GET_LICENSES ) public Response addLicense ( @ Auth final DbCredential credential , @ PathParam ( "gavc" ) final String gavc , @ QueryParam ( ServerAPI . LICENSE_ID_PARAM ) final String licenseId ) { } } | if ( ! credential . getRoles ( ) . contains ( AvailableRoles . DATA_UPDATER ) && ! credential . getRoles ( ) . contains ( AvailableRoles . LICENSE_SETTER ) ) { throw new WebApplicationException ( Response . status ( Response . Status . UNAUTHORIZED ) . build ( ) ) ; } if ( LOG . isInfoEnabled ( ) ) { LOG . info ( String . format ( "Got a add license request [%s]" , gavc ) ) ; } if ( licenseId == null ) { return Response . serverError ( ) . status ( HttpStatus . NOT_ACCEPTABLE_406 ) . build ( ) ; } getArtifactHandler ( ) . addLicenseToArtifact ( gavc , licenseId ) ; cacheUtils . clear ( CacheName . PROMOTION_REPORTS ) ; return Response . ok ( "done" ) . build ( ) ; |
public class QueryBuilder { /** * The product of two terms , as in { @ code WHERE k = left * right } . */
@ NonNull public static Term multiply ( @ NonNull Term left , @ NonNull Term right ) { } } | return new BinaryArithmeticTerm ( ArithmeticOperator . PRODUCT , left , right ) ; |
public class YokeSecurity { /** * Returns the original value is the signature is correct . Null otherwise . */
public static String unsign ( @ NotNull String val , @ NotNull Mac mac ) { } } | int idx = val . lastIndexOf ( '.' ) ; if ( idx == - 1 ) { return null ; } String str = val . substring ( 0 , idx ) ; if ( val . equals ( sign ( str , mac ) ) ) { return str ; } return null ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.