signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class StockholmFileParser { /** * parses an { @ link InputStream } and returns at maximum < code > max < / code > objects contained in that file . < br >
* This method leaves the stream open for further calls of { @ link # parse ( InputStream , int ) } ( same function ) or
* { @ link # parseNext ( int ) } .
* @ see # parseNext ( int )
* @ param inStream
* the stream to parse
* @ param max
* maximum number of structures to try to parse , { @ link # INFINITY } to try to obtain as much as possible .
* @ return a { @ link List } of { @ link StockholmStructure } objects . If there are no more structures , an empty list is
* returned .
* @ throws IOException
* in case an I / O Exception occurred . */
public List < StockholmStructure > parse ( InputStream inStream , int max ) throws IOException { } } | if ( max < INFINITY ) { throw new IllegalArgumentException ( "max can't be -ve value " + max ) ; } if ( inStream != this . cashedInputStream ) { this . cashedInputStream = inStream ; this . internalScanner = null ; } if ( internalScanner == null ) { internalScanner = new Scanner ( inStream ) ; } ArrayList < StockholmStructure > structures = new ArrayList < StockholmStructure > ( ) ; while ( max != INFINITY && max -- > 0 ) { StockholmStructure structure = parse ( internalScanner ) ; if ( structure != null ) { structures . add ( structure ) ; } else { break ; } } return structures ; |
public class ConcurrentHashMap { /** * Remove any singe element from the map .
* @ return Object the removed Object or null . */
public final Object removeOne ( ) { } } | // Avoid locking the whole Map by looking at the subMaps indivdually starting at a
// random point in the sequence .
int index = new java . util . Random ( Thread . currentThread ( ) . hashCode ( ) ) . nextInt ( subMaps . length ) ; int firstIndex = index ; Object removedObject = null ; do { java . util . Map subMap = subMaps [ index ] ; synchronized ( subMap ) { if ( ! subMap . isEmpty ( ) ) { java . util . Iterator iterator = subMap . values ( ) . iterator ( ) ; removedObject = iterator . next ( ) ; iterator . remove ( ) ; break ; } // if ( freeTransactions . isEmpty ( ) ) .
} // synchronized ( subMap ) .
index ++ ; if ( index == subMaps . length ) index = 0 ; } while ( index != firstIndex ) ; return removedObject ; |
public class AbstractWarningsParser { /** * Converts a string line number to an integer value . If the string is not a
* valid line number , then 0 is returned which indicates a warning at the
* top of the file .
* @ param lineNumber
* the line number ( as a string )
* @ return the line number */
protected final int getLineNumber ( final String lineNumber ) { } } | if ( StringUtils . isNotBlank ( lineNumber ) ) { try { return Integer . parseInt ( lineNumber ) ; } catch ( NumberFormatException exception ) { // ignore and return 0
} } return 0 ; |
public class NetUtil { /** * Converts a 32 - bit integer into an IPv4 address . */
public static String intToIpAddress ( int i ) { } } | StringBuilder buf = new StringBuilder ( 15 ) ; buf . append ( i >> 24 & 0xff ) ; buf . append ( '.' ) ; buf . append ( i >> 16 & 0xff ) ; buf . append ( '.' ) ; buf . append ( i >> 8 & 0xff ) ; buf . append ( '.' ) ; buf . append ( i & 0xff ) ; return buf . toString ( ) ; |
public class AppServiceCertificateOrdersInner { /** * Create or update a certificate purchase order .
* Create or update a certificate purchase order .
* @ param resourceGroupName Name of the resource group to which the resource belongs .
* @ param certificateOrderName Name of the certificate order .
* @ param certificateDistinguishedName Distinguished name to to use for the certificate order .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws DefaultErrorResponseException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the AppServiceCertificateOrderInner object if successful . */
public AppServiceCertificateOrderInner beginCreateOrUpdate ( String resourceGroupName , String certificateOrderName , AppServiceCertificateOrderInner certificateDistinguishedName ) { } } | return beginCreateOrUpdateWithServiceResponseAsync ( resourceGroupName , certificateOrderName , certificateDistinguishedName ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class CommerceWarehouseItemLocalServiceWrapper { /** * Deletes the commerce warehouse item with the primary key from the database . Also notifies the appropriate model listeners .
* @ param commerceWarehouseItemId the primary key of the commerce warehouse item
* @ return the commerce warehouse item that was removed
* @ throws PortalException if a commerce warehouse item with the primary key could not be found */
@ Override public com . liferay . commerce . model . CommerceWarehouseItem deleteCommerceWarehouseItem ( long commerceWarehouseItemId ) throws com . liferay . portal . kernel . exception . PortalException { } } | return _commerceWarehouseItemLocalService . deleteCommerceWarehouseItem ( commerceWarehouseItemId ) ; |
public class OpenAPIUtils { /** * Print map to string
* @ param map - the map to be printed to String */
public static String mapToString ( Map < String , ? > map ) { } } | StringBuilder sb = new StringBuilder ( ) ; sb . append ( "{\n" ) ; for ( String key : map . keySet ( ) ) { if ( map . get ( key ) != null ) { sb . append ( key + ": " + map . get ( key ) + "\n " ) ; } else { continue ; } } sb . append ( "}" ) ; return sb . toString ( ) ; |
public class Change { /** * Applies a mapping function to both the old and the new value , wrapping the result
* in a new Change .
* @ param fn the mapping function
* @ param < R > type returned by the mapping function
* @ return a new Change with mapped values */
public < R > Change < R > map ( Function < T , R > fn ) { } } | return new Change < > ( fn . apply ( getOldValue ( ) ) , fn . apply ( getNewValue ( ) ) ) ; |
public class Matrix3d { /** * Set this matrix to a rotation matrix which rotates the given radians about a given axis .
* The axis described by the three components needs to be a unit vector .
* When used with a right - handed coordinate system , the produced rotation will rotate a vector
* counter - clockwise around the rotation axis , when viewing along the negative axis direction towards the origin .
* When used with a left - handed coordinate system , the rotation is clockwise .
* The resulting matrix can be multiplied against another transformation
* matrix to obtain an additional rotation .
* In order to apply the rotation transformation to an existing transformation ,
* use { @ link # rotate ( double , double , double , double ) rotate ( ) } instead .
* Reference : < a href = " http : / / en . wikipedia . org / wiki / Rotation _ matrix # Rotation _ matrix _ from _ axis _ and _ angle " > http : / / en . wikipedia . org < / a >
* @ see # rotate ( double , double , double , double )
* @ param angle
* the angle in radians
* @ param x
* the x - component of the rotation axis
* @ param y
* the y - component of the rotation axis
* @ param z
* the z - component of the rotation axis
* @ return this */
public Matrix3d rotation ( double angle , double x , double y , double z ) { } } | double sin = Math . sin ( angle ) ; double cos = Math . cosFromSin ( sin , angle ) ; double C = 1.0 - cos ; double xy = x * y , xz = x * z , yz = y * z ; m00 = cos + x * x * C ; m10 = xy * C - z * sin ; m20 = xz * C + y * sin ; m01 = xy * C + z * sin ; m11 = cos + y * y * C ; m21 = yz * C - x * sin ; m02 = xz * C - y * sin ; m12 = yz * C + x * sin ; m22 = cos + z * z * C ; return this ; |
public class BlobServicesInner { /** * Gets the properties of a storage account ’ s Blob service , including properties for Storage Analytics and CORS ( Cross - Origin Resource Sharing ) rules .
* @ param resourceGroupName The name of the resource group within the user ' s subscription . The name is case insensitive .
* @ param accountName The name of the storage account within the specified resource group . Storage account names must be between 3 and 24 characters in length and use numbers and lower - case letters only .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the BlobServicePropertiesInner object */
public Observable < BlobServicePropertiesInner > getServicePropertiesAsync ( String resourceGroupName , String accountName ) { } } | return getServicePropertiesWithServiceResponseAsync ( resourceGroupName , accountName ) . map ( new Func1 < ServiceResponse < BlobServicePropertiesInner > , BlobServicePropertiesInner > ( ) { @ Override public BlobServicePropertiesInner call ( ServiceResponse < BlobServicePropertiesInner > response ) { return response . body ( ) ; } } ) ; |
public class Iterables { /** * Combines multiple iterables into a single iterable . The returned iterable
* has an iterator that traverses the elements of each iterable in
* { @ code inputs } . The input iterators are not polled until necessary .
* < p > The returned iterable ' s iterator supports { @ code remove ( ) } when the
* corresponding input iterator supports it . The methods of the returned
* iterable may throw { @ code NullPointerException } if any of the input
* iterators is null . */
public static < T > Iterable < T > concat ( final Iterable < ? extends Iterable < ? extends T > > inputs ) { } } | checkNotNull ( inputs ) ; return new FluentIterable < T > ( ) { @ Override public Iterator < T > iterator ( ) { return Iterators . concat ( iterators ( inputs ) ) ; } } ; |
public class MapFixture { /** * Stores boolean value in map .
* @ param value value to be passed .
* @ param name name to use this value for .
* @ param map map to store value in . */
public void setBooleanValueForIn ( boolean value , String name , Map < String , Object > map ) { } } | setValueForIn ( Boolean . valueOf ( value ) , name , map ) ; |
public class TextStructureLayerStored { @ Override public List < TextSpan > getSpans ( String type ) { } } | List < TextSpan > spans = new ArrayList < TextSpan > ( ) ; Map < Token , TextSpan > tokToSpan = connector . token2ItsTextSpans . get ( type ) ; if ( tokToSpan != null ) { spans . addAll ( tokToSpan . values ( ) ) ; } return spans ; |
public class LocaleUtils { /** * Determines whether a key matches any of the set filters .
* @ param key
* the property key
* @ param filters
* @ return true if the key matches any of the set filters . */
public static boolean matchesFilter ( String key , List < String > filters ) { } } | boolean rets = ( null == filters ) ; if ( ! rets ) { for ( Iterator < String > it = filters . iterator ( ) ; it . hasNext ( ) && ! rets ; ) rets = key . startsWith ( it . next ( ) ) ; } return rets ; |
public class FedoraBaseResource { /** * Get the FedoraResource for the resource at the external path
* @ param externalPath the external path
* @ return the fedora resource at the external path */
@ VisibleForTesting public FedoraResource getResourceFromPath ( final String externalPath ) { } } | final Resource resource = translator ( ) . toDomain ( externalPath ) ; final FedoraResource fedoraResource = translator ( ) . convert ( resource ) ; if ( fedoraResource instanceof Tombstone ) { final String resourceURI = TRAILING_SLASH_REGEX . matcher ( resource . getURI ( ) ) . replaceAll ( "" ) ; throw new TombstoneException ( fedoraResource , resourceURI + "/fcr:tombstone" ) ; } return fedoraResource ; |
public class FormatUtils { /** * Converts an integer to a string , prepended with a variable amount of ' 0'
* pad characters , and writes it to the given writer .
* < p > This method is optimized for converting small values to strings .
* @ param out receives integer converted to a string
* @ param value value to convert to a string
* @ param size minimum amount of digits to append */
public static void writePaddedInteger ( Writer out , long value , int size ) throws IOException { } } | int intValue = ( int ) value ; if ( intValue == value ) { writePaddedInteger ( out , intValue , size ) ; } else if ( size <= 19 ) { out . write ( Long . toString ( value ) ) ; } else { if ( value < 0 ) { out . write ( '-' ) ; if ( value != Long . MIN_VALUE ) { value = - value ; } else { for ( ; size > 19 ; size -- ) { out . write ( '0' ) ; } out . write ( "9223372036854775808" ) ; return ; } } int digits = ( int ) ( Math . log ( value ) / LOG_10 ) + 1 ; for ( ; size > digits ; size -- ) { out . write ( '0' ) ; } out . write ( Long . toString ( value ) ) ; } |
public class ListDevicesRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( ListDevicesRequest listDevicesRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( listDevicesRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( listDevicesRequest . getAccessToken ( ) , ACCESSTOKEN_BINDING ) ; protocolMarshaller . marshall ( listDevicesRequest . getLimit ( ) , LIMIT_BINDING ) ; protocolMarshaller . marshall ( listDevicesRequest . getPaginationToken ( ) , PAGINATIONTOKEN_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class Ix { /** * Emits a range of incrementing integer values , starting from { @ code start } and
* up to { @ code count } times .
* @ param start the starting value
* @ param count the number of integers to emit , non - negative
* @ return the new Ix instance
* @ throws IllegalArgumentException if count is negative
* @ since 1.0 */
public static Ix < Integer > range ( int start , int count ) { } } | if ( count == 0 ) { return empty ( ) ; } if ( count == 1 ) { return just ( start ) ; } if ( count < 0 ) { throw new IllegalArgumentException ( "count >= 0 required but it was " + count ) ; } return new IxRange ( start , count ) ; |
public class AbstractManagerFactoryBuilder { /** * Specify runtime codecs to register with Achilles
* < br / >
* < pre class = " code " > < code class = " java " >
* < strong > final Codec & lt ; MyBean , String & gt ; beanCodec = new . . . . / / Create your codec with initialization logic here < / strong >
* < strong > final Codec & lt ; MyEnum , String & gt ; enumCodec = new . . . . / / Create your codec with initialization logic here < / strong >
* final CodecSignature & lt ; MyBean , String & gt ; codecSignature1 = new CodecSignature ( MyBean . class , String . class ) ;
* final CodecSignature & lt ; MyBean , String & gt ; codecSignature2 = new CodecSignature ( MyEnum . class , String . class ) ;
* final Map & lt ; CodecSignature & lt ; ? , ? & gt ; , Codec & lt ; ? , ? & gt ; & gt ; runtimeCodecs = new HashMap & lt ; & gt ; ( ) ;
* runtimeCodecs . put ( codecSignature1 , beanCodec ) ;
* runtimeCodecs . put ( codecSignature2 , enumCodec ) ;
* ManagerFactory factory = ManagerFactoryBuilder
* . builder ( cluster )
* < strong > . withRuntimeCodecs ( runtimeCodecs ) < / strong >
* . build ( ) ;
* < / code > < / pre >
* < br / >
* < br / >
* < em > Remark : you can call this method as many time as there are runtime codecs to be registered < / em >
* @ param runtimeCodecs a map of codec signature and its corresponding codec
* @ return ManagerFactoryBuilder */
public T withRuntimeCodecs ( Map < CodecSignature < ? , ? > , Codec < ? , ? > > runtimeCodecs ) { } } | if ( ! configMap . containsKey ( RUNTIME_CODECS ) ) { configMap . put ( RUNTIME_CODECS , new HashMap < CodecSignature < ? , ? > , Codec < ? , ? > > ( ) ) ; } configMap . < Map < CodecSignature < ? , ? > , Codec < ? , ? > > > getTyped ( RUNTIME_CODECS ) . putAll ( runtimeCodecs ) ; return getThis ( ) ; |
public class ClassPathResource { /** * This implementation returns a description that includes the class path location . */
public String getDescription ( ) { } } | StringBuilder builder = new StringBuilder ( "class path resource [" ) ; if ( clazz != null ) { builder . append ( GrailsResourceUtils . classPackageAsResourcePath ( clazz ) ) ; builder . append ( '/' ) ; } builder . append ( path ) ; builder . append ( ']' ) ; return builder . toString ( ) ; |
public class IfOperator { /** * Execute IF operator . Evaluate given < code > expression < / code > and return evaluation result . Returned value acts as branch
* enabled flag .
* @ param element context element , unused ,
* @ param scope scope object ,
* @ param expression conditional expression ,
* @ param arguments optional arguments , not used .
* @ return true if < code > element < / code > and all its descendants should be included in processed document .
* @ throws TemplateException if content value is undefined . */
@ Override protected Object doExec ( Element element , Object scope , String expression , Object ... arguments ) throws TemplateException { } } | ConditionalExpression conditionalExpression = new ConditionalExpression ( content , scope , expression ) ; return conditionalExpression . value ( ) ; |
public class PearsonKernel { /** * Set the omega parameter .
* @ param omega Omega parameter . */
public void setOmega ( double omega ) { } } | this . omega = omega ; this . constant = 2 * Math . sqrt ( Math . pow ( 2 , ( 1 / omega ) ) - 1 ) / sigma ; |
public class ClassPath { /** * Load the class name
* @ param classPath
* the path of the class
* @ return the byte of the class
* @ throws IOException */
private byte [ ] loadClassBytes ( File classFile ) throws IOException { } } | int size = ( int ) classFile . length ( ) ; byte buff [ ] = new byte [ size ] ; FileInputStream fis = new FileInputStream ( classFile ) ; DataInputStream dis = null ; try { dis = new DataInputStream ( fis ) ; dis . readFully ( buff ) ; } finally { if ( dis != null ) dis . close ( ) ; } return buff ; |
public class TypeQualifierApplications { /** * Get the collection of resolved TypeQualifierAnnotations for a given
* parameter , taking into account annotations applied to outer scopes ( e . g . ,
* enclosing classes and packages . )
* @ param o
* a method
* @ param parameter
* a parameter ( 0 = = first parameter )
* @ return Collection of resolved TypeQualifierAnnotations */
private static Collection < TypeQualifierAnnotation > getApplicableScopedApplications ( XMethod o , int parameter ) { } } | Set < TypeQualifierAnnotation > result = new HashSet < > ( ) ; ElementType e = ElementType . PARAMETER ; getApplicableScopedApplications ( result , o , e ) ; getDirectApplications ( result , o , parameter ) ; return result ; |
public class StateResolver { /** * Configure the state priorities
* @ param priorities
* array of String . eg , STATE , priorityValue */
public void configurePriorities ( final String [ ] priorities ) { } } | // Set the non defined state in the property at 0 priority
// Enumeration of existing state
int priority ; // Get the custom priority
for ( final String state : priorities ) { // count the token separated by " , "
final StringTokenizer tmpPriorityTokens = new StringTokenizer ( state . trim ( ) , "," ) ; if ( tmpPriorityTokens . countTokens ( ) == 2 ) { // To avoid the the pb of case
final String tmpState = tmpPriorityTokens . nextToken ( ) . trim ( ) . toUpperCase ( ) ; // If the custom state exist
if ( StateUtilities . isStateExist ( tmpState ) ) { try { priority = Integer . valueOf ( tmpPriorityTokens . nextToken ( ) . trim ( ) ) ; } catch ( final NumberFormatException e ) { priority = 0 ; } putStatePriority ( StateUtilities . getStateForName ( tmpState ) , priority ) ; } } } |
public class PluginGroup { /** * Returns the first { @ link Plugin } of the specified { @ code clazz } as wrapped by an { @ link Optional } . */
< T extends Plugin > Optional < T > findFirstPlugin ( Class < T > clazz ) { } } | requireNonNull ( clazz , "clazz" ) ; return plugins . stream ( ) . filter ( clazz :: isInstance ) . map ( clazz :: cast ) . findFirst ( ) ; |
public class OffsetRange { /** * Provides an { @ link Ordering } of { @ link OffsetRange } s by their end position . Note that this is
* not a total ordering because { @ link OffsetRange } s with the same end position but different
* start positions will compare as equal .
* Consider producing a compound ordering with { @ link # byStartOrdering ( ) } using { @ link
* Ordering # compound ( Comparator ) } or using one of the predefined total orderings . */
public static < T extends Offset < T > > Ordering < OffsetRange < T > > byEndOrdering ( ) { } } | return Ordering . < T > natural ( ) . onResultOf ( OffsetRange . < T > toEndInclusiveFunction ( ) ) ; |
public class SSLDiscriminatorState { /** * Update this state object with current information . This is called when a
* YES response comes from the discriminator . The position and limit must be
* saved here so the ready method can adjust them right away .
* @ param context
* @ param engine
* @ param result
* @ param decNetBuf
* @ param position
* @ param limit */
public void updateState ( SSLContext context , SSLEngine engine , SSLEngineResult result , WsByteBuffer decNetBuf , int position , int limit ) { } } | this . sslContext = context ; this . sslEngine = engine ; this . sslEngineResult = result ; this . decryptedNetBuffer = decNetBuf ; this . netBufferPosition = position ; this . netBufferLimit = limit ; |
public class AvroFlattener { /** * Flatten Record schema
* @ param schema Record Schema to flatten
* @ param shouldPopulateLineage If lineage information should be tagged in the field , this is true when we are
* un - nesting fields
* @ param flattenComplexTypes Flatten complex types recursively other than Record and Option
* @ return Flattened Record Schema */
private Schema flattenRecord ( Schema schema , boolean shouldPopulateLineage , boolean flattenComplexTypes ) { } } | Preconditions . checkNotNull ( schema ) ; Preconditions . checkArgument ( Schema . Type . RECORD . equals ( schema . getType ( ) ) ) ; Schema flattenedSchema ; List < Schema . Field > flattenedFields = new ArrayList < > ( ) ; if ( schema . getFields ( ) . size ( ) > 0 ) { for ( Schema . Field oldField : schema . getFields ( ) ) { List < Schema . Field > newFields = flattenField ( oldField , ImmutableList . < String > of ( ) , shouldPopulateLineage , flattenComplexTypes , Optional . < Schema > absent ( ) ) ; if ( null != newFields && newFields . size ( ) > 0 ) { flattenedFields . addAll ( newFields ) ; } } } flattenedSchema = Schema . createRecord ( schema . getName ( ) , schema . getDoc ( ) , schema . getNamespace ( ) , schema . isError ( ) ) ; flattenedSchema . setFields ( flattenedFields ) ; return flattenedSchema ; |
public class FileUtils { /** * Crea el directorio y devuelve el objeto File asociado , devuelve null si no se ha podido crear
* @ param root
* @ param relativePathToCreate
* @ return */
public static File createPathAndGetFile ( File root , String relativePathToCreate ) { } } | File target = new File ( root , relativePathToCreate ) ; if ( ! target . exists ( ) ) { if ( target . mkdirs ( ) ) { return target ; } else { log . warn ( "No se ha podido crear el directorio:'" + target . getAbsolutePath ( ) + "'" ) ; return null ; } } else { return target ; } |
public class RuleClassifierNBayes { /** * The following three functions are used for the prediction */
protected double [ ] firstHitNB ( Instance inst ) { } } | int countFired = 0 ; boolean fired = false ; double [ ] votes = new double [ this . numClass ] ; for ( int j = 0 ; j < this . ruleSet . size ( ) ; j ++ ) { if ( this . ruleSet . get ( j ) . ruleEvaluate ( inst ) == true ) { countFired = countFired + 1 ; if ( this . ruleSet . get ( j ) . obserClassDistrib . sumOfValues ( ) >= this . nbThresholdOption . getValue ( ) ) { votes = NaiveBayes . doNaiveBayesPredictionLog ( inst , this . ruleSet . get ( j ) . obserClassDistrib , this . ruleSet . get ( j ) . observers , this . ruleSet . get ( j ) . observersGauss ) ; votes = exponential ( votes ) ; votes = normalize ( votes ) ; } else { for ( int z = 0 ; z < this . numClass ; z ++ ) { votes [ z ] = this . ruleSet . get ( j ) . obserClassDistrib . getValue ( z ) / this . ruleSet . get ( j ) . obserClassDistrib . sumOfValues ( ) ; } } break ; } } if ( countFired > 0 ) { fired = true ; } else { fired = false ; } if ( fired == false ) { if ( super . getWeightSeen ( ) >= this . nbThresholdOption . getValue ( ) ) { votes = NaiveBayes . doNaiveBayesPredictionLog ( inst , this . observedClassDistribution , this . attributeObservers , this . attributeObserversGauss ) ; votes = exponential ( votes ) ; votes = normalize ( votes ) ; } else { votes = super . oberversDistribProb ( inst , this . observedClassDistribution ) ; } } return votes ; |
public class X509CertImpl { /** * Gets the signature algorithm OID string from the certificate .
* For example , the string " 1.2.840.10040.4.3"
* @ return the signature algorithm oid string . */
public String getSigAlgOID ( ) { } } | if ( algId == null ) return null ; ObjectIdentifier oid = algId . getOID ( ) ; return ( oid . toString ( ) ) ; |
public class TileWriter { /** * Write the tile table tile image set within the GeoPackage file to the
* provided directory
* @ param geoPackageFile
* GeoPackage file
* @ param tileTable
* tile table
* @ param directory
* output directory
* @ param imageFormat
* image format
* @ param width
* optional image width
* @ param height
* optional image height
* @ param tileType
* tile type
* @ param rawImage
* use raw image flag
* @ throws IOException
* upon failure
* @ since 1.2.0 */
public static void writeTiles ( File geoPackageFile , String tileTable , File directory , String imageFormat , Integer width , Integer height , TileFormatType tileType , boolean rawImage ) throws IOException { } } | GeoPackage geoPackage = GeoPackageManager . open ( geoPackageFile ) ; try { writeTiles ( geoPackage , tileTable , directory , imageFormat , width , height , tileType , rawImage ) ; } finally { geoPackage . close ( ) ; } |
public class EvolutionMonitor { /** * { @ inheritDoc } */
public void populationUpdate ( PopulationData < ? extends T > populationData ) { } } | for ( IslandEvolutionObserver < ? super T > view : views ) { view . populationUpdate ( populationData ) ; } |
public class WarUtils { /** * < p > Adds a child xml element to a parent element relative to other elements with a tagname . < / p >
* < p > If first is true then the child is added before any elements with a tagname , the opposite happens when first is false . < / p >
* @ param parent The parent xml element .
* @ param child The child xml element to add .
* @ param tagname The tagname to be relative to .
* @ param first A flag that describes the relative relationship between the child element and its siblings named by tagname . */
public static void addRelativeTo ( Element parent , Element child , String tagname , boolean first ) { } } | NodeList nodes = parent . getChildNodes ( ) ; if ( nodes . getLength ( ) > 0 ) { Node relativeEl = null ; boolean found = false ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { Node node = nodes . item ( i ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { Element el = ( Element ) node ; if ( el . getTagName ( ) . equals ( tagname ) ) { if ( relativeEl == null || ! first ) { relativeEl = el ; } else if ( first && ! found ) { relativeEl = el ; } found = true ; } } } if ( relativeEl != null && ! first ) { relativeEl = relativeEl . getNextSibling ( ) ; } if ( relativeEl == null && first ) { relativeEl = nodes . item ( 0 ) ; } else { parent . appendChild ( child ) ; } if ( relativeEl != null ) { parent . insertBefore ( child , relativeEl ) ; } } else { // There are no elements in the parent node so lets just append child .
parent . appendChild ( child ) ; } |
public class CommerceCurrencyLocalServiceBaseImpl { /** * Returns a range of all the commerce currencies .
* Useful when paginating results . Returns a maximum of < code > end - start < / code > instances . < code > start < / code > and < code > end < / code > are not primary keys , they are indexes in the result set . Thus , < code > 0 < / code > refers to the first result in the set . Setting both < code > start < / code > and < code > end < / code > to { @ link com . liferay . portal . kernel . dao . orm . QueryUtil # ALL _ POS } will return the full result set . If < code > orderByComparator < / code > is specified , then the query will include the given ORDER BY logic . If < code > orderByComparator < / code > is absent and pagination is required ( < code > start < / code > and < code > end < / code > are not { @ link com . liferay . portal . kernel . dao . orm . QueryUtil # ALL _ POS } ) , then the query will include the default ORDER BY logic from { @ link com . liferay . commerce . currency . model . impl . CommerceCurrencyModelImpl } . If both < code > orderByComparator < / code > and pagination are absent , for performance reasons , the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order .
* @ param start the lower bound of the range of commerce currencies
* @ param end the upper bound of the range of commerce currencies ( not inclusive )
* @ return the range of commerce currencies */
@ Override public List < CommerceCurrency > getCommerceCurrencies ( int start , int end ) { } } | return commerceCurrencyPersistence . findAll ( start , end ) ; |
public class ParticleGame { /** * Add an emitter to the particle system held here
* @ param emitter
* The emitter to add */
public void addEmitter ( ConfigurableEmitter emitter ) { } } | emitters . add ( emitter ) ; if ( system == null ) { waiting . add ( emitter ) ; } else { system . addEmitter ( emitter ) ; } |
public class RamlTypeValidations { /** * Adds validation annotations to the supplied method
* @ param getter
* getter method to add validation annotation to
* @ param addValidAnnotation
* if { @ code @ Valid } annotation dhould be added */
public void annotateFieldJSR303 ( JMethod getter , boolean addValidAnnotation ) { } } | if ( isRequired ( ) ) { getter . annotate ( NotNull . class ) ; } if ( StringUtils . hasText ( getPattern ( ) ) ) { JAnnotationUse annotation = getter . annotate ( Pattern . class ) ; annotation . param ( "regexp" , getPattern ( ) ) ; } if ( getMinLength ( ) != null || getMaxLength ( ) != null ) { JAnnotationUse annotation = getter . annotate ( Size . class ) ; if ( getMinLength ( ) != null ) { annotation . param ( "min" , getMinLength ( ) ) ; } if ( getMaxLength ( ) != null ) { annotation . param ( "max" , getMaxLength ( ) ) ; } } if ( addValidAnnotation ) { getter . annotate ( Valid . class ) ; } if ( minimum != null ) { JAnnotationUse annotation = getter . annotate ( DecimalMin . class ) ; annotation . param ( "value" , String . valueOf ( minimum ) ) ; } if ( maximum != null ) { JAnnotationUse annotation = getter . annotate ( DecimalMax . class ) ; annotation . param ( "value" , String . valueOf ( maximum ) ) ; } |
public class DeveloperUtilitiesServiceProgrammatic { @ Programmatic public Blob downloadLayouts ( ) { } } | final LayoutJsonExporter exporter = new LayoutJsonExporter ( ) ; final Collection < ObjectSpecification > allSpecs = specificationLoader . allSpecifications ( ) ; final Collection < ObjectSpecification > domainObjectSpecs = Collections2 . filter ( allSpecs , new Predicate < ObjectSpecification > ( ) { @ Override public boolean apply ( final ObjectSpecification input ) { return ! input . isAbstract ( ) && ! input . isService ( ) && ! input . isValue ( ) && ! input . isParentedOrFreeCollection ( ) ; } } ) ; try { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; final ZipOutputStream zos = new ZipOutputStream ( baos ) ; final OutputStreamWriter writer = new OutputStreamWriter ( zos ) ; for ( final ObjectSpecification objectSpec : domainObjectSpecs ) { zos . putNextEntry ( new ZipEntry ( zipEntryNameFor ( objectSpec ) ) ) ; writer . write ( exporter . asJson ( objectSpec ) ) ; writer . flush ( ) ; zos . closeEntry ( ) ; } writer . close ( ) ; return new Blob ( "layouts.zip" , mimeTypeApplicationZip , baos . toByteArray ( ) ) ; } catch ( final IOException ex ) { throw new FatalException ( "Unable to create zip of layouts" , ex ) ; } |
public class Handshake { /** * Create the { @ code ExtensionFunction } list associated with the negotiated extensions defined in the exchange ' s response .
* @ param exchange the exchange used to retrieve negotiated extensions
* @ return a list of { @ code ExtensionFunction } with the implementation of the extensions */
protected final List < ExtensionFunction > initExtensions ( final WebSocketHttpExchange exchange ) { } } | String extHeader = exchange . getResponseHeaders ( ) . get ( Headers . SEC_WEB_SOCKET_EXTENSIONS_STRING ) != null ? exchange . getResponseHeaders ( ) . get ( Headers . SEC_WEB_SOCKET_EXTENSIONS_STRING ) . get ( 0 ) : null ; List < ExtensionFunction > negotiated = new ArrayList < > ( ) ; if ( extHeader != null ) { List < WebSocketExtension > extensions = WebSocketExtension . parse ( extHeader ) ; if ( extensions != null && ! extensions . isEmpty ( ) ) { for ( WebSocketExtension ext : extensions ) { for ( ExtensionHandshake extHandshake : availableExtensions ) { if ( extHandshake . getName ( ) . equals ( ext . getName ( ) ) ) { negotiated . add ( extHandshake . create ( ) ) ; } } } } } return negotiated ; |
public class AdvancedRecyclerArrayAdapter { /** * Inserts the specified object at the specified index in the array .
* @ param object The object to insert into the array .
* @ param index The index at which the object must be inserted . */
public void insert ( @ NonNull T object , int index ) { } } | synchronized ( mLock ) { mObjects . add ( index , object ) ; notifyItemInserted ( index ) ; } |
public class CharacterStringBinding { /** * { @ inheritDoc } */
@ Override public Character unmarshal ( String object ) { } } | if ( object . length ( ) == 1 ) { return Character . valueOf ( object . charAt ( 0 ) ) ; } else { throw new IllegalArgumentException ( "Only single character String can be unmarshalled to a Character" ) ; } |
public class CmsJspActionElement { /** * Generates an initialized instance of { @ link CmsMessages } for
* convenient access to localized resource bundles . < p >
* @ param bundleName the name of the ResourceBundle to use
* @ param language language identifier for the locale of the bundle
* @ param defaultLanguage default for the language , will be used
* if language is null or empty String " " , and defaultLanguage is not null
* @ return CmsMessages a message bundle initialized with the provided values */
public CmsMessages getMessages ( String bundleName , String language , String defaultLanguage ) { } } | return getMessages ( bundleName , language , "" , "" , defaultLanguage ) ; |
public class LinkPost { /** * Get the detail for this post ( and the base detail )
* @ return the details */
@ Override public Map < String , Object > detail ( ) { } } | final Map < String , Object > detail = super . detail ( ) ; detail . put ( "title" , title ) ; detail . put ( "url" , url ) ; detail . put ( "description" , description ) ; return detail ; |
public class TraceNLSResolver { /** * Get a reference to the specified ResourceBundle and look up the specified
* key . If the key has no value , use the defaultString instead . If so
* indicated , format the text using the specified arguments . Such formatting
* is done using the java . text . MessageFormat class . Substitution parameters
* are handled according to the rules of that class . Most notably , that
* class does special formatting for native java Date and Number objects .
* If an error occurs in obtaining a reference to the ResourceBundle , or in
* looking up the key , this method will take appropriate actions . This may
* include returning a non - null error message .
* @ param aClass
* the class representing the caller of the method - - used for
* loading the right resource bundle
* @ param bundle
* the ResourceBundle to use for lookups . Null is tolerated . If
* null is passed , the resource bundle will be looked up from
* bundleName . If not null , bundleName must match .
* @ param bundleName
* the fully qualified name of the ResourceBundle . Must not be
* null .
* @ param key
* the key to use in the ResourceBundle lookup . Must not be null .
* @ param args
* substitution parameters that are inserted into the message
* text . Null is tolerated
* @ param defaultString
* text to use if the localized text cannot be found . Must not be
* null .
* @ param locale
* the Locale object to use when looking up the ResourceBundle .
* If null is passed , the default Locale will be used .
* @ param quiet
* indicates whether or not errors will be logged when
* encountered , and must be used in conjunction with com . ibm .
* @ return a non - null message that is localized and formatted as
* appropriate . */
public String getMessage ( Class < ? > aClass , ResourceBundle bundle , String bundleName , String key , Object [ ] args , String defaultString , boolean format , Locale locale , boolean quiet ) { } } | String returnValue = null ; if ( locale == null ) locale = Locale . getDefault ( ) ; try { // Retrieve a reference to the ResourceBundle and do the lookup on
// the key .
if ( bundle == null ) bundle = getResourceBundle ( aClass , bundleName , locale ) ; returnValue = bundle . getString ( key ) ; // The lookup may have returned empty string if key was found , but
// there is no value .
if ( returnValue . equals ( "" ) ) { // Log this occurrence , it needs to be fixed .
if ( ! quiet ) logEvent ( svMalformedMessage , new Object [ ] { key , bundleName } ) ; // Determine which value to continue with . Default text takes
// priority over key .
if ( defaultString == null ) returnValue = key ; else returnValue = defaultString ; } // We have a non - null returnValue , either from the lookup or we are
// using the default text .
if ( format == false ) return returnValue ; else return getFormattedMessage ( returnValue , args ) ; } catch ( RuntimeException re ) { // sort our error conditions here . Order dependencies in following
// logic
if ( bundleName == null ) { // Caller passed a null bundleName argument . Log a message to
// let the developer know there is a bug in his code . Proceed .
// Need to determine what String to use . For this condition ,
// defaultText takes priority over key . One must be non - null .
if ( ( key == null ) && ( defaultString == null ) ) { if ( ! quiet ) logEvent ( svNullBundleName , new Object [ ] { nullKey } ) ; return MessageFormat . format ( svNullBundleName , new Object [ ] { nullKey } ) ; } if ( defaultString == null ) { if ( ! quiet ) logEvent ( svNullBundleName , new Object [ ] { defaultString } ) ; returnValue = key ; } else { if ( ! quiet ) logEvent ( svNullBundleName , new Object [ ] { key } ) ; returnValue = defaultString ; } if ( format == false ) return returnValue ; else return getFormattedMessage ( returnValue , args ) ; } // end null resourceBundleName
if ( bundle == null ) { // ResourceBundle lookup failed . Log a message so the problem
// can be fixed .
if ( ! quiet ) logEvent ( svBundleNotLoaded , new Object [ ] { bundleName } ) ; // Proceed . Need to determine what String to use . For this
// condition , defaultText takes priority over key . One must be
// non - null .
if ( ( key == null ) && ( defaultString == null ) ) return MessageFormat . format ( svBundleNotLoaded , new Object [ ] { bundleName } ) ; if ( defaultString == null ) returnValue = key ; else returnValue = defaultString ; if ( format == false ) return returnValue ; else return getFormattedMessage ( returnValue , args ) ; } // end null ResourceBundle
if ( key == null ) { // ResourceBundle was loaded , caller passed a null key . Log a
// message so it can be fixed .
if ( ! quiet ) logEvent ( svNullKeyMessage , new Object [ ] { bundleName } ) ; // Proceed . For this condition , defaultText must be non - null .
if ( defaultString == null ) return MessageFormat . format ( svNullKeyMessage , new Object [ ] { bundleName } ) ; else returnValue = defaultString ; if ( format == false ) return returnValue ; else return getFormattedMessage ( returnValue , args ) ; } // end null key
// Must be a keyNotFound in Bundle condition .
if ( ! quiet ) logEvent ( svMalformedMessage , new Object [ ] { key , bundleName } ) ; // Proceed . For this condition , key cannot be null .
if ( defaultString == null ) returnValue = key ; else returnValue = defaultString ; if ( format == false ) return returnValue ; else return getFormattedMessage ( returnValue , args ) ; } |
public class BaseDestinationHandler { /** * ( non - Javadoc )
* @ see com . ibm . ws . sib . processor . impl . interfaces . DestinationHandler # isSystem ( ) */
@ Override public boolean isSystem ( ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) { SibTr . entry ( tc , "isSystem" ) ; SibTr . exit ( tc , "isSystem" , Boolean . valueOf ( _isSystem ) ) ; } return _isSystem ; |
public class ApplicationRealm { /** * acquisition , so it is negligible if this executes a few times instead of just once . */
protected final Application ensureApplicationReference ( ) { } } | if ( this . application == null ) { assertState ( ) ; Application tmpApp = applicationResolver . getApplication ( client , applicationRestUrl ) ; if ( tmpApp == null ) { throw new IllegalStateException ( "ApplicationResolver returned 'null' Application, this is likely a configuration error." ) ; } this . application = tmpApp ; } return this . application ; |
public class StringUtil { /** * functional compare for two strings as ignore - case text */
public static boolean equalsText ( String s1 , String s2 ) { } } | if ( s1 == null ) { if ( s2 != null ) { return false ; } } else { if ( s2 == null ) { return false ; } } if ( ( s1 != null ) && ( s2 != null ) ) { s1 = s1 . replaceAll ( "\\s" , "" ) . toLowerCase ( ) ; s2 = s2 . replaceAll ( "\\s" , "" ) . toLowerCase ( ) ; if ( ! s1 . equals ( s2 ) ) { return false ; } } return true ; |
public class CountedCompleter { /** * Equivalent to { @ code getRoot ( ) . quietlyComplete ( ) } . */
public final void quietlyCompleteRoot ( ) { } } | for ( CountedCompleter < ? > a = this , p ; ; ) { if ( ( p = a . completer ) == null ) { a . quietlyComplete ( ) ; return ; } a = p ; } |
public class HadoopUtils { /** * A thread safe variation of { @ link # renamePath ( FileSystem , Path , Path ) } which can be used in
* multi - threaded / multi - mapper environment . The rename operation always happens at file level hence directories are
* not overwritten under the ' to ' path .
* If the contents of destination ' to ' path is not expected to be modified concurrently , use
* { @ link # renamePath ( FileSystem , Path , Path ) } which is faster and more optimized
* < b > NOTE : This does not seem to be working for all { @ link FileSystem } implementations . Use
* { @ link # renameRecursively ( FileSystem , Path , Path ) } < / b >
* @ param fileSystem on which the data needs to be moved
* @ param from path of the data to be moved
* @ param to path of the data to be moved */
public static void safeRenameRecursively ( FileSystem fileSystem , Path from , Path to ) throws IOException { } } | for ( FileStatus fromFile : FileListUtils . listFilesRecursively ( fileSystem , from ) ) { Path relativeFilePath = new Path ( StringUtils . substringAfter ( fromFile . getPath ( ) . toString ( ) , from . toString ( ) + Path . SEPARATOR ) ) ; Path toFilePath = new Path ( to , relativeFilePath ) ; if ( ! fileSystem . exists ( toFilePath ) ) { boolean renamed = false ; // underlying file open can fail with file not found error due to some race condition
// when the parent directory is created in another thread , so retry a few times
for ( int i = 0 ; ! renamed && i < MAX_RENAME_TRIES ; i ++ ) { try { renamed = fileSystem . rename ( fromFile . getPath ( ) , toFilePath ) ; break ; } catch ( FileNotFoundException e ) { if ( i + 1 >= MAX_RENAME_TRIES ) { throw e ; } } } if ( ! renamed ) { throw new IOException ( String . format ( "Failed to rename %s to %s." , fromFile . getPath ( ) , toFilePath ) ) ; } log . info ( String . format ( "Renamed %s to %s" , fromFile . getPath ( ) , toFilePath ) ) ; } else { log . info ( String . format ( "File already exists %s. Will not rewrite" , toFilePath ) ) ; } } |
public class JcrVersionManager { /** * Checks in the given node , creating ( and returning ) a new { @ link Version } .
* @ param node the node to be checked in
* @ return the { @ link Version } object created as a result of this checkin
* @ throws RepositoryException if an error occurs during the checkin . See { @ link javax . jcr . Node # checkin ( ) } for a full
* description of the possible error conditions .
* @ see # checkin ( String )
* @ see AbstractJcrNode # checkin ( ) */
JcrVersionNode checkin ( AbstractJcrNode node ) throws RepositoryException { } } | checkVersionable ( node ) ; if ( node . isNew ( ) || node . isModified ( ) ) { throw new InvalidItemStateException ( JcrI18n . noPendingChangesAllowed . text ( ) ) ; } // Check this separately since it throws a different type of exception
if ( node . isLocked ( ) && ! node . holdsLock ( ) ) { throw new LockException ( JcrI18n . lockTokenNotHeld . text ( node . getPath ( ) ) ) ; } if ( node . getProperty ( JcrLexicon . MERGE_FAILED ) != null ) { throw new VersionException ( JcrI18n . pendingMergeConflicts . text ( node . getPath ( ) ) ) ; } javax . jcr . Property isCheckedOut = node . getProperty ( JcrLexicon . IS_CHECKED_OUT ) ; if ( ! isCheckedOut . getBoolean ( ) ) { return node . getBaseVersion ( ) ; } // Collect some of the information about the node that we ' ll need . . .
SessionCache cache = cache ( ) ; NodeKey versionedKey = node . key ( ) ; Path versionHistoryPath = versionHistoryPathFor ( versionedKey ) ; CachedNode cachedNode = node . node ( ) ; DateTime now = session ( ) . dateFactory ( ) . create ( ) ; // Create the system content that we ' ll use to update the system branch . . .
SessionCache systemSession = session . createSystemCache ( false ) ; SystemContent systemContent = new SystemContent ( systemSession ) ; MutableCachedNode version = null ; try { // Create a new version in the history for this node ; this initializes the version history if it is missing . . .
List < Property > versionableProps = new ArrayList < Property > ( ) ; addVersionedPropertiesFor ( node , false , versionableProps ) ; AtomicReference < MutableCachedNode > frozen = new AtomicReference < MutableCachedNode > ( ) ; version = systemContent . recordNewVersion ( cachedNode , cache , versionHistoryPath , null , versionableProps , now , frozen ) ; NodeKey historyKey = version . getParentKey ( systemSession ) ; // Update the node ' s ' mix : versionable ' properties , using a new session . . .
SessionCache versionSession = session . spawnSessionCache ( false ) ; MutableCachedNode versionableNode = versionSession . mutable ( versionedKey ) ; PropertyFactory props = propertyFactory ( ) ; ReferenceFactory refFactory = session . referenceFactory ( ) ; Reference historyRef = refFactory . create ( historyKey , true ) ; Reference baseVersionRef = refFactory . create ( version . getKey ( ) , true ) ; versionableNode . setProperty ( versionSession , props . create ( JcrLexicon . VERSION_HISTORY , historyRef ) ) ; versionableNode . setProperty ( versionSession , props . create ( JcrLexicon . BASE_VERSION , baseVersionRef ) ) ; versionableNode . setProperty ( versionSession , props . create ( JcrLexicon . IS_CHECKED_OUT , Boolean . FALSE ) ) ; // The ' jcr : predecessors ' set to an empty array , per Section 15.2 in JSR - 283
versionableNode . setProperty ( versionSession , props . create ( JcrLexicon . PREDECESSORS , new Object [ ] { } ) ) ; // Now process the children of the versionable node , and add them under the frozen node . . .
MutableCachedNode frozenNode = frozen . get ( ) ; for ( ChildReference childRef : versionableNode . getChildReferences ( versionSession ) ) { AbstractJcrNode child = session . node ( childRef . getKey ( ) , null , versionedKey ) ; versionNodeAt ( child , childRef . getName ( ) , frozenNode , false , versionSession , systemSession ) ; } // Now save all of the changes .
// the system session must be saved first so that its nodes are cleared first from the shared ws cache
// this is required because there are references from the other session pointing towards the system session
systemSession . save ( versionSession , null ) ; } finally { // TODO : Versioning : may want to catch this block and retry , if the new version name couldn ' t be created
} // return the version node from the system cache , not this session ' s cache because this session is asynchronously
// notified of system ws changes and may not always get the latest data immediately
return ( JcrVersionNode ) session . node ( version , systemSession , Type . VERSION , null ) ; |
public class MOEADUtils { /** * Quick sort procedure ( ascending order )
* @ param array
* @ param idx
* @ param from
* @ param to */
public static void quickSort ( double [ ] array , int [ ] idx , int from , int to ) { } } | if ( from < to ) { double temp = array [ to ] ; int tempIdx = idx [ to ] ; int i = from - 1 ; for ( int j = from ; j < to ; j ++ ) { if ( array [ j ] <= temp ) { i ++ ; double tempValue = array [ j ] ; array [ j ] = array [ i ] ; array [ i ] = tempValue ; int tempIndex = idx [ j ] ; idx [ j ] = idx [ i ] ; idx [ i ] = tempIndex ; } } array [ to ] = array [ i + 1 ] ; array [ i + 1 ] = temp ; idx [ to ] = idx [ i + 1 ] ; idx [ i + 1 ] = tempIdx ; quickSort ( array , idx , from , i ) ; quickSort ( array , idx , i + 1 , to ) ; } |
public class Searches { /** * Searches the last matching element returning it .
* @ param < E > the element type parameter
* @ param array the array to be searched
* @ param predicate the predicate to be applied to each element
* @ throws IllegalArgumentException if no element matches
* @ return the last element found */
public static < E > E findLast ( E [ ] array , Predicate < E > predicate ) { } } | final Iterator < E > filtered = new FilteringIterator < E > ( new ArrayIterator < E > ( array ) , predicate ) ; return new LastElement < E > ( ) . apply ( filtered ) ; |
public class RTMPProtocolEncoder { /** * { @ inheritDoc } */
public IoBuffer encodeChunkSize ( ChunkSize chunkSize ) { } } | final IoBuffer out = IoBuffer . allocate ( 4 ) ; out . putInt ( chunkSize . getSize ( ) ) ; return out ; |
public class PrcAccSettingsSave { /** * < p > Process entity request . < / p >
* @ param pAddParam 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 AccSettings process ( final Map < String , Object > pAddParam , final AccSettings pEntity , final IRequestData pRequestData ) throws Exception { } } | srvAccSettings . saveAccSettings ( pAddParam , pEntity ) ; return pEntity ; |
public class Favorites { /** * Add an item as a favorite for a user
* Fires { @ link FavoriteListener # fireOnAddFavourite ( Item , User ) }
* @ param user to add the favorite to
* @ param item to favorite
* @ throws FavoriteException */
public static void addFavorite ( @ Nonnull User user , @ Nonnull Item item ) throws FavoriteException { } } | try { if ( ! isFavorite ( user , item ) ) { FavoriteUserProperty property = getProperty ( user ) ; property . addFavorite ( item . getFullName ( ) ) ; FavoriteListener . fireOnAddFavourite ( item , user ) ; } else { throw new FavoriteException ( "Favourite is already set for User: <" + user . getFullName ( ) + "> Item: <" + item . getFullName ( ) + ">" ) ; } } catch ( IOException e ) { throw new FavoriteException ( "Could not add Favorite. User: <" + user . getFullName ( ) + "> Item: <" + item . getFullName ( ) + ">" , e ) ; } |
public class ResourceManager { /** * Registers the events for the ResourceBuilder
* @ param resourceBuilder an instance of ResourceBuilder */
private void registerEventsForResourceBuilder ( ResourceBuilderModel resourceBuilder ) { } } | List < ? extends EventModel < ? > > events = resourceBuilder . announceEvents ( ) ; if ( events == null ) return ; events . stream ( ) . filter ( event -> event . getAllInformations ( ) != null ) . flatMap ( event -> event . getAllInformations ( ) . stream ( ) ) . map ( this :: getRegisteredListForEvent ) . forEach ( list -> list . add ( resourceBuilder ) ) ; |
public class JournalRecoveryLog { /** * Concrete sub - classes should call this method from their constructor , or
* as soon as the log is ready for writing . */
public void logHeaderInfo ( Map < String , String > parameters ) { } } | StringBuffer buffer = new StringBuffer ( "Recovery parameters:" ) ; for ( Iterator < String > keys = parameters . keySet ( ) . iterator ( ) ; keys . hasNext ( ) ; ) { Object key = keys . next ( ) ; Object value = parameters . get ( key ) ; buffer . append ( "\n " ) . append ( key ) . append ( "=" ) . append ( value ) ; } log ( buffer . toString ( ) ) ; |
public class MessageEndpointBase { /** * Called after the pool discards the object . This gives the
* object an opportunity to perform any required clean up . */
public static void discard ( MessageEndpointBase proxy ) { } } | // Ensure we are no longer holding any object references .
proxy . ivMDB = null ; proxy . ivMessageEndpointFactory = null ; proxy . ivMethod = null ; proxy . ivXAResource = null ; proxy . ivRecoverableXAResource = false ; proxy . container = null ; proxy . ivEJSDeployedSupport = null ; proxy . ivTransactionManager = null ; proxy . ivThread = null ; |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link SoftwareAgent } { @ code > } } */
@ XmlElementDecl ( namespace = PROV_NS , name = "softwareAgent" ) public JAXBElement < SoftwareAgent > createSoftwareAgent ( SoftwareAgent value ) { } } | return new JAXBElement < SoftwareAgent > ( _SoftwareAgent_QNAME , SoftwareAgent . class , null , value ) ; |
public class JtsBinaryParser { /** * Parse data from the given { @ link org . postgis . binary . ValueGetter } into a JTS
* { @ link org . locationtech . jts . geom . Geometry } with the given SRID .
* @ param data { @ link org . postgis . binary . ValueGetter } to parse .
* @ param srid SRID to give to the parsed geometry ( different of the inherited SRID ) .
* @ param inheritSrid Make the new { @ link org . locationtech . jts . geom . Geometry } inherit its SRID if set to true ,
* otherwise use the parameter given SRID .
* @ return Parsed JTS { @ link org . locationtech . jts . geom . Geometry } with SRID . */
protected Geometry parseGeometry ( ValueGetter data , int srid , boolean inheritSrid ) { } } | byte endian = data . getByte ( ) ; if ( endian != data . endian ) { throw new IllegalArgumentException ( "Endian inconsistency!" ) ; } else { int typeword = data . getInt ( ) ; int realtype = typeword & 536870911 ; boolean haveZ = ( typeword & - 2147483648 ) != 0 ; boolean haveM = ( typeword & 1073741824 ) != 0 ; boolean haveS = ( typeword & 536870912 ) != 0 ; if ( haveS ) { int newsrid = org . postgis . Geometry . parseSRID ( data . getInt ( ) ) ; if ( inheritSrid && newsrid != srid ) { throw new IllegalArgumentException ( "Inconsistent srids in complex geometry: " + srid + ", " + newsrid ) ; } srid = newsrid ; } else if ( ! inheritSrid ) { srid = 0 ; } Geometry result ; switch ( realtype ) { case 1 : result = this . parsePoint ( data , haveZ , haveM ) ; break ; case 2 : result = this . parseLineString ( data , haveZ , haveM ) ; break ; case 3 : result = this . parsePolygon ( data , haveZ , haveM , srid ) ; break ; case 4 : result = this . parseMultiPoint ( data , srid ) ; break ; case 5 : result = this . parseMultiLineString ( data , srid ) ; break ; case 6 : result = this . parseMultiPolygon ( data , srid ) ; break ; case 7 : result = this . parseCollection ( data , srid ) ; break ; default : throw new IllegalArgumentException ( "Unknown Geometry Type!" ) ; } result . setSRID ( srid ) ; return result ; } |
public class DescribeTapesResult { /** * An array of virtual tape descriptions .
* @ param tapes
* An array of virtual tape descriptions . */
public void setTapes ( java . util . Collection < Tape > tapes ) { } } | if ( tapes == null ) { this . tapes = null ; return ; } this . tapes = new com . amazonaws . internal . SdkInternalList < Tape > ( tapes ) ; |
public class GeneratedDConnectionDaoImpl { /** * query - by method for field providerId
* @ param providerId the specified attribute
* @ return an Iterable of DConnections for the specified providerId */
public Iterable < DConnection > queryByProviderId ( java . lang . String providerId ) { } } | return queryByField ( null , DConnectionMapper . Field . PROVIDERID . getFieldName ( ) , providerId ) ; |
public class ConnectionFactory { /** * Determines if the H2 database file exists . If it does not exist then the
* data structure will need to be created .
* @ param configuration the configured settings
* @ return true if the H2 database file does not exist ; otherwise false
* @ throws IOException thrown if the data directory does not exist and
* cannot be created */
public static boolean h2DataFileExists ( Settings configuration ) throws IOException { } } | final File file = getH2DataFile ( configuration ) ; return file . exists ( ) ; |
public class BasicModMixer { /** * Do the events during a Tick .
* @ return true , if finished ! */
protected boolean doTickEvents ( ) { } } | // Global Fade Out
if ( doFadeOut ) { fadeOutValue -= fadeOutSub ; if ( fadeOutValue <= 0 ) return true ; // We did a fadeout and are finished now
} final int nChannels = maxChannels ; if ( patternTicksDelayCount > 0 ) { for ( int c = 0 ; c < nChannels ; c ++ ) { final ChannelMemory aktMemo = channelMemory [ c ] ; processEffekts ( true , aktMemo ) ; } patternTicksDelayCount -- ; } else { currentTick -- ; if ( currentTick <= 0 ) { currentTick = currentTempo ; // if PatternDelay , do it and return
if ( patternDelayCount > 0 ) { for ( int c = 0 ; c < nChannels ; c ++ ) { final ChannelMemory aktMemo = channelMemory [ c ] ; processEffekts ( false , aktMemo ) ; } patternDelayCount -- ; } else if ( currentArrangement >= mod . getSongLength ( ) ) { return true ; // Ticks finished and no new row - - > FINITO !
} else { // Do the row events
doRowEvent ( ) ; // and step to the next row . . . Even if there are no more - we will find out later !
currentRow ++ ; if ( patternJumpPatternIndex != - 1 ) // Do not check infinit Loops here , this is never infinit
{ currentRow = patternJumpPatternIndex ; patternJumpPatternIndex = - 1 ; } if ( currentRow >= currentPattern . getRowCount ( ) || patternBreakRowIndex != - 1 || patternBreakJumpPatternIndex != - 1 ) { mod . setArrangementPositionPlayed ( currentArrangement ) ; if ( patternBreakJumpPatternIndex != - 1 ) { final int checkRow = ( patternBreakRowIndex != - 1 ) ? patternBreakRowIndex : currentRow - 1 ; final boolean infinitLoop = isInfinitLoop ( patternBreakJumpPatternIndex , checkRow ) ; if ( infinitLoop && doNoLoops == Helpers . PLAYER_LOOP_IGNORE ) { patternBreakRowIndex = patternBreakJumpPatternIndex = - 1 ; resetJumpPositionSet ( ) ; currentArrangement ++ ; } else { currentArrangement = patternBreakJumpPatternIndex ; } patternBreakJumpPatternIndex = - 1 ; // and activate fadeout , if wished
if ( infinitLoop && doNoLoops == Helpers . PLAYER_LOOP_FADEOUT ) doFadeOut = true ; } else { resetJumpPositionSet ( ) ; currentArrangement ++ ; } if ( patternBreakRowIndex != - 1 ) { currentRow = patternBreakRowIndex ; patternBreakRowIndex = - 1 ; } else currentRow = 0 ; // End of song ? Fetch new pattern if not . . .
if ( currentArrangement < mod . getSongLength ( ) ) { currentPatternIndex = mod . getArrangement ( ) [ currentArrangement ] ; currentPattern = mod . getPatternContainer ( ) . getPattern ( currentPatternIndex ) ; } else { currentPatternIndex = - 1 ; currentPattern = null ; } } } } else { // Do all Tickevents , ' cause we are in a Tick . . .
for ( int c = 0 ; c < nChannels ; c ++ ) { final ChannelMemory aktMemo = channelMemory [ c ] ; processEffekts ( true , aktMemo ) ; } } } return false ; |
public class N { /** * Method newInstance .
* @ param cls
* @ return T */
public static < T > T newInstance ( final Class < T > cls ) { } } | if ( Modifier . isAbstract ( cls . getModifiers ( ) ) ) { if ( cls . equals ( Map . class ) ) { return ( T ) new HashMap < > ( ) ; } else if ( cls . equals ( List . class ) ) { return ( T ) new ArrayList < > ( ) ; } else if ( cls . equals ( Set . class ) ) { return ( T ) new HashSet < > ( ) ; } else if ( cls . equals ( Queue . class ) ) { return ( T ) new LinkedList < > ( ) ; } else if ( cls . equals ( Deque . class ) ) { return ( T ) new LinkedList < > ( ) ; } else if ( cls . equals ( SortedSet . class ) || cls . equals ( NavigableSet . class ) ) { return ( T ) new TreeSet < > ( ) ; } else if ( cls . equals ( SortedMap . class ) || cls . equals ( NavigableMap . class ) ) { return ( T ) new TreeMap < > ( ) ; } } try { if ( Modifier . isStatic ( cls . getModifiers ( ) ) == false && ( cls . isAnonymousClass ( ) || cls . isMemberClass ( ) ) ) { // http : / / stackoverflow . com / questions / 2097982 / is - it - possible - to - create - an - instance - of - nested - class - using - java - reflection
final List < Class < ? > > toInstantiate = new ArrayList < > ( ) ; Class < ? > parent = cls . getEnclosingClass ( ) ; do { toInstantiate . add ( parent ) ; parent = parent . getEnclosingClass ( ) ; } while ( parent != null && Modifier . isStatic ( parent . getModifiers ( ) ) == false && ( parent . isAnonymousClass ( ) || parent . isMemberClass ( ) ) ) ; if ( parent != null ) { toInstantiate . add ( parent ) ; } N . reverse ( toInstantiate ) ; Object instance = null ; for ( Class < ? > current : toInstantiate ) { instance = instance == null ? invoke ( ClassUtil . getDeclaredConstructor ( current ) ) : invoke ( ClassUtil . getDeclaredConstructor ( current , instance . getClass ( ) ) , instance ) ; } return invoke ( ClassUtil . getDeclaredConstructor ( cls , instance . getClass ( ) ) , instance ) ; } else { return invoke ( ClassUtil . getDeclaredConstructor ( cls ) ) ; } } catch ( InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw N . toRuntimeException ( e ) ; } |
public class ElasticSearchRestDAOV5 { /** * Tries to find object ids for a given query in an index .
* @ param indexName The name of the index .
* @ param queryBuilder The query to use for searching .
* @ param start The start to use .
* @ param size The total return size .
* @ param sortOptions A list of string options to sort in the form VALUE : ORDER ; where ORDER is optional and can be either ASC OR DESC .
* @ param docType The document type to searchObjectIdsViaExpression for .
* @ return The SearchResults which includes the count and IDs that were found .
* @ throws IOException If we cannot communicate with ES . */
private SearchResult < String > searchObjectIds ( String indexName , QueryBuilder queryBuilder , int start , int size , List < String > sortOptions , String docType ) throws IOException { } } | SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder ( ) ; searchSourceBuilder . query ( queryBuilder ) ; searchSourceBuilder . from ( start ) ; searchSourceBuilder . size ( size ) ; if ( sortOptions != null && ! sortOptions . isEmpty ( ) ) { for ( String sortOption : sortOptions ) { SortOrder order = SortOrder . ASC ; String field = sortOption ; int index = sortOption . indexOf ( ":" ) ; if ( index > 0 ) { field = sortOption . substring ( 0 , index ) ; order = SortOrder . valueOf ( sortOption . substring ( index + 1 ) ) ; } searchSourceBuilder . sort ( new FieldSortBuilder ( field ) . order ( order ) ) ; } } // Generate the actual request to send to ES .
SearchRequest searchRequest = new SearchRequest ( indexName ) ; searchRequest . types ( docType ) ; searchRequest . source ( searchSourceBuilder ) ; SearchResponse response = elasticSearchClient . search ( searchRequest ) ; List < String > result = new LinkedList < > ( ) ; response . getHits ( ) . forEach ( hit -> result . add ( hit . getId ( ) ) ) ; long count = response . getHits ( ) . getTotalHits ( ) ; return new SearchResult < > ( count , result ) ; |
public class MethodHelpDto { /** * ~ Methods * * * * * */
private static List < MethodParameterDto > _getMethodParams ( Method method ) { } } | List < MethodParameterDto > result = new ArrayList < > ( ) ; Annotation [ ] [ ] parameterAnnotations = method . getParameterAnnotations ( ) ; Class < ? > [ ] parameterTypes = method . getParameterTypes ( ) ; for ( int i = 0 ; i < parameterTypes . length ; i ++ ) { Class < ? > parameterType = parameterTypes [ i ] ; Annotation [ ] annotations = parameterAnnotations [ i ] ; if ( annotations . length > 0 ) { if ( Context . class . isAssignableFrom ( annotations [ 0 ] . getClass ( ) ) ) { continue ; } MethodParameterDto param = new MethodParameterDto ( ) ; for ( int j = 0 ; j < annotations . length ; j ++ ) { Annotation annotation = annotations [ j ] ; if ( QueryParam . class . isAssignableFrom ( annotation . getClass ( ) ) ) { QueryParam queryParam = QueryParam . class . cast ( annotation ) ; param . setName ( queryParam . value ( ) ) ; param . setParamType ( "query" ) ; } else if ( FormParam . class . isAssignableFrom ( annotation . getClass ( ) ) ) { FormParam queryParam = FormParam . class . cast ( annotation ) ; param . setName ( queryParam . value ( ) ) ; param . setParamType ( "form" ) ; } else if ( PathParam . class . isAssignableFrom ( annotation . getClass ( ) ) ) { PathParam queryParam = PathParam . class . cast ( annotation ) ; param . setName ( queryParam . value ( ) ) ; param . setParamType ( "path" ) ; } else if ( DefaultValue . class . isAssignableFrom ( annotation . getClass ( ) ) ) { DefaultValue defaultValue = DefaultValue . class . cast ( annotation ) ; param . setDefaultValue ( defaultValue . value ( ) ) ; } try { if ( BaseDto . class . isAssignableFrom ( parameterType ) ) { param . setSchema ( BaseDto . class . cast ( parameterType . newInstance ( ) ) . createExample ( ) ) ; } } catch ( Exception ex ) { param . setSchema ( parameterType ) ; } String paramName = parameterType . getSimpleName ( ) . toLowerCase ( ) ; param . setDataType ( paramName . toLowerCase ( ) . replaceAll ( "dto" , "" ) ) ; } result . add ( param ) ; } else { MethodParameterDto param = new MethodParameterDto ( ) ; String paramName = parameterType . getSimpleName ( ) . toLowerCase ( ) ; param . setDataType ( paramName . toLowerCase ( ) . replaceAll ( "dto" , "" ) ) ; param . setName ( "body" ) ; param . setParamType ( "body" ) ; try { if ( BaseDto . class . isAssignableFrom ( parameterType ) ) { param . setSchema ( BaseDto . class . cast ( parameterType . newInstance ( ) ) . createExample ( ) ) ; } } catch ( Exception ex ) { param . setSchema ( parameterType ) ; } result . add ( param ) ; } // end if - else
} // end for
return result ; |
public class ScheduledActionMarshaller { /** * Marshall the given parameter object . */
public void marshall ( ScheduledAction scheduledAction , ProtocolMarshaller protocolMarshaller ) { } } | if ( scheduledAction == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( scheduledAction . getScheduledActionName ( ) , SCHEDULEDACTIONNAME_BINDING ) ; protocolMarshaller . marshall ( scheduledAction . getScheduledActionARN ( ) , SCHEDULEDACTIONARN_BINDING ) ; protocolMarshaller . marshall ( scheduledAction . getServiceNamespace ( ) , SERVICENAMESPACE_BINDING ) ; protocolMarshaller . marshall ( scheduledAction . getSchedule ( ) , SCHEDULE_BINDING ) ; protocolMarshaller . marshall ( scheduledAction . getResourceId ( ) , RESOURCEID_BINDING ) ; protocolMarshaller . marshall ( scheduledAction . getScalableDimension ( ) , SCALABLEDIMENSION_BINDING ) ; protocolMarshaller . marshall ( scheduledAction . getStartTime ( ) , STARTTIME_BINDING ) ; protocolMarshaller . marshall ( scheduledAction . getEndTime ( ) , ENDTIME_BINDING ) ; protocolMarshaller . marshall ( scheduledAction . getScalableTargetAction ( ) , SCALABLETARGETACTION_BINDING ) ; protocolMarshaller . marshall ( scheduledAction . getCreationTime ( ) , CREATIONTIME_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class EmitToGraphiteLogbackAppender { /** * Starts the appender by starting a background thread to poll the error counters and publish them to Graphite .
* Multiple instances of this EmitToGraphiteLogbackAppender will only start one background thread .
* This method also starts the heartbeat metric background thread . */
@ Override public void start ( ) { } } | super . start ( ) ; // If disabled we do not create a publisher to graphite but error counts are still collected .
if ( enabled ) { metricPublishing . start ( new GraphiteConfigImpl ( host , port , pollintervalseconds , queuesize , sendasrate ) ) ; } this . startUpMetric = factory . createStartUpMetric ( metricObjects , subsystem , new Timer ( ) ) ; startUpMetric . start ( ) ; |
public class FineUploader5Validation { /** * Restrict images to a maximum height in pixels ( wherever possible ) .
* @ param nImageMaxHeight
* New value . Must be & ge ; 0.
* @ return this for chaining */
@ Nonnull public FineUploader5Validation setImageMaxHeight ( @ Nonnegative final int nImageMaxHeight ) { } } | ValueEnforcer . isGE0 ( nImageMaxHeight , "ImageMaxHeight" ) ; m_nValidationImageMaxHeight = nImageMaxHeight ; return this ; |
public class JCudaDriver { /** * Maps an OpenGL buffer object .
* < pre >
* CUresult cuGLMapBufferObjectAsync (
* CUdeviceptr * dptr ,
* size _ t * size ,
* GLuint buffer ,
* CUstream hStream )
* < / pre >
* < div >
* < p > Maps an OpenGL buffer object .
* Deprecated < span > This function is
* deprecated as of Cuda 3.0 . < / span > Maps the buffer object specified by
* < tt > buffer < / tt > into the address space of the current CUDA context
* and returns in < tt > * dptr < / tt > and < tt > * size < / tt > the base pointer
* and size of the resulting mapping .
* < p > There must be a valid OpenGL context
* bound to the current thread when this function is called . This must be
* the same context ,
* or a member of the same shareGroup ,
* as the context that was bound when the buffer was registered .
* < p > Stream < tt > hStream < / tt > in the
* current CUDA context is synchronized with the current GL context .
* < div >
* < span > Note : < / span >
* < p > Note that
* this function may also return error codes from previous , asynchronous
* launches .
* < / div >
* < / div >
* @ param dptr Returned mapped base pointer
* @ param size Returned size of mapping
* @ param buffer The name of the buffer object to map
* @ param hStream Stream to synchronize
* @ return CUDA _ SUCCESS , CUDA _ ERROR _ DEINITIALIZED , CUDA _ ERROR _ NOT _ INITIALIZED ,
* CUDA _ ERROR _ INVALID _ CONTEXT , CUDA _ ERROR _ INVALID _ VALUE ,
* CUDA _ ERROR _ MAP _ FAILED
* @ see JCudaDriver # cuGraphicsMapResources
* @ deprecated Deprecated as of CUDA 3.0 */
@ Deprecated public static int cuGLMapBufferObjectAsync ( CUdeviceptr dptr , long size [ ] , int buffer , CUstream hStream ) { } } | return checkResult ( ( cuGLMapBufferObjectAsyncNative ( dptr , size , buffer , hStream ) ) ) ; |
public class ScriptBytecodeAdapter { public static void setPropertyOnSuper ( Object messageArgument , Class senderClass , GroovyObject receiver , String messageName ) throws Throwable { } } | try { InvokerHelper . setAttribute ( receiver , messageName , messageArgument ) ; } catch ( GroovyRuntimeException gre ) { throw unwrap ( gre ) ; } |
public class ChronosServer { /** * Initialize persistent timestamp and start to serve as active master . */
@ Override public void doAsActiveServer ( ) { } } | try { LOG . info ( "As active master, init timestamp from ZooKeeper" ) ; chronosImplement . initTimestamp ( ) ; } catch ( Exception e ) { LOG . fatal ( "Exception to init timestamp from ZooKeeper, exit immediately" ) ; System . exit ( 0 ) ; } chronosServerWatcher . setBeenActiveMaster ( true ) ; LOG . info ( "Start to accept thrift request" ) ; startThriftServer ( ) ; |
public class NeuralNetwork { /** * Propagates the signals through the neural network . */
private void propagate ( ) { } } | for ( int l = 0 ; l < net . length - 1 ; l ++ ) { propagate ( net [ l ] , net [ l + 1 ] ) ; } |
public class RelationalOperations { /** * Returns true if polyline _ a is disjoint from point _ b . */
private static boolean polylineDisjointPoint_ ( Polyline polyline_a , Point point_b , double tolerance , ProgressTracker progress_tracker ) { } } | // Quick rasterize test to see whether the the geometries are disjoint .
if ( tryRasterizedContainsOrDisjoint_ ( polyline_a , point_b , tolerance , false ) == Relation . disjoint ) return true ; Point2D pt_b = point_b . getXY ( ) ; return ! linearPathIntersectsPoint_ ( polyline_a , pt_b , tolerance ) ; |
public class AbstractAtomicMapService { /** * Updates the given value .
* @ param key the key to update
* @ param value the value to update */
protected void putValue ( K key , MapEntryValue value ) { } } | MapEntryValue oldValue = entries ( ) . put ( key , value ) ; cancelTtl ( oldValue ) ; scheduleTtl ( key , value ) ; |
public class ClusterInstance { /** * Removes all allocated slices on this instance and frees
* up their allocated resources .
* @ return a list of all removed slices */
synchronized List < AllocatedSlice > removeAllAllocatedSlices ( ) { } } | final List < AllocatedSlice > slices = new ArrayList < AllocatedSlice > ( this . allocatedSlices . values ( ) ) ; final Iterator < AllocatedSlice > it = slices . iterator ( ) ; while ( it . hasNext ( ) ) { removeAllocatedSlice ( it . next ( ) . getAllocationID ( ) ) ; } return slices ; |
public class MACAddressSection { /** * @ return the number of bits in the prefix .
* The prefix is the smallest bit length x for which all possible values with the same first x bits are included in this range of sections ,
* unless that value x matches the bit count of this section , in which case the prefix is null .
* If the prefix is the OUI bit length ( 24 ) then the ODI segments cover all possibly values . */
@ Override public Integer getPrefixLength ( ) { } } | Integer ret = cachedPrefixLength ; if ( ret == null ) { int prefix = getMinPrefixLengthForBlock ( ) ; if ( prefix == getBitCount ( ) ) { cachedPrefixLength = NO_PREFIX_LENGTH ; return null ; } return cachedPrefixLength = prefix ; } if ( ret . intValue ( ) == NO_PREFIX_LENGTH . intValue ( ) ) { return null ; } return ret ; |
public class NTLMUtilities { /** * Writes the Windows OS version passed in as three byte values
* ( majorVersion . minorVersion . buildNumber ) to the given byte array
* at < code > offset < / code > .
* @ param majorVersion the major version number
* @ param minorVersion the minor version number
* @ param buildNumber the build number
* @ param b the target byte array
* @ param offset the offset at which to write in the array */
public static void writeOSVersion ( byte majorVersion , byte minorVersion , short buildNumber , byte [ ] b , int offset ) { } } | b [ offset ] = majorVersion ; b [ offset + 1 ] = minorVersion ; b [ offset + 2 ] = ( byte ) buildNumber ; b [ offset + 3 ] = ( byte ) ( buildNumber >> 8 ) ; b [ offset + 4 ] = 0 ; b [ offset + 5 ] = 0 ; b [ offset + 6 ] = 0 ; b [ offset + 7 ] = 0x0F ; |
public class ISO8601 { /** * Parses an ISO8601 formatted string a returns a Calendar instance .
* @ param dateTimeString the ISO8601 formatted string
* @ return a Calendar instance for the ISO8601 formatted string
* @ throws ParseException if the provided string is not in the proper format */
public static Calendar toCalendar ( String dateTimeString ) throws ParseException { } } | Date date = toDate ( dateTimeString ) ; if ( date == null ) { return ( null ) ; } Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date ) ; return ( cal ) ; |
public class DistributedLogServerContext { /** * Changes the roles . */
private void changeRole ( PrimaryTerm term ) { } } | threadContext . execute ( ( ) -> { if ( term . term ( ) >= currentTerm ) { log . debug ( "{} - Term changed: {}" , memberId , term ) ; currentTerm = term . term ( ) ; leader = term . primary ( ) != null ? term . primary ( ) . memberId ( ) : null ; followers = term . backups ( replicationFactor - 1 ) . stream ( ) . map ( GroupMember :: memberId ) . collect ( Collectors . toList ( ) ) ; if ( Objects . equals ( leader , clusterMembershipService . getLocalMember ( ) . id ( ) ) ) { if ( this . role == null ) { this . role = new LeaderRole ( this ) ; log . debug ( "{} transitioning to {}" , clusterMembershipService . getLocalMember ( ) . id ( ) , Role . LEADER ) ; } else if ( this . role . role ( ) != Role . LEADER ) { this . role . close ( ) ; this . role = new LeaderRole ( this ) ; log . debug ( "{} transitioning to {}" , clusterMembershipService . getLocalMember ( ) . id ( ) , Role . LEADER ) ; } } else if ( followers . contains ( clusterMembershipService . getLocalMember ( ) . id ( ) ) ) { if ( this . role == null ) { this . role = new FollowerRole ( this ) ; log . debug ( "{} transitioning to {}" , clusterMembershipService . getLocalMember ( ) . id ( ) , Role . FOLLOWER ) ; } else if ( this . role . role ( ) != Role . FOLLOWER ) { this . role . close ( ) ; this . role = new FollowerRole ( this ) ; log . debug ( "{} transitioning to {}" , clusterMembershipService . getLocalMember ( ) . id ( ) , Role . FOLLOWER ) ; } } else { if ( this . role == null ) { this . role = new NoneRole ( this ) ; log . debug ( "{} transitioning to {}" , clusterMembershipService . getLocalMember ( ) . id ( ) , Role . NONE ) ; } else if ( this . role . role ( ) != Role . NONE ) { this . role . close ( ) ; this . role = new NoneRole ( this ) ; log . debug ( "{} transitioning to {}" , clusterMembershipService . getLocalMember ( ) . id ( ) , Role . NONE ) ; } } } } ) ; |
public class CurvedArrow { /** * Sets the end point .
* @ param x2
* the x coordinate of the end point
* @ param y2
* the y coordinate of the end point */
public void setEnd ( int x2 , int y2 ) { } } | end . x = x2 ; end . y = y2 ; needsRefresh = true ; |
public class VAlarmAudioValidator { /** * { @ inheritDoc } */
public void validate ( VAlarm target ) throws ValidationException { } } | /* * ; the following is optional , ; but MUST NOT occur more than once attach / */
PropertyValidator . getInstance ( ) . assertOneOrLess ( ATTACH , target . getProperties ( ) ) ; |
public class Matchers { /** * Matches an AST node which is the same object reference as the given node . */
public static < T extends Tree > Matcher < T > isSame ( final Tree t ) { } } | return new Matcher < T > ( ) { @ Override public boolean matches ( T tree , VisitorState state ) { return tree == t ; } } ; |
public class ECoordinate { /** * user defined tolerance . */
boolean tolEq ( ECoordinate v , double tolerance ) // ! = = with tolerance
{ } } | return Math . abs ( m_value - v . m_value ) <= tolerance || eq ( v ) ; |
public class RepositoryReaderImpl { /** * returns log records from the binary repository that are within the level range as specified by the parameters .
* @ param minLevel integer value of the minimum { @ link Level } that the returned records need to match
* @ param maxLevel integer value of the maximum { @ link Level } that the returned records need to match
* @ return the iterable instance of a list of log records within a process that are within the parameter range
* If no records meet the criteria , an Iterable is returned with no entries */
public Iterable < ServerInstanceLogRecordList > getLogLists ( int minLevel , int maxLevel ) { } } | return getLogLists ( ( Date ) null , ( Date ) null , new LevelFilter ( minLevel , maxLevel ) ) ; |
public class DashboardController { /** * Get count of all filtered dashboards
* @ return Integer */
@ RequestMapping ( value = "/dashboard/filter/count/{title}/{type}" , method = GET , produces = APPLICATION_JSON_VALUE ) public long dashboardsFilterCount ( @ PathVariable String title , @ PathVariable String type ) { } } | return dashboardService . getAllDashboardsByTitleCount ( title , type ) ; |
public class DocTreeScanner { /** * { @ inheritDoc } This implementation scans the children in left to right order .
* @ param node { @ inheritDoc }
* @ param p { @ inheritDoc }
* @ return the result of scanning */
@ Override public R visitSince ( SinceTree node , P p ) { } } | return scan ( node . getBody ( ) , p ) ; |
public class ManagementResources { /** * Disables the warden .
* @ param req The HTTP request .
* @ return Response object indicating whether the operation was successful or not . */
@ PUT @ Path ( "/disablewarden" ) @ Produces ( MediaType . APPLICATION_JSON ) @ Description ( "Disables warden." ) public Response disableWarden ( @ Context HttpServletRequest req ) { } } | validatePrivilegedUser ( req ) ; managementService . disableWarden ( ) ; return Response . status ( Status . OK ) . build ( ) ; |
public class Connector { /** * Internal method to send the payload to ROX center agnostic to the payload optimization
* @ param payload The payload to send to ROX center
* @ param optimized Define if the payload is optimized or not
* @ return True if the payload was sent successfully */
private boolean sendPayload ( URL payloadResourceUrl , RoxPayload payload , boolean optimized ) { } } | HttpURLConnection conn = null ; final String payloadLogString = optimized ? "optimized payload" : "payload" ; try { conn = uploadPayload ( payloadResourceUrl , payload ) ; if ( conn . getResponseCode ( ) == 202 ) { LOGGER . info ( "The {} was successfully sent to ROX Center." , payloadLogString ) ; return true ; } else { LOGGER . error ( "Unable to send the {} to Rox. Return code: {}, content: {}" , payloadLogString , conn . getResponseCode ( ) , readInputStream ( conn . getInputStream ( ) ) ) ; } } catch ( IOException ioe ) { if ( ! configuration . isPayloadPrint ( ) ) { OutputStreamWriter baos = null ; try { baos = new OutputStreamWriter ( new ByteArrayOutputStream ( ) , Charset . forName ( Constants . ENCODING ) . newEncoder ( ) ) ; serializer . serializePayload ( baos , payload , true ) ; LOGGER . error ( "The {} in error: {}" , payloadLogString , baos . toString ( ) ) ; } catch ( IOException baosIoe ) { } finally { try { if ( baos != null ) { baos . close ( ) ; } } catch ( IOException baosIoe ) { } } if ( conn != null ) { try { if ( conn . getErrorStream ( ) != null ) { LOGGER . error ( "Unable to send the {} to ROX. Error: {}" , payloadLogString , readInputStream ( conn . getErrorStream ( ) ) ) ; } else { LOGGER . error ( "Unable to send the " + payloadLogString + " to ROX. This is probably due to an unreachable network issue." , ioe ) ; } } catch ( IOException errorIoe ) { LOGGER . error ( "Unable to send the {} to ROX for unknown reason." , payloadLogString ) ; } } else { LOGGER . error ( "Unable to send the |{} to ROX. Error: {}" , payloadLogString , ioe . getMessage ( ) ) ; } } } return false ; |
public class CommandLine { /** * Delegates to { @ link # invoke ( String , Class , PrintStream , PrintStream , Help . Ansi , String . . . ) } with { @ code System . out } for
* requested usage help messages , { @ code System . err } for diagnostic error messages , and { @ link Help . Ansi # AUTO } .
* @ param methodName the { @ code @ Command } - annotated method to build a { @ link CommandSpec } model from ,
* and run when { @ linkplain # parseArgs ( String . . . ) parsing } succeeds .
* @ param cls the class where the { @ code @ Command } - annotated method is declared , or a subclass
* @ param args the command line arguments to parse
* @ see # invoke ( String , Class , PrintStream , PrintStream , Help . Ansi , String . . . )
* @ throws InitializationException if the specified method does not have a { @ link Command } annotation ,
* or if the specified class contains multiple { @ code @ Command } - annotated methods with the specified name
* @ throws ExecutionException if the Runnable throws an exception
* @ see # parseWithHandlers ( IParseResultHandler2 , IExceptionHandler2 , String . . . )
* @ since 3.6 */
public static Object invoke ( String methodName , Class < ? > cls , String ... args ) { } } | return invoke ( methodName , cls , System . out , System . err , Help . Ansi . AUTO , args ) ; |
public class ConciseSet { /** * Assures that the length of { @ link # words } is sufficient to contain
* the given index . */
private void ensureCapacity ( int index ) { } } | int capacity = words == null ? 0 : words . length ; if ( capacity > index ) { return ; } capacity = Math . max ( capacity << 1 , index + 1 ) ; if ( words == null ) { // nothing to copy
words = new int [ capacity ] ; return ; } words = Arrays . copyOf ( words , capacity ) ; |
public class BaseSamlRegisteredServiceMetadataResolver { /** * Build metadata resolver from document .
* @ param service the service
* @ param metadataDocument the metadata document
* @ return the metadata resolver */
protected AbstractMetadataResolver buildMetadataResolverFrom ( final SamlRegisteredService service , final SamlMetadataDocument metadataDocument ) { } } | try { val desc = StringUtils . defaultString ( service . getDescription ( ) , service . getName ( ) ) ; val metadataResource = ResourceUtils . buildInputStreamResourceFrom ( metadataDocument . getDecodedValue ( ) , desc ) ; val metadataResolver = new InMemoryResourceMetadataResolver ( metadataResource , configBean ) ; val metadataFilterList = new ArrayList < MetadataFilter > ( ) ; if ( StringUtils . isNotBlank ( metadataDocument . getSignature ( ) ) ) { val signatureResource = ResourceUtils . buildInputStreamResourceFrom ( metadataDocument . getSignature ( ) , desc ) ; buildSignatureValidationFilterIfNeeded ( service , metadataFilterList , signatureResource ) ; } configureAndInitializeSingleMetadataResolver ( metadataResolver , service , metadataFilterList ) ; return metadataResolver ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return null ; |
public class GuardianEntity { /** * Request all the Guardian Factors . A token with scope read : guardian _ factors is needed .
* @ return a Request to execute .
* @ see < a href = " https : / / auth0 . com / docs / api / management / v2 # ! / Guardian / get _ factors " > Management API2 docs < / a > */
public Request < List < Factor > > listFactors ( ) { } } | String url = baseUrl . newBuilder ( ) . addPathSegments ( "api/v2/guardian/factors" ) . build ( ) . toString ( ) ; CustomRequest < List < Factor > > request = new CustomRequest < > ( client , url , "GET" , new TypeReference < List < Factor > > ( ) { } ) ; request . addHeader ( "Authorization" , "Bearer " + apiToken ) ; return request ; |
public class SVGPath { /** * Smooth Cubic Bezier line to the given coordinates .
* @ param c2xy second control point
* @ param xy new coordinates
* @ return path object , for compact syntax . */
public SVGPath smoothCubicTo ( double [ ] c2xy , double [ ] xy ) { } } | return append ( PATH_SMOOTH_CUBIC_TO ) . append ( c2xy [ 0 ] ) . append ( c2xy [ 1 ] ) . append ( xy [ 0 ] ) . append ( xy [ 1 ] ) ; |
public class BasePanel { /** * Process the " Move " Commands .
* @ param nIDMoveCommand The move command ( first / last / next / prev ) .
* @ return true if successful . */
public boolean onMove ( int nIDMoveCommand ) { } } | Record record = this . getMainRecord ( ) ; if ( record == null ) return false ; try { if ( record . isModified ( false ) ) { if ( record . getEditMode ( ) == Constants . EDIT_IN_PROGRESS ) record . set ( ) ; else if ( record . getEditMode ( ) == Constants . EDIT_ADD ) record . add ( ) ; } if ( ( nIDMoveCommand == Constants . NEXT_RECORD ) && ( ! record . hasNext ( ) ) ) this . onAdd ( ) ; // Next record , enter " Add " mode
else if ( ( nIDMoveCommand == Constants . PREVIOUS_RECORD ) && ( ! record . hasPrevious ( ) ) ) this . onMove ( Constants . FIRST_RECORD ) ; // Can ' t move before the first record
else record . move ( nIDMoveCommand ) ; record . isModified ( false ) ; this . clearStatusText ( ) ; } catch ( DBException ex ) { this . displayError ( ex ) ; return false ; } return true ; // Command processed |
public class Menu { /** * { @ inheritDoc } */
@ Override public boolean hasAccess ( final TargetMode _targetMode , final Instance _instance ) throws EFapsException { } } | boolean ret = super . hasAccess ( _targetMode , _instance ) ; if ( ! ret && getCommands ( ) . size ( ) > 0 && ! AppAccessHandler . excludeMode ( ) && isTypeMenu ( ) ) { ret = true ; } return ret ; |
public class ConstraintsConverter { /** * Serialise a constraint .
* @ param o the constraint
* @ return the resulting encoded constraint
* @ throws JSONConverterException if the conversion failed */
public JSONObject toJSON ( Constraint o ) throws JSONConverterException { } } | ConstraintConverter c = java2json . get ( o . getClass ( ) ) ; if ( c == null ) { throw new JSONConverterException ( "No converter available for a constraint with the '" + o . getClass ( ) + "' className" ) ; } return c . toJSON ( o ) ; |
public class Point { /** * Returns value of the given vertex attribute ' s ordinate . The ordinate is
* always 0 because integer attributes always have one component .
* @ param semantics
* The attribute semantics .
* @ param ordinate
* The attribute ' s ordinate . For example , the y coordinate of the
* NORMAL has ordinate of 1.
* @ return The ordinate value truncated to a 32 bit integer value . */
public int getAttributeAsInt ( int semantics , int ordinate ) { } } | if ( isEmptyImpl ( ) ) throw new GeometryException ( "This operation was performed on an Empty Geometry." ) ; int ncomps = VertexDescription . getComponentCount ( semantics ) ; if ( ordinate >= ncomps ) throw new IndexOutOfBoundsException ( ) ; int attributeIndex = m_description . getAttributeIndex ( semantics ) ; if ( attributeIndex >= 0 ) return ( int ) m_attributes [ m_description . _getPointAttributeOffset ( attributeIndex ) + ordinate ] ; else return ( int ) VertexDescription . getDefaultValue ( semantics ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.