signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class AuthenticatorFactory { /** * Creates an Authenticator that knows how to do Facebook authentication .
* @ param token Facebook access token */
public static Authenticator createFacebookAuthenticator ( String token ) { } } | Map < String , String > params = new HashMap < String , String > ( ) ; params . put ( "access_token" , token ) ; return new TokenAuthenticator ( "_facebook" , params ) ; |
public class Agg { /** * Get a { @ link Collector } that calculates the < code > MODE ( ) < / code > function . */
public static < T , U > Collector < T , ? , Optional < T > > modeBy ( Function < ? super T , ? extends U > function ) { } } | return Collectors . collectingAndThen ( modeAllBy ( function ) , s -> s . findFirst ( ) ) ; |
public class ProGradePolicy { /** * Private method for initializing static policy .
* @ throws Exception when there was any problem during initializing static policy */
private void initializeStaticPolicy ( List < ProGradePolicyEntry > grantEntriesList ) throws Exception { } } | // grant codeBase " file : $ { { java . ext . dirs } } / * " {
// permission java . security . AllPermission ;
ProGradePolicyEntry p1 = new ProGradePolicyEntry ( true , debug ) ; Certificate [ ] certificates = null ; URL url = new URL ( expandStringWithProperty ( "file:${{java.ext.dirs}}/*" ) ) ; CodeSource cs = new CodeSource ( adaptURL ( url ) , certificates ) ; p1 . setCodeSource ( cs ) ; p1 . addPermission ( new AllPermission ( ) ) ; grantEntriesList . add ( p1 ) ; // grant {
// permission java . lang . RuntimePermission " stopThread " ;
// permission java . net . SocketPermission " localhost : 1024 - " , " listen " ;
// permission java . util . PropertyPermission " java . version " , " read " ;
// permission java . util . PropertyPermission " java . vendor " , " read " ;
// permission java . util . PropertyPermission " java . vendor . url " , " read " ;
// permission java . util . PropertyPermission " java . class . version " , " read " ;
// permission java . util . PropertyPermission " os . name " , " read " ;
// permission java . util . PropertyPermission " os . version " , " read " ;
// permission java . util . PropertyPermission " os . arch " , " read " ;
// permission java . util . PropertyPermission " file . separator " , " read " ;
// permission java . util . PropertyPermission " path . separator " , " read " ;
// permission java . util . PropertyPermission " line . separator " , " read " ;
// permission java . util . PropertyPermission " java . specification . version " , " read " ;
// permission java . util . PropertyPermission " java . specification . vendor " , " read " ;
// permission java . util . PropertyPermission " java . specification . name " , " read " ;
// permission java . util . PropertyPermission " java . vm . specification . version " , " read " ;
// permission java . util . PropertyPermission " java . vm . specification . vendor " , " read " ;
// permission java . util . PropertyPermission " java . vm . specification . name " , " read " ;
// permission java . util . PropertyPermission " java . vm . version " , " read " ;
// permission java . util . PropertyPermission " java . vm . vendor " , " read " ;
// permission java . util . PropertyPermission " java . vm . name " , " read " ;
ProGradePolicyEntry p2 = new ProGradePolicyEntry ( true , debug ) ; p2 . addPermission ( new RuntimePermission ( "stopThread" ) ) ; p2 . addPermission ( new SocketPermission ( "localhost:1024-" , "listen" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.version" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vendor" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vendor.url" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.class.version" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "os.name" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "os.version" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "os.arch" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "file.separator" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "path.separator" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "line.separator" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.specification.version" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.specification.vendor" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.specification.name" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vm.specification.version" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vm.specification.vendor" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vm.specification.name" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vm.version" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vm.vendor" , "read" ) ) ; p2 . addPermission ( new PropertyPermission ( "java.vm.name" , "read" ) ) ; grantEntriesList . add ( p2 ) ; |
public class JavaEscape { /** * Perform a Java level 1 ( only basic set ) < strong > escape < / strong > operation
* on a < tt > char [ ] < / tt > input .
* < em > Level 1 < / em > means this method will only escape the Java basic escape set :
* < ul >
* < li > The < em > Single Escape Characters < / em > :
* < tt > & # 92 ; b < / tt > ( < tt > U + 0008 < / tt > ) ,
* < tt > & # 92 ; t < / tt > ( < tt > U + 0009 < / tt > ) ,
* < tt > & # 92 ; n < / tt > ( < tt > U + 000A < / tt > ) ,
* < tt > & # 92 ; f < / tt > ( < tt > U + 000C < / tt > ) ,
* < tt > & # 92 ; r < / tt > ( < tt > U + 000D < / tt > ) ,
* < tt > & # 92 ; & quot ; < / tt > ( < tt > U + 0022 < / tt > ) ,
* < tt > & # 92 ; & # 39 ; < / tt > ( < tt > U + 0027 < / tt > ) and
* < tt > & # 92 ; & # 92 ; < / tt > ( < tt > U + 005C < / tt > ) . Note < tt > & # 92 ; & # 39 ; < / tt > is not really needed in
* String literals ( only in Character literals ) , so it won ' t be used until escape level 3.
* < / li >
* < li >
* Two ranges of non - displayable , control characters ( some of which are already part of the
* < em > single escape characters < / em > list ) : < tt > U + 0000 < / tt > to < tt > U + 001F < / tt >
* and < tt > U + 007F < / tt > to < tt > U + 009F < / tt > .
* < / li >
* < / ul >
* This method calls { @ link # escapeJava ( char [ ] , int , int , java . io . Writer , JavaEscapeLevel ) }
* with the following preconfigured values :
* < ul >
* < li > < tt > level < / tt > :
* { @ link JavaEscapeLevel # LEVEL _ 1 _ BASIC _ ESCAPE _ SET } < / li >
* < / ul >
* This method is < strong > thread - safe < / strong > .
* @ param text the < tt > char [ ] < / tt > to be escaped .
* @ param offset the position in < tt > text < / tt > at which the escape operation should start .
* @ param len the number of characters in < tt > text < / tt > that should be escaped .
* @ param writer the < tt > java . io . Writer < / tt > to which the escaped result will be written . Nothing will
* be written at all to this writer if input is < tt > null < / tt > .
* @ throws IOException if an input / output exception occurs */
public static void escapeJavaMinimal ( final char [ ] text , final int offset , final int len , final Writer writer ) throws IOException { } } | escapeJava ( text , offset , len , writer , JavaEscapeLevel . LEVEL_1_BASIC_ESCAPE_SET ) ; |
public class PortletContextLoader { /** * Obtain the Spring root portlet application context for the current thread
* ( i . e . for the current thread ' s context ClassLoader , which needs to be
* the web application ' s ClassLoader ) .
* @ return the current root web application context , or < code > null < / code >
* if none found
* @ see org . springframework . web . context . support . SpringBeanAutowiringSupport */
public static PortletApplicationContext getCurrentPortletApplicationContext ( ) { } } | ClassLoader ccl = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( ccl != null ) { PortletApplicationContext ccpt = currentContextPerThread . get ( ccl ) ; if ( ccpt != null ) { return ccpt ; } } return currentContext ; |
public class SimpleFormat { /** * Writes a formatted string to the output destination of the { @ code Formatter } .
* @ param format
* a format string .
* @ param args
* the arguments list used in the { @ code format ( ) } method . If there are
* more arguments than those specified by the format string , then
* the additional arguments are ignored .
* @ return this { @ code Formatter } .
* @ throws IllegalFormatFlagsException
* if the format string is illegal or incompatible with the
* arguments , or if fewer arguments are sent than those required by
* the format string , or any other illegal situation . */
public static String format ( String format , Object ... args ) { } } | SimpleFormat f = new SimpleFormat ( ) ; f . doFormat ( format , args ) ; return f . out . toString ( ) ; |
public class ArrayMap { private MapCollections < K , V > getCollection ( ) { } } | @ WeakOuter class InteropMapCollections extends MapCollections < K , V > { @ Override protected int colGetSize ( ) { return mSize ; } @ Override protected Object colGetEntry ( int index , int offset ) { return mArray [ ( index << 1 ) + offset ] ; } @ Override protected int colIndexOfKey ( Object key ) { return key == null ? indexOfNull ( ) : indexOf ( key , key . hashCode ( ) ) ; } @ Override protected int colIndexOfValue ( Object value ) { return indexOfValue ( value ) ; } @ Override protected Map < K , V > colGetMap ( ) { return ArrayMap . this ; } @ Override protected void colPut ( K key , V value ) { put ( key , value ) ; } @ Override protected V colSetValue ( int index , V value ) { return setValueAt ( index , value ) ; } @ Override protected void colRemoveAt ( int index ) { removeAt ( index ) ; } @ Override protected void colClear ( ) { clear ( ) ; } } if ( mCollections == null ) { mCollections = new InteropMapCollections ( ) ; } return mCollections ; |
public class BshClassPath { /** * Search jar file system for classes .
* @ param the jar : file system url
* @ return array of class names found
* @ throws IOException */
static String [ ] searchJarFSForClasses ( URL url ) throws IOException { } } | try { try { FileSystems . newFileSystem ( url . toURI ( ) , new HashMap < > ( ) ) ; } catch ( FileSystemAlreadyExistsException e ) { /* ignore */
} Path path = FileSystems . getFileSystem ( url . toURI ( ) ) . getPath ( "/" ) ; return Files . walk ( path ) . map ( Path :: toString ) . filter ( BshClassPath :: isClassFileName ) . map ( BshClassPath :: canonicalizeClassName ) . toArray ( String [ ] :: new ) ; } catch ( URISyntaxException e ) { /* ignore */
} return new String [ 0 ] ; |
public class Assertions { /** * Assert that value is not null
* @ param < T > type of the object to check
* @ param object the object to check
* @ return the same input parameter if all is ok
* @ throws AssertionError it will be thrown if the value is null
* @ since 1.0 */
@ Nonnull public static < T > T assertNotNull ( @ Nullable final T object ) { } } | return assertNotNull ( null , object ) ; |
public class InternalPureXbaseParser { /** * InternalPureXbase . g : 906:1 : entryRuleOpSingleAssign returns [ String current = null ] : iv _ ruleOpSingleAssign = ruleOpSingleAssign EOF ; */
public final String entryRuleOpSingleAssign ( ) throws RecognitionException { } } | String current = null ; AntlrDatatypeRuleToken iv_ruleOpSingleAssign = null ; try { // InternalPureXbase . g : 906:54 : ( iv _ ruleOpSingleAssign = ruleOpSingleAssign EOF )
// InternalPureXbase . g : 907:2 : iv _ ruleOpSingleAssign = ruleOpSingleAssign EOF
{ if ( state . backtracking == 0 ) { newCompositeNode ( grammarAccess . getOpSingleAssignRule ( ) ) ; } pushFollow ( FOLLOW_1 ) ; iv_ruleOpSingleAssign = ruleOpSingleAssign ( ) ; state . _fsp -- ; if ( state . failed ) return current ; if ( state . backtracking == 0 ) { current = iv_ruleOpSingleAssign . getText ( ) ; } match ( input , EOF , FOLLOW_2 ) ; if ( state . failed ) return current ; } } catch ( RecognitionException re ) { recover ( input , re ) ; appendSkippedTokens ( ) ; } finally { } return current ; |
public class HomophoneOccurrenceDumper { /** * Get the context ( left and right words ) for the given word ( s ) . This is slow ,
* as it needs to scan the whole index . */
Map < String , Long > getContext ( String ... tokens ) throws IOException { } } | Objects . requireNonNull ( tokens ) ; TermsEnum iterator = getIterator ( ) ; Map < String , Long > result = new HashMap < > ( ) ; BytesRef byteRef ; int i = 0 ; while ( ( byteRef = iterator . next ( ) ) != null ) { String term = new String ( byteRef . bytes , byteRef . offset , byteRef . length ) ; for ( String token : tokens ) { if ( term . contains ( " " + token + " " ) ) { String [ ] split = term . split ( " " ) ; if ( split . length == 3 ) { long count = getCount ( Arrays . asList ( split [ 0 ] , split [ 1 ] , split [ 2 ] ) ) ; result . put ( term , count ) ; } } } /* if ( i + + > 1_000_000 ) { / / comment in for faster testing with subsets of the data
break ; */
} return result ; |
public class MeanVariance { /** * Join the data of another MeanVariance instance .
* @ param other Data to join with */
@ Override public void put ( Mean other ) { } } | if ( ! ( other instanceof MeanVariance ) ) { throw new IllegalArgumentException ( "I cannot combine Mean and MeanVariance to a MeanVariance." ) ; } final MeanVariance mvo = ( MeanVariance ) other ; final double on = mvo . n , osum = mvo . sum ; final double tmp = n * osum - sum * on ; final double oldn = n ; // tmp copy
n += on ; sum += osum ; m2 += mvo . m2 + tmp * tmp / ( on * n * oldn ) ; |
public class ObjectInputStream { /** * Reads { @ code byteCount } bytes from the source stream into the byte array { @ code dst } .
* @ param dst
* the byte array in which to store the bytes read .
* @ param offset
* the initial position in { @ code dst } to store the bytes
* read from the source stream .
* @ param byteCount
* the number of bytes to read .
* @ throws EOFException
* if the end of the input is reached before the read
* request can be satisfied .
* @ throws IOException
* if an error occurs while reading from the source stream . */
public void readFully ( byte [ ] dst , int offset , int byteCount ) throws IOException { } } | primitiveTypes . readFully ( dst , offset , byteCount ) ; |
public class QueryImpl { /** * ( non - Javadoc )
* @ see javax . persistence . Query # getResultList ( ) */
@ Override public List < ? > getResultList ( ) { } } | if ( log . isDebugEnabled ( ) ) log . info ( "On getResultList() executing query: " + getJPAQuery ( ) ) ; // as per JPA post event should happen before fetching data from
// database .
List results = null ; if ( getEntityMetadata ( ) == null ) { // Scalar Query
if ( kunderaQuery . isDeleteUpdate ( ) ) { executeUpdate ( ) ; } else { Client client = persistenceDelegeator . getClient ( kunderaQuery . getPersistenceUnit ( ) ) ; results = populateEntities ( null , client ) ; } } else { handlePostEvent ( ) ; if ( kunderaQuery . isDeleteUpdate ( ) ) { executeUpdate ( ) ; } else { results = fetch ( ) ; assignReferenceToProxy ( results ) ; } } return results != null ? results : new ArrayList ( ) ; |
public class SchemaGeneratorHelper { /** * builds directives from a type and its extensions */
public GraphQLDirective buildDirective ( Directive directive , Set < GraphQLDirective > directiveDefinitions , DirectiveLocation directiveLocation ) { } } | Optional < GraphQLDirective > directiveDefinition = directiveDefinitions . stream ( ) . filter ( dd -> dd . getName ( ) . equals ( directive . getName ( ) ) ) . findFirst ( ) ; GraphQLDirective . Builder builder = GraphQLDirective . newDirective ( ) . name ( directive . getName ( ) ) . description ( buildDescription ( directive , null ) ) . validLocations ( directiveLocation ) ; List < GraphQLArgument > arguments = directive . getArguments ( ) . stream ( ) . map ( arg -> buildDirectiveArgument ( arg , directiveDefinition ) ) . collect ( Collectors . toList ( ) ) ; if ( directiveDefinition . isPresent ( ) ) { arguments = transferMissingArguments ( arguments , directiveDefinition . get ( ) ) ; } arguments . forEach ( builder :: argument ) ; return builder . build ( ) ; |
public class DynamicAccessModule { /** * Maybe these methods ' exposure needs to be re - thought ? */
public String [ ] getObjectHistory ( Context context , String PID ) throws ServerException { } } | return da . getObjectHistory ( context , PID ) ; |
public class SelectionManager { /** * returns wheher the connector is connected to a shape not in the selection .
* As this could be connected to a nested shape , it iterates from that shape ( not in the selection ) until it finds it ' s parent in the selection or it returns null .
* @ param connector
* @ return */
private boolean isExternallyConnected ( final WiresConnector connector ) { } } | WiresShape headShape = null ; WiresShape tailShape = null ; if ( connector . getHeadConnection ( ) . getMagnet ( ) != null ) { headShape = connector . getHeadConnection ( ) . getMagnet ( ) . getMagnets ( ) . getWiresShape ( ) ; } if ( connector . getTailConnection ( ) . getMagnet ( ) != null ) { tailShape = connector . getTailConnection ( ) . getMagnet ( ) . getMagnets ( ) . getWiresShape ( ) ; } final boolean hasHeadShapeNotInSelection = ( headShape != null ) && ( m_selected . findParentIfInSelection ( headShape ) == null ) ; final boolean hasTailShapeNotInSelection = ( tailShape != null ) && ( m_selected . findParentIfInSelection ( tailShape ) == null ) ; return hasHeadShapeNotInSelection || hasTailShapeNotInSelection ; |
public class NumberUtils { /** * Produces an array with a sequence of integer numbers , using a step .
* @ param from value to start the sequence from
* @ param to value to produce the sequence to
* @ param step the step to be used
* @ return the Integer [ ] sequence
* @ since 2.0.9 */
public static Integer [ ] sequence ( final Integer from , final Integer to , final Integer step ) { } } | Validate . notNull ( from , "Value to start the sequence from cannot be null" ) ; Validate . notNull ( to , "Value to generate the sequence up to cannot be null" ) ; Validate . notNull ( step , "Step to generate the sequence cannot be null" ) ; final int iFrom = from . intValue ( ) ; final int iTo = to . intValue ( ) ; final int iStep = step . intValue ( ) ; if ( iFrom == iTo ) { return new Integer [ ] { Integer . valueOf ( iFrom ) } ; } if ( iStep == 0 ) { // with iStep = = 0 , this would only be valid if iFrom = = iTo , which it isn ' t - the rest are impossible
throw new IllegalArgumentException ( "Cannot create sequence from " + iFrom + " to " + iTo + " with step " + iStep ) ; } final List < Integer > values = new ArrayList < Integer > ( 10 ) ; if ( iFrom < iTo && iStep > 0 ) { int i = iFrom ; while ( i <= iTo ) { values . add ( Integer . valueOf ( i ) ) ; i += iStep ; } } else if ( iFrom > iTo && iStep < 0 ) { // iFrom > iTo
int i = iFrom ; while ( i >= iTo ) { values . add ( Integer . valueOf ( i ) ) ; i += iStep ; } } return values . toArray ( new Integer [ values . size ( ) ] ) ; |
public class FeatureTokens { /** * indexed getter for beginnings - gets an indexed value -
* @ generated
* @ param i index in the array to get
* @ return value of the element at index i */
public int getBeginnings ( int i ) { } } | if ( FeatureTokens_Type . featOkTst && ( ( FeatureTokens_Type ) jcasType ) . casFeat_beginnings == null ) jcasType . jcas . throwFeatMissing ( "beginnings" , "ch.epfl.bbp.uima.types.FeatureTokens" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( FeatureTokens_Type ) jcasType ) . casFeatCode_beginnings ) , i ) ; return jcasType . ll_cas . ll_getIntArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( FeatureTokens_Type ) jcasType ) . casFeatCode_beginnings ) , i ) ; |
public class DataSet { /** * Applies a Filter transformation on a { @ link DataSet } . < br / >
* The transformation calls a { @ link FilterFunction } for each element of the DataSet
* and retains only those element for which the function returns true . Elements for
* which the function returns false are filtered .
* @ param filter The FilterFunction that is called for each element of the DataSet .
* @ return A FilterOperator that represents the filtered DataSet .
* @ see FilterFunction
* @ see FilterOperator
* @ see DataSet */
public FilterOperator < T > filter ( FilterFunction < T > filter ) { } } | if ( filter == null ) { throw new NullPointerException ( "Filter function must not be null." ) ; } return new FilterOperator < T > ( this , filter ) ; |
public class CommonOps_DDRM { /** * Performs the following operation : < br >
* < br >
* c = & alpha ; * a < sup > T < / sup > * b < sup > T < / sup > < br >
* c < sub > ij < / sub > = & alpha ; & sum ; < sub > k = 1 : n < / sub > { a < sub > ki < / sub > * b < sub > jk < / sub > }
* @ param alpha Scaling factor .
* @ param a The left matrix in the multiplication operation . Not modified .
* @ param b The right matrix in the multiplication operation . Not modified .
* @ param c Where the results of the operation are stored . Modified . */
public static void multTransAB ( double alpha , DMatrix1Row a , DMatrix1Row b , DMatrix1Row c ) { } } | // TODO add a matrix vectory multiply here
if ( a . numCols >= EjmlParameters . MULT_TRANAB_COLUMN_SWITCH ) { MatrixMatrixMult_DDRM . multTransAB_aux ( alpha , a , b , c , null ) ; } else { MatrixMatrixMult_DDRM . multTransAB ( alpha , a , b , c ) ; } |
public class DeepSubtypeAnalysis { /** * Given two JavaClasses , try to estimate the probability that an reference
* of type x is also an instance of type y . Will return 0 only if it is
* impossible and 1 only if it is guaranteed .
* @ param x
* Known type of object
* @ param y
* Type queried about
* @ return 0 - 1 value indicating probability */
public static double deepInstanceOf ( JavaClass x , JavaClass y ) throws ClassNotFoundException { } } | return Analyze . deepInstanceOf ( x , y ) ; |
public class dnsaction64 { /** * Use this API to add dnsaction64 resources . */
public static base_responses add ( nitro_service client , dnsaction64 resources [ ] ) throws Exception { } } | base_responses result = null ; if ( resources != null && resources . length > 0 ) { dnsaction64 addresources [ ] = new dnsaction64 [ resources . length ] ; for ( int i = 0 ; i < resources . length ; i ++ ) { addresources [ i ] = new dnsaction64 ( ) ; addresources [ i ] . actionname = resources [ i ] . actionname ; addresources [ i ] . prefix = resources [ i ] . prefix ; addresources [ i ] . mappedrule = resources [ i ] . mappedrule ; addresources [ i ] . excluderule = resources [ i ] . excluderule ; } result = add_bulk_request ( client , addresources ) ; } return result ; |
public class MessageFormat { /** * Sets the Format object to use for the format elements within the
* previously set pattern string that use the given argument
* index .
* The argument index is part of the format element definition and
* represents an index into the < code > arguments < / code > array passed
* to the < code > format < / code > methods or the result array returned
* by the < code > parse < / code > methods .
* If the argument index is used for more than one format element
* in the pattern string , then the new format is used for all such
* format elements . If the argument index is not used for any format
* element in the pattern string , then the new format is ignored .
* This method is only supported when exclusively numbers are used for
* argument names . Otherwise an IllegalArgumentException is thrown .
* @ param argumentIndex the argument index for which to use the new format
* @ param newFormat the new format to use
* @ throws IllegalArgumentException if this format uses named arguments */
public void setFormatByArgumentIndex ( int argumentIndex , Format newFormat ) { } } | if ( msgPattern . hasNamedArguments ( ) ) { throw new IllegalArgumentException ( "This method is not available in MessageFormat objects " + "that use alphanumeric argument names." ) ; } for ( int partIndex = 0 ; ( partIndex = nextTopLevelArgStart ( partIndex ) ) >= 0 ; ) { if ( msgPattern . getPart ( partIndex + 1 ) . getValue ( ) == argumentIndex ) { setCustomArgStartFormat ( partIndex , newFormat ) ; } } |
public class EnumConstantWriterImpl { /** * { @ inheritDoc } */
protected Content getNavSummaryLink ( ClassDoc cd , boolean link ) { } } | if ( link ) { if ( cd == null ) { return writer . getHyperLink ( SectionName . ENUM_CONSTANT_SUMMARY , writer . getResource ( "doclet.navEnum" ) ) ; } else { return writer . getHyperLink ( SectionName . ENUM_CONSTANTS_INHERITANCE , configuration . getClassName ( cd ) , writer . getResource ( "doclet.navEnum" ) ) ; } } else { return writer . getResource ( "doclet.navEnum" ) ; } |
public class SlideShowView { /** * Pause the slide show */
public void pause ( ) { } } | switch ( status ) { case PAUSED : case STOPPED : return ; case PLAYING : status = Status . PAUSED ; // Remove all callbacks
slideHandler . removeCallbacksAndMessages ( null ) ; } |
public class JexlScriptExecutor { /** * 初始化function */
public void initialize ( ) { } } | if ( cacheSize <= 0 ) { // 不考虑cacheSize为0的情况 , 强制使用LRU cache机制
cacheSize = DEFAULT_CACHE_SIZE ; } functions = new HashMap < String , Object > ( ) ; engine = new ScriptJexlEngine ( ) ; engine . setCache ( cacheSize ) ; engine . setSilent ( true ) ; engine . setFunctions ( functions ) ; // 注册functions |
public class Preset { /** * Return the Maestrano API configuration as a hash
* @ param marketplace
* @ return metadata hash */
public Map < String , Object > toMetadataHash ( ) { } } | Map < String , Object > hash = new LinkedHashMap < String , Object > ( ) ; hash . put ( "marketplace" , marketplace ) ; hash . put ( "app" , app . toMetadataHash ( ) ) ; hash . put ( "api" , api . toMetadataHash ( ) ) ; hash . put ( "sso" , sso . toMetadataHash ( ) ) ; hash . put ( "connec" , connec . toMetadataHash ( ) ) ; hash . put ( "webhook" , webhook . toMetadataHash ( ) ) ; return hash ; |
public class VirtualMachineScaleSetRollingUpgradesInner { /** * Cancels the current virtual machine scale set rolling upgrade .
* @ param resourceGroupName The name of the resource group .
* @ param vmScaleSetName The name of the VM scale set .
* @ param serviceCallback the async ServiceCallback to handle successful and failed responses .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceFuture } object */
public ServiceFuture < OperationStatusResponseInner > cancelAsync ( String resourceGroupName , String vmScaleSetName , final ServiceCallback < OperationStatusResponseInner > serviceCallback ) { } } | return ServiceFuture . fromResponse ( cancelWithServiceResponseAsync ( resourceGroupName , vmScaleSetName ) , serviceCallback ) ; |
public class DefaultEngine { /** * Get template .
* @ param name - template name
* @ param locale - template locale
* @ param encoding - template encoding
* @ return template instance
* @ throws IOException - If an I / O error occurs
* @ throws ParseException - If the template cannot be parsed
* @ see # getEngine ( ) */
@ SuppressWarnings ( "unchecked" ) public Template getTemplate ( String name , Locale locale , String encoding , Object args ) throws IOException , ParseException { } } | name = UrlUtils . cleanName ( name ) ; locale = cleanLocale ( locale ) ; Map < Object , Object > cache = this . cache ; // safe copy reference
if ( cache == null ) { return parseTemplate ( null , name , locale , encoding , args ) ; } Resource resource = null ; long lastModified ; if ( reloadable ) { resource = loadResource ( name , locale , encoding ) ; lastModified = resource . getLastModified ( ) ; } else { lastModified = Long . MIN_VALUE ; } String key = name ; if ( locale != null || encoding != null ) { StringBuilder buf = new StringBuilder ( name . length ( ) + 20 ) ; buf . append ( name ) ; if ( locale != null ) { buf . append ( "_" ) ; buf . append ( locale ) ; } if ( encoding != null ) { buf . append ( "_" ) ; buf . append ( encoding ) ; } key = buf . toString ( ) ; } VolatileReference < Template > reference = ( VolatileReference < Template > ) cache . get ( key ) ; if ( reference == null ) { if ( cache instanceof ConcurrentMap ) { reference = new VolatileReference < Template > ( ) ; // quickly
VolatileReference < Template > old = ( VolatileReference < Template > ) ( ( ConcurrentMap < Object , Object > ) cache ) . putIfAbsent ( key , reference ) ; if ( old != null ) { // duplicate
reference = old ; } } else { synchronized ( cache ) { // cache lock
reference = ( VolatileReference < Template > ) cache . get ( key ) ; if ( reference == null ) { // double check
reference = new VolatileReference < Template > ( ) ; // quickly
cache . put ( key , reference ) ; } } } } assert ( reference != null ) ; Template template = reference . get ( ) ; if ( template == null || template . getLastModified ( ) < lastModified ) { synchronized ( reference ) { // reference lock
template = reference . get ( ) ; if ( template == null || template . getLastModified ( ) < lastModified ) { // double check
template = parseTemplate ( resource , name , locale , encoding , args ) ; // slowly
reference . set ( template ) ; } } } assert ( template != null ) ; return template ; |
public class TicketGrantingTicketImpl { /** * Update service and track session .
* @ param id the id
* @ param service the service
* @ param onlyTrackMostRecentSession the only track most recent session */
protected void trackServiceSession ( final String id , final Service service , final boolean onlyTrackMostRecentSession ) { } } | update ( ) ; service . setPrincipal ( getRoot ( ) . getAuthentication ( ) . getPrincipal ( ) . getId ( ) ) ; if ( onlyTrackMostRecentSession ) { val path = normalizePath ( service ) ; val existingServices = this . services . values ( ) ; existingServices . stream ( ) . filter ( existingService -> path . equals ( normalizePath ( existingService ) ) ) . findFirst ( ) . ifPresent ( existingServices :: remove ) ; } this . services . put ( id , service ) ; |
public class JSDocInfoBuilder { /** * Returns whether this builder is populated with information that can be
* used to { @ link # build } a { @ link JSDocInfo } object that has a
* fileoverview tag . */
public boolean isPopulatedWithFileOverview ( ) { } } | return isPopulated ( ) && ( currentInfo . hasFileOverview ( ) || currentInfo . isExterns ( ) || currentInfo . isNoCompile ( ) || currentInfo . isTypeSummary ( ) ) ; |
public class Tuple15 { /** * Split this tuple into two tuples of degree 12 and 3. */
public final Tuple2 < Tuple12 < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 > , Tuple3 < T13 , T14 , T15 > > split12 ( ) { } } | return new Tuple2 < > ( limit12 ( ) , skip12 ( ) ) ; |
public class CmsDisplayResource { /** * Prepends the site - root to the given URL . < p >
* @ param url the URL
* @ return the absolute URL */
private String prependSiteRoot ( String url ) { } } | String site = getCms ( ) . getRequestContext ( ) . getSiteRoot ( ) ; if ( CmsStringUtil . isEmptyOrWhitespaceOnly ( site ) || OpenCms . getSiteManager ( ) . isSharedFolder ( site ) ) { site = OpenCms . getSiteManager ( ) . getDefaultUri ( ) ; if ( CmsStringUtil . isEmptyOrWhitespaceOnly ( site ) || ( OpenCms . getSiteManager ( ) . getSiteForSiteRoot ( site ) == null ) ) { return OpenCms . getSiteManager ( ) . getWorkplaceServer ( ) + url ; } else { return OpenCms . getSiteManager ( ) . getSiteForSiteRoot ( site ) . getUrl ( ) + url ; } } return OpenCms . getSiteManager ( ) . getSiteForSiteRoot ( site ) . getUrl ( ) + url ; |
public class MediaTypeUtils { /** * Checks if the media type is supported by the service .
* @ param mediaType Internet media type for the file
* @ return true if it is supported , false if not . */
public static boolean isValidMediaType ( final String mediaType ) { } } | return ( mediaType != null ) && MEDIA_TYPES . values ( ) . contains ( mediaType . toLowerCase ( ) ) ; |
public class FactoryOrientationAlgs { /** * Estimates the orientation of a region by using a sliding window across the different potential
* angles .
* @ see OrientationSlidingWindow
* @ param config Configuration for algorithm . If null defaults will be used .
* @ param integralType Type of integral image being processed .
* @ return OrientationIntegral */
public static < II extends ImageGray < II > > OrientationIntegral < II > sliding_ii ( ConfigSlidingIntegral config , Class < II > integralType ) { } } | if ( config == null ) config = new ConfigSlidingIntegral ( ) ; config . checkValidity ( ) ; return ( OrientationIntegral < II > ) new ImplOrientationSlidingWindowIntegral ( config . objectRadiusToScale , config . samplePeriod , config . windowSize , config . radius , config . weightSigma , config . sampleWidth , integralType ) ; |
public class LibUtils { /** * Calculates the current OSType
* @ return The current OSType */
public static OSType calculateOS ( ) { } } | String vendor = System . getProperty ( "java.vendor" ) ; if ( "The Android Project" . equals ( vendor ) ) { return OSType . ANDROID ; } String osName = System . getProperty ( "os.name" ) ; osName = osName . toLowerCase ( Locale . ENGLISH ) ; if ( osName . startsWith ( "mac os" ) ) { return OSType . APPLE ; } if ( osName . startsWith ( "windows" ) ) { return OSType . WINDOWS ; } if ( osName . startsWith ( "linux" ) ) { return OSType . LINUX ; } if ( osName . startsWith ( "sun" ) ) { return OSType . SUN ; } return OSType . UNKNOWN ; |
public class DataLoader { /** * Normally { @ link # dispatch ( ) } is an asynchronous operation but this version will ' join ' on the
* results if dispatch and wait for them to complete . If the { @ link CompletableFuture } callbacks make more
* calls to this data loader then the { @ link # dispatchDepth ( ) } will be & gt ; 0 and this method will loop
* around and wait for any other extra batch loads to occur .
* @ return the list of all results when the { @ link # dispatchDepth ( ) } reached 0 */
public List < V > dispatchAndJoin ( ) { } } | List < V > results = new ArrayList < > ( ) ; List < V > joinedResults = dispatch ( ) . join ( ) ; results . addAll ( joinedResults ) ; while ( this . dispatchDepth ( ) > 0 ) { joinedResults = dispatch ( ) . join ( ) ; results . addAll ( joinedResults ) ; } return results ; |
public class IRFactory { /** * This reduces the cost of these properties to O ( nodes ) to O ( files ) . */
private Node createTemplateNode ( ) { } } | // The Node type choice is arbitrary .
Node templateNode = new Node ( Token . SCRIPT ) ; templateNode . setStaticSourceFile ( sourceFile ) ; return templateNode ; |
public class EMatrixUtils { /** * Returns a new matrix by subtracting elements column by column .
* @ param matrix The input matrix
* @ param vector The vector to be subtracted from columns
* @ return A new matrix of which the vector is subtracted column by column */
public static RealMatrix colSubtract ( RealMatrix matrix , double [ ] vector ) { } } | // Declare and initialize the new matrix :
double [ ] [ ] retval = new double [ matrix . getRowDimension ( ) ] [ matrix . getColumnDimension ( ) ] ; // Iterate over rows :
for ( int col = 0 ; col < retval . length ; col ++ ) { // Iterate over columns :
for ( int row = 0 ; row < retval [ 0 ] . length ; row ++ ) { retval [ row ] [ col ] = matrix . getEntry ( row , col ) - vector [ row ] ; } } // Done , return a new matrix :
return MatrixUtils . createRealMatrix ( retval ) ; |
public class Parameters { /** * Returns the specified namespace joined into a string , for example { @ code " foo . bar " } for { @ code
* [ " foo " , " bar " ] } . The namespace may consist of any number of elements , including none at all .
* No element in the namespace may begin or end with a period . */
public static String joinNamespace ( final List < String > namespace ) { } } | for ( final String element : namespace ) { checkArgument ( ! element . startsWith ( DELIM ) , "Namespace element may not begin with a period: " + element ) ; checkArgument ( ! element . endsWith ( DELIM ) , "Namespace element may not end with a period: " + element ) ; } return JOINER . join ( namespace ) ; |
public class CmsHtmlParser { /** * Collapse HTML whitespace in the given String . < p >
* @ param string the string to collapse
* @ return the input String with all HTML whitespace collapsed */
protected String collapse ( String string ) { } } | int len = string . length ( ) ; StringBuffer result = new StringBuffer ( len ) ; int state = 0 ; for ( int i = 0 ; i < len ; i ++ ) { char c = string . charAt ( i ) ; switch ( c ) { // see HTML specification section 9.1 White space
// http : / / www . w3 . org / TR / html4 / struct / text . html # h - 9.1
case '\u0020' : case '\u0009' : case '\u000C' : case '\u200B' : case '\r' : case '\n' : if ( 0 != state ) { state = 1 ; } break ; default : if ( 1 == state ) { result . append ( ' ' ) ; } state = 2 ; result . append ( c ) ; } } return result . toString ( ) ; |
public class Properties { /** * Sets the " raw " comment for the specified key . Each line of the
* comment must be either empty , whitespace - only , or preceded by a
* comment marker ( " # " or " ! " ) . This is not enforced by this class .
* < br >
* Note : if you set a comment , you must set a corresponding value before
* calling store or storeToXML .
* @ param key property key whose comment should be set
* @ param rawComment raw comment to go with property key , " " for no comment */
public void setRawComment ( String key , String rawComment ) { } } | if ( rawComment == null ) throw new NullPointerException ( ) ; Entry entry = props . get ( key ) ; if ( entry == null ) { entry = new Entry ( rawComment , null ) ; props . put ( key , entry ) ; } else { entry . setRawComment ( rawComment ) ; } |
public class AttributeValue { /** * An attribute of type Binary Set . For example :
* < code > " BS " : [ " U3Vubnk = " , " UmFpbnk = " , " U25vd3k = " ] < / code >
* @ param bS
* An attribute of type Binary Set . For example : < / p >
* < code > " BS " : [ " U3Vubnk = " , " UmFpbnk = " , " U25vd3k = " ] < / code > */
public void setBS ( java . util . Collection < java . nio . ByteBuffer > bS ) { } } | if ( bS == null ) { this . bS = null ; return ; } this . bS = new java . util . ArrayList < java . nio . ByteBuffer > ( bS ) ; |
public class Monitors { /** * Creates a monitor config based on an annotation . */
private static MonitorConfig newConfig ( Class < ? > c , String defaultName , String id , com . netflix . servo . annotations . Monitor anno , TagList tags ) { } } | String name = anno . name ( ) ; if ( name . isEmpty ( ) ) { name = defaultName ; } MonitorConfig . Builder builder = MonitorConfig . builder ( name ) ; builder . withTag ( "class" , className ( c ) ) ; builder . withTag ( anno . type ( ) ) ; builder . withTag ( anno . level ( ) ) ; if ( tags != null ) { builder . withTags ( tags ) ; } if ( id != null ) { builder . withTag ( "id" , id ) ; } return builder . build ( ) ; |
public class PGXADataSourceFactory { /** * All the other PostgreSQL DataSource use PGObjectFactory directly , but we can ' t do that with
* PGXADataSource because referencing PGXADataSource from PGObjectFactory would break
* " JDBC2 Enterprise " edition build which doesn ' t include PGXADataSource . */
public Object getObjectInstance ( Object obj , Name name , Context nameCtx , Hashtable < ? , ? > environment ) throws Exception { } } | Reference ref = ( Reference ) obj ; String className = ref . getClassName ( ) ; if ( className . equals ( "org.postgresql.xa.PGXADataSource" ) ) { return loadXADataSource ( ref ) ; } else { return null ; } |
public class Lexicon { /** * Returns a { @ link Function } that delegates to { @ code function } and falls back to
* { @ code defaultFunction } for null return values . */
static < F , T > Function < F , T > fallback ( Function < F , T > function , Function < ? super F , ? extends T > defaultFunction ) { } } | return from -> { T result = function . apply ( from ) ; return result == null ? defaultFunction . apply ( from ) : result ; } ; |
public class InternalXbaseParser { /** * InternalXbase . g : 367:1 : ruleXOtherOperatorExpression : ( ( rule _ _ XOtherOperatorExpression _ _ Group _ _ 0 ) ) ; */
public final void ruleXOtherOperatorExpression ( ) throws RecognitionException { } } | int stackSize = keepStackSize ( ) ; try { // InternalXbase . g : 371:2 : ( ( ( rule _ _ XOtherOperatorExpression _ _ Group _ _ 0 ) ) )
// InternalXbase . g : 372:2 : ( ( rule _ _ XOtherOperatorExpression _ _ Group _ _ 0 ) )
{ // InternalXbase . g : 372:2 : ( ( rule _ _ XOtherOperatorExpression _ _ Group _ _ 0 ) )
// InternalXbase . g : 373:3 : ( rule _ _ XOtherOperatorExpression _ _ Group _ _ 0 )
{ if ( state . backtracking == 0 ) { before ( grammarAccess . getXOtherOperatorExpressionAccess ( ) . getGroup ( ) ) ; } // InternalXbase . g : 374:3 : ( rule _ _ XOtherOperatorExpression _ _ Group _ _ 0 )
// InternalXbase . g : 374:4 : rule _ _ XOtherOperatorExpression _ _ Group _ _ 0
{ pushFollow ( FOLLOW_2 ) ; rule__XOtherOperatorExpression__Group__0 ( ) ; state . _fsp -- ; if ( state . failed ) return ; } if ( state . backtracking == 0 ) { after ( grammarAccess . getXOtherOperatorExpressionAccess ( ) . getGroup ( ) ) ; } } } } catch ( RecognitionException re ) { reportError ( re ) ; recover ( input , re ) ; } finally { restoreStackSize ( stackSize ) ; } return ; |
public class SignatureConverter { /** * Convenience method for generating a method signature in human readable
* form .
* @ param className
* name of the class containing the method
* @ param methodName
* the name of the method
* @ param methodSig
* the signature of the method */
public static String convertMethodSignature ( String className , String methodName , String methodSig ) { } } | return convertMethodSignature ( className , methodName , methodSig , "" ) ; |
public class AbstractKubernetesResourceProvider { /** * Get the value ( ) from the specified annotation using reflection .
* @ param annotation
* The annotation . */
private String getAnnotationValue ( Annotation annotation ) { } } | Class < ? extends Annotation > type = annotation . annotationType ( ) ; try { Method method = type . getDeclaredMethod ( VALUE ) ; return String . valueOf ( method . invoke ( annotation , NO_ARGS ) ) ; } catch ( NoSuchMethodException e ) { return null ; } catch ( InvocationTargetException e ) { return null ; } catch ( IllegalAccessException e ) { return null ; } |
public class MariaDbStatement { /** * Retrieves the current result as an update count ; if the result is a ResultSet object or there
* are no more results , - 1 is returned . This method should be called only once per result .
* @ return the current result as an update count ; - 1 if the current result is a ResultSet object
* or there are no more results */
public int getUpdateCount ( ) { } } | if ( results != null && results . getCmdInformation ( ) != null && ! results . isBatch ( ) ) { return results . getCmdInformation ( ) . getUpdateCount ( ) ; } return - 1 ; |
public class BusNetwork { /** * Add a bus line inside the bus network .
* @ param busLine is the bus line to insert .
* @ return < code > true < / code > if the bus line was added , otherwise < code > false < / code > */
public boolean addBusLine ( BusLine busLine ) { } } | if ( busLine == null ) { return false ; } if ( this . busLines . indexOf ( busLine ) != - 1 ) { return false ; } if ( ! this . busLines . add ( busLine ) ) { return false ; } final boolean isValidLine = busLine . isValidPrimitive ( ) ; busLine . setEventFirable ( isEventFirable ( ) ) ; busLine . setContainer ( this ) ; if ( isEventFirable ( ) ) { fireShapeChanged ( new BusChangeEvent ( this , BusChangeEventType . LINE_ADDED , busLine , this . busLines . size ( ) - 1 , "shape" , // $ NON - NLS - 1 $
null , null ) ) ; if ( ! isValidLine ) { revalidate ( ) ; } else { checkPrimitiveValidity ( ) ; } } return true ; |
public class FileObjectReaderImpl { /** * { @ inheritDoc } */
public long read ( OutputStream stream , long length ) throws IOException { } } | if ( stream instanceof FileOutputStream ) { // use NIO
return channel . transferTo ( 0 , length , ( ( FileOutputStream ) stream ) . getChannel ( ) ) ; } else { // bytes copy
ByteBuffer buff = ByteBuffer . allocate ( SerializationConstants . INTERNAL_BUFFER_SIZE ) ; int r ; int readed = 0 ; while ( ( r = channel . read ( buff ) ) <= 0 ) { stream . write ( buff . array ( ) , 0 , r ) ; buff . rewind ( ) ; readed += r ; } return readed ; } |
public class RuntimeUtil { /** * Executes an external command and provides results of execution .
* Will accumulate limited output from the external process .
* @ param command array containing the command to call and its arguments .
* @ param maxBuffer max size of buffers < code > out , err < / code > . An external process may produce a
* lot of output , be careful setting to a large value . The buffer will not be allocated to this
* this size at the start , but will grow until it reaches it . The program will continue toi execute , and the buffer
* will be ' tailing ' the output of the external process .
* @ return instance of { @ link Response } with result of execution . */
public static Response execute ( int maxBuffer , String ... command ) { } } | if ( command . length == 0 ) { throw new IllegalArgumentException ( "Command must be provided." ) ; } String [ ] commandAndArgs = command . length == 1 && command [ 0 ] . contains ( " " ) ? Util . split ( command [ 0 ] , " " ) : command ; try { Process process = Runtime . getRuntime ( ) . exec ( commandAndArgs ) ; OutputReader stdOutReader = new OutputReader ( process . getInputStream ( ) , maxBuffer ) ; OutputReader stdErrReader = new OutputReader ( process . getErrorStream ( ) , maxBuffer ) ; Thread t1 = new Thread ( stdOutReader ) ; t1 . start ( ) ; Thread t2 = new Thread ( stdErrReader ) ; t2 . start ( ) ; int code = process . waitFor ( ) ; t1 . join ( ) ; t2 . join ( ) ; String out = stdOutReader . getOutput ( ) ; String err = stdErrReader . getOutput ( ) ; return new Response ( out , err , code ) ; } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; throw new RuntimeException ( "Interrupted" ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } |
public class WriterBasedGenerator { /** * Method called to append escape sequence for given character , at the
* end of standard output buffer ; or if not possible , write out directly . */
private final void _appendCharacterEscape ( char ch , int escCode ) throws IOException , JsonGenerationException { } } | if ( escCode >= 0 ) { // \ \ N ( 2 char )
if ( ( _outputTail + 2 ) > _outputEnd ) { _flushBuffer ( ) ; } _outputBuffer [ _outputTail ++ ] = '\\' ; _outputBuffer [ _outputTail ++ ] = ( char ) escCode ; return ; } if ( escCode != CharacterEscapes . ESCAPE_CUSTOM ) { // std , \ \ uXXXX
if ( ( _outputTail + 2 ) > _outputEnd ) { _flushBuffer ( ) ; } int ptr = _outputTail ; char [ ] buf = _outputBuffer ; buf [ ptr ++ ] = '\\' ; buf [ ptr ++ ] = 'u' ; // We know it ' s a control char , so only the last 2 chars are non - 0
if ( ch > 0xFF ) { // beyond 8 bytes
int hi = ( ch >> 8 ) & 0xFF ; buf [ ptr ++ ] = HEX_CHARS [ hi >> 4 ] ; buf [ ptr ++ ] = HEX_CHARS [ hi & 0xF ] ; ch &= 0xFF ; } else { buf [ ptr ++ ] = '0' ; buf [ ptr ++ ] = '0' ; } buf [ ptr ++ ] = HEX_CHARS [ ch >> 4 ] ; buf [ ptr ] = HEX_CHARS [ ch & 0xF ] ; _outputTail = ptr ; return ; } |
public class Main { /** * Calculate the nth centered hexagonal number .
* Examples :
* > > > nth _ centered _ hexagonal _ num ( 10)
* 271
* > > > nth _ centered _ hexagonal _ num ( 2)
* > > > nth _ centered _ hexagonal _ num ( 9)
* 217
* @ param index : The nth position of the centered hexagonal number series to return
* @ return : The nth centered hexagonal number */
public static int nth_centered_hexagonal_num ( int index ) { } public static void main ( String [ ] args ) { System . out . println ( nth_centered_hexagonal_num ( 10 ) ) ; System . out . println ( nth_centered_hexagonal_num ( 2 ) ) ; System . out . println ( nth_centered_hexagonal_num ( 9 ) ) ; } } | return 3 * index * ( index - 1 ) + 1 ; |
public class Combinations { /** * Extracts the entire bucket . Will add elements to the provided list or create a new one
* @ param storage Optional storage . If null a list is created . clear ( ) is automatically called .
* @ return List containing the bucket */
public List < T > getBucket ( List < T > storage ) { } } | if ( storage == null ) storage = new ArrayList < T > ( ) ; else storage . clear ( ) ; for ( int i = 0 ; i < bins . length ; i ++ ) { storage . add ( a . get ( bins [ i ] ) ) ; } return storage ; |
public class AttributeDataset { /** * Returns a column . */
public AttributeVector column ( String col ) { } } | int i = - 1 ; for ( int j = 0 ; j < attributes . length ; j ++ ) { if ( attributes [ j ] . getName ( ) . equals ( col ) ) { i = j ; break ; } } if ( i == - 1 ) { throw new IllegalArgumentException ( "Invalid column name: " + col ) ; } return column ( i ) ; |
public class XForLoopExpressionImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public boolean eIsSet ( int featureID ) { } } | switch ( featureID ) { case XbasePackage . XFOR_LOOP_EXPRESSION__FOR_EXPRESSION : return forExpression != null ; case XbasePackage . XFOR_LOOP_EXPRESSION__EACH_EXPRESSION : return eachExpression != null ; case XbasePackage . XFOR_LOOP_EXPRESSION__DECLARED_PARAM : return declaredParam != null ; } return super . eIsSet ( featureID ) ; |
public class DefaultDOManager { /** * Gets a list of the requested next available PIDs . the number of PIDs .
* @ param numPIDs
* The number of PIDs to generate . Defaults to 1 if the number is
* not a positive integer .
* @ param namespace
* The namespace to be used when generating the PIDs . If null ,
* the namespace defined by the < i > pidNamespace < / i > parameter in
* the fedora . fcfg configuration file is used .
* @ return An array of PIDs .
* @ throws ServerException
* If an error occurs in generating the PIDs . */
@ Override public String [ ] getNextPID ( int numPIDs , String namespace ) throws ServerException { } } | if ( numPIDs < 1 ) { numPIDs = 1 ; } String [ ] pidList = new String [ numPIDs ] ; if ( namespace == null || namespace . isEmpty ( ) ) { namespace = m_pidNamespace ; } try { for ( int i = 0 ; i < numPIDs ; i ++ ) { pidList [ i ] = m_pidGenerator . generatePID ( namespace ) . toString ( ) ; } return pidList ; } catch ( IOException ioe ) { throw new GeneralException ( "DefaultDOManager.getNextPID: Error " + "generating PID, PIDGenerator returned unexpected error: (" + ioe . getClass ( ) . getName ( ) + ") - " + ioe . getMessage ( ) ) ; } |
public class RelationExtractor { /** * read predictions */
private List readPredictionFile ( File pred ) throws IOException { } } | List list = new ArrayList ( ) ; LineNumberReader lr = new LineNumberReader ( new FileReader ( pred ) ) ; String line = null ; while ( ( line = lr . readLine ( ) ) != null ) { // logger . debug ( line ) ;
list . add ( new Double ( line . trim ( ) ) ) ; } // end while
lr . close ( ) ; return list ; |
public class ClockSkewDetector { /** * Attach the current client time to the { { @ link # mDev } identifier .
* if clientTime is null , the current time is used .
* @ param clientTime the supplied client time , use null for current time
* @ throws IfmapErrorResult
* @ throws IfmapException */
private void publishTime ( Calendar clientTime ) throws IfmapErrorResult , IfmapException { } } | PublishElement pu ; PublishRequest pr ; String date = DateHelpers . getUtcTimeAsIso8601 ( clientTime ) ; Document timeMd = mMetadataFac . createClientTime ( date ) ; pu = Requests . createPublishUpdate ( mDev , timeMd , MetadataLifetime . session ) ; pr = Requests . createPublishReq ( pu ) ; mSsrc . publish ( pr ) ; |
public class SeaGlassStyle { /** * Getter for a region specific style property .
* < p > Overridden to cause this style to populate itself with data from
* UIDefaults , if necessary . < / p >
* < p > Properties in UIDefaults may be specified in a chained manner . For
* example : < / p >
* < pre >
* background
* Button . opacity
* Button . Enabled . foreground
* Button . Enabled + Selected . background
* < / pre >
* < p > In this example , suppose you were in the Enabled + Selected state and
* searched for " foreground " . In this case , we first check for
* Button . Enabled + Selected . foreground , but no such color exists . We then
* fall back to the next valid state , in this case ,
* Button . Enabled . foreground , and have a match . So we return it . < / p >
* < p > Again , if we were in the state Enabled and looked for " background " , we
* wouldn ' t find it in Button . Enabled , or in Button , but would at the top
* level in UIManager . So we return that value . < / p >
* < p > One special note : the " key " passed to this method could be of the form
* " background " or " Button . background " where " Button " equals the prefix
* passed to the SeaGlassStyle constructor . In either case , it looks for
* " background " . < / p >
* @ param ctx SynthContext identifying requester
* @ param key Property being requested . Must not be null .
* @ return Value of the named property * */
@ Override public Object get ( SynthContext ctx , Object key ) { } } | Values v = getValues ( ctx ) ; // strip off the prefix , if there is one .
String fullKey = key . toString ( ) ; String partialKey = fullKey . substring ( fullKey . indexOf ( "." ) + 1 ) ; Object obj = null ; int xstate = getExtendedState ( ctx , v ) ; // check the cache
tmpKey . init ( partialKey , xstate ) ; obj = v . cache . get ( tmpKey ) ; boolean wasInCache = obj != null ; if ( ! wasInCache ) { // Search exact matching states and then lesser matching states
RuntimeState s = null ; int [ ] lastIndex = new int [ ] { - 1 } ; while ( obj == null && ( s = getNextState ( v . states , lastIndex , xstate ) ) != null ) { obj = s . defaults . get ( partialKey ) ; } // Search Region Defaults
if ( obj == null && v . defaults != null ) { obj = v . defaults . get ( partialKey ) ; } // return found object
// Search UIManager Defaults
if ( obj == null ) obj = UIManager . get ( fullKey ) ; // Search Synth Defaults for InputMaps
if ( obj == null && partialKey . equals ( "focusInputMap" ) ) { obj = super . get ( ctx , fullKey ) ; } // if all we got was a null , store this fact for later use
v . cache . put ( new CacheKey ( partialKey , xstate ) , obj == null ? NULL : obj ) ; } // return found object
return obj == NULL ? null : obj ; |
public class CommonUtils { /** * Returns XSD declaration of given property . */
public static XSDeclaration getXsdDeclaration ( CPropertyInfo propertyInfo ) { } } | XSComponent schemaComponent = propertyInfo . getSchemaComponent ( ) ; if ( ! ( schemaComponent instanceof XSParticle ) ) { // XSComplexType for example :
return null ; } XSTerm term = ( ( XSParticle ) schemaComponent ) . getTerm ( ) ; if ( ! ( term instanceof XSDeclaration ) ) { // XSModelGroup for example :
return null ; } return ( XSDeclaration ) term ; |
public class MappeableBitmapContainer { /** * Find the index of the previous set bit less than or equal to i , returns - 1 if none found .
* @ param i starting index
* @ return index of the previous set bit */
public int prevSetBit ( final int i ) { } } | int x = i >> 6 ; // signed i / 64
long w = bitmap . get ( x ) ; w <<= 64 - i - 1 ; if ( w != 0 ) { return i - Long . numberOfLeadingZeros ( w ) ; } for ( -- x ; x >= 0 ; -- x ) { long X = bitmap . get ( x ) ; if ( X != 0 ) { return x * 64 + 63 - Long . numberOfLeadingZeros ( X ) ; } } return - 1 ; |
public class ControlFilter { /** * ( non - Javadoc )
* @ see
* org . fcrepo . server . security . xacml . pep . rest . filters . RESTFilter # handleRequest ( javax . servlet
* . http . HttpServletRequest , javax . servlet . http . HttpServletResponse ) */
@ Override public RequestCtx handleRequest ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { } } | RequestCtx req = null ; String action = request . getParameter ( "action" ) ; if ( action == null ) { throw new ServletException ( "Invalid request, action parameter must be specified." ) ; } Map < URI , AttributeValue > actions = new HashMap < URI , AttributeValue > ( ) ; Map < URI , AttributeValue > resAttr ; try { resAttr = ResourceAttributes . getRepositoryResources ( ) ; // note - no API specified in legacy XACML , so none specified here
/* actions . put ( Constants . ACTION . API . getURI ( ) ,
Constants . ACTION . APIA . getStringAttribute ( ) ) ) ; */
if ( action . equals ( "status" ) ) { actions . put ( Constants . ACTION . ID . getURI ( ) , Constants . ACTION . SERVER_STATUS . getStringAttribute ( ) ) ; } else if ( action . equals ( "reloadPolicies" ) ) { actions . put ( Constants . ACTION . ID . getURI ( ) , Constants . ACTION . RELOAD_POLICIES . getStringAttribute ( ) ) ; } else if ( action . equals ( "modifyDatastreamControlGroup" ) ) { // FCREPO - 765 , no specific URI defined for this operation
actions . put ( Constants . ACTION . ID . getURI ( ) , Constants . ACTION . RELOAD_POLICIES . getStringAttribute ( ) ) ; } else { throw new ServletException ( "Invalid request, invalid action parameter specified:" + action ) ; } req = getContextHandler ( ) . buildRequest ( getSubjects ( request ) , actions , resAttr , getEnvironment ( request ) ) ; LogUtil . statLog ( request . getRemoteUser ( ) , Constants . ACTION . LIST_METHODS . uri , Constants . FEDORA_REPOSITORY_PID . uri , null ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; throw new ServletException ( e ) ; } return req ; |
public class WildPath { /** * convertFileWildCardToRegx .
* @ param wildcard a { @ link java . lang . String } object .
* @ return a { @ link java . util . regex . Pattern } object . */
public static Pattern convertFileWildCardToRegx ( final String wildcard ) { } } | String regex = wildcard ; regex = regex . replaceAll ( "[.]" , "\\\\." ) ; regex = regex . replaceAll ( "[?]" , "." ) ; regex = regex . replaceAll ( "[*]" , ".*" ) ; return Pattern . compile ( "^" + regex + "$" , Pattern . CASE_INSENSITIVE ) ; |
public class DigestAuthHeaderFunction { /** * Generates digest hexadecimal string representation of a key with given
* algorithm .
* @ param algorithm
* @ param key
* @ return */
private String getDigestHex ( String algorithm , String key ) { } } | if ( algorithm . equals ( "md5" ) ) { return DigestUtils . md5Hex ( key ) ; } else if ( algorithm . equals ( "sha" ) ) { return DigestUtils . shaHex ( key ) ; } throw new CitrusRuntimeException ( "Unsupported digest algorithm: " + algorithm ) ; |
public class QuotedStringTokenizer { @ Override public String nextToken ( ) throws NoSuchElementException { } } | if ( ! hasMoreTokens ( ) || _token == null ) throw new NoSuchElementException ( ) ; String t = _token . toString ( ) ; _token . setLength ( 0 ) ; _hasToken = false ; return t ; |
public class ClassNodeUtils { /** * Return true if we have a static accessor */
public static boolean hasPossibleStaticProperty ( ClassNode cNode , String methodName ) { } } | // assume explicit static method call checked first so we can assume a simple check here
if ( ! methodName . startsWith ( "get" ) && ! methodName . startsWith ( "is" ) ) { return false ; } String propName = getPropNameForAccessor ( methodName ) ; PropertyNode pNode = getStaticProperty ( cNode , propName ) ; return pNode != null && ( methodName . startsWith ( "get" ) || boolean_TYPE . equals ( pNode . getType ( ) ) ) ; |
public class BatchedTimeoutManager { /** * The group alarm call . The context on this call will be null . */
public void alarm ( Object context ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "alarm" , context ) ; btmLockManager . lock ( ) ; boolean btmLocked = true ; timeoutLockManager . lockExclusive ( ) ; boolean timeoutLocked = true ; try { // we won ' t be called unless there are alarms which have timedout but check anyway
if ( ! timedout . isEmpty ( ) && ! isStopped ) { btmLockManager . unlock ( ) ; btmLocked = false ; // see defect 280069:
// So that we can release the exclusive lock before calling processTimedoutEntries
// ( and so avoid deadlock on streamStatus monitor ) we take a local copy
// ( which therefore cannot be modified by anyone behind us ) and create
// a new list ; this replaces holding the exclusive lock for the duration of the method
// and then clearing the list at the end .
List tempTimeoutList = timedout ; // take a local copy of the list
timedout = new ArrayList < BatchedTimeoutEntry > ( ) ; // the timeout entries will be dealt with
// presently . Meantime we empty the timedout list so that subsequent timeouts
// can be added to it without affecting processTimedoutEntries
timeoutLockManager . unlockExclusive ( ) ; // we no longer care if timedout
timeoutLocked = false ; // changes underneath us so we can release the exclusive lock .
try { // call the processor with the list of timedout BTEs , which should not be changed
handler . processTimedoutEntries ( tempTimeoutList ) ; // We had a good batch - clear any previous failures
batchFailed = false ; batchCleared = false ; } catch ( Throwable e ) { // FFDC the problem with the alarm , but don ' t re - throw the exception
FFDCFilter . processException ( e , "com.ibm.ws.sib.processor.utils.am.BatchedTimeoutManager.alarm" , "1:280:1.24" , new Object [ ] { this , handler , tempTimeoutList } ) ; SibTr . exception ( tc , e ) ; // Alarms registered with the BatchedTimeoutManager are set to auto - repeat ,
// if we simply report the failure in an alarm it ' ll probably happen again
// and again , forever . So we need to take steps to stop that happening , by
// removing entries and possibly even stopping the manager ( athough as a manager
// is specific to a certain object ( e . g . a specific AOStream ) the damage should
// be contained - although still serious .
// We worked the previous time so we ' ll give the alarms one more try before
// bombing out
if ( ! batchFailed ) batchFailed = true ; // If we ' ve failed before , this was our last chance , something is wrong with
// at least one of the entries , but we can ' t tell which one so we ' ll have to
// remove all the entries - which will stop the error happening over and over
// again ( but not fix the reason for the error ! )
else { batchFailed = false ; // Remove all the entries and see if that stops the error happening
Iterator itr = tempTimeoutList . iterator ( ) ; while ( itr . hasNext ( ) ) { BatchedTimeoutEntry bte = ( BatchedTimeoutEntry ) itr . next ( ) ; removeTimeoutEntry ( bte ) ; } // If we ' ve already been here and cleared the entries but something has
// reregistered a new alarm that caused another problem ( probably the same
// one ) we just give up and stop the alarm manager to prevent new alarms
// being registered
if ( batchCleared ) { // This is serious , throw another FFDC
SIErrorException e2 = new SIErrorException ( nls . getFormattedMessage ( "INTERNAL_MESSAGING_ERROR_CWSIP0001" , new Object [ ] { "com.ibm.ws.sib.processor.utils.am.BatchedTimeoutManager.alarm" , "1:325:1.24" } , null ) , e ) ; FFDCFilter . processException ( e2 , "com.ibm.ws.sib.processor.utils.am.BatchedTimeoutManager.alarm" , "1:331:1.24" , this ) ; SibTr . exception ( tc , e2 ) ; // Stop the timer
stopTimer ( ) ; } // Remember that we ' ve just cleared up after a problem
else batchCleared = true ; } } // restart the entries
restartEntries ( tempTimeoutList ) ; } } finally { if ( timeoutLocked ) timeoutLockManager . unlockExclusive ( ) ; if ( btmLocked ) btmLockManager . unlock ( ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "alarm" ) ; |
public class JavaDate2SqlTimestampFieldConversion { /** * @ see FieldConversion # sqlToJava ( Object ) */
public Object sqlToJava ( Object source ) { } } | if ( source instanceof java . sql . Timestamp ) { return new java . util . Date ( ( ( java . sql . Timestamp ) source ) . getTime ( ) ) ; } else { return source ; } |
public class BatchListObjectParentPathsResponseMarshaller { /** * Marshall the given parameter object . */
public void marshall ( BatchListObjectParentPathsResponse batchListObjectParentPathsResponse , ProtocolMarshaller protocolMarshaller ) { } } | if ( batchListObjectParentPathsResponse == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( batchListObjectParentPathsResponse . getPathToObjectIdentifiersList ( ) , PATHTOOBJECTIDENTIFIERSLIST_BINDING ) ; protocolMarshaller . marshall ( batchListObjectParentPathsResponse . getNextToken ( ) , NEXTTOKEN_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class ControlBeanContextServicesSupport { /** * Try to find the registered service for a service object instance .
* May return null if the object instance is not from a service registered
* with this service provider .
* @ return Service class for service instance .
* @ throws IllegalArgumentException if service class can not be found . */
private Class findServiceClass ( Object service ) { } } | for ( Class sc : _serviceProviders . keySet ( ) ) { if ( sc . isInstance ( service ) ) { return sc ; } } throw new IllegalArgumentException ( "Cannot find service provider for: " + service . getClass ( ) . getCanonicalName ( ) ) ; |
public class NetworkMessageEntity { /** * Read the first byte to retrieve the total number of key and call { @ link # decode ( DataInputStream , int ) for each
* key } .
* @ param buffer The current buffer to read .
* @ throws IOException Exception in case of error . */
@ Override protected void decode ( DataInputStream buffer ) throws IOException { } } | entityId = buffer . readShort ( ) ; final int number = buffer . readByte ( ) ; for ( int i = 0 ; i < number ; i ++ ) { decode ( buffer , i ) ; } |
public class _Private_IonTextAppender { /** * LOBs */
public void printBlob ( _Private_IonTextWriterBuilder _options , byte [ ] value , int start , int len ) throws IOException { } } | if ( value == null ) { appendAscii ( "null.blob" ) ; return ; } @ SuppressWarnings ( "resource" ) TextStream ts = new TextStream ( new ByteArrayInputStream ( value , start , len ) ) ; // base64 encoding is 6 bits per char so
// it evens out at 3 bytes in 4 characters
char [ ] buf = new char [ _options . isPrettyPrintOn ( ) ? 80 : 400 ] ; CharBuffer cb = CharBuffer . wrap ( buf ) ; if ( _options . _blob_as_string ) { appendAscii ( '"' ) ; } else { appendAscii ( "{{" ) ; if ( _options . isPrettyPrintOn ( ) ) { appendAscii ( ' ' ) ; } } for ( ; ; ) { // TODO is it better to fill up the CharBuffer before outputting ?
int clen = ts . read ( buf , 0 , buf . length ) ; if ( clen < 1 ) break ; appendAscii ( cb , 0 , clen ) ; } if ( _options . _blob_as_string ) { appendAscii ( '"' ) ; } else { if ( _options . isPrettyPrintOn ( ) ) { appendAscii ( ' ' ) ; } appendAscii ( "}}" ) ; } |
public class DefaultGroovyMethods { /** * Drops the given number of key / value pairs from the head of this map if they are available .
* < pre class = " groovyTestCase " >
* def strings = [ ' a ' : 10 , ' b ' : 20 , ' c ' : 30 ]
* assert strings . drop ( 0 ) = = [ ' a ' : 10 , ' b ' : 20 , ' c ' : 30 ]
* assert strings . drop ( 2 ) = = [ ' c ' : 30 ]
* assert strings . drop ( 5 ) = = [ : ]
* < / pre >
* If the map instance does not have ordered keys , then this function could drop a random < code > num < / code >
* entries . Groovy by default uses LinkedHashMap , so this shouldn ' t be an issue in the main .
* @ param self the original map
* @ param num the number of elements to drop from this map
* @ return a map consisting of all key / value pairs of this map except the first
* < code > num < / code > ones , or else the empty map , if this map has
* less than < code > num < / code > elements .
* @ since 1.8.1 */
public static < K , V > Map < K , V > drop ( Map < K , V > self , int num ) { } } | if ( self . size ( ) <= num ) { return createSimilarMap ( self ) ; } if ( num == 0 ) { return cloneSimilarMap ( self ) ; } Map < K , V > ret = createSimilarMap ( self ) ; for ( Map . Entry < K , V > entry : self . entrySet ( ) ) { K key = entry . getKey ( ) ; V value = entry . getValue ( ) ; if ( num -- <= 0 ) { ret . put ( key , value ) ; } } return ret ; |
public class AwsUtils { /** * Returns the AccountId of the user who is running the instance .
* @ return String representing the AccountId or the owner - id
* @ throws java . io . IOException if failed to retrieve the AccountId using the
* Cloud infrastructure */
public static String getAccountId ( ) throws IOException { } } | // Get the MAC address of the machine .
String macUrl = getMetadataUrl ( ) + "/network/interfaces/macs/" ; String mac = invokeUrl ( macUrl ) . trim ( ) ; // Use the MAC address to obtain the owner - id or the
// AWS AccountId .
String idUrl = macUrl + mac + "owner-id" ; String acctId = invokeUrl ( idUrl ) . trim ( ) ; assert acctId != null ; return acctId ; |
public class CachedRemoteTable { /** * Build a new remote session and initialize it .
* @ param parentSessionObject The parent session for this new session ( if null , parent = me ) .
* @ param strSessionClassName The class name of the remote session to build . */
public org . jbundle . thin . base . remote . RemoteBaseSession makeRemoteSession ( String strSessionClassName ) throws RemoteException { } } | return m_tableRemote . makeRemoteSession ( strSessionClassName ) ; |
public class Ifc4PackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public EClass getIfcPlanarForceMeasure ( ) { } } | if ( ifcPlanarForceMeasureEClass == null ) { ifcPlanarForceMeasureEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( Ifc4Package . eNS_URI ) . getEClassifiers ( ) . get ( 850 ) ; } return ifcPlanarForceMeasureEClass ; |
public class route6 { /** * Use this API to fetch all the route6 resources that are configured on netscaler . */
public static route6 [ ] get ( nitro_service service ) throws Exception { } } | route6 obj = new route6 ( ) ; route6 [ ] response = ( route6 [ ] ) obj . get_resources ( service ) ; return response ; |
public class HttpUtils { /** * Delete
* @ param host
* @ param path
* @ param headers
* @ param queries
* @ return
* @ throws Exception */
public static String doDelete ( String host , String path , Map < String , String > headers , Map < String , String > queries , Map < String , String > body ) throws Exception { } } | return EntityUtils . toString ( doDeleteResponse ( host , path , headers , queries , JsonUtils . toJSON ( body ) ) . getEntity ( ) , "utf-8" ) ; |
public class AmazonGlacierClient { /** * This operation downloads the output of the job you initiated using < a > InitiateJob < / a > . Depending on the job type
* you specified when you initiated the job , the output will be either the content of an archive or a vault
* inventory .
* You can download all the job output or download a portion of the output by specifying a byte range . In the case
* of an archive retrieval job , depending on the byte range you specify , Amazon Glacier returns the checksum for the
* portion of the data . You can compute the checksum on the client and verify that the values match to ensure the
* portion you downloaded is the correct data .
* A job ID will not expire for at least 24 hours after Amazon Glacier completes the job . That a byte range . For
* both archive and inventory retrieval jobs , you should verify the downloaded size against the size returned in the
* headers from the < b > Get Job Output < / b > response .
* For archive retrieval jobs , you should also verify that the size is what you expected . If you download a portion
* of the output , the expected size is based on the range of bytes you specified . For example , if you specify a
* range of < code > bytes = 0-1048575 < / code > , you should verify your download size is 1,048,576 bytes . If you download
* an entire archive , the expected size is the size of the archive when you uploaded it to Amazon Glacier The
* expected size is also returned in the headers from the < b > Get Job Output < / b > response .
* In the case of an archive retrieval job , depending on the byte range you specify , Amazon Glacier returns the
* checksum for the portion of the data . To ensure the portion you downloaded is the correct data , compute the
* checksum on the client , verify that the values match , and verify that the size is what you expected .
* A job ID does not expire for at least 24 hours after Amazon Glacier completes the job . That is , you can download
* the job output within the 24 hours period after Amazon Glacier completes the job .
* An AWS account has full permission to perform all operations ( actions ) . However , AWS Identity and Access
* Management ( IAM ) users don ' t have any permissions by default . You must grant them explicit permission to perform
* specific actions . For more information , see < a
* href = " http : / / docs . aws . amazon . com / amazonglacier / latest / dev / using - iam - with - amazon - glacier . html " > Access Control
* Using AWS Identity and Access Management ( IAM ) < / a > .
* For conceptual information and the underlying REST API , see < a
* href = " http : / / docs . aws . amazon . com / amazonglacier / latest / dev / vault - inventory . html " > Downloading a Vault
* Inventory < / a > , < a
* href = " http : / / docs . aws . amazon . com / amazonglacier / latest / dev / downloading - an - archive . html " > Downloading an
* Archive < / a > , and < a href = " http : / / docs . aws . amazon . com / amazonglacier / latest / dev / api - job - output - get . html " > Get Job
* Output < / a >
* @ param getJobOutputRequest
* Provides options for downloading output of an Amazon Glacier job .
* @ return Result of the GetJobOutput operation returned by the service .
* @ throws ResourceNotFoundException
* Returned if the specified resource ( such as a vault , upload ID , or job ID ) doesn ' t exist .
* @ throws InvalidParameterValueException
* Returned if a parameter of the request is incorrectly specified .
* @ throws MissingParameterValueException
* Returned if a required header or parameter is missing from the request .
* @ throws ServiceUnavailableException
* Returned if the service cannot complete the request .
* @ sample AmazonGlacier . GetJobOutput */
@ Override public GetJobOutputResult getJobOutput ( GetJobOutputRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeGetJobOutput ( request ) ; |
public class FactoryStereoDisparity { /** * Returns an algorithm for computing a dense disparity images with sub - pixel disparity accuracy .
* NOTE : For RECT _ FIVE the size of the sub - regions it uses is what is specified .
* @ param minDisparity Minimum disparity that it will check . Must be & ge ; 0 and & lt ; maxDisparity
* @ param maxDisparity Maximum disparity that it will calculate . Must be & gt ; 0
* @ param regionRadiusX Radius of the rectangular region along x - axis . Try 3.
* @ param regionRadiusY Radius of the rectangular region along y - axis . Try 3.
* @ param maxPerPixelError Maximum allowed error in a region per pixel . Set to & lt ; 0 to disable .
* @ param validateRtoL Tolerance for how difference the left to right associated values can be . Try 6
* @ param texture Tolerance for how similar optimal region is to other region . Disable with a value & le ; 0.
* Closer to zero is more tolerant . Try 0.1
* @ param imageType Type of input image .
* @ return Rectangular region based WTA disparity . algorithm . */
public static < T extends ImageGray < T > > StereoDisparity < T , GrayF32 > regionSubpixelWta ( DisparityAlgorithms whichAlg , int minDisparity , int maxDisparity , int regionRadiusX , int regionRadiusY , double maxPerPixelError , int validateRtoL , double texture , Class < T > imageType ) { } } | double maxError = ( regionRadiusX * 2 + 1 ) * ( regionRadiusY * 2 + 1 ) * maxPerPixelError ; // 3 regions are used not just one in this case
if ( whichAlg == DisparityAlgorithms . RECT_FIVE ) maxError *= 3 ; DisparitySelect select ; if ( imageType == GrayU8 . class || imageType == GrayS16 . class ) { select = selectDisparitySubpixel_S32 ( ( int ) maxError , validateRtoL , texture ) ; } else if ( imageType == GrayF32 . class ) { select = selectDisparitySubpixel_F32 ( ( int ) maxError , validateRtoL , texture ) ; } else { throw new IllegalArgumentException ( "Unknown image type" ) ; } DisparityScoreRowFormat < T , GrayF32 > alg = null ; switch ( whichAlg ) { case RECT : if ( imageType == GrayU8 . class ) { alg = FactoryStereoDisparityAlgs . scoreDisparitySadRect_U8 ( minDisparity , maxDisparity , regionRadiusX , regionRadiusY , select ) ; } else if ( imageType == GrayS16 . class ) { alg = FactoryStereoDisparityAlgs . scoreDisparitySadRect_S16 ( minDisparity , maxDisparity , regionRadiusX , regionRadiusY , select ) ; } else if ( imageType == GrayF32 . class ) { alg = FactoryStereoDisparityAlgs . scoreDisparitySadRect_F32 ( minDisparity , maxDisparity , regionRadiusX , regionRadiusY , select ) ; } break ; case RECT_FIVE : if ( imageType == GrayU8 . class ) { alg = FactoryStereoDisparityAlgs . scoreDisparitySadRectFive_U8 ( minDisparity , maxDisparity , regionRadiusX , regionRadiusY , select ) ; } else if ( imageType == GrayS16 . class ) { alg = FactoryStereoDisparityAlgs . scoreDisparitySadRectFive_S16 ( minDisparity , maxDisparity , regionRadiusX , regionRadiusY , select ) ; } else if ( imageType == GrayF32 . class ) { alg = FactoryStereoDisparityAlgs . scoreDisparitySadRectFive_F32 ( minDisparity , maxDisparity , regionRadiusX , regionRadiusY , select ) ; } break ; default : throw new IllegalArgumentException ( "Unknown algorithms " + whichAlg ) ; } if ( alg == null ) throw new RuntimeException ( "Image type not supported: " + imageType . getSimpleName ( ) ) ; return new WrapDisparitySadRect < > ( alg ) ; |
public class StringUtils { /** * Constructs a new < code > String < / code > by decoding the specified array of bytes using the given charset .
* @ param bytes
* The bytes to be decoded into characters
* @ param charset
* The { @ link Charset } to encode the { @ code String }
* @ return A new < code > String < / code > decoded from the specified array of bytes using the given charset ,
* or { @ code null } if the input byte array was { @ code null } .
* @ throws NullPointerException
* Thrown if { @ link Charsets # UTF _ 8 } is not initialized , which should never happen since it is
* required by the Java platform specification . */
private static String newString ( byte [ ] bytes , Charset charset ) { } } | return bytes == null ? null : new String ( bytes , charset ) ; |
public class BaseFactoryImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public EObject create ( EClass eClass ) { } } | switch ( eClass . getClassifierID ( ) ) { case BasePackage . AFP : return createAFP ( ) ; case BasePackage . UNKNSF : return createUNKNSF ( ) ; case BasePackage . SF_GROUPER : return createSFGrouper ( ) ; default : throw new IllegalArgumentException ( "The class '" + eClass . getName ( ) + "' is not a valid classifier" ) ; } |
public class OrcFile { /** * Creates an { @ link Corc } instance and stores it in the context to be reused for all rows . */
@ Override public void sourcePrepare ( FlowProcess < ? extends Configuration > flowProcess , SourceCall < Corc , RecordReader > sourceCall ) throws IOException { } } | sourceCall . setContext ( ( Corc ) sourceCall . getInput ( ) . createValue ( ) ) ; |
public class StopWatch { /** * Return a string with a table describing all tasks performed .
* For custom reporting , call getTaskInfo ( ) and use the task info directly . */
public String prettyPrint ( ) { } } | StringBuilder sb = new StringBuilder ( shortSummary ( ) ) ; sb . append ( '\n' ) ; sb . append ( "-----------------------------------------\n" ) ; sb . append ( "ms % Task name\n" ) ; sb . append ( "-----------------------------------------\n" ) ; NumberFormat nf = NumberFormat . getNumberInstance ( ) ; nf . setMinimumIntegerDigits ( 5 ) ; nf . setGroupingUsed ( false ) ; NumberFormat pf = NumberFormat . getPercentInstance ( ) ; pf . setMinimumIntegerDigits ( 3 ) ; pf . setGroupingUsed ( false ) ; final TaskInfo [ ] taskInfos = getTaskInfo ( ) ; Arrays . sort ( taskInfos , new Comparator < TaskInfo > ( ) { @ Override public int compare ( TaskInfo o1 , TaskInfo o2 ) { return Long . compare ( o1 . getTimeMillis ( ) , o2 . getTimeMillis ( ) ) ; } } ) ; for ( TaskInfo task : taskInfos ) { sb . append ( nf . format ( task . getTimeMillis ( ) ) ) . append ( " " ) ; sb . append ( pf . format ( task . getTimeSeconds ( ) / getTotalTimeSeconds ( ) ) ) . append ( " " ) ; sb . append ( task . getTaskName ( ) ) . append ( "\n" ) ; } return sb . toString ( ) ; |
public class NativeJavaMethod { /** * Find the index of the correct function to call given the set of methods
* or constructors and the arguments .
* If no function can be found to call , return - 1. */
static int findFunction ( Context cx , MemberBox [ ] methodsOrCtors , Object [ ] args ) { } } | if ( methodsOrCtors . length == 0 ) { return - 1 ; } else if ( methodsOrCtors . length == 1 ) { MemberBox member = methodsOrCtors [ 0 ] ; Class < ? > [ ] argTypes = member . getParameterTypes ( ) ; int alength = argTypes . length ; if ( member . isVarArgs ( ) ) { alength -- ; if ( alength > args . length ) { return - 1 ; } } else { if ( alength != args . length ) { return - 1 ; } } for ( int j = 0 ; j != alength ; ++ j ) { if ( ! NativeJavaObject . canConvert ( args [ j ] , argTypes [ j ] ) ) { if ( debug ) printDebug ( "Rejecting (args can't convert) " , member , args ) ; return - 1 ; } } if ( debug ) printDebug ( "Found " , member , args ) ; return 0 ; } int firstBestFit = - 1 ; int [ ] extraBestFits = null ; int extraBestFitsCount = 0 ; search : for ( int i = 0 ; i < methodsOrCtors . length ; i ++ ) { MemberBox member = methodsOrCtors [ i ] ; Class < ? > [ ] argTypes = member . getParameterTypes ( ) ; int alength = argTypes . length ; if ( member . isVarArgs ( ) ) { alength -- ; if ( alength > args . length ) { continue search ; } } else { if ( alength != args . length ) { continue search ; } } for ( int j = 0 ; j < alength ; j ++ ) { if ( ! NativeJavaObject . canConvert ( args [ j ] , argTypes [ j ] ) ) { if ( debug ) printDebug ( "Rejecting (args can't convert) " , member , args ) ; continue search ; } } if ( firstBestFit < 0 ) { if ( debug ) printDebug ( "Found first applicable " , member , args ) ; firstBestFit = i ; } else { // Compare with all currently fit methods .
// The loop starts from - 1 denoting firstBestFit and proceed
// until extraBestFitsCount to avoid extraBestFits allocation
// in the most common case of no ambiguity
int betterCount = 0 ; // number of times member was prefered over
// best fits
int worseCount = 0 ; // number of times best fits were prefered
// over member
for ( int j = - 1 ; j != extraBestFitsCount ; ++ j ) { int bestFitIndex ; if ( j == - 1 ) { bestFitIndex = firstBestFit ; } else { bestFitIndex = extraBestFits [ j ] ; } MemberBox bestFit = methodsOrCtors [ bestFitIndex ] ; if ( cx . hasFeature ( Context . FEATURE_ENHANCED_JAVA_ACCESS ) && bestFit . isPublic ( ) != member . isPublic ( ) ) { // When FEATURE _ ENHANCED _ JAVA _ ACCESS gives us access
// to non - public members , continue to prefer public
// methods in overloading
if ( bestFit . isPublic ( ) ) ++ betterCount ; else ++ worseCount ; } else { int preference = preferSignature ( args , argTypes , member . isVarArgs ( ) , bestFit . getParameterTypes ( ) , bestFit . isVarArgs ( ) ) ; if ( preference == PREFERENCE_AMBIGUOUS ) { break ; } else if ( preference == PREFERENCE_FIRST_ARG ) { ++ betterCount ; } else if ( preference == PREFERENCE_SECOND_ARG ) { ++ worseCount ; } else { if ( preference != PREFERENCE_EQUAL ) Kit . codeBug ( ) ; // This should not happen in theory
// but on some JVMs , Class . getMethods will return all
// static methods of the class hierarchy , even if
// a derived class ' s parameters match exactly .
// We want to call the derived class ' s method .
if ( bestFit . isStatic ( ) && bestFit . getDeclaringClass ( ) . isAssignableFrom ( member . getDeclaringClass ( ) ) ) { // On some JVMs , Class . getMethods will return all
// static methods of the class hierarchy , even if
// a derived class ' s parameters match exactly .
// We want to call the derived class ' s method .
if ( debug ) printDebug ( "Substituting (overridden static)" , member , args ) ; if ( j == - 1 ) { firstBestFit = i ; } else { extraBestFits [ j ] = i ; } } else { if ( debug ) printDebug ( "Ignoring same signature member " , member , args ) ; } continue search ; } } } if ( betterCount == 1 + extraBestFitsCount ) { // member was prefered over all best fits
if ( debug ) printDebug ( "New first applicable " , member , args ) ; firstBestFit = i ; extraBestFitsCount = 0 ; } else if ( worseCount == 1 + extraBestFitsCount ) { // all best fits were prefered over member , ignore it
if ( debug ) printDebug ( "Rejecting (all current bests better) " , member , args ) ; } else { // some ambiguity was present , add member to best fit set
if ( debug ) printDebug ( "Added to best fit set " , member , args ) ; if ( extraBestFits == null ) { // Allocate maximum possible array
extraBestFits = new int [ methodsOrCtors . length - 1 ] ; } extraBestFits [ extraBestFitsCount ] = i ; ++ extraBestFitsCount ; } } } if ( firstBestFit < 0 ) { // Nothing was found
return - 1 ; } else if ( extraBestFitsCount == 0 ) { // single best fit
return firstBestFit ; } // report remaining ambiguity
StringBuilder buf = new StringBuilder ( ) ; for ( int j = - 1 ; j != extraBestFitsCount ; ++ j ) { int bestFitIndex ; if ( j == - 1 ) { bestFitIndex = firstBestFit ; } else { bestFitIndex = extraBestFits [ j ] ; } buf . append ( "\n " ) ; buf . append ( methodsOrCtors [ bestFitIndex ] . toJavaDeclaration ( ) ) ; } MemberBox firstFitMember = methodsOrCtors [ firstBestFit ] ; String memberName = firstFitMember . getName ( ) ; String memberClass = firstFitMember . getDeclaringClass ( ) . getName ( ) ; if ( methodsOrCtors [ 0 ] . isCtor ( ) ) { throw Context . reportRuntimeError3 ( "msg.constructor.ambiguous" , memberName , scriptSignature ( args ) , buf . toString ( ) ) ; } throw Context . reportRuntimeError4 ( "msg.method.ambiguous" , memberClass , memberName , scriptSignature ( args ) , buf . toString ( ) ) ; |
public class StackdriverQuickstart { /** * Main launcher for the Stackdriver example . */
public static void main ( String [ ] args ) throws IOException , InterruptedException { } } | // Register the view . It is imperative that this step exists ,
// otherwise recorded metrics will be dropped and never exported .
View view = View . create ( Name . create ( "task_latency_distribution" ) , "The distribution of the task latencies." , LATENCY_MS , Aggregation . Distribution . create ( LATENCY_BOUNDARIES ) , Collections . < TagKey > emptyList ( ) ) ; // Create the view manager
ViewManager viewManager = Stats . getViewManager ( ) ; // Then finally register the views
viewManager . registerView ( view ) ; // [ START setup _ exporter ]
// Enable OpenCensus exporters to export metrics to Stackdriver Monitoring .
// Exporters use Application Default Credentials to authenticate .
// See https : / / developers . google . com / identity / protocols / application - default - credentials
// for more details .
StackdriverStatsExporter . createAndRegister ( ) ; // [ END setup _ exporter ]
// Record 100 fake latency values between 0 and 5 seconds .
Random rand = new Random ( ) ; for ( int i = 0 ; i < 100 ; i ++ ) { long ms = ( long ) ( TimeUnit . MILLISECONDS . convert ( 5 , TimeUnit . SECONDS ) * rand . nextDouble ( ) ) ; System . out . println ( String . format ( "Latency %d: %d" , i , ms ) ) ; STATS_RECORDER . newMeasureMap ( ) . put ( LATENCY_MS , ms ) . record ( ) ; } // The default export interval is 60 seconds . The thread with the StackdriverStatsExporter must
// live for at least the interval past any metrics that must be collected , or some risk being
// lost if they are recorded after the last export .
System . out . println ( String . format ( "Sleeping %d seconds before shutdown to ensure all records are flushed." , EXPORT_INTERVAL ) ) ; Thread . sleep ( TimeUnit . MILLISECONDS . convert ( EXPORT_INTERVAL , TimeUnit . SECONDS ) ) ; |
public class ServletUtil { /** * Sends a redirect with relative paths determined from the request servlet path .
* @ see # getRedirectLocation ( javax . servlet . http . HttpServletRequest , javax . servlet . http . HttpServletResponse , java . lang . String , java . lang . String ) for transformations applied to the href */
public static void sendRedirect ( HttpServletRequest request , HttpServletResponse response , String href , int status ) throws IllegalStateException , IOException { } } | sendRedirect ( response , getRedirectLocation ( request , response , request . getServletPath ( ) , href ) , status ) ; |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link BigInteger } { @ code > }
* @ param value
* Java instance representing xml element ' s value .
* @ return
* the new instance of { @ link JAXBElement } { @ code < } { @ link BigInteger } { @ code > } */
@ XmlElementDecl ( namespace = "http://www.opengis.net/gml" , name = "Count" ) public JAXBElement < BigInteger > createCount ( BigInteger value ) { } } | return new JAXBElement < BigInteger > ( _Count_QNAME , BigInteger . class , null , value ) ; |
public class Preconditions { /** * See { @ link # checkArgument ( boolean , String , Object . . . ) } */
public static void checkArgument ( boolean b , String msg , Object arg1 ) { } } | if ( ! b ) { throwEx ( msg , arg1 ) ; } |
public class AbstractInstrumentation { /** * Instrument the classes and jar files . */
public void executeInstrumentation ( ) throws IOException { } } | errors . clear ( ) ; // Iterate over all entries in the classes list
for ( File f : this . classFiles ) { try { if ( ! f . canRead ( ) || ! f . canWrite ( ) ) { throw new IOException ( f + " can not be replaced" ) ; } instrumentClassFile ( f ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; errors . add ( e ) ; } } // Iterate over all entries in the jar list
for ( File f : this . jarFiles ) { try { instrumentZipFile ( f ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; errors . add ( e ) ; } } // Chain the first exception and report the error count
if ( ! errors . isEmpty ( ) ) { Throwable t = errors . get ( 0 ) ; IOException ioe = new IOException ( errors . size ( ) + " errors occurred" ) ; ioe . initCause ( t ) ; throw ioe ; } |
public class RaidShell { /** * Scan file and verify the checksums match the checksum store if have
* args [ ] contains the root where we need to check */
private void verifyFile ( String [ ] args , int startIndex ) { } } | Path root = null ; if ( args . length <= startIndex ) { throw new IllegalArgumentException ( "too few arguments" ) ; } String arg = args [ startIndex ] ; root = new Path ( arg ) ; try { FileSystem fs = root . getFileSystem ( conf ) ; // Make sure default uri is the same as root
conf . set ( FileSystem . FS_DEFAULT_NAME_KEY , fs . getUri ( ) . toString ( ) ) ; FileVerifier fv = new FileVerifier ( conf ) ; fv . verifyFile ( root , System . out ) ; } catch ( IOException ex ) { System . err . println ( "verifyFile: " + ex ) ; } |
public class RestServiceMethod { /** * Enclosed curly braces cannot be matched with a regex . Thus we remove them before applying the replaceAll method */
private String removeEnclosedCurlyBraces ( String str ) { } } | final char curlyReplacement = 6 ; char [ ] chars = str . toCharArray ( ) ; int open = 0 ; for ( int i = 0 ; i < chars . length ; i ++ ) { if ( chars [ i ] == '{' ) { if ( open != 0 ) chars [ i ] = curlyReplacement ; open ++ ; } else if ( chars [ i ] == '}' ) { open -- ; if ( open != 0 ) { chars [ i ] = curlyReplacement ; } } } char [ ] res = new char [ chars . length ] ; int j = 0 ; for ( int i = 0 ; i < chars . length ; i ++ ) { if ( chars [ i ] != curlyReplacement ) { res [ j ++ ] = chars [ i ] ; } } return new String ( Arrays . copyOf ( res , j ) ) ; |
public class ImageSegmentationOps { /** * Indicates border pixels between two regions . If two adjacent pixels ( 4 - connect ) are not from the same region
* then both pixels are marked as true ( value of 1 ) in output image , all other pixels are false ( 0 ) .
* @ param labeled Input segmented image .
* @ param output Output binary image . 1 for border pixels . */
public static void markRegionBorders ( GrayS32 labeled , GrayU8 output ) { } } | InputSanityCheck . checkSameShape ( labeled , output ) ; ImageMiscOps . fill ( output , 0 ) ; for ( int y = 0 ; y < output . height - 1 ; y ++ ) { int indexLabeled = labeled . startIndex + y * labeled . stride ; int indexOutput = output . startIndex + y * output . stride ; for ( int x = 0 ; x < output . width - 1 ; x ++ , indexLabeled ++ , indexOutput ++ ) { int region0 = labeled . data [ indexLabeled ] ; int region1 = labeled . data [ indexLabeled + 1 ] ; int region2 = labeled . data [ indexLabeled + labeled . stride ] ; if ( region0 != region1 ) { output . data [ indexOutput ] = 1 ; output . data [ indexOutput + 1 ] = 1 ; } if ( region0 != region2 ) { output . data [ indexOutput ] = 1 ; output . data [ indexOutput + output . stride ] = 1 ; } } } for ( int y = 0 ; y < output . height - 1 ; y ++ ) { int indexLabeled = labeled . startIndex + y * labeled . stride + output . width - 1 ; int indexOutput = output . startIndex + y * output . stride + output . width - 1 ; int region0 = labeled . data [ indexLabeled ] ; int region2 = labeled . data [ indexLabeled + labeled . stride ] ; if ( region0 != region2 ) { output . data [ indexOutput ] = 1 ; output . data [ indexOutput + output . stride ] = 1 ; } } int y = output . height - 1 ; int indexLabeled = labeled . startIndex + y * labeled . stride ; int indexOutput = output . startIndex + y * output . stride ; for ( int x = 0 ; x < output . width - 1 ; x ++ , indexLabeled ++ , indexOutput ++ ) { int region0 = labeled . data [ indexLabeled ] ; int region1 = labeled . data [ indexLabeled + 1 ] ; if ( region0 != region1 ) { output . data [ indexOutput ] = 1 ; output . data [ indexOutput + 1 ] = 1 ; } } |
public class JavaInlineExpressionCompiler { /** * Append the inline code for the given XNullLiteral .
* @ param expression the expression of the operation .
* @ param parentExpression is the expression that contains this one , or { @ code null } if the current expression is
* the root expression .
* @ param feature the feature that contains the expression .
* @ param output the output .
* @ return { @ code true } if a text was appended . */
protected Boolean _generate ( XNullLiteral expression , XExpression parentExpression , XtendExecutable feature , InlineAnnotationTreeAppendable output ) { } } | if ( parentExpression == null && feature instanceof XtendFunction ) { final XtendFunction function = ( XtendFunction ) feature ; output . append ( "(" ) ; // $ NON - NLS - 1 $
final JvmTypeReference reference = getFunctionTypeReference ( function ) ; if ( reference != null ) { final JvmType type = reference . getType ( ) ; if ( type != null ) { output . append ( type ) ; } else { output . append ( Object . class ) ; } } else { output . append ( Object . class ) ; } output . append ( ")" ) ; // $ NON - NLS - 1 $
output . append ( Objects . toString ( null ) ) ; output . setConstant ( true ) ; } else { output . appendConstant ( Objects . toString ( null ) ) ; } return Boolean . TRUE ; |
public class ClasspathUrlFinder { /** * Uses the java . class . path system property to obtain a list of URLs that represent the CLASSPATH
* paths is used as a filter to only include paths that have the specific relative file within it
* @ param paths comma list of files that should exist in a particular path
* @ return */
public static URL [ ] findClassPaths ( String ... paths ) { } } | ArrayList < URL > list = new ArrayList < URL > ( ) ; String classpath = System . getProperty ( "java.class.path" ) ; StringTokenizer tokenizer = new StringTokenizer ( classpath , File . pathSeparator ) ; for ( int i = 0 ; i < paths . length ; i ++ ) { paths [ i ] = paths [ i ] . trim ( ) ; } while ( tokenizer . hasMoreTokens ( ) ) { String path = tokenizer . nextToken ( ) . trim ( ) ; boolean found = false ; for ( String wantedPath : paths ) { if ( path . endsWith ( File . separator + wantedPath ) ) { found = true ; break ; } } if ( ! found ) { continue ; } File fp = new File ( path ) ; if ( ! fp . exists ( ) ) { throw new RuntimeException ( "File in java.class.path does not exists: " + fp ) ; } try { list . add ( fp . toURL ( ) ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } return list . toArray ( new URL [ list . size ( ) ] ) ; |
public class ProxyFactory { /** * Sets the invocation handler for a proxy . This method is less efficient than
* { @ link # setInvocationHandler ( Object , InvocationHandler ) } , however it will work on any proxy , not just proxies from a
* specific factory .
* @ param proxy the proxy to modify
* @ param handler the handler to use */
public static void setInvocationHandlerStatic ( Object proxy , InvocationHandler handler ) { } } | try { final Field field = proxy . getClass ( ) . getDeclaredField ( INVOCATION_HANDLER_FIELD ) ; AccessController . doPrivileged ( new SetAccessiblePrivilege ( field ) ) ; field . set ( proxy , handler ) ; } catch ( NoSuchFieldException e ) { throw new RuntimeException ( "Could not find invocation handler on generated proxy" , e ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.