signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class LegacySpy { /** * Alias for { @ link # expectBetween ( int , int , Threads , Query ) } with arguments { @ code allowedStatements } , { @ code allowedStatements } , { @ link Threads # CURRENT } , { @ code queryType }
* @ since 2.2 */
@ Deprecated public C expect ( int allowedStatements , Query query ) { } } | return expect ( SqlQueries . exactQueries ( allowedStatements ) . type ( adapter ( query ) ) ) ; |
public class SourceRenderFilter { /** * Extracts request parameters , and sets the corresponding request
* attributes if specified .
* @ param pRequest
* @ param pResponse
* @ param pChain
* @ throws IOException
* @ throws ServletException */
protected void doFilterImpl ( ServletRequest pRequest , ServletResponse pResponse , FilterChain pChain ) throws IOException , ServletException { } } | // TODO : Max size configuration , to avoid DOS attacks ? OutOfMemory
// Size parameters
int width = ServletUtil . getIntParameter ( pRequest , sizeWidthParam , - 1 ) ; int height = ServletUtil . getIntParameter ( pRequest , sizeHeightParam , - 1 ) ; if ( width > 0 || height > 0 ) { pRequest . setAttribute ( ImageServletResponse . ATTRIB_SIZE , new Dimension ( width , height ) ) ; } // Size uniform / percent
boolean uniform = ServletUtil . getBooleanParameter ( pRequest , sizeUniformParam , true ) ; if ( ! uniform ) { pRequest . setAttribute ( ImageServletResponse . ATTRIB_SIZE_UNIFORM , Boolean . FALSE ) ; } boolean percent = ServletUtil . getBooleanParameter ( pRequest , sizePercentParam , false ) ; if ( percent ) { pRequest . setAttribute ( ImageServletResponse . ATTRIB_SIZE_PERCENT , Boolean . TRUE ) ; } // Area of interest parameters
int x = ServletUtil . getIntParameter ( pRequest , regionLeftParam , - 1 ) ; // Default is center
int y = ServletUtil . getIntParameter ( pRequest , regionTopParam , - 1 ) ; // Default is center
width = ServletUtil . getIntParameter ( pRequest , regionWidthParam , - 1 ) ; height = ServletUtil . getIntParameter ( pRequest , regionHeightParam , - 1 ) ; if ( width > 0 || height > 0 ) { pRequest . setAttribute ( ImageServletResponse . ATTRIB_AOI , new Rectangle ( x , y , width , height ) ) ; } // AOI uniform / percent
uniform = ServletUtil . getBooleanParameter ( pRequest , regionUniformParam , false ) ; if ( uniform ) { pRequest . setAttribute ( ImageServletResponse . ATTRIB_SIZE_UNIFORM , Boolean . TRUE ) ; } percent = ServletUtil . getBooleanParameter ( pRequest , regionPercentParam , false ) ; if ( percent ) { pRequest . setAttribute ( ImageServletResponse . ATTRIB_SIZE_PERCENT , Boolean . TRUE ) ; } super . doFilterImpl ( pRequest , pResponse , pChain ) ; |
public class RadialSelectorView { /** * Initialize this selector with the state of the picker .
* @ param context Current context .
* @ param is24HourMode Whether the selector is in 24 - hour mode , which will tell us
* whether the circle ' s center is moved up slightly to make room for the AM / PM circles .
* @ param hasInnerCircle Whether we have both an inner and an outer circle of numbers
* that may be selected . Should be true for 24 - hour mode in the hours circle .
* @ param disappearsOut Whether the numbers ' animation will have them disappearing out
* or disappearing in .
* @ param selectionDegrees The initial degrees to be selected .
* @ param isInnerCircle Whether the initial selection is in the inner or outer circle .
* Will be ignored when hasInnerCircle is false . */
public void initialize ( Context context , boolean is24HourMode , boolean hasInnerCircle , boolean disappearsOut , int selectionDegrees , boolean isInnerCircle ) { } } | if ( mIsInitialized ) { Log . e ( TAG , "This RadialSelectorView may only be initialized once." ) ; return ; } Resources res = context . getResources ( ) ; mPaint . setAntiAlias ( true ) ; // Calculate values for the circle radius size .
mIs24HourMode = is24HourMode ; if ( is24HourMode ) { mCircleRadiusMultiplier = Float . parseFloat ( res . getString ( R . string . time_circle_radius_multiplier_24HourMode ) ) ; } else { mCircleRadiusMultiplier = Float . parseFloat ( res . getString ( R . string . time_circle_radius_multiplier ) ) ; mAmPmCircleRadiusMultiplier = Float . parseFloat ( res . getString ( R . string . time_ampm_circle_radius_multiplier ) ) ; } // Calculate values for the radius size ( s ) of the numbers circle ( s ) .
mHasInnerCircle = hasInnerCircle ; if ( hasInnerCircle ) { mInnerNumbersRadiusMultiplier = Float . parseFloat ( res . getString ( R . string . time_numbers_radius_multiplier_inner ) ) ; mOuterNumbersRadiusMultiplier = Float . parseFloat ( res . getString ( R . string . time_numbers_radius_multiplier_outer ) ) ; } else { mNumbersRadiusMultiplier = Float . parseFloat ( res . getString ( R . string . time_time_numbers_radius_multiplier_normal ) ) ; } mSelectionRadiusMultiplier = Float . parseFloat ( res . getString ( R . string . time_selection_radius_multiplier ) ) ; // Calculate values for the transition mid - way states .
mAnimationRadiusMultiplier = 1 ; mInvalidateUpdateListener = new InvalidateUpdateListener ( ) ; setSelection ( selectionDegrees , isInnerCircle , false ) ; mIsInitialized = true ; |
public class A_CmsVfsDocument { /** * Generates a new lucene document instance from contents of the given resource for the provided index . < p >
* @ see org . opencms . search . documents . I _ CmsDocumentFactory # createDocument ( CmsObject , CmsResource , I _ CmsSearchIndex ) */
public I_CmsSearchDocument createDocument ( CmsObject cms , CmsResource resource , I_CmsSearchIndex index ) throws CmsException { } } | // extract the content from the resource
I_CmsExtractionResult content = null ; if ( index . isExtractingContent ( ) ) { // do full text content extraction only if required
// check if caching is enabled for this document type
CmsExtractionResultCache cache = getCache ( ) ; String cacheName = null ; if ( ( cache != null ) && ( resource . getSiblingCount ( ) > 1 ) ) { // hard drive based caching only makes sense for resources that have siblings ,
// because the index will also store the content as a blob
cacheName = cache . getCacheName ( resource , isLocaleDependend ( ) ? index . getLocaleForResource ( cms , resource , null ) : null , getName ( ) ) ; content = cache . getCacheObject ( cacheName ) ; } if ( content == null ) { // extraction result has not been found in the cache
// use the currently indexed content , if it is still up to date .
content = index . getContentIfUnchanged ( resource ) ; } if ( content == null ) { // extraction result has not been attached to the resource
try { content = extractContent ( cms , resource , index ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Extracting content for '" + resource . getRootPath ( ) + "' successful." ) ; } if ( ( cache != null ) && ( resource . getSiblingCount ( ) > 1 ) ) { // save extracted content to the cache
cache . saveCacheObject ( cacheName , content ) ; } } catch ( CmsIndexNoContentException e ) { // there was no content found for the resource
LOG . info ( Messages . get ( ) . getBundle ( ) . key ( Messages . ERR_TEXT_EXTRACTION_1 , resource . getRootPath ( ) ) + " " + e . getMessage ( ) ) ; } catch ( Throwable e ) { // text extraction failed for document - continue indexing meta information only
LOG . error ( Messages . get ( ) . getBundle ( ) . key ( Messages . ERR_TEXT_EXTRACTION_1 , resource . getRootPath ( ) ) , e ) ; } } } // create the Lucene document according to the index field configuration
return index . getFieldConfiguration ( ) . createDocument ( cms , resource , index , content ) ; |
public class DriverFactory { /** * Build a feed using reflection
* @ param feedDesc
* @ return */
public static Feed buildFeed ( FeedDesc feedDesc ) { } } | Feed feed = null ; NitFactory nitFactory = new NitFactory ( ) ; NitDesc nitDesc = nitDescFromDynamic ( feedDesc ) ; nitDesc . setConstructorParameters ( new Class [ ] { Map . class } ) ; nitDesc . setConstructorArguments ( new Object [ ] { feedDesc . getProperties ( ) } ) ; try { feed = nitFactory . construct ( nitDesc ) ; } catch ( NitException e ) { throw new RuntimeException ( e ) ; } return feed ; |
public class LiteralConditionImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public void setTrue ( boolean newTrue ) { } } | boolean oldTrue = true_ ; true_ = newTrue ; if ( eNotificationRequired ( ) ) eNotify ( new ENotificationImpl ( this , Notification . SET , XtextPackage . LITERAL_CONDITION__TRUE , oldTrue , true_ ) ) ; |
public class TermFrequencyCandidateAnswerScore { /** * 统计文本中出现的候选答案及其词频
* @ return */
private Map < String , Integer > getWordFrequency ( String title , String snippet ) { } } | List < String > titleNames = new ArrayList < > ( ) ; List < String > snippetNames = new ArrayList < > ( ) ; // 处理title
List < Word > words = WordParser . parse ( title ) ; for ( Word word : words ) { if ( word . getPartOfSpeech ( ) . getPos ( ) . startsWith ( question . getQuestionType ( ) . getPos ( ) ) ) { titleNames . add ( word . getText ( ) ) ; } } // 处理snippet
words = WordParser . parse ( snippet ) ; for ( Word word : words ) { if ( word . getPartOfSpeech ( ) . getPos ( ) . startsWith ( question . getQuestionType ( ) . getPos ( ) ) ) { snippetNames . add ( word . getText ( ) ) ; } } // 统计词频
// title中出现一次算两次
// snippet中出现一次算一次
Map < String , Integer > map = new HashMap < > ( ) ; for ( String name : titleNames ) { Integer count = map . get ( name ) ; if ( count == null ) { count = TITLE_WEIGHT ; } else { count += TITLE_WEIGHT ; } map . put ( name , count ) ; } for ( String name : snippetNames ) { Integer count = map . get ( name ) ; if ( count == null ) { count = 1 ; } else { count ++ ; } map . put ( name , count ) ; } return map ; |
public class SetOperation { /** * Wrap takes the SetOperation image in Memory and refers to it directly .
* There is no data copying onto the java heap .
* Only " Direct " SetOperations that have been explicitly stored as direct can be wrapped .
* @ param srcMem an image of a SetOperation where the hash of the given seed matches the image seed hash .
* < a href = " { @ docRoot } / resources / dictionary . html # mem " > See Memory < / a >
* @ param seed < a href = " { @ docRoot } / resources / dictionary . html # seed " > See Update Hash Seed < / a > .
* @ return a SetOperation backed by the given Memory */
public static SetOperation wrap ( final Memory srcMem , final long seed ) { } } | final byte famID = srcMem . getByte ( FAMILY_BYTE ) ; final Family family = idToFamily ( famID ) ; final int serVer = srcMem . getByte ( SER_VER_BYTE ) ; if ( serVer != 3 ) { throw new SketchesArgumentException ( "SerVer must be 3: " + serVer ) ; } switch ( family ) { case UNION : { return UnionImpl . wrapInstance ( srcMem , seed ) ; } case INTERSECTION : { return IntersectionImplR . wrapInstance ( srcMem , seed ) ; } default : throw new SketchesArgumentException ( "SetOperation cannot wrap family: " + family . toString ( ) ) ; } |
public class RegistryService { /** * Re - creates an entry in the group .
* @ param sessionProvider the session provider
* @ throws RepositoryException */
@ Override public void recreateEntry ( final SessionProvider sessionProvider , final String groupPath , final RegistryEntry entry ) throws RepositoryException { } } | final String entryRelPath = EXO_REGISTRY + "/" + groupPath + "/" + entry . getName ( ) ; final String parentFullPath = "/" + EXO_REGISTRY + "/" + groupPath ; try { Session session = session ( sessionProvider , repositoryService . getCurrentRepository ( ) ) ; // Don ' t care about concurrency , Session should be dedicated to the Thread , see JCR - 765
// synchronized ( session ) {
Node node = session . getRootNode ( ) . getNode ( entryRelPath ) ; // delete existing entry . . .
node . remove ( ) ; // create same entry ,
// [ PN ] no check we need here , as we have deleted this node before
// checkGroup ( sessionProvider , fullParentPath ) ;
session . importXML ( parentFullPath , entry . getAsInputStream ( ) , IMPORT_UUID_CREATE_NEW ) ; // save recreated changes
session . save ( ) ; } catch ( IOException ioe ) { throw new RepositoryException ( "Item " + parentFullPath + "can't be created " + ioe ) ; } catch ( TransformerException te ) { throw new RepositoryException ( "Can't get XML representation from stream " + te ) ; } |
public class SDBaseOps { /** * Element - wise scalar floor modulus operation : out = floorMod ( in , value ) .
* i . e . , returns the remainder after division by ' value '
* @ param in Input variable
* @ param value Scalar value to compare
* @ return Output variable */
public SDVariable scalarFloorMod ( SDVariable in , Number value ) { } } | return scalarFloorMod ( null , in , value ) ; |
public class Head { /** * The parent can only take one string . If we need to , concatenate the
* strings . The argument tag should never be empty , but tail could be .
* @ param tag tag string
* @ param tail tail string
* @ return the constructed string */
private static String buildParentString ( final String tag , final String tail ) { } } | if ( tail . isEmpty ( ) ) { return tag ; } else { return tag + " " + tail ; } |
public class SubscriptionAdminClient { /** * Removes an existing snapshot . Snapshots are used in & lt ; a
* href = " https : / / cloud . google . com / pubsub / docs / replay - overview " & gt ; Seek & lt ; / a & gt ; operations , which
* allow you to manage message acknowledgments in bulk . That is , you can set the acknowledgment
* state of messages in an existing subscription to the state captured by a
* snapshot . & lt ; br & gt ; & lt ; br & gt ; & lt ; b & gt ; BETA : & lt ; / b & gt ; This feature is part of a beta release .
* This API might be changed in backward - incompatible ways and is not recommended for production
* use . It is not subject to any SLA or deprecation policy . When the snapshot is deleted , all
* messages retained in the snapshot are immediately dropped . After a snapshot is deleted , a new
* one may be created with the same name , but the new one has no association with the old snapshot
* or its subscription , unless the same subscription is specified .
* < p > Sample code :
* < pre > < code >
* try ( SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient . create ( ) ) {
* ProjectSnapshotName snapshot = ProjectSnapshotName . of ( " [ PROJECT ] " , " [ SNAPSHOT ] " ) ;
* subscriptionAdminClient . deleteSnapshot ( snapshot ) ;
* < / code > < / pre >
* @ param snapshot The name of the snapshot to delete . Format is
* ` projects / { project } / snapshots / { snap } ` .
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
public final void deleteSnapshot ( ProjectSnapshotName snapshot ) { } } | DeleteSnapshotRequest request = DeleteSnapshotRequest . newBuilder ( ) . setSnapshot ( snapshot == null ? null : snapshot . toString ( ) ) . build ( ) ; deleteSnapshot ( request ) ; |
public class GoogleHadoopFSInputStream { /** * Sets the current position within the file being read .
* @ param pos The position to seek to .
* @ throws IOException if an IO error occurs or if the target position is invalid . */
@ Override public synchronized void seek ( long pos ) throws IOException { } } | long startTime = System . nanoTime ( ) ; logger . atFine ( ) . log ( "seek: %d" , pos ) ; try { channel . position ( pos ) ; } catch ( IllegalArgumentException e ) { throw new IOException ( e ) ; } long duration = System . nanoTime ( ) - startTime ; ghfs . increment ( GoogleHadoopFileSystemBase . Counter . SEEK ) ; ghfs . increment ( GoogleHadoopFileSystemBase . Counter . SEEK_TIME , duration ) ; |
public class ReidSolomonCodes { /** * Computes the syndromes for the message ( input + ecc ) . If there ' s no error then the output will be zero .
* @ param input Data portion of the message
* @ param ecc ECC portion of the message
* @ param syndromes ( Output ) results of the syndromes computations */
void computeSyndromes ( GrowQueue_I8 input , GrowQueue_I8 ecc , GrowQueue_I8 syndromes ) { } } | syndromes . resize ( syndromeLength ( ) ) ; for ( int i = 0 ; i < syndromes . size ; i ++ ) { int val = math . power ( 2 , i ) ; syndromes . data [ i ] = ( byte ) math . polyEval ( input , val ) ; syndromes . data [ i ] = ( byte ) math . polyEvalContinue ( syndromes . data [ i ] & 0xFF , ecc , val ) ; } |
public class Application { /** * Get this standard resource .
* This is a utility method for loading and caching resources .
* The returned Resources object can be called just like a resource object with some
* extra functions .
* @ param strResourceName The class name of the resource file to load .
* @ param bReturnKeyOnMissing Return the string key if the resource is missing ( typically , pass true ) .
* @ return The Resources object . */
public ResourceBundle getResources ( String strResourceName , boolean bReturnKeyOnMissing ) { } } | ResourceBundle resources = null ; try { Locale currentLocale = this . getLocale ( ) ; // Locale . getDefault ( ) ;
strResourceName = this . getResourcePath ( strResourceName ) ; if ( m_resources != null ) if ( strResourceName . equals ( m_resources . getClass ( ) . getName ( ) ) ) return m_resources ; resources = ClassServiceUtility . getClassService ( ) . getResourceBundle ( strResourceName , currentLocale , null , this . getClass ( ) . getClassLoader ( ) ) ; } catch ( MissingResourceException ex ) { Util . getLogger ( ) . warning ( "Missing resource " + strResourceName + " locale: " + this . getLocale ( ) ) ; resources = null ; } m_resources = resources ; // Last accessed
return resources ; |
public class CatalogDiffEngine { /** * Return an error message asserting that we cannot create a view
* with a given name .
* @ param viewName The name of the view we are refusing to create .
* @ param singleTableName The name of the source table if there is
* one source table . If there are multiple
* tables this should be null . This only
* affects the wording of the error message .
* @ return */
private String createViewDisallowedMessage ( String viewName , String singleTableName ) { } } | boolean singleTable = ( singleTableName != null ) ; return String . format ( "Unable to create %sview %s %sbecause the view definition uses operations that cannot always be applied if %s." , ( singleTable ? "single table " : "multi-table " ) , viewName , ( singleTable ? String . format ( "on table %s " , singleTableName ) : "" ) , ( singleTable ? "the table already contains data" : "none of the source tables are empty" ) ) ; |
public class ReentrantTransactionDispatcher { /** * Wait for exclusive permit during a timeout in milliseconds .
* @ return number of acquired permits if > 0 */
private int tryAcquireExclusiveTransaction ( @ NotNull final Thread thread , final int timeout ) { } } | long nanos = TimeUnit . MILLISECONDS . toNanos ( timeout ) ; try ( CriticalSection ignored = criticalSection . enter ( ) ) { if ( getThreadPermits ( thread ) > 0 ) { throw new ExodusException ( "Exclusive transaction can't be nested" ) ; } final Condition condition = criticalSection . newCondition ( ) ; final long currentOrder = acquireOrder ++ ; regularQueue . put ( currentOrder , condition ) ; while ( acquiredPermits > 0 || regularQueue . firstKey ( ) != currentOrder ) { try { nanos = condition . awaitNanos ( nanos ) ; if ( nanos < 0 ) { break ; } } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; break ; } } if ( acquiredPermits == 0 && regularQueue . firstKey ( ) == currentOrder ) { regularQueue . pollFirstEntry ( ) ; acquiredPermits = availablePermits ; threadPermits . put ( thread , availablePermits ) ; return availablePermits ; } regularQueue . remove ( currentOrder ) ; notifyNextWaiters ( ) ; } return 0 ; |
public class Messages { /** * < p > getResourceBundle . < / p >
* @ param bundleName a { @ link java . lang . String } object .
* @ param locale a { @ link java . util . Locale } object .
* @ return a { @ link java . util . ResourceBundle } object . */
public static ResourceBundle getResourceBundle ( String bundleName , Locale locale ) { } } | ResourceBundle bundle = null ; boolean isDev = false ; if ( Ameba . getApp ( ) != null ) { isDev = Ameba . getApp ( ) . getMode ( ) . isDev ( ) ; BUNDLE_CONTROL . noCache = isDev ; } if ( ! isDev ) { bundle = RESOURCE_BUNDLES . get ( bundleName , locale ) ; } if ( bundle == null ) { try { bundle = ResourceBundle . getBundle ( bundleName , locale , ClassUtils . getContextClassLoader ( ) , BUNDLE_CONTROL ) ; } catch ( MissingResourceException e ) { // no op
} } if ( bundle != null && ! isDev ) { RESOURCE_BUNDLES . put ( bundleName , locale , bundle ) ; } return bundle ; |
public class AggregateDirContextProcessor { /** * @ see org . springframework . ldap . core . DirContextProcessor # postProcess ( javax . naming . directory . DirContext ) */
public void postProcess ( DirContext ctx ) throws NamingException { } } | for ( DirContextProcessor processor : dirContextProcessors ) { processor . postProcess ( ctx ) ; } |
public class ClassLister { /** * loads the props file and interpretes it . */
public void initialize ( ) { } } | Enumeration enm ; String superclass ; String [ ] packages ; try { m_CacheNames = new HashMap < > ( ) ; m_ListNames = new HashMap < > ( ) ; m_CacheClasses = new HashMap < > ( ) ; m_ListClasses = new HashMap < > ( ) ; enm = m_Packages . propertyNames ( ) ; while ( enm . hasMoreElements ( ) ) { superclass = ( String ) enm . nextElement ( ) ; packages = m_Packages . getProperty ( superclass ) . replaceAll ( " " , "" ) . split ( "," ) ; addHierarchy ( superclass , packages ) ; } } catch ( Exception e ) { getLogger ( ) . log ( Level . SEVERE , "Failed to determine packages/classes:" , e ) ; m_Packages = new Properties ( ) ; } |
public class HystrixCollapserMetrics { /** * Get or create the { @ link HystrixCollapserMetrics } instance for a given { @ link HystrixCollapserKey } .
* This is thread - safe and ensures only 1 { @ link HystrixCollapserMetrics } per { @ link HystrixCollapserKey } .
* @ param key
* { @ link HystrixCollapserKey } of { @ link HystrixCollapser } instance requesting the { @ link HystrixCollapserMetrics }
* @ return { @ link HystrixCollapserMetrics } */
public static HystrixCollapserMetrics getInstance ( HystrixCollapserKey key , HystrixCollapserProperties properties ) { } } | // attempt to retrieve from cache first
HystrixCollapserMetrics collapserMetrics = metrics . get ( key . name ( ) ) ; if ( collapserMetrics != null ) { return collapserMetrics ; } // it doesn ' t exist so we need to create it
collapserMetrics = new HystrixCollapserMetrics ( key , properties ) ; // attempt to store it ( race other threads )
HystrixCollapserMetrics existing = metrics . putIfAbsent ( key . name ( ) , collapserMetrics ) ; if ( existing == null ) { // we won the thread - race to store the instance we created
return collapserMetrics ; } else { // we lost so return ' existing ' and let the one we created be garbage collected
return existing ; } |
public class GroupApi { /** * Create a new group variable .
* < pre > < code > GitLab Endpoint : POST / groups / : id / variables < / code > < / pre >
* @ param groupIdOrPath the group ID , path of the group , or a Group instance holding the group ID or path , required
* @ param key the key of a variable ; must have no more than 255 characters ; only A - Z , a - z , 0-9 , and _ are allowed , required
* @ param value the value for the variable , required
* @ param isProtected whether the variable is protected , optional
* @ return a Variable instance with the newly created variable
* @ throws GitLabApiException if any exception occurs during execution */
public Variable createVariable ( Object groupIdOrPath , String key , String value , Boolean isProtected ) throws GitLabApiException { } } | GitLabApiForm formData = new GitLabApiForm ( ) . withParam ( "key" , key , true ) . withParam ( "value" , value , true ) . withParam ( "protected" , isProtected ) ; Response response = post ( Response . Status . CREATED , formData , "groups" , getGroupIdOrPath ( groupIdOrPath ) , "variables" ) ; return ( response . readEntity ( Variable . class ) ) ; |
public class MetadataDocumentPropertyWriter { /** * Write either a { @ code < Property > } or { @ code < NavigationProperty > } element
* for the given { @ code StructuralProperty } .
* @ param property The given structural property . It can not be { @ code null } .
* @ throws javax . xml . stream . XMLStreamException If unable to write to stream */
public void write ( StructuralProperty property ) throws XMLStreamException { } } | LOG . debug ( "Writing property {} of type {}" , property . getName ( ) , property . getTypeName ( ) ) ; if ( property instanceof NavigationProperty ) { NavigationProperty navProperty = ( NavigationProperty ) property ; xmlWriter . writeStartElement ( NAVIGATION_PROPERTY ) ; writeCommonPropertyAttributes ( property ) ; if ( ! isNullOrEmpty ( navProperty . getPartnerName ( ) ) ) { xmlWriter . writeAttribute ( PARTNER , navProperty . getPartnerName ( ) ) ; } xmlWriter . writeEndElement ( ) ; } else { xmlWriter . writeStartElement ( PROPERTY ) ; writeCommonPropertyAttributes ( property ) ; xmlWriter . writeEndElement ( ) ; } |
public class FieldBuilder { /** * Build the comments for the field . Do nothing if
* { @ link Configuration # nocomment } is set to true .
* @ param node the XML element that specifies which components to document
* @ param fieldDocTree the content tree to which the documentation will be added */
public void buildFieldComments ( XMLNode node , Content fieldDocTree ) { } } | if ( ! configuration . nocomment ) { writer . addComments ( currentElement , fieldDocTree ) ; } |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link ObligationExpressionsType } { @ code > } } */
@ XmlElementDecl ( namespace = "urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" , name = "ObligationExpressions" ) public JAXBElement < ObligationExpressionsType > createObligationExpressions ( ObligationExpressionsType value ) { } } | return new JAXBElement < ObligationExpressionsType > ( _ObligationExpressions_QNAME , ObligationExpressionsType . class , null , value ) ; |
public class Util { /** * Determines the client ' s preferred locales from the request , and compares
* each of the locales ( in order of preference ) against the available
* locales in order to determine the best matching locale .
* @ param pageContext the page in which the resource bundle with the given
* base name is requested @ param basename the resource bundle ' s base name
* @ return the localization context containing the resource bundle with the
* given base name and best matching locale , or < tt > null < / tt > if no
* resource bundle match was found */
private static LocalizationContext findMatch ( PageContext pageContext , String basename ) { } } | LocalizationContext locCtxt = null ; // Determine locale from client ' s browser settings .
for ( Enumeration enum_ = Util . getRequestLocales ( ( HttpServletRequest ) pageContext . getRequest ( ) ) ; enum_ . hasMoreElements ( ) ; ) { Locale pref = ( Locale ) enum_ . nextElement ( ) ; ResourceBundle match = findMatch ( basename , pref ) ; if ( match != null ) { locCtxt = new LocalizationContext ( match , pref ) ; break ; } } return locCtxt ; |
public class SelectionVisibility { /** * Determine if an object is selected .
* @ param object the object
* @ return object is selected */
static boolean isSelected ( IChemObject object , RendererModel model ) { } } | if ( object . getProperty ( StandardGenerator . HIGHLIGHT_COLOR ) != null ) return true ; if ( model . getSelection ( ) != null ) return model . getSelection ( ) . contains ( object ) ; return false ; |
public class ClassInfoScreen { /** * Process the command .
* < br / > Step 1 - Process the command if possible and return true if processed .
* < br / > Step 2 - If I can ' t process , pass to all children ( with me as the source ) .
* < br / > Step 3 - If children didn ' t process , pass to parent ( with me as the source ) .
* < br / > Note : Never pass to a parent or child that matches the source ( to avoid an endless loop ) .
* @ param strCommand The command to process .
* @ param sourceSField The source screen field ( to avoid echos ) .
* @ param iCommandOptions If this command creates a new screen , create in a new window ?
* @ return true if success . */
public boolean doCommand ( String strCommand , ScreenField sourceSField , int iCommandOptions ) { } } | boolean bFlag = false ; if ( ( strCommand . indexOf ( "FileHdrScreen" ) != - 1 ) || ( strCommand . indexOf ( "LayoutScreen" ) != - 1 ) ) iCommandOptions = ScreenConstants . USE_NEW_WINDOW | ScreenConstants . DONT_PUSH_TO_BROWSER ; if ( ( strCommand . indexOf ( "ExportRecordsToXml" ) != - 1 ) || ( strCommand . indexOf ( "AccessGridScreen" ) != - 1 ) ) { iCommandOptions = ScreenConstants . USE_NEW_WINDOW | ScreenConstants . DONT_PUSH_TO_BROWSER ; strCommand = Utility . addURLParam ( strCommand , DBParams . RECORD , this . getMainRecord ( ) . getField ( ClassInfo . CLASS_NAME ) . toString ( ) ) ; String packageName = ( ( ClassInfo ) this . getMainRecord ( ) ) . getPackageName ( null ) ; strCommand = Utility . addURLParam ( strCommand , "package" , packageName ) ; strCommand = Utility . addURLParam ( strCommand , "project" , Converter . stripNonNumber ( this . getMainRecord ( ) . getField ( ClassInfo . CLASS_PROJECT_ID ) . toString ( ) ) ) ; } if ( ! DBConstants . RESET . equalsIgnoreCase ( strCommand ) ) if ( ( this . getMainRecord ( ) . getEditMode ( ) == DBConstants . EDIT_ADD ) || ( this . getMainRecord ( ) . getEditMode ( ) == DBConstants . EDIT_IN_PROGRESS ) ) { try { this . getMainRecord ( ) . writeAndRefresh ( false ) ; // Make sure data is current before doing any command .
if ( this . getScreenRecord ( ) . getField ( ClassVars . CLASS_KEY ) . getListener ( SwitchClassSub . class ) != null ) { ScreenField screen = ( ( SwitchClassSub ) this . getScreenRecord ( ) . getField ( ClassVars . CLASS_KEY ) . getListener ( SwitchClassSub . class ) ) . getSubScreen ( ) ; if ( screen instanceof Screen ) ( ( Screen ) screen ) . getMainRecord ( ) . writeAndRefresh ( false ) ; // Make sure data is current before doing any command .
else if ( screen instanceof GridScreen ) ( ( GridScreen ) screen ) . finalizeThisScreen ( ) ; // ? Validate current row
} } catch ( DBException e ) { e . printStackTrace ( ) ; } } if ( bFlag == false ) bFlag = super . doCommand ( strCommand , sourceSField , iCommandOptions ) ; // This will send the command to my parent
return bFlag ; |
public class JdbcCpoAdapter { /** * Update the Object in the datasource . The CpoAdapter will check to see if the object exists in the datasource . If it
* exists then the object will be updated . If it does not exist , an exception will be thrown
* < pre > Example :
* < code >
* class SomeObject so = new SomeObject ( ) ;
* class CpoAdapter cpo = null ;
* try {
* cpo = new JdbcCpoAdapter ( new JdbcDataSourceInfo ( driver , url , user , password , 1,1 , false ) ) ;
* } catch ( CpoException ce ) {
* / / Handle the error
* cpo = null ;
* if ( cpo ! = null ) {
* so . setId ( 1 ) ;
* so . setName ( " SomeName " ) ;
* try {
* cpo . updateObject ( so ) ;
* } catch ( CpoException ce ) {
* / / Handle the error
* < / code >
* < / pre >
* @ param obj This is an object that has been defined within the metadata of the datasource . If the class is not
* defined an exception will be thrown .
* @ return The number of objects updated in the datasource
* @ throws CpoException Thrown if there are errors accessing the datasource */
@ Override public < T > long updateObject ( T obj ) throws CpoException { } } | return processUpdateGroup ( obj , JdbcCpoAdapter . UPDATE_GROUP , null , null , null , null ) ; |
public class OnStableNodeFirst { /** * For each node , we fill ins to indicate the VMs
* that go on this node . We also fulfill stays and move
* TODO : stays and move seems redundant ! */
private void makeIncoming ( ) { } } | if ( stays == null && move == null ) { for ( BitSet in : ins ) { in . clear ( ) ; } stays = new BitSet ( ) ; move = new BitSet ( ) ; for ( int i = 0 ; i < hosts . length ; i ++ ) { if ( hosts [ i ] != null && hosts [ i ] . isInstantiated ( ) ) { int newPos = hosts [ i ] . getValue ( ) ; if ( oldPos [ i ] != - 1 && newPos != oldPos [ i ] ) { // The VM has move
ins [ newPos ] . set ( i ) ; move . set ( i ) ; } else if ( newPos == oldPos [ i ] ) { stays . set ( i ) ; } } } } |
public class JvmCompoundTypeReferenceImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public boolean eIsSet ( int featureID ) { } } | switch ( featureID ) { case TypesPackage . JVM_COMPOUND_TYPE_REFERENCE__TYPE : return type != null ; case TypesPackage . JVM_COMPOUND_TYPE_REFERENCE__REFERENCES : return references != null && ! references . isEmpty ( ) ; } return super . eIsSet ( featureID ) ; |
public class NodeTypeDataManagerImpl { /** * { @ inheritDoc } */
public PlainChangesLog setPrimaryType ( final NodeData nodeData , final InternalQName nodeTypeName ) throws RepositoryException { } } | final PlainChangesLog changesLog = new PlainChangesLogImpl ( ) ; final NodeTypeData ancestorDefinition = getNodeType ( nodeData . getPrimaryTypeName ( ) ) ; final NodeTypeData recipientDefinition = getNodeType ( nodeTypeName ) ; InternalQName [ ] ancestorAllNodeTypeNames = null ; if ( nodeData . getMixinTypeNames ( ) == null || nodeData . getMixinTypeNames ( ) . length == 0 ) { ancestorAllNodeTypeNames = new InternalQName [ ] { nodeData . getPrimaryTypeName ( ) } ; } else { ancestorAllNodeTypeNames = new InternalQName [ nodeData . getMixinTypeNames ( ) . length + 1 ] ; ancestorAllNodeTypeNames [ 0 ] = nodeData . getPrimaryTypeName ( ) ; System . arraycopy ( nodeData . getMixinTypeNames ( ) , 0 , ancestorAllNodeTypeNames , 1 , nodeData . getMixinTypeNames ( ) . length ) ; } InternalQName [ ] recipienAllNodeTypeNames = null ; if ( nodeData . getMixinTypeNames ( ) == null || nodeData . getMixinTypeNames ( ) . length == 0 ) { recipienAllNodeTypeNames = new InternalQName [ ] { nodeTypeName } ; } else { recipienAllNodeTypeNames = new InternalQName [ nodeData . getMixinTypeNames ( ) . length + 1 ] ; recipienAllNodeTypeNames [ 0 ] = nodeTypeName ; System . arraycopy ( nodeData . getMixinTypeNames ( ) , 0 , recipienAllNodeTypeNames , 1 , nodeData . getMixinTypeNames ( ) . length ) ; } final boolean recipientsMixVersionable = isNodeType ( Constants . MIX_VERSIONABLE , recipienAllNodeTypeNames ) ; final boolean ancestorIsMixVersionable = isNodeType ( Constants . MIX_VERSIONABLE , ancestorAllNodeTypeNames ) ; ItemAutocreator itemAutocreator = new ItemAutocreator ( this , valueFactory , dataManager , false ) ; if ( recipientsMixVersionable && ! ancestorIsMixVersionable ) { changesLog . addAll ( itemAutocreator . makeMixVesionableChanges ( nodeData ) . getAllStates ( ) ) ; } else if ( ! recipientsMixVersionable && ancestorIsMixVersionable ) { final StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( "Fail to change node type from " ) ; buffer . append ( ancestorDefinition . getName ( ) . getAsString ( ) ) ; buffer . append ( " to " ) ; buffer . append ( recipientDefinition . getName ( ) . getAsString ( ) ) ; buffer . append ( " because change from mix:versionable = true " ) ; buffer . append ( " to mix:versionable = false is not alowed" ) ; throw new ConstraintViolationException ( buffer . toString ( ) ) ; } // update primary type
final PropertyData item = ( PropertyData ) this . dataManager . getItemData ( nodeData , new QPathEntry ( Constants . JCR_PRIMARYTYPE , 1 ) , ItemType . PROPERTY ) ; final TransientPropertyData primaryTypeData = new TransientPropertyData ( item . getQPath ( ) , item . getIdentifier ( ) , item . getPersistedVersion ( ) , item . getType ( ) , item . getParentIdentifier ( ) , item . isMultiValued ( ) , new TransientValueData ( nodeTypeName ) ) ; changesLog . add ( ItemState . createUpdatedState ( primaryTypeData , true ) ) ; final List < NodeData > affectedNodes = new ArrayList < NodeData > ( ) ; affectedNodes . add ( nodeData ) ; // child nodes
final NodeDefinitionComparator nodeDefinitionComparator = new NodeDefinitionComparator ( this , dataManager , itemAutocreator , affectedNodes ) ; changesLog . addAll ( nodeDefinitionComparator . compare ( recipientDefinition , getAllChildNodeDefinitions ( ancestorAllNodeTypeNames ) , getAllChildNodeDefinitions ( recipienAllNodeTypeNames ) ) . getAllStates ( ) ) ; // properties defs
final PropertyDefinitionComparator propertyDefinitionComparator = new PropertyDefinitionComparator ( this , dataManager , itemAutocreator , affectedNodes , locationFactory ) ; changesLog . addAll ( propertyDefinitionComparator . compare ( recipientDefinition , getAllPropertyDefinitions ( ancestorAllNodeTypeNames ) , getAllPropertyDefinitions ( recipienAllNodeTypeNames ) ) . getAllStates ( ) ) ; return changesLog ; |
public class JFinal { /** * jfinal 3.5 更新 ( 2018-09-01 ) :
* 由于 jfinal 3.5 解决了 IDEA 下 JFinal . start ( 四个参数 ) 无法启动的问题 ,
* 此方法已被废弃 , 建议使用 JFinal . start ( 四个参数 ) 带四个参数的 start ( )
* 方法来启动项目 , IDEA 下也支持热加载 , 注意要先配置自动编译 , jfinal 是
* 通过监测被编译的 class 文件的修改来触发热加载的
* 用于在 IDEA 中 , 通过创建 main 方法的方式启动项目 , 不支持热加载
* 本方法存在的意义在于此方法启动的速度比 maven 下的 jetty 插件要快得多
* 注意 : 不支持热加载 。 建议通过 Ctrl + F5 快捷键 , 来快速重新启动项目 , 速度并不会比 eclipse 下的热加载慢多少
* 实际操作中是先通过按 Alt + 5 打开 debug 窗口 , 才能按 Ctrl + F5 重启项目 */
@ Deprecated public static void start ( String webAppDir , int port , String context ) { } } | // server = new JettyServerForIDEA ( webAppDir , port , context ) ;
// server . start ( ) ;
start ( webAppDir , port , context , 0 ) ; |
public class Matrix1NornRescaler { /** * Scaling factors for symmetric ( not singular ) matrices .
* Just the subdiagonal elements of the matrix are required .
* @ see Daniel Ruiz , " A scaling algorithm to equilibrate both rows and columns norms in matrices "
* @ see Philip A . Knight , Daniel Ruiz , Bora Ucar " A Symmetry Preserving Algorithm for Matrix Scaling " */
@ Override public DoubleMatrix1D getMatrixScalingFactorsSymm ( DoubleMatrix2D A ) { } } | DoubleFactory1D F1 = DoubleFactory1D . dense ; DoubleFactory2D F2 = DoubleFactory2D . sparse ; int dim = A . columns ( ) ; DoubleMatrix1D D1 = F1 . make ( dim , 1 ) ; DoubleMatrix2D AK = A . copy ( ) ; DoubleMatrix2D DR = F2 . identity ( dim ) ; DoubleMatrix1D DRInv = F1 . make ( dim ) ; int maxIteration = 50 ; for ( int k = 0 ; k <= maxIteration ; k ++ ) { double normR = - Double . MAX_VALUE ; for ( int i = 0 ; i < dim ; i ++ ) { double dri = getRowInfinityNorm ( AK , i ) ; DR . setQuick ( i , i , Math . sqrt ( dri ) ) ; DRInv . setQuick ( i , 1. / Math . sqrt ( dri ) ) ; normR = Math . max ( normR , Math . abs ( 1 - dri ) ) ; if ( Double . isNaN ( normR ) ) { throw new IllegalArgumentException ( "matrix is singular" ) ; } } if ( normR < eps ) { break ; } for ( int i = 0 ; i < dim ; i ++ ) { double prevD1I = D1 . getQuick ( i ) ; double newD1I = prevD1I * DRInv . getQuick ( i ) ; D1 . setQuick ( i , newD1I ) ; } if ( k == maxIteration ) { log . warn ( "max iteration reached" ) ; } AK = ColtUtils . diagonalMatrixMult ( DRInv , AK , DRInv ) ; } return D1 ; |
public class Sort { /** * Check if the byte array is reverse sorted . It loops through the entire byte
* array once , checking that the elements are reverse sorted .
* < br >
* < br >
* < i > Runtime : < / i > O ( n )
* @ param byteArray the byte array to check
* @ return < i > true < / i > if the byte array is reverse sorted , else < i > false < / i > . */
public static boolean isReverseSorted ( byte [ ] byteArray ) { } } | for ( int i = 0 ; i < byteArray . length - 1 ; i ++ ) { if ( byteArray [ i ] < byteArray [ i + 1 ] ) { return false ; } } return true ; |
public class PGPMessageSigner { /** * @ see MessageSigner # signMessage ( InputStream , String , String , InputStream , OutputStream )
* @ param privateKeyOfSender
* the private key of the sender
* @ param userIdForPrivateKey
* the user id of the sender
* @ param passwordOfPrivateKey
* the password for the private key
* @ param message
* the message / data to verify
* @ param signature
* the ( detached ) signature
* @ return */
@ Override public boolean signMessage ( InputStream privateKeyOfSender , final String userIdForPrivateKey , String passwordOfPrivateKey , InputStream message , OutputStream signature ) { } } | LOGGER . trace ( "signMessage(InputStream, String, String, InputStream, OutputStream)" ) ; LOGGER . trace ( "Private Key: {}, User ID: {}, Password: {}, Data: {}, Signature: {}" , privateKeyOfSender == null ? "not set" : "set" , userIdForPrivateKey , passwordOfPrivateKey == null ? "not set" : "********" , message == null ? "not set" : "set" , signature == null ? "not set" : "set" ) ; boolean result = false ; try { LOGGER . debug ( "Retrieving Private Key" ) ; PGPPrivateKey privateKey = findPrivateKey ( privateKeyOfSender , passwordOfPrivateKey , new KeyFilter < PGPSecretKey > ( ) { @ Override public boolean accept ( PGPSecretKey secretKey ) { boolean result = secretKey . isSigningKey ( ) ; if ( result ) { Iterator < String > userIdIterator = secretKey . getUserIDs ( ) ; boolean containsUserId = false ; while ( userIdIterator . hasNext ( ) && ! containsUserId ) { containsUserId |= userIdForPrivateKey . equals ( userIdIterator . next ( ) ) ; } } return result ; } } ) ; LOGGER . debug ( "Initializing signature generator" ) ; final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator ( new BcPGPContentSignerBuilder ( privateKey . getPublicKeyPacket ( ) . getAlgorithm ( ) , HashAlgorithmTags . SHA256 ) ) ; signatureGenerator . init ( PGPSignature . BINARY_DOCUMENT , privateKey ) ; LOGGER . debug ( "Wrapping signature stream in ArmoredOutputStream and PGOutputStream" ) ; try ( BCPGOutputStream outputStream = new BCPGOutputStream ( new ArmoredOutputStream ( signature ) ) ) { IOUtils . process ( message , new IOUtils . StreamHandler ( ) { @ Override public void handleStreamBuffer ( byte [ ] buffer , int offset , int length ) throws IOException { signatureGenerator . update ( buffer , offset , length ) ; } } ) ; LOGGER . info ( "Writing signature out" ) ; signatureGenerator . generate ( ) . encode ( outputStream ) ; } result = true ; } catch ( IOException | PGPException e ) { result &= false ; LOGGER . error ( "{}" , e . getMessage ( ) ) ; } return result ; |
public class Filter { /** * Adds an attribute to the dashboard filter .
* @ param attribute The attribute to add to the dashboard filter */
public void addAttribute ( String attribute ) { } } | if ( this . attributes == null ) this . attributes = new ArrayList < String > ( ) ; this . attributes . add ( attribute ) ; |
public class ADTLearner { /** * Verify the proposed ADT replacement by checking the actual behavior of the system under learning . During the
* verification process , the system under learning may behave differently from what the ADT replacement suggests :
* This means a counterexample is witnessed and it is added to the queue of counterexamples for later investigation .
* Albeit observing diverging behavior , this method continues to trying to construct a valid ADT using the observed
* output . If for two states , no distinguishing output can be observed , the states a separated by means of { @ link
* # resolveAmbiguities ( ADTNode , ADTNode , ADTState , Set ) } .
* @ param nodeToReplace
* the old ADT ( subtree ) to be replaced
* @ param replacement
* the new ADT ( subtree ) . Must have the form of an ADS , i . e . no reset nodes
* @ param cachedLeaves
* a set containing the leaves of the current tree , so they don ' t have to be re - fetched for every
* replacement verification
* @ param cutout
* the set of states not covered by the new ADT
* @ return A verified ADT that correctly distinguishes the states covered by the original ADT */
private ADTNode < ADTState < I , O > , I , O > verifyADS ( final ADTNode < ADTState < I , O > , I , O > nodeToReplace , final ADTNode < ADTState < I , O > , I , O > replacement , final Set < ADTNode < ADTState < I , O > , I , O > > cachedLeaves , final Set < ADTState < I , O > > cutout ) { } } | final Map < ADTState < I , O > , Pair < Word < I > , Word < O > > > traces = new LinkedHashMap < > ( ) ; ADTUtil . collectLeaves ( replacement ) . forEach ( x -> traces . put ( x . getHypothesisState ( ) , ADTUtil . buildTraceForNode ( x ) ) ) ; final Pair < Word < I > , Word < O > > parentTrace = ADTUtil . buildTraceForNode ( nodeToReplace ) ; final Word < I > parentInput = parentTrace . getFirst ( ) ; final Word < O > parentOutput = parentTrace . getSecond ( ) ; ADTNode < ADTState < I , O > , I , O > result = null ; // validate
for ( final Map . Entry < ADTState < I , O > , Pair < Word < I > , Word < O > > > entry : traces . entrySet ( ) ) { final ADTState < I , O > state = entry . getKey ( ) ; final Word < I > accessSequence = state . getAccessSequence ( ) ; this . oracle . reset ( ) ; accessSequence . forEach ( this . oracle :: query ) ; parentInput . forEach ( this . oracle :: query ) ; final Word < I > adsInput = entry . getValue ( ) . getFirst ( ) ; final Word < O > adsOutput = entry . getValue ( ) . getSecond ( ) ; final WordBuilder < I > inputWb = new WordBuilder < > ( adsInput . size ( ) ) ; final WordBuilder < O > outputWb = new WordBuilder < > ( adsInput . size ( ) ) ; final Iterator < I > inputIter = adsInput . iterator ( ) ; final Iterator < O > outputIter = adsOutput . iterator ( ) ; boolean equal = true ; while ( equal && inputIter . hasNext ( ) ) { final I in = inputIter . next ( ) ; final O realOut = this . oracle . query ( in ) ; final O expectedOut = outputIter . next ( ) ; inputWb . append ( in ) ; outputWb . append ( realOut ) ; if ( ! expectedOut . equals ( realOut ) ) { equal = false ; } } final Word < I > traceInput = inputWb . toWord ( ) ; final Word < O > traceOutput = outputWb . toWord ( ) ; if ( ! equal ) { this . openCounterExamples . add ( new DefaultQuery < > ( accessSequence . concat ( parentInput , traceInput ) , this . hypothesis . computeOutput ( state . getAccessSequence ( ) ) . concat ( parentOutput , traceOutput ) ) ) ; } final ADTNode < ADTState < I , O > , I , O > trace = ADTUtil . buildADSFromObservation ( traceInput , traceOutput , state ) ; if ( result == null ) { result = trace ; } else { if ( ! ADTUtil . mergeADS ( result , trace ) ) { this . resolveAmbiguities ( nodeToReplace , result , state , cachedLeaves ) ; } } } for ( final ADTState < I , O > s : cutout ) { this . resolveAmbiguities ( nodeToReplace , result , s , cachedLeaves ) ; } return result ; |
public class MessageControllerManager { /** * without jdk8 , @ Repeatable doesn ' t work , so we use @ JsTopicControls annotation and parse it
* @ param topic
* @ param controllers
* @ return */
JsTopicMessageController getJsTopicMessageControllerFromIterable ( String topic , Iterable < JsTopicMessageController < ? > > controllers ) { } } | if ( null == controllers || null == topic ) { return null ; } for ( JsTopicMessageController < ? > jsTopicMessageController : controllers ) { JsTopicControls jsTopicControls = jsTopicControlsTools . getJsTopicControlsFromProxyClass ( jsTopicMessageController . getClass ( ) ) ; if ( null != jsTopicControls ) { JsTopicControl [ ] jsTopicControlList = jsTopicControls . value ( ) ; for ( JsTopicControl jsTopicControl : jsTopicControlList ) { if ( topic . equals ( jsTopicControl . value ( ) ) ) { logger . debug ( "Found messageController for topic '{}' from JsTopicControls annotation" , topic ) ; return jsTopicMessageController ; } } } } return null ; |
public class ServerFilter { /** * Method allow to restrict status of target servers
* @ param statuses is a list target server statuses
* @ return { @ link GroupFilter } */
public ServerFilter status ( String ... statuses ) { } } | allItemsNotNull ( statuses , "Statuses" ) ; predicate = predicate . and ( combine ( ServerMetadata :: getStatus , in ( statuses ) ) ) ; return this ; |
public class QrCodeActivity { /** * This function is invoked in its own thread and can take as long as you want . */
@ Override protected void processImage ( ImageBase image ) { } } | // Detect the QR Code
// GrayU8 image was specified in onCreate ( )
long time0 = System . nanoTime ( ) ; detector . process ( ( GrayU8 ) image ) ; long time1 = System . nanoTime ( ) ; timeDetection . update ( ( time1 - time0 ) * 1e-6 ) ; // Create a copy of what we will visualize here . In general you want a copy because
// the UI and image processing is done on two different threads
synchronized ( foundQR ) { foundQR . reset ( ) ; List < QrCode > found = detector . getDetections ( ) ; for ( int i = 0 ; i < found . size ( ) ; i ++ ) { QrCode qr = found . get ( i ) ; foundQR . grow ( ) . set ( qr . bounds ) ; message = qr . message ; } } |
public class SSOCookieHelperImpl { /** * Returns the SSO domain based . Expected return values are derived from the domain name
* of the host name in the request which may be matched with the WebAppConfig domain name
* list . If there is no match with the ssoDomainList and useURLDomain = true , returns the
* hostname domain . Otherwise it returns null for the following conditions :
* 1 ) ssoDomainList is null
* 2 ) The hostname is not fully qualify or localhost
* 3 ) useURLDomain is false
* 3 ) Request URL is an IP address
* @ param req
* @ param ssoDomainList
* @ param useDomainFromURL
* @ return */
@ Override public String getSSODomainName ( HttpServletRequest req , List < String > ssoDomainList , boolean useDomainFromURL ) { } } | try { final String host = getHostNameFromRequestURL ( req ) ; String ipAddr = AccessController . doPrivileged ( new PrivilegedAction < String > ( ) { @ Override public String run ( ) { return getHostIPAddr ( host ) ; } } ) ; if ( host . equals ( ipAddr ) || host . indexOf ( "." ) == - 1 ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) Tr . debug ( tc , "URL host is an IP or locahost, no SSO domain will be set." ) ; return null ; } String domain = host . substring ( host . indexOf ( "." ) ) ; if ( ssoDomainList != null && ! ssoDomainList . isEmpty ( ) ) { for ( Iterator < String > itr = ssoDomainList . iterator ( ) ; itr . hasNext ( ) ; ) { String dm = itr . next ( ) ; if ( domain . endsWith ( dm ) ) return dm ; } } if ( useDomainFromURL ) { return domain ; } } catch ( MalformedURLException e ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) Tr . debug ( tc , "Unexpected exception getting request SSO domain" , new Object [ ] { e } ) ; } return null ; |
public class QueryImpl { /** * ( non - Javadoc )
* @ see javax . persistence . Query # getSingleResult ( ) */
@ Override public Object getSingleResult ( ) { } } | // to fetch a single result form database .
isSingleResult = true ; List results = getResultList ( ) ; isSingleResult = false ; return onReturnResults ( results ) ; |
public class NameSpaceAddressManager { /** * The purpose of this method is to update in memory references to primary
* and standby . Please override this method and do the zookeeper specific
* logic in the method and call this method on successful zookeeper write . */
public void setPrimary ( InstanceId ofPrimary ) throws IOException { } } | if ( ofPrimary == null ) { // failover in progress
primaryNode = null ; standbyNode = null ; return ; } switch ( ofPrimary ) { case NODEZERO : primaryNode = getNodeZero ( ) ; standbyNode = getNodeOne ( ) ; case NODEONE : primaryNode = getNodeOne ( ) ; standbyNode = getNodeZero ( ) ; } |
public class SlideShowView { /** * Once the previous slide has disappeared , we remove its view from our hierarchy and add it to
* the views that can be re - used .
* @ param position The position of the slide to recycle
* @ param view The view to recycle */
private void recyclePreviousSlideView ( int position , View view ) { } } | // Remove view from our hierarchy
removeView ( view ) ; // Add to recycled views
int viewType = adapter . getItemViewType ( position ) ; recycledViews . put ( viewType , view ) ; view . destroyDrawingCache ( ) ; if ( view instanceof ImageView ) { ( ( ImageView ) view ) . setImageDrawable ( null ) ; } Log . d ( "SlideShowView" , "View added to recycling bin: " + view ) ; // The adapter can recycle some memory with discard slide
adapter . discardSlide ( position ) ; // The adapter can prepare the next slide
prepareSlide ( getPlaylist ( ) . getNextSlide ( ) ) ; |
public class DetectCircleRegularGrid { /** * Puts the grid into a canonical orientation */
@ Override protected void putGridIntoCanonical ( Grid g ) { } } | // first put it into a plausible solution
if ( g . columns != numCols ) { rotateGridCCW ( g ) ; } if ( isClockWise ( g ) ) { flipHorizontal ( g ) ; } // pick the solutin which puts ( 0,0 ) coordinate the closest to the top left corner to resolve ambiguity
if ( g . columns == g . rows ) { closestCorner [ 0 ] = g . get ( 0 , 0 ) . center . normSq ( ) ; closestCorner [ 1 ] = g . get ( numRows - 1 , 0 ) . center . normSq ( ) ; closestCorner [ 2 ] = g . get ( numRows - 1 , numCols - 1 ) . center . normSq ( ) ; closestCorner [ 3 ] = g . get ( 0 , numCols - 1 ) . center . normSq ( ) ; int best = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) { if ( closestCorner [ i ] < closestCorner [ best ] ) { best = i ; } } for ( int i = 0 ; i < best ; i ++ ) { rotateGridCCW ( g ) ; } } else { double d00 = g . get ( 0 , 0 ) . center . normSq ( ) ; double d11 = g . get ( numRows - 1 , numCols - 1 ) . center . normSq ( ) ; if ( d11 < d00 ) { rotateGridCCW ( g ) ; rotateGridCCW ( g ) ; } } |
public class JavaTypeUtil { /** * 判断指定数组是否是java八大基本类型 ( int [ ] 、 short [ ] 等 , 不包含对应的封装类型 )
* @ param name 指定数组名称
* @ return 如果是基本类型则返回 < code > true < / code > */
public static boolean isGeneralArrayType ( String name ) { } } | return "byte[]" . equals ( name ) || "short[]" . equals ( name ) || "int[]" . equals ( name ) || "long[]" . equals ( name ) || "double[]" . equals ( name ) || "float[]" . equals ( name ) || "boolean[]" . equals ( name ) || "char[]" . equals ( name ) ; |
public class CSSExpression { /** * Shortcut method to add a simple text value .
* @ param sValue
* The value to be added . May neither be < code > null < / code > nor empty .
* @ return this */
@ Nonnull public CSSExpression addTermSimple ( @ Nonnull @ Nonempty final String sValue ) { } } | return addMember ( new CSSExpressionMemberTermSimple ( sValue ) ) ; |
public class EJSWrapper { /** * p116276 - add code to push / pop java namespace onto ThreadContext . */
@ Override public Handle getHandle ( ) throws RemoteException { } } | ComponentMetaDataAccessorImpl cmdAccessor = null ; // p125735
try { cmdAccessor = ComponentMetaDataAccessorImpl . getComponentMetaDataAccessor ( ) ; // p125735
cmdAccessor . beginContext ( bmd ) ; // p125735
return beanId . getHome ( ) . createHandle ( beanId ) ; } finally { if ( cmdAccessor != null ) cmdAccessor . endContext ( ) ; // p125735
} |
public class YamlDataSet { /** * Applies the case - insensitive strategy ( orthography ) to the given < code > name < / code > , if
* { @ link # isCaseSensitiveTableNames ( ) } is < code > false < / code > .
* @ param name The identifier name
* @ return The adjusted identifier name
* @ see Orthography */
String applyCaseInsensitivity ( String name ) { } } | return ( name != null ) ? isCaseSensitiveTableNames ( ) ? name : isCaseInsensitiveStrategyLowerCase ( ) ? name . toLowerCase ( Locale . ENGLISH ) : name . toUpperCase ( Locale . ENGLISH ) : null ; |
public class FormatterResolver { /** * パターンを指定して新たに書式を作成する 。
* @ param formatPattern 書式パターン 。
* @ return パースしたフォーマッタ 。 */
public CellFormatter createFormatter ( final String formatPattern ) { } } | final CellFormatter formatter = customFormatterFactory . create ( formatPattern ) ; return formatter ; |
public class UserPreferences { /** * Gets the int .
* @ param key the key
* @ param def the def
* @ return the int
* @ see java . util . prefs . Preferences # getInt ( java . lang . String , int ) */
public static int getInt ( final String key , final int def ) { } } | try { return systemRoot . getInt ( fixKey ( key ) , def ) ; } catch ( final Exception e ) { // just eat the exception to avoid any system crash on system issues
return def ; } |
public class MapUtil { /** * 创建Map包装类MapWrapper < br >
* { @ link MapWrapper } 对Map做一次包装
* @ param map 被代理的Map
* @ return { @ link MapWrapper }
* @ since 4.5.4 */
public static < K , V > MapWrapper < K , V > wrap ( Map < K , V > map ) { } } | return new MapWrapper < K , V > ( map ) ; |
public class S2SBaseFormGenerator { /** * This method will get the childAnswer for sub question */
protected String getAnswers ( Integer questionSeqId , List < ? extends AnswerHeaderContract > answerHeaders ) { } } | String answer = null ; String childAnswer = null ; StringBuilder stringBuilder = new StringBuilder ( ) ; if ( answerHeaders != null && ! answerHeaders . isEmpty ( ) ) { for ( AnswerHeaderContract answerHeader : answerHeaders ) { List < ? extends AnswerContract > answerDetails = answerHeader . getAnswers ( ) ; for ( AnswerContract answers : answerDetails ) { if ( questionSeqId . equals ( getQuestionAnswerService ( ) . findQuestionById ( answers . getQuestionId ( ) ) . getQuestionSeqId ( ) ) ) { answer = answers . getAnswer ( ) ; if ( answer != null ) { if ( ! answer . equals ( NOT_ANSWERED ) ) { stringBuilder . append ( answer ) ; stringBuilder . append ( "," ) ; } } childAnswer = stringBuilder . toString ( ) ; } } } } return childAnswer ; |
public class WicketImage { /** * { @ inheritDoc } */
@ Override protected void onComponentTag ( final ComponentTag tag ) { } } | checkComponentTag ( tag , "img" ) ; super . onComponentTag ( tag ) ; final String modelObjectAsString = getDefaultModelObjectAsString ( ) ; final String contextPath = ApplicationExtensions . getContextPath ( ( WebApplication ) getApplication ( ) ) ; final String imagePath = contextPath + modelObjectAsString ; tag . put ( "src" , imagePath ) ; |
public class ManagedInstanceVulnerabilityAssessmentsInner { /** * Gets the managed instance ' s vulnerability assessment policies .
* @ param nextPageLink The NextLink from the previous successful call to List operation .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the PagedList & lt ; ManagedInstanceVulnerabilityAssessmentInner & gt ; object */
public Observable < ServiceResponse < Page < ManagedInstanceVulnerabilityAssessmentInner > > > listByInstanceNextWithServiceResponseAsync ( final String nextPageLink ) { } } | return listByInstanceNextSinglePageAsync ( nextPageLink ) . concatMap ( new Func1 < ServiceResponse < Page < ManagedInstanceVulnerabilityAssessmentInner > > , Observable < ServiceResponse < Page < ManagedInstanceVulnerabilityAssessmentInner > > > > ( ) { @ Override public Observable < ServiceResponse < Page < ManagedInstanceVulnerabilityAssessmentInner > > > call ( ServiceResponse < Page < ManagedInstanceVulnerabilityAssessmentInner > > page ) { String nextPageLink = page . body ( ) . nextPageLink ( ) ; if ( nextPageLink == null ) { return Observable . just ( page ) ; } return Observable . just ( page ) . concatWith ( listByInstanceNextWithServiceResponseAsync ( nextPageLink ) ) ; } } ) ; |
public class VariantMerger { /** * Calls { @ link # merge ( Variant , Collection ) }
* @ param current { @ link Variant } to update .
* @ param load { @ link Variant } to be merged .
* @ return Merged Variant object . */
public Variant merge ( Variant current , Variant load ) { } } | return merge ( current , Collections . singleton ( load ) ) ; |
public class ge_scalarmult_base { /** * CONVERT # include " crypto _ uint32 . h " */
static int equal ( byte b , byte c ) { } } | int ub = b ; int uc = c ; int x = ub ^ uc ; /* 0 : yes ; 1 . . 255 : no */
int y = x ; /* 0 : yes ; 1 . . 255 : no */
y -= 1 ; /* 4294967295 : yes ; 0 . . 254 : no */
y >>>= 31 ; /* 1 : yes ; 0 : no */
return y ; |
public class ExtensionFeedItem { /** * Gets the campaignTargeting value for this ExtensionFeedItem .
* @ return campaignTargeting * Campaign targeting specifying what campaign this extension
* can serve with .
* On update , if the field is left unspecified , the previous
* campaign targeting state
* will not be changed .
* On update , if the field is set with an empty FeedItemCampaignTargeting ,
* the
* campaign targeting will be cleared .
* Note : If adGroupTargeting and campaignTargeting are
* set ( either in the request or pre - existing
* from a previous request ) , the targeted campaign must
* match the targeted adgroup ' s campaign .
* If only adGroupTargeting is specified and there is
* no campaignTargeting , then a
* campaignTargeting will be set to the targeted adgroup ' s
* campaign . */
public com . google . api . ads . adwords . axis . v201809 . cm . FeedItemCampaignTargeting getCampaignTargeting ( ) { } } | return campaignTargeting ; |
public class RaftNodeImpl { /** * Updates Raft group members .
* @ see RaftState # updateGroupMembers ( long , Collection ) */
public void updateGroupMembers ( long logIndex , Collection < Endpoint > members ) { } } | state . updateGroupMembers ( logIndex , members ) ; printMemberState ( ) ; |
public class Unchecked { /** * Wrap a { @ link CheckedDoubleFunction } in a { @ link DoubleFunction } .
* Example :
* < code > < pre >
* DoubleStream . of ( 1.0 , 2.0 , 3.0 ) . mapToObj ( Unchecked . doubleFunction ( d - > {
* if ( d & lt ; 0.0)
* throw new Exception ( " Only positive numbers allowed " ) ;
* return " " + d ;
* < / pre > < / code > */
public static < R > DoubleFunction < R > doubleFunction ( CheckedDoubleFunction < R > function ) { } } | return doubleFunction ( function , THROWABLE_TO_RUNTIME_EXCEPTION ) ; |
public class ValueAnimator { /** * Constructs and returns a ValueAnimator that animates between int values . A single
* value implies that that value is the one being animated to . However , this is not typically
* useful in a ValueAnimator object because there is no way for the object to determine the
* starting value for the animation ( unlike ObjectAnimator , which can derive that value
* from the target object and property being animated ) . Therefore , there should typically
* be two or more values .
* @ param values A set of values that the animation will animate between over time .
* @ return A ValueAnimator object that is set up to animate between the given values . */
public static ValueAnimator ofInt ( int ... values ) { } } | ValueAnimator anim = new ValueAnimator ( ) ; anim . setIntValues ( values ) ; return anim ; |
public class JavaScriptEscape { /** * Perform a JavaScript < strong > unescape < / strong > operation on a < tt > String < / tt > input ,
* writing results to a < tt > Writer < / tt > .
* No additional configuration arguments are required . Unescape operations
* will always perform < em > complete < / em > JavaScript unescape of SECs , x - based , u - based
* and octal escapes .
* This method is < strong > thread - safe < / strong > .
* @ param text the < tt > String < / tt > to be unescaped .
* @ param writer the < tt > java . io . Writer < / tt > to which the unescaped 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
* @ since 1.1.2 */
public static void unescapeJavaScript ( final String text , final Writer writer ) throws IOException { } } | if ( writer == null ) { throw new IllegalArgumentException ( "Argument 'writer' cannot be null" ) ; } if ( text == null ) { return ; } if ( text . indexOf ( '\\' ) < 0 ) { // Fail fast , avoid more complex ( and less JIT - table ) method to execute if not needed
writer . write ( text ) ; return ; } JavaScriptEscapeUtil . unescape ( new InternalStringReader ( text ) , writer ) ; |
public class DeleteDeploymentConfigRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( DeleteDeploymentConfigRequest deleteDeploymentConfigRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( deleteDeploymentConfigRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( deleteDeploymentConfigRequest . getDeploymentConfigName ( ) , DEPLOYMENTCONFIGNAME_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class AsianPersonRecognition { /** * 人名识别
* @ param term
* @ param offe
* @ param freq */
private Term nameFind ( int offe , int beginFreq , int size ) { } } | StringBuilder sb = new StringBuilder ( ) ; int undefinite = 0 ; skip = false ; PersonNatureAttr pna = null ; int index = 0 ; int freq = 0 ; double allFreq = 0 ; Term term = null ; int i = offe ; for ( ; i < terms . length ; i ++ ) { // 走到结尾处识别出来一个名字 .
if ( terms [ i ] == null ) { continue ; } term = terms [ i ] ; pna = term . termNatures ( ) . personAttr ; // 在这个长度的这个位置的词频 , 如果没有可能就干掉 , 跳出循环
if ( ( freq = pna . getFreq ( size , index ) ) == 0 ) { return null ; } if ( pna . allFreq > 0 ) { undefinite ++ ; } sb . append ( term . getName ( ) ) ; allFreq += Math . log ( term . termNatures ( ) . allFreq + 1 ) ; allFreq += - Math . log ( ( freq ) ) ; index ++ ; if ( index == size + 2 ) { break ; } } double score = - Math . log ( FACTORY [ size ] ) ; score += allFreq ; double endFreq = 0 ; // 开始寻找结尾词
boolean flag = true ; while ( flag ) { i ++ ; if ( i >= terms . length ) { endFreq = 10 ; flag = false ; } else if ( terms [ i ] != null ) { int twoWordFreq = NgramLibrary . getTwoWordFreq ( term , terms [ i ] ) ; if ( twoWordFreq > 3 ) { return null ; } endFreq = terms [ i ] . termNatures ( ) . personAttr . end + 1 ; flag = false ; } } score -= Math . log ( endFreq ) ; score -= Math . log ( beginFreq ) ; if ( score > - 3 ) { return null ; } if ( allFreq > 0 && undefinite > 0 ) { return null ; } skip = undefinite == 0 ; term = new Term ( sb . toString ( ) , offe , TermNatures . NR ) ; term . selfScore ( score ) ; return term ; |
public class BulkEmailDestination { /** * A list of tags , in the form of name / value pairs , to apply to an email that you send using
* < code > SendBulkTemplatedEmail < / code > . Tags correspond to characteristics of the email that you define , so that you
* can publish email sending events .
* @ param replacementTags
* A list of tags , in the form of name / value pairs , to apply to an email that you send using
* < code > SendBulkTemplatedEmail < / code > . Tags correspond to characteristics of the email that you define , so
* that you can publish email sending events . */
public void setReplacementTags ( java . util . Collection < MessageTag > replacementTags ) { } } | if ( replacementTags == null ) { this . replacementTags = null ; return ; } this . replacementTags = new com . amazonaws . internal . SdkInternalList < MessageTag > ( replacementTags ) ; |
public class HBaseSchemaManager { /** * create method creates schema and table for the list of tableInfos .
* @ param tableInfos
* list of TableInfos . */
protected void create ( List < TableInfo > tableInfos ) { } } | try { if ( admin . isTableAvailable ( databaseName ) ) { addColumnFamilies ( tableInfos , admin . getTableDescriptor ( databaseName . getBytes ( ) ) , false ) ; } else { createTable ( tableInfos ) ; } if ( admin . isTableDisabled ( databaseName ) ) { admin . enableTable ( databaseName ) ; } } catch ( TableNotFoundException e ) { logger . info ( "creating table " + databaseName ) ; } catch ( IOException ioex ) { logger . error ( "Either table isn't in enabled state or some network problem, Caused by: " , ioex ) ; throw new SchemaGenerationException ( ioex , "Hbase" ) ; } |
public class UnicodeSetStringSpan { /** * Algorithm for spanNot ( ) = = span ( SpanCondition . NOT _ CONTAINED )
* Theoretical algorithm :
* - Iterate through the string , and at each code point boundary :
* + If the code point there is in the set , then return with the current position .
* + If a set string matches at the current position , then return with the current position .
* Optimized implementation :
* ( Same assumption as for span ( ) above . )
* Create and cache a spanNotSet which contains
* all of the single code points of the original set but none of its strings .
* For each set string add its initial code point to the spanNotSet .
* ( Also add its final code point for spanNotBack ( ) . )
* - Loop :
* + Do spanLength = spanNotSet . span ( SpanCondition . NOT _ CONTAINED ) .
* + If the current code point is in the original set , then return the current position .
* + If any set string matches at the current position , then return the current position .
* + If there is no match at the current position , neither for the code point
* there nor for any set string , then skip this code point and continue the loop .
* This happens for set - string - initial code points that were added to spanNotSet
* when there is not actually a match for such a set string .
* @ param s The string to be spanned
* @ param start The start index that the span begins
* @ param outCount If not null : Receives the number of code points across the span .
* @ return the limit ( exclusive end ) of the span */
private int spanNot ( CharSequence s , int start , OutputInt outCount ) { } } | int length = s . length ( ) ; int pos = start , rest = length - start ; int stringsLength = strings . size ( ) ; int count = 0 ; do { // Span until we find a code point from the set ,
// or a code point that starts or ends some string .
int spanLimit ; if ( outCount == null ) { spanLimit = spanNotSet . span ( s , pos , SpanCondition . NOT_CONTAINED ) ; } else { spanLimit = spanNotSet . spanAndCount ( s , pos , SpanCondition . NOT_CONTAINED , outCount ) ; outCount . value = count = count + outCount . value ; } if ( spanLimit == length ) { return length ; // Reached the end of the string .
} pos = spanLimit ; rest = length - spanLimit ; // Check whether the current code point is in the original set ,
// without the string starts and ends .
int cpLength = spanOne ( spanSet , s , pos , rest ) ; if ( cpLength > 0 ) { return pos ; // There is a set element at pos .
} // Try to match the strings at pos .
for ( int i = 0 ; i < stringsLength ; ++ i ) { if ( spanLengths [ i ] == ALL_CP_CONTAINED ) { continue ; // Irrelevant string .
} String string = strings . get ( i ) ; int length16 = string . length ( ) ; if ( length16 <= rest && matches16CPB ( s , pos , length , string , length16 ) ) { return pos ; // There is a set element at pos .
} } // The span ( while not contained ) ended on a string start / end which is
// not in the original set . Skip this code point and continue .
// cpLength < 0
pos -= cpLength ; rest += cpLength ; ++ count ; } while ( rest != 0 ) ; if ( outCount != null ) { outCount . value = count ; } return length ; // Reached the end of the string . |
public class StringHelper { /** * Get a string that is filled at the beginning with the passed character until
* the minimum length is reached . If the input string is empty , the result is a
* string with the provided len only consisting of the passed characters . If the
* input String is longer than the provided length , it is returned unchanged .
* @ param sSrc
* Source string . May be < code > null < / code > .
* @ param nMinLen
* Minimum length . Should be & gt ; 0.
* @ param cFront
* The character to be used at the beginning
* @ return A non - < code > null < / code > string that has at least nLen chars */
@ Nonnull public static String getWithLeading ( @ Nullable final String sSrc , @ Nonnegative final int nMinLen , final char cFront ) { } } | return _getWithLeadingOrTrailing ( sSrc , nMinLen , cFront , true ) ; |
public class ComponentHandler { /** * Method handles UIComponent tree creation in accordance with the JSF 1.2 spec .
* < ol >
* < li > First determines this UIComponent ' s id by calling { @ link # getId ( FaceletContext ) getId ( FaceletContext ) } . < / li >
* < li > Search the parent for an existing UIComponent of the id we just grabbed < / li >
* < li > If found , { @ link # markForDeletion ( UIComponent ) mark } its children for deletion . < / li >
* < li > If < i > not < / i > found , call { @ link # createComponent ( FaceletContext ) createComponent } .
* < ol >
* < li > Only here do we apply { @ link ObjectHandler # setAttributes ( FaceletContext , Object ) attributes } < / li >
* < li > Set the UIComponent ' s id < / li >
* < li > Set the RendererType of this instance < / li >
* < / ol >
* < / li >
* < li > Now apply the nextHandler , passing the UIComponent we ' ve created / found . < / li >
* < li > Now add the UIComponent to the passed parent < / li >
* < li > Lastly , if the UIComponent already existed ( found ) , then { @ link # finalizeForDeletion ( UIComponent ) finalize }
* for deletion . < / li >
* < / ol >
* @ see javax . faces . view . facelets . FaceletHandler # apply ( javax . faces . view . facelets . FaceletContext , javax . faces . component . UIComponent )
* @ throws TagException
* if the UIComponent parent is null */
public final void apply ( FaceletContext ctx , UIComponent parent ) throws IOException , FacesException , ELException { } } | // make sure our parent is not null
if ( parent == null ) { throw new TagException ( this . tag , "Parent UIComponent was null" ) ; } // possible facet scoped
String facetName = this . getFacetName ( ctx , parent ) ; // our id
String id = ctx . generateUniqueId ( this . tagId ) ; // grab our component
UIComponent c = ComponentSupport . findChildByTagId ( parent , id ) ; boolean componentFound = false ; if ( c != null ) { componentFound = true ; // mark all children for cleaning
if ( log . isLoggable ( Level . FINE ) ) { log . fine ( this . tag + " Component[" + id + "] Found, marking children for cleanup" ) ; } ComponentSupport . markForDeletion ( c ) ; } else { c = this . createComponent ( ctx ) ; if ( log . isLoggable ( Level . FINE ) ) { log . fine ( this . tag + " Component[" + id + "] Created: " + c . getClass ( ) . getName ( ) ) ; } this . setAttributes ( ctx , c ) ; // mark it owned by a facelet instance
c . getAttributes ( ) . put ( ComponentSupport . MARK_CREATED , id ) ; // assign our unique id
if ( this . id != null ) { c . setId ( this . id . getValue ( ctx ) ) ; } else { UIViewRoot root = ComponentSupport . getViewRoot ( ctx , parent ) ; if ( root != null ) { String uid = root . createUniqueId ( ) ; c . setId ( uid ) ; } } if ( this . rendererType != null ) { c . setRendererType ( this . rendererType ) ; } // hook method
this . onComponentCreated ( ctx , c , parent ) ; } // first allow c to get populated
this . applyNextHandler ( ctx , c ) ; // finish cleaning up orphaned children
if ( componentFound ) { ComponentSupport . finalizeForDeletion ( c ) ; if ( facetName == null ) { parent . getChildren ( ) . remove ( c ) ; } } this . onComponentPopulated ( ctx , c , parent ) ; // add to the tree afterwards
// this allows children to determine if it ' s
// been part of the tree or not yet
if ( facetName == null ) { parent . getChildren ( ) . add ( c ) ; } else { parent . getFacets ( ) . put ( facetName , c ) ; } |
public class Algorithms { /** * Generates an unused algorithm id .
* @ return an algorithm id < code > String < / code > . */
String getNextAlgorithmObjectId ( ) { } } | if ( idsToAlgorithms . size ( ) == Integer . MAX_VALUE ) { throw new IllegalArgumentException ( "Maximum number of algorithm objects reached" ) ; } while ( true ) { String candidate = "ALGORITHM_" + currentAlgorithmId ++ ; if ( isUniqueAlgorithmObjectId ( candidate ) ) { return candidate ; } } |
public class CmsTextBox { /** * Enables or disables read - only mode . < p >
* @ param readOnly if true , enables read - only mode , else disables it */
public void setReadOnly ( boolean readOnly ) { } } | m_textbox . setReadOnly ( readOnly ) ; if ( readOnly ) { addStyleName ( CSS . textBoxReadOnly ( ) ) ; } else { removeStyleName ( CSS . textBoxReadOnly ( ) ) ; } |
public class UberData { /** * Take a list of { @ link Affordance } - based { @ link Link } s , and overlay them with intersecting , declared { @ link Link } s .
* @ param affordanceBasedLinks
* @ param links
* @ return */
private static List < UberData > mergeDeclaredLinksIntoAffordanceLinks ( List < UberData > affordanceBasedLinks , List < UberData > links ) { } } | return affordanceBasedLinks . stream ( ) . flatMap ( affordance -> links . stream ( ) . filter ( link -> link . getUrl ( ) . equals ( affordance . getUrl ( ) ) ) . map ( link -> { if ( link . getAction ( ) == affordance . getAction ( ) ) { List < LinkRelation > rels = new ArrayList < > ( link . getRel ( ) ) ; rels . addAll ( affordance . getRel ( ) ) ; return affordance . withName ( rels . get ( 0 ) . value ( ) ) . withRel ( rels ) ; } else { return affordance ; } } ) ) . collect ( Collectors . toList ( ) ) ; |
public class DefaultFileSet { /** * Creates a new builder with the specified base folder and manifest .
* @ param baseFolder the base folder
* @ param manifest the manifest
* @ param manifestPath the path to the manifest within the file set
* @ return returns a new builder
* @ throws IllegalArgumentException if the manifest isn ' t a descendant of the base folder */
public static DefaultFileSet . Builder with ( BaseFolder baseFolder , AnnotatedFile manifest , String manifestPath ) { } } | return new Builder ( baseFolder , manifest , manifestPath ) ; |
public class PropsUtils { /** * Convert props to json string
* @ param props props
* @ param localOnly include local prop sets only or not
* @ return json string format of props */
public static String toJSONString ( final Props props , final boolean localOnly ) { } } | final Map < String , String > map = toStringMap ( props , localOnly ) ; return JSONUtils . toJSON ( map ) ; |
public class StateHelper { /** * < p > Returns the Clock implementation using commons discovery . < / p >
* @ return the Clock implementation using commons discovery . */
public static Clock getClockImpl ( ) { } } | Clock c = null ; try { DiscoverClass dc = new DiscoverClass ( ) ; c = ( Clock ) dc . newInstance ( Clock . class , Clock . DEFAULT_CLOCK_IMPL ) ; } catch ( Exception ex ) { // ignore as default implementation will be used .
} return c ; |
public class HtmlBaseTag { /** * Sets the onKeyPress javascript event .
* @ param onkeypress the onKeyPress event .
* @ jsptagref . attributedescription The onKeyPress JavaScript event .
* @ jsptagref . databindable false
* @ jsptagref . attributesyntaxvalue < i > string _ onKeyPress < / i >
* @ netui : attribute required = " false " rtexprvalue = " true "
* description = " The onKeyPress JavaScript event . " */
public void setOnKeyPress ( String onkeypress ) { } } | AbstractHtmlState tsh = getState ( ) ; tsh . registerAttribute ( AbstractHtmlState . ATTR_JAVASCRIPT , ONKEYPRESS , onkeypress ) ; |
public class CernunnosDataImporter { /** * / * ( non - Javadoc )
* @ see org . apereo . portal . io . xml . crn . AbstractDom4jImporter # importDataNode ( org . apereo . portal . utils . Tuple ) */
@ Override protected void importDataElement ( Tuple < String , Element > data ) { } } | final RuntimeRequestResponse request = new RuntimeRequestResponse ( ) ; request . setAttribute ( Attributes . NODE , data . second ) ; request . setAttribute ( Attributes . LOCATION , StringUtils . trimToEmpty ( data . first ) ) ; final ReturnValueImpl result = new ReturnValueImpl ( ) ; final TaskResponse response = new RuntimeRequestResponse ( Collections . < String , Object > singletonMap ( "Attributes.RETURN_VALUE" , result ) ) ; this . task . perform ( request , response ) ; |
public class CollectionPrinter { /** * List to json string string .
* @ param list the list
* @ return the string */
static public String listToJSONString ( List < ? > list ) { } } | if ( list == null || list . size ( ) == 0 ) { return "[]" ; } StringBuilder sb = new StringBuilder ( "[" ) ; for ( Object o : list ) { buildAppendString ( sb , o ) . append ( ',' ) . append ( ' ' ) ; } return sb . delete ( sb . length ( ) - 2 , sb . length ( ) ) . append ( ']' ) . toString ( ) ; |
public class Node { /** * Remove a named attribute . < br / >
* @ param name
* The attribute name
* @ return The attribute value that was removed , or null if the attribute with the given name was not found .
* @ throws IllegalArgumentException
* If the name is not specified */
public String removeAttribute ( final String name ) throws IllegalArgumentException { } } | // Precondition check
if ( name == null || name . length ( ) == 0 ) { throw new IllegalArgumentException ( "name must be specified" ) ; } final String remove = this . attributes . remove ( name ) ; return remove ; |
public class Configuration { /** * Adds metadata that will be displayed at the main page of the report . It is useful when there is a few reports are
* generated at the same time but with different parameters / configurations .
* @ param name name of the property
* @ param value value of the property */
public void addClassifications ( String name , String value ) { } } | classifications . add ( new AbstractMap . SimpleEntry < > ( name , value ) ) ; |
public class SpatialReferenceSystemDao { /** * { @ inheritDoc } */
@ Override public List < SpatialReferenceSystem > queryForEq ( String fieldName , Object value ) throws SQLException { } } | List < SpatialReferenceSystem > srsList = super . queryForEq ( fieldName , value ) ; setDefinition_12_063 ( srsList ) ; return srsList ; |
public class TrmMeLinkRequestImpl { /** * Set the requesting ME UUID in the message .
* Javadoc description supplied by TrmMeLinkRequest interface . */
public void setRequestingMeUuid ( SIBUuid8 value ) { } } | if ( value != null ) jmo . setField ( TrmFirstContactAccess . BODY_MELINKREQUEST_REQUESTINGMEUUID , value . toByteArray ( ) ) ; else jmo . setField ( TrmFirstContactAccess . BODY_MELINKREQUEST_REQUESTINGMEUUID , null ) ; |
public class MongoNativeExtractor { /** * Gets split data collection shard enviroment .
* @ param shards the shards
* @ param dbName the db name
* @ param collectionName the collection name
* @ return the split data collection shard enviroment */
private Pair < BasicDBList , List < ServerAddress > > getSplitDataCollectionShardEnviroment ( Map < String , String [ ] > shards , String dbName , String collectionName ) { } } | MongoClient mongoClient = null ; try { Set < String > keys = shards . keySet ( ) ; for ( String key : keys ) { List < ServerAddress > addressList = getServerAddressList ( Arrays . asList ( shards . get ( key ) ) ) ; mongoClient = new MongoClient ( addressList ) ; BasicDBList dbList = getSplitData ( mongoClient . getDB ( dbName ) . getCollection ( collectionName ) ) ; if ( dbList != null ) { return Pair . create ( dbList , addressList ) ; } } } catch ( UnknownHostException e ) { throw new DeepGenericException ( e ) ; } finally { if ( mongoClient != null ) { mongoClient . close ( ) ; } } return null ; |
public class Component { /** * Filename of the form " < ksname > / < cfname > - [ tmp - ] [ < version > - ] < gen > - < component > " ,
* @ return A Descriptor for the SSTable , and a Component for this particular file .
* TODO move descriptor into Component field */
public static Pair < Descriptor , Component > fromFilename ( File directory , String name ) { } } | Pair < Descriptor , String > path = Descriptor . fromFilename ( directory , name ) ; // parse the component suffix
Type type = Type . fromRepresentation ( path . right ) ; // build ( or retrieve singleton for ) the component object
Component component ; switch ( type ) { case DATA : component = Component . DATA ; break ; case PRIMARY_INDEX : component = Component . PRIMARY_INDEX ; break ; case FILTER : component = Component . FILTER ; break ; case COMPRESSION_INFO : component = Component . COMPRESSION_INFO ; break ; case STATS : component = Component . STATS ; break ; case DIGEST : component = Component . DIGEST ; break ; case CRC : component = Component . CRC ; break ; case SUMMARY : component = Component . SUMMARY ; break ; case TOC : component = Component . TOC ; break ; case CUSTOM : component = new Component ( Type . CUSTOM , path . right ) ; break ; default : throw new IllegalStateException ( ) ; } return Pair . create ( path . left , component ) ; |
public class MorphingClockSkin { /** * * * * * * Resizing * * * * * */
@ Override protected void resize ( ) { } } | width = clock . getWidth ( ) - clock . getInsets ( ) . getLeft ( ) - clock . getInsets ( ) . getRight ( ) ; height = clock . getHeight ( ) - clock . getInsets ( ) . getTop ( ) - clock . getInsets ( ) . getBottom ( ) ; if ( aspectRatio * width > height ) { width = 1 / ( aspectRatio / height ) ; } else if ( 1 / ( aspectRatio / height ) > width ) { height = aspectRatio * width ; } if ( width > 0 && height > 0 ) { pane . setMaxSize ( width , height ) ; pane . relocate ( ( clock . getWidth ( ) - height ) * 0.5 , ( clock . getHeight ( ) - height ) * 0.5 ) ; canvas . setWidth ( width ) ; canvas . setHeight ( height ) ; dotSize = height * 0.045455 ; spacer = height * 0.022727 ; digitWidth = 8 * dotSize + 7 * spacer ; digitHeight = 15 * dotSize + 14 * spacer ; digitSpacer = height * 0.09090909 ; } |
public class QuadraticWeight { /** * Evaluate quadratic weight . stddev is ignored . */
@ Override public double getWeight ( double distance , double max , double stddev ) { } } | if ( max <= 0 ) { return 1.0 ; } double relativedistance = distance / max ; return 1.0 - 0.9 * relativedistance * relativedistance ; |
public class JobWorkspaceRestore { /** * Will be restored the workspace .
* @ throws Throwable
* will be generated the Throwable */
protected void restoreWorkspace ( ) throws Throwable { } } | boolean restored = true ; RepositoryImpl repository = ( RepositoryImpl ) repositoryService . getRepository ( repositoryName ) ; try { RepositoryEntry reEntry = repository . getConfiguration ( ) ; backupManager . restore ( new BackupChainLog ( backupChainLogFile ) , reEntry . getName ( ) , wEntry , false ) ; } catch ( InvalidItemStateException e ) { restored = false ; throw new WorkspaceRestoreExeption ( "Workspace '" + "/" + repositoryName + "/" + wEntry . getName ( ) + "' can not be restored! There was database error!" , e ) ; } catch ( Throwable t ) // NOSONAR
{ restored = false ; throw new WorkspaceRestoreExeption ( "Workspace '" + "/" + repositoryName + "/" + wEntry . getName ( ) + "' can not be restored!" , t ) ; } finally { if ( ! restored ) { try { removeWorkspace ( repository , wEntry . getName ( ) ) ; } catch ( Throwable thr ) // NOSONAR
{ throw new WorkspaceRestoreExeption ( "Workspace '" + "/" + repositoryName + "/" + wEntry . getName ( ) + "' can not be restored!" , thr ) ; } } } |
public class UrlFactory { /** * Finds a link to object if one exists .
* @ param o
* Object that might have a page that can be linked .
* @ return Link to objects page or the toString ( ) text if no link could not
* be created . */
public static String getUrl ( Object o ) { } } | if ( o instanceof VerifierRule ) { VerifierRule rule = ( VerifierRule ) o ; return getRuleUrl ( UrlFactory . RULE_FOLDER , rule . getPath ( ) , rule . getName ( ) ) ; } return o . toString ( ) ; |
public class RdmaServerEndpoint { /** * Extract the first connection request on the queue of pending connections .
* @ throws Exception on failure . */
public C accept ( ) throws IOException { } } | try { synchronized ( this ) { if ( connState != CONN_STATE_READY_FOR_ACCEPT ) { throw new IOException ( "bind needs to be called before accept (1), current state =" + connState ) ; } logger . info ( "starting accept" ) ; if ( requested . peek ( ) == null ) { wait ( ) ; } } C endpoint = requested . poll ( ) ; logger . info ( "connect request received" ) ; endpoint . accept ( ) ; return endpoint ; } catch ( Exception e ) { throw new IOException ( e ) ; } |
public class Ssh2Channel { /** * Closes the channel . No data may be sent or receieved after this method
* completes . */
public void close ( ) { } } | boolean performClose = false ; ; synchronized ( this ) { if ( ! closing && state == CHANNEL_OPEN ) { performClose = closing = true ; } } if ( performClose ) { synchronized ( listeners ) { for ( Enumeration < ChannelEventListener > e = listeners . elements ( ) ; e . hasMoreElements ( ) ; ) { ( e . nextElement ( ) ) . channelClosing ( this ) ; } } try { // Close the ChannelOutputStream
out . close ( ! isLocalEOF ) ; // Send our close message
ByteArrayWriter msg = new ByteArrayWriter ( 5 ) ; msg . write ( SSH_MSG_CHANNEL_CLOSE ) ; msg . writeInt ( remoteid ) ; try { if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Sending SSH_MSG_CHANNEL_CLOSE id=" + channelid + " rid=" + remoteid ) ; } connection . sendMessage ( msg . toByteArray ( ) , true ) ; } catch ( SshException ex1 ) { if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Exception attempting to send SSH_MSG_CHANNEL_CLOSE id=" + channelid + " rid=" + remoteid , ex1 ) ; } } finally { msg . close ( ) ; } this . state = CHANNEL_CLOSED ; } catch ( EOFException eof ) { // Ignore this is the message store informing of close / eof
} catch ( SshIOException ex ) { if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "SSH Exception during close reason=" + ex . getRealException ( ) . getReason ( ) + " id=" + channelid + " rid=" + remoteid , ex . getRealException ( ) ) ; } // IO Error during close so the connection has dropped
connection . transport . disconnect ( TransportProtocol . CONNECTION_LOST , "IOException during channel close: " + ex . getMessage ( ) ) ; } catch ( IOException ex ) { if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Exception during close id=" + channelid + " rid=" + remoteid , ex ) ; } // IO Error during close so the connection has dropped
connection . transport . disconnect ( TransportProtocol . CONNECTION_LOST , "IOException during channel close: " + ex . getMessage ( ) ) ; } finally { checkCloseStatus ( ms . isClosed ( ) ) ; } } |
public class ExecutionStats { /** * Add statistics about sent emails .
* @ param recipients The list of recipients .
* @ param storageUsed If a remote storage was used . */
public void addEmailStats ( final InternetAddress [ ] recipients , final boolean storageUsed ) { } } | this . storageUsed = storageUsed ; for ( InternetAddress recipient : recipients ) { emailDests . add ( recipient . getAddress ( ) ) ; } |
public class ElementMatchers { /** * Only matches method descriptions that yield the provided signature token .
* @ param token The signature token to match against .
* @ param < T > The type of the matched object .
* @ return A matcher for a method with the provided signature token . */
public static < T extends MethodDescription > ElementMatcher . Junction < T > hasSignature ( MethodDescription . SignatureToken token ) { } } | return new SignatureTokenMatcher < T > ( is ( token ) ) ; |
public class ThreadPoolController { /** * report variable values that may be set by system property */
private void reportSystemProperties ( ) { } } | StringBuilder sb = new StringBuilder ( ) ; sb . append ( "\n interval: " ) . append ( String . format ( "%6d" , Long . valueOf ( interval ) ) ) ; sb . append ( " hangInterval: " ) . append ( String . format ( "%6d" , Long . valueOf ( hangInterval ) ) ) ; sb . append ( " compareRange: " ) . append ( String . format ( "%6d" , Integer . valueOf ( compareRange ) ) ) ; sb . append ( " highCpu: " ) . append ( String . format ( "%4d" , Integer . valueOf ( highCpu ) ) ) ; sb . append ( "\n tputRatioPruneLevel: " ) . append ( String . format ( "%2.2f" , Double . valueOf ( tputRatioPruneLevel ) ) ) ; sb . append ( " poolTputRatioHigh: " ) . append ( String . format ( "%2.2f" , Double . valueOf ( poolTputRatioHigh ) ) ) ; sb . append ( " poolTputRatioLow: " ) . append ( String . format ( "%2.2f" , Double . valueOf ( poolTputRatioLow ) ) ) ; sb . append ( " compareSpanRatioMultiplier: " ) . append ( String . format ( "%3d" , Integer . valueOf ( compareSpanRatioMultiplier ) ) ) ; sb . append ( "\n growScoreFilterLevel: " ) . append ( String . format ( "%2.2f" , Double . valueOf ( growScoreFilterLevel ) ) ) ; sb . append ( " shrinkScoreFilterLevel: " ) . append ( String . format ( "%2.2f" , Double . valueOf ( shrinkScoreFilterLevel ) ) ) ; sb . append ( " growShrinkDiffFilter: " ) . append ( String . format ( "%2.2f" , Double . valueOf ( growShrinkDiffFilter ) ) ) ; sb . append ( " dataAgePruneLevel: " ) . append ( String . format ( "%2.2f" , Double . valueOf ( dataAgePruneLevel ) ) ) ; sb . append ( " compareSpanPruneMultiplier: " ) . append ( String . format ( "%3d" , Integer . valueOf ( compareSpanPruneMultiplier ) ) ) ; sb . append ( "\n poolIncrementMin: " ) . append ( String . format ( "%3d" , Integer . valueOf ( poolIncrementMin ) ) ) ; sb . append ( " poolIncrementMax: " ) . append ( String . format ( "%4d" , Integer . valueOf ( poolIncrementMax ) ) ) ; sb . append ( " poolIncrementBoundLow: " ) . append ( String . format ( "%4d" , Integer . valueOf ( poolIncrementBoundLow ) ) ) ; sb . append ( " poolIncrementBoundMedium: " ) . append ( String . format ( "%4d" , Integer . valueOf ( poolIncrementBoundMedium ) ) ) ; sb . append ( " minimumDesiredPoolSizeAdjustments : " ) . append ( String . format ( "%4d" , Integer . valueOf ( minimumDesiredPoolSizeAdjustments ) ) ) ; sb . append ( "\n resetDistroStdDevEwmaRatio: " ) . append ( String . format ( "%2.2f" , Double . valueOf ( resetDistroStdDevEwmaRatio ) ) ) ; sb . append ( " resetDistroNewTputEwmaRatio: " ) . append ( String . format ( "%2.2f" , Double . valueOf ( resetDistroNewTputEwmaRatio ) ) ) ; sb . append ( " resetDistroConsecutiveOutliers: " ) . append ( String . format ( "%2.2f" , Double . valueOf ( resetDistroConsecutiveOutliers ) ) ) ; Tr . event ( tc , "Initial config settings:" , sb ) ; |
public class Action { /** * Sets content type to the response */
public static Action contentType ( final String contentType ) { } } | return new Action ( r -> { r . setContentType ( contentType ) ; return r ; } ) ; |
public class IfcMaterialListImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ SuppressWarnings ( "unchecked" ) public EList < IfcMaterial > getMaterials ( ) { } } | return ( EList < IfcMaterial > ) eGet ( Ifc2x3tc1Package . Literals . IFC_MATERIAL_LIST__MATERIALS , true ) ; |
public class Sets { /** * Creates a { @ code SortedSet } instance containing the given elements .
* @ param elements the elements that the set should contain
* @ return a newly - created { @ code SortedSet } containing those elements ( minus
* duplicates ) */
public static < E > SortedSet < E > newSortedSet ( E ... elements ) { } } | SortedSet < E > set = new TreeSet < E > ( ) ; Collections . addAll ( set , elements ) ; return set ; |
public class BitVector { /** * NOTE : preserved for performance testing */
int firstOneInRange ( int from , int to ) { } } | if ( from < 0 ) throw new IllegalArgumentException ( ) ; if ( to < from ) throw new IllegalArgumentException ( ) ; from += start ; to += start ; if ( to > finish ) throw new IllegalArgumentException ( ) ; return firstOneInRangeAdj ( from , to ) - start ; |
public class GoogleWebmasterDataFetcherImpl { /** * This doesn ' t cover all cases but more than 99.9 % captured .
* According to the standard ( RFC - 3986 ) , here are possible characters :
* unreserved = ALPHA / DIGIT / " - " / " . " / " _ " / " ~ "
* reserved = gen - delims / sub - delims
* gen - delims = " : " / " / " / " ? " / " # " / " [ " / " ] " / " @ "
* sub - delims = " ! " / " $ " / " & " / " ' " / " ( " / " ) " / " * " / " + " / " , " / " ; " / " = "
* Not included :
* reserved = gen - delims / sub - delims
* gen - delims = " [ " / " ] "
* sub - delims = " ( " / " ) " / " , " / " ; " */
private ArrayList < String > getUrlPartitions ( String prefix ) { } } | ArrayList < String > expanded = new ArrayList < > ( ) ; // The page prefix is case insensitive , A - Z is not necessary .
for ( char c = 'a' ; c <= 'z' ; ++ c ) { expanded . add ( prefix + c ) ; } for ( int num = 0 ; num <= 9 ; ++ num ) { expanded . add ( prefix + num ) ; } expanded . add ( prefix + "-" ) ; expanded . add ( prefix + "." ) ; expanded . add ( prefix + "_" ) ; // most important
expanded . add ( prefix + "~" ) ; expanded . add ( prefix + "/" ) ; // most important
expanded . add ( prefix + "%" ) ; // most important
expanded . add ( prefix + ":" ) ; expanded . add ( prefix + "?" ) ; expanded . add ( prefix + "#" ) ; expanded . add ( prefix + "@" ) ; expanded . add ( prefix + "!" ) ; expanded . add ( prefix + "$" ) ; expanded . add ( prefix + "&" ) ; expanded . add ( prefix + "+" ) ; expanded . add ( prefix + "*" ) ; expanded . add ( prefix + "'" ) ; expanded . add ( prefix + "=" ) ; return expanded ; |
public class ProgressMonitoringBeanFactoryPostProcessor { /** * Notifies this instance ' s associated progress monitor of progress made
* while processing the given bean factory .
* @ param beanFactory the bean factory that is to be processed . */
public void postProcessBeanFactory ( final ConfigurableListableBeanFactory beanFactory ) throws BeansException { } } | if ( beanFactory == null ) { return ; } String [ ] beanNames = beanFactory . getBeanDefinitionNames ( ) ; int singletonBeanCount = 0 ; for ( int i = 0 ; i < beanNames . length ; i ++ ) { // using beanDefinition to check singleton property because when
// accessing through
// context ( applicationContext . isSingleton ( beanName ) ) , bean will be
// created already ,
// possibly bypassing other BeanFactoryPostProcessors
BeanDefinition beanDefinition = beanFactory . getBeanDefinition ( beanNames [ i ] ) ; if ( beanDefinition . isSingleton ( ) ) { singletonBeanCount ++ ; } } this . progressMonitor . taskStarted ( this . loadingAppContextMessage , singletonBeanCount ) ; beanFactory . addBeanPostProcessor ( new ProgressMonitoringBeanPostProcessor ( beanFactory ) ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.