signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class AttributeTypeServiceImpl { /** * Check if the new enriched type is broader the the previously found type
* @ return */
private boolean isBroader ( AttributeType enrichedTypeGuess , AttributeType columnTypeGuess ) { } } | if ( columnTypeGuess == null && enrichedTypeGuess != null || columnTypeGuess == null ) { return true ; } switch ( columnTypeGuess ) { case INT : return enrichedTypeGuess . equals ( INT ) || enrichedTypeGuess . equals ( LONG ) || enrichedTypeGuess . equals ( DECIMAL ) || enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; case DECIMAL : return enrichedTypeGuess . equals ( DECIMAL ) || enrichedTypeGuess . equals ( DATE ) || enrichedTypeGuess . equals ( DATE_TIME ) || enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; case LONG : return enrichedTypeGuess . equals ( LONG ) || enrichedTypeGuess . equals ( DECIMAL ) || enrichedTypeGuess . equals ( DATE ) || enrichedTypeGuess . equals ( DATE_TIME ) || enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; case BOOL : return enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; case STRING : return enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; case DATE_TIME : return enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; case DATE : return enrichedTypeGuess . equals ( STRING ) || enrichedTypeGuess . equals ( TEXT ) ; default : return false ; } |
public class MtasSolrComponentCollection { /** * String to string values .
* @ param stringValue the string value
* @ return the hash set
* @ throws IOException Signals that an I / O exception has occurred . */
private static HashSet < String > stringToStringValues ( String stringValue ) throws IOException { } } | // should be improved to support escaped characters
HashSet < String > stringValues = new HashSet < > ( ) ; JSONParser jsonParser = new JSONParser ( stringValue ) ; int event = jsonParser . nextEvent ( ) ; if ( event == JSONParser . ARRAY_START ) { while ( ( event = jsonParser . nextEvent ( ) ) != JSONParser . ARRAY_END ) { if ( jsonParser . getLevel ( ) == 1 ) { switch ( event ) { case JSONParser . STRING : stringValues . add ( jsonParser . getString ( ) ) ; break ; case JSONParser . BIGNUMBER : case JSONParser . NUMBER : case JSONParser . LONG : stringValues . add ( jsonParser . getNumberChars ( ) . toString ( ) ) ; break ; case JSONParser . BOOLEAN : stringValues . add ( Boolean . toString ( jsonParser . getBoolean ( ) ) ) ; break ; default : // do nothing
break ; } } } } else { throw new IOException ( "unsupported json structure" ) ; } return stringValues ; |
public class CompositeExclusionFilter { /** * / * ( non - Javadoc )
* @ see org . archive . wayback . resourceindex . SearchResultFilter # filterSearchResult ( org . archive . wayback . core . SearchResult ) */
public int filterObject ( CaptureSearchResult r ) { } } | Iterator < ExclusionFilter > itr = filters . iterator ( ) ; while ( itr . hasNext ( ) ) { ObjectFilter < CaptureSearchResult > filter = itr . next ( ) ; if ( filter == null ) { return FILTER_EXCLUDE ; } int result = filter . filterObject ( r ) ; if ( result != FILTER_INCLUDE ) { return result ; } } return FILTER_INCLUDE ; |
public class CPInstancePersistenceImpl { /** * Returns the first cp instance in the ordered set where CPDefinitionId = & # 63 ; .
* @ param CPDefinitionId the cp definition ID
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the first matching cp instance , or < code > null < / code > if a matching cp instance could not be found */
@ Override public CPInstance fetchByCPDefinitionId_First ( long CPDefinitionId , OrderByComparator < CPInstance > orderByComparator ) { } } | List < CPInstance > list = findByCPDefinitionId ( CPDefinitionId , 0 , 1 , orderByComparator ) ; if ( ! list . isEmpty ( ) ) { return list . get ( 0 ) ; } return null ; |
public class AbstractMapJsonDeserializer { /** * < p > newInstance < / p >
* @ param keyDeserializer { @ link KeyDeserializer } used to deserialize the keys .
* @ param valueDeserializer { @ link JsonDeserializer } used to deserialize the values .
* @ param < K > Type of the keys inside the { @ link AbstractMap }
* @ param < V > Type of the values inside the { @ link AbstractMap }
* @ return a new instance of { @ link AbstractMapJsonDeserializer } */
public static < K , V > AbstractMapJsonDeserializer < K , V > newInstance ( KeyDeserializer < K > keyDeserializer , JsonDeserializer < V > valueDeserializer ) { } } | return new AbstractMapJsonDeserializer < K , V > ( keyDeserializer , valueDeserializer ) ; |
public class CmsPermissionDialog { /** * Refreshes the display of the resource permission display . < p > */
@ SuppressWarnings ( "unchecked" ) private void refreshOwnEntries ( ) { } } | m_resourcePermissions . removeAllComponents ( ) ; String sitePath = m_cms . getSitePath ( m_resource ) ; // create new ArrayLists in which inherited and non inherited entries are stored
ArrayList < CmsAccessControlEntry > ownEntries = new ArrayList < CmsAccessControlEntry > ( ) ; try { Iterator < CmsAccessControlEntry > itAces = m_cms . getAccessControlEntries ( sitePath , false ) . iterator ( ) ; HashSet < CmsPermissionBean > newBeans = ( HashSet < CmsPermissionBean > ) ( ( HashSet < CmsPermissionBean > ) ( m_permissionToChange ) ) . clone ( ) ; while ( itAces . hasNext ( ) ) { CmsAccessControlEntry curEntry = itAces . next ( ) ; if ( ! curEntry . isInherited ( ) ) { // add the entry to the own rights list
CmsPermissionBean bean = CmsPermissionBean . getBeanForPrincipal ( m_permissionToChange , CmsPermissionBean . getPrincipalNameFromACE ( m_cms , curEntry ) ) ; if ( bean == null ) { ownEntries . add ( curEntry ) ; } else { if ( ! bean . isDeleted ( ) ) { ownEntries . add ( bean . toAccessControlEntry ( m_cms , m_resource . getStructureId ( ) ) ) ; } // No new entry - > remove from new list
newBeans . remove ( bean ) ; } } } for ( CmsPermissionBean newBean : newBeans ) { if ( ! newBean . isDeleted ( ) ) { ownEntries . add ( newBean . toAccessControlEntry ( m_cms , m_resource . getStructureId ( ) ) ) ; } } } catch ( CmsException e ) { // can usually be ignored
} addEntryTableToLayout ( ownEntries , m_resourcePermissions , true , false ) ; |
public class QueryBuilder { /** * Builds the query from the clauses .
* @ return the c query */
@ Override public String buildQuery ( ) { } } | validateQuery ( ) ; StringBuilder stringBuilder = new StringBuilder ( ) ; if ( ! Strings . isNullOrEmpty ( select ) ) { stringBuilder = stringBuilder . append ( SELECT ) . append ( " " ) . append ( select ) . append ( " " ) ; } if ( ! Strings . isNullOrEmpty ( from ) ) { stringBuilder = stringBuilder . append ( FROM ) . append ( " " ) . append ( from ) . append ( " " ) ; } if ( ! Strings . isNullOrEmpty ( where ) ) { stringBuilder = stringBuilder . append ( WHERE ) . append ( " " ) . append ( where ) . append ( " " ) ; } if ( ! Strings . isNullOrEmpty ( orderBy ) ) { stringBuilder = stringBuilder . append ( ORDER_BY ) . append ( " " ) . append ( orderBy ) . append ( " " ) ; } if ( limit != null ) { stringBuilder = stringBuilder . append ( LIMIT ) . append ( " " ) . append ( limit ) . append ( " " ) ; } if ( offset != null ) { stringBuilder = stringBuilder . append ( OFFSET ) . append ( " " ) . append ( offset ) . append ( " " ) ; } return stringBuilder . toString ( ) . trim ( ) ; |
public class ADatabaseSyntaxHelper { /** * Get the compatibility name by the db specific type .
* @ param dbSpecificType the db specific name , as for example DOUBLE ;
* @ return the compat data type ; */
public String ofDbType ( String dbSpecificType ) { } } | if ( dbSpecificType . equals ( TEXT ( ) ) ) { return COMPAT_TEXT ; } else if ( dbSpecificType . equals ( INTEGER ( ) ) ) { return COMPAT_INT ; } else if ( dbSpecificType . equals ( LONG ( ) ) ) { return COMPAT_LONG ; } else if ( dbSpecificType . equals ( REAL ( ) ) ) { return COMPAT_REAL ; } else if ( dbSpecificType . equals ( BLOB ( ) ) ) { return COMPAT_BLOB ; } else if ( dbSpecificType . equals ( CLOB ( ) ) ) { return COMPAT_CLOB ; } throw new RuntimeException ( "No type for name: " + dbSpecificType ) ; |
public class SelectObjectContentEventStream { /** * Apply the provided { @ link SelectObjectContentEventVisitor } to each { @ link SelectObjectContentEvent } in this stream
* in the order they are returned by S3 . This will lazily - load the events from S3 , minimizing the amount of memory used .
* This will raise a runtime exception if { @ link # getAllEvents ( ) } , { @ link # getRecordsInputStream ( ) } or { @ link # getEventsIterator ( ) }
* have already been used .
* After using this method , you still must { @ link # close ( ) } this object to release the connection to S3.
* @ param visitor The visitor that should be applied to each event in this stream . */
public void visitAllEvents ( SelectObjectContentEventVisitor visitor ) throws SelectObjectContentEventException { } } | Iterator < SelectObjectContentEvent > eventsIterator = getEventsIterator ( ) ; while ( eventsIterator . hasNext ( ) ) { eventsIterator . next ( ) . visit ( visitor ) ; } |
public class TransactionControlImpl { /** * Ensure that the local transaction context for the bean instance
* represented by the given BeanId is active on the thread . With
* the introduction of ActivitySessions in R5.0 the bean may have
* a sticky local tx context which needs to be resumed . < p > */
public TxContextChange setupLocalTxContext ( EJBKey key ) throws CSIException // d174358.1
{ } } | LocalTransactionCoordinator suspendedLocalTx = null ; Transaction suspendedGlobalTx = null ; // LIDB1673.2.1.5
LocalTransactionCoordinator activatedLocalTx = null ; BeanMetaData bmd = ( ( BeanId ) key ) . getHome ( ) . getBeanMetaData ( key ) ; int localTxBoundary = bmd . _localTran . getBoundary ( ) ; // See if global transaction is active on thread .
Transaction globalTxCoord = getGlobalCoord ( ) ; // LIDB1673.2.1.5
if ( globalTxCoord != null ) { // If sticky local tx exists for this bean , swap contexts .
// Otherwise , leave global tx on thread . Sticky local
// transctions may only be present if this is an EJB 2.0 bean
// with local transaction boundary set to ActivitySession .
// For EJB 1.1 , local transaction boundary may never be set to
// ActivitySession . This is enforced by a check in BeanMetaData .
if ( localTxBoundary == LocalTransactionSettings . BOUNDARY_ACTIVITY_SESSION ) { // d135218
// see if this bean has a suspended sticky local tx
LocalTransactionCoordinator stickyLocalTx = stickyLocalTxTable . remove ( key ) ; // If sticky local tx exists , swap contexts . The contexts
// will be swapped back by teardownLocalTxContext .
if ( stickyLocalTx != null ) { // 174358.1 - - - - - >
try { // d174358.1
suspendedGlobalTx = suspendGlobalTx ( TIMEOUT_CLOCK_STOP ) ; } // d174358.1
catch ( CSIException csie ) // d174358.1
{ // d174358.1
FFDCFilter . processException ( csie , CLASS_NAME + ".setupLocalTxContext" , "937" , this ) ; // d174358.3
stickyLocalTxTable . put ( key , stickyLocalTx ) ; // d174358.1
throw csie ; // d174358.1
} // d174358.1
// < - - - - - 174358.1
resumeLocalTx ( stickyLocalTx ) ; activatedLocalTx = stickyLocalTx ; } } // Else , there may be a local transaction context on the thread
} else { // See if there is already a local tx context on the thread
LocalTransactionCoordinator currentLocalTx = getLocalCoord ( ) ; // See if this bean also has a sticky local tx . Sticky local
// transctions may only be present if this is an EJB 2.0 bean
// with local transaction boundary set to ActivitySession . For
// EJB 1.1 beans , local tx boundary may not be set to ActivitySession .
// This is enforced by a check in BeanMetaData .
LocalTransactionCoordinator stickyLocalTx = null ; if ( localTxBoundary == LocalTransactionSettings . BOUNDARY_ACTIVITY_SESSION ) { // d135218
stickyLocalTx = stickyLocalTxTable . remove ( key ) ; } if ( ( currentLocalTx != null ) && ( stickyLocalTx != null ) ) { // Local tx exists on thread , but bean also has a sticky local tx
// so swap contexts now . The contexts will be swapped back by
// teardownLocalTxContext .
suspendLocalTx ( ) ; suspendedLocalTx = currentLocalTx ; resumeLocalTx ( stickyLocalTx ) ; activatedLocalTx = stickyLocalTx ; // If sticky local tx exists , but thread has no local tx resume sticky
// local tx . The sticky local tx will be suspended again by
// teardownLocalTxContext .
} else if ( ( currentLocalTx == null ) && ( stickyLocalTx != null ) ) { resumeLocalTx ( stickyLocalTx ) ; activatedLocalTx = stickyLocalTx ; // Otherwise , do nothing . The thread may have an existing local tx context
// or no transaction context at all .
} else { // do nothing
} } // end if no global tx present
return ( new TxContextChange ( suspendedLocalTx , suspendedGlobalTx , activatedLocalTx , key ) ) ; |
public class SerializedFormBuilder { /** * Build the field deprecation information .
* @ param node the XML element that specifies which components to document
* @ param fieldsContentTree content tree to which the documentation will be added */
public void buildFieldDeprecationInfo ( XMLNode node , Content fieldsContentTree ) { } } | if ( ! currentClass . definesSerializableFields ( ) ) { FieldDoc field = ( FieldDoc ) currentMember ; fieldWriter . addMemberDeprecatedInfo ( field , fieldsContentTree ) ; } |
public class ScriptableObject { /** * Implements SameValue as described in ES5 9.12 , additionally checking
* if new value is defined .
* @ param newValue the new value
* @ param currentValue the current value
* @ return true if values are the same as defined by ES5 9.12 */
protected boolean sameValue ( Object newValue , Object currentValue ) { } } | if ( newValue == NOT_FOUND ) { return true ; } if ( currentValue == NOT_FOUND ) { currentValue = Undefined . instance ; } // Special rules for numbers : NaN is considered the same value ,
// while zeroes with different signs are considered different .
if ( currentValue instanceof Number && newValue instanceof Number ) { double d1 = ( ( Number ) currentValue ) . doubleValue ( ) ; double d2 = ( ( Number ) newValue ) . doubleValue ( ) ; if ( Double . isNaN ( d1 ) && Double . isNaN ( d2 ) ) { return true ; } if ( d1 == 0.0 && Double . doubleToLongBits ( d1 ) != Double . doubleToLongBits ( d2 ) ) { return false ; } } return ScriptRuntime . shallowEq ( currentValue , newValue ) ; |
public class ExpressionBuilder { /** * ( non - Javadoc )
* @ see com . sun . el . parser . NodeVisitor # visit ( com . sun . el . parser . Node ) */
@ Override public void visit ( Node node ) throws ELException { } } | if ( node instanceof AstFunction ) { AstFunction funcNode = ( AstFunction ) node ; Method m = null ; if ( this . fnMapper != null ) { m = fnMapper . resolveFunction ( funcNode . getPrefix ( ) , funcNode . getLocalName ( ) ) ; } // References to variables that refer to lambda expressions will be
// parsed as functions . This is handled at runtime but at this point
// need to treat it as a variable rather than a function .
if ( m == null && this . varMapper != null && funcNode . getPrefix ( ) . length ( ) == 0 ) { this . varMapper . resolveVariable ( funcNode . getLocalName ( ) ) ; return ; } if ( this . fnMapper == null ) { throw new ELException ( MessageFactory . get ( "error.fnMapper.null" ) ) ; } if ( m == null ) { throw new ELException ( MessageFactory . get ( "error.fnMapper.method" , funcNode . getOutputName ( ) ) ) ; } int methodParameterCount = m . getParameterTypes ( ) . length ; // AstFunction - > MethodParameters - > Parameters ( )
int inputParameterCount = node . jjtGetChild ( 0 ) . jjtGetNumChildren ( ) ; if ( m . isVarArgs ( ) && inputParameterCount < methodParameterCount - 1 || ! m . isVarArgs ( ) && inputParameterCount != methodParameterCount ) { throw new ELException ( MessageFactory . get ( "error.fnMapper.paramcount" , funcNode . getOutputName ( ) , "" + methodParameterCount , "" + node . jjtGetChild ( 0 ) . jjtGetNumChildren ( ) ) ) ; } } else if ( node instanceof AstIdentifier && this . varMapper != null ) { String variable = ( ( AstIdentifier ) node ) . getImage ( ) ; // simply capture it
this . varMapper . resolveVariable ( variable ) ; } |
public class Budget { /** * The cost filters , such as service or region , that are applied to a budget .
* AWS Budgets supports the following services as a filter for RI budgets :
* < ul >
* < li >
* Amazon Elastic Compute Cloud - Compute
* < / li >
* < li >
* Amazon Redshift
* < / li >
* < li >
* Amazon Relational Database Service
* < / li >
* < li >
* Amazon ElastiCache
* < / li >
* < li >
* Amazon Elasticsearch Service
* < / li >
* < / ul >
* @ param costFilters
* The cost filters , such as service or region , that are applied to a budget . < / p >
* AWS Budgets supports the following services as a filter for RI budgets :
* < ul >
* < li >
* Amazon Elastic Compute Cloud - Compute
* < / li >
* < li >
* Amazon Redshift
* < / li >
* < li >
* Amazon Relational Database Service
* < / li >
* < li >
* Amazon ElastiCache
* < / li >
* < li >
* Amazon Elasticsearch Service
* < / li >
* @ return Returns a reference to this object so that method calls can be chained together . */
public Budget withCostFilters ( java . util . Map < String , java . util . List < String > > costFilters ) { } } | setCostFilters ( costFilters ) ; return this ; |
public class ClientConnection { /** * Send the given byte [ ] as a message to the client .
* @ param message */
public synchronized void sendMessage ( final byte [ ] message ) { } } | this . send ( ReefServiceProtos . JobStatusProto . newBuilder ( ) . setIdentifier ( this . jobIdentifier ) . setState ( ReefServiceProtos . State . RUNNING ) . setMessage ( ByteString . copyFrom ( message ) ) . build ( ) ) ; |
public class YankPoolManager { /** * Closes all connection pools */
protected synchronized void releaseAllConnectionPools ( ) { } } | for ( HikariDataSource pool : pools . values ( ) ) { if ( pool != null ) { logger . info ( "Releasing pool: {}..." , pool . getPoolName ( ) ) ; pool . close ( ) ; } } |
public class CallOptions { /** * Get the value for a custom option or its inherent default .
* @ param key Key identifying option */
@ ExperimentalApi ( "https://github.com/grpc/grpc-java/issues/1869" ) @ SuppressWarnings ( "unchecked" ) public < T > T getOption ( Key < T > key ) { } } | Preconditions . checkNotNull ( key , "key" ) ; for ( int i = 0 ; i < customOptions . length ; i ++ ) { if ( key . equals ( customOptions [ i ] [ 0 ] ) ) { return ( T ) customOptions [ i ] [ 1 ] ; } } return key . defaultValue ; |
public class OidcCommonClientRequest { /** * do not overridden */
public void errorCommon ( String msgCode , Object [ ] objects ) { } } | if ( ! bInboundSupported ) { Tr . error ( tcCommon , msgCode , objects ) ; } |
public class WriteResources { /** * WriteDetailLine Method . */
public void writeDetailLine ( Record registration , StreamOut out , boolean bResourceListBundle ) { } } | String strKey = registration . getField ( Registration . KEY_VALUE ) . toString ( ) ; String strValue = registration . getField ( Registration . OBJECT_VALUE ) . toString ( ) ; strValue = ResourcesUtilities . fixPropertyValue ( strValue , bResourceListBundle ) ; if ( bResourceListBundle ) out . writeit ( "\t{\"" + strKey + "\", " + strValue + "}" ) ; else out . writeit ( ResourcesUtilities . fixPropertyKey ( strKey ) + "=" + strValue ) ; |
public class DefaultGroovyMethods { /** * A convenience method for making a collection unique using a Closure
* to determine duplicate ( equal ) items .
* If the closure takes a single parameter , the
* argument passed will be each element , and the closure
* should return a value used for comparison ( either using
* { @ link java . lang . Comparable # compareTo ( java . lang . Object ) } or { @ link java . lang . Object # equals ( java . lang . Object ) } ) .
* If the closure takes two parameters , two items from the collection
* will be passed as arguments , and the closure should return an
* int value ( with 0 indicating the items are not unique ) .
* < pre class = " groovyTestCase " > assert [ 1,4 ] = = [ 1,3,4,5 ] . unique { it % 2 } < / pre >
* < pre class = " groovyTestCase " > assert [ 2,3,4 ] = = [ 2,3,3,4 ] . unique { a , b { @ code - > } a { @ code < = > } b } < / pre >
* @ param self a Collection
* @ param closure a 1 or 2 arg Closure used to determine unique items
* @ return self without any duplicates
* @ see # unique ( Collection , boolean , Closure )
* @ since 1.0 */
public static < T > Collection < T > unique ( Collection < T > self , @ ClosureParams ( value = FromString . class , options = { } } | "T" , "T,T" } ) Closure closure ) { return unique ( self , true , closure ) ; |
public class TransformerColl { /** * define the transform process
* @ param method a function returns it ' s transformed state .
* @ return collection with objects after the transform */
public Coll via ( def < R > method ) { } } | Aggregation . $ ( map ) . forEach ( ( k , v ) -> { collection . add ( method . apply ( k , v ) ) ; } ) ; return collection ; |
public class CmsContextMenuItemProviderGroup { /** * Adds a new provider class . < p >
* @ param providerClass the provider class */
public void addProvider ( Class < ? extends I_CmsContextMenuItemProvider > providerClass ) { } } | try { m_providerMap . put ( providerClass , providerClass . newInstance ( ) ) ; } catch ( Exception e ) { LOG . error ( e . getLocalizedMessage ( ) , e ) ; } |
public class PipelineManager { /** * Return handleException method ( if callErrorHandler is < code > true < / code > ) .
* Otherwise return first run method ( order is defined by order of
* { @ link Class # getMethods ( ) } is return . < br >
* TODO ( user ) Consider actually looking for a method with matching
* signature < br >
* TODO ( maximf ) Consider getting rid of reflection based invocations
* completely .
* @ param klass Class of the user provided job
* @ param callErrorHandler should handleException method be returned instead
* of run
* @ param params parameters to be passed to the method to invoke
* @ return Either run or handleException method of { @ code class } . < code > null
* < / code > is returned if @ { code callErrorHandler } is < code > true < / code >
* and no handleException with matching signature is found . */
@ SuppressWarnings ( "unchecked" ) private static Method findJobMethodToInvoke ( Class < ? > klass , boolean callErrorHandler , Object [ ] params ) { } } | Method runMethod = null ; if ( callErrorHandler ) { if ( params . length != 1 ) { throw new RuntimeException ( "Invalid number of parameters passed to handleException:" + params . length ) ; } Object parameter = params [ 0 ] ; if ( parameter == null ) { throw new RuntimeException ( "Null parameters passed to handleException:" + params . length ) ; } Class < ? extends Object > parameterClass = parameter . getClass ( ) ; if ( ! Throwable . class . isAssignableFrom ( parameterClass ) ) { throw new RuntimeException ( "Parameter that is not an exception passed to handleException:" + parameterClass . getName ( ) ) ; } Class < ? extends Throwable > exceptionClass = ( Class < ? extends Throwable > ) parameterClass ; do { try { runMethod = klass . getMethod ( JobRecord . EXCEPTION_HANDLER_METHOD_NAME , new Class < ? > [ ] { exceptionClass } ) ; break ; } catch ( NoSuchMethodException e ) { // Ignore , try parent instead .
} exceptionClass = ( Class < ? extends Throwable > ) exceptionClass . getSuperclass ( ) ; } while ( exceptionClass != null ) ; } else { for ( Method method : klass . getMethods ( ) ) { if ( "run" . equals ( method . getName ( ) ) ) { runMethod = method ; break ; } } } return runMethod ; |
public class AbstractWsBridgeSession { /** * Log out of the login context associated with this WebSocket session .
* Used to clean up any login context state that should be cleaned up . */
public void logout ( ) { } } | if ( loginContext != null ) { try { loginContext . logout ( ) ; if ( logoutLogger . isDebugEnabled ( ) ) { logoutLogger . debug ( "[ws/#" + getId ( ) + "] Logout successful." ) ; } } catch ( LoginException e ) { logoutLogger . trace ( "[ws/#" + getId ( ) + "] Exception occurred logging out of this WebSocket session." , e ) ; } } loginContext = null ; |
public class SynchronousRequest { /** * For more info on v1 wvw matches API go < a href = " https : / / wiki . guildwars2 . com / wiki / API : 1 / wvw / matches " > here < / a > < br / >
* @ return simple wvw matches info
* @ throws GuildWars2Exception see { @ link ErrorCode } for detail
* @ see AllWvWMatchOverview wvw matches */
public AllWvWMatchOverview getAllWvWMatchOverview ( ) throws GuildWars2Exception { } } | try { Response < AllWvWMatchOverview > response = gw2API . getAllWvWMatchOverview ( ) . execute ( ) ; if ( ! response . isSuccessful ( ) ) throwError ( response . code ( ) , response . errorBody ( ) ) ; return response . body ( ) ; } catch ( IOException e ) { throw new GuildWars2Exception ( ErrorCode . Network , "Network Error: " + e . getMessage ( ) ) ; } |
public class SampleSourceFilter { /** * This Sample Source Filter filter out messages that have been received more than 3 times and
* accountIDs in a certain range .
* It is useful when you only want to retry on failed message up to certain times . */
@ Override public boolean filterSource ( CloudTrailSource source ) throws CallbackException { } } | source = ( SQSBasedSource ) source ; Map < String , String > sourceAttributes = source . getSourceAttributes ( ) ; String accountId = sourceAttributes . get ( SourceAttributeKeys . ACCOUNT_ID . getAttributeKey ( ) ) ; String receivedCount = sourceAttributes . get ( SourceAttributeKeys . APPROXIMATE_RECEIVE_COUNT . getAttributeKey ( ) ) ; int approximateReceivedCount = Integer . parseInt ( receivedCount ) ; return approximateReceivedCount <= MAX_RECEIVED_COUNT && accountIDs . contains ( accountId ) ; |
public class PathfindableModel { /** * Pathfindable */
@ Override public void prepare ( FeatureProvider provider ) { } } | super . prepare ( provider ) ; id = provider . getFeature ( Identifiable . class ) . getId ( ) ; transformable = provider . getFeature ( Transformable . class ) ; orientable . prepare ( provider ) ; if ( provider instanceof PathfindableListener ) { addListener ( ( PathfindableListener ) provider ) ; } |
public class SoapTransportCommandProcessor { /** * Deserialise enums explicitly */
private Object toEnum ( ParameterType parameterType , String enumTextValue , String paramName , boolean hardFailEnumDeserialisation ) { } } | try { return EnumUtils . readEnum ( parameterType . getImplementationClass ( ) , enumTextValue , hardFailEnumDeserialisation ) ; } catch ( Exception e ) { throw XMLTranscriptionInput . exceptionDuringDeserialisation ( parameterType , paramName , e , false ) ; } |
public class CitrusExtension { /** * Searches for method parameter of type test designer .
* @ param method
* @ return */
private static boolean isDesignerMethod ( Method method ) { } } | Class < ? > [ ] parameterTypes = method . getParameterTypes ( ) ; for ( Class < ? > parameterType : parameterTypes ) { if ( parameterType . isAssignableFrom ( TestDesigner . class ) ) { return true ; } } return false ; |
public class Attribute { /** * return an Attribute object from the given object .
* @ param o the object we want converted .
* @ exception IllegalArgumentException if the object cannot be converted . */
public static Attribute getInstance ( Object o ) { } } | if ( o == null || o instanceof Attribute ) { return ( Attribute ) o ; } if ( o instanceof ASN1Sequence ) { return new Attribute ( ( ASN1Sequence ) o ) ; } throw new IllegalArgumentException ( "unknown object in factory" ) ; |
public class CommerceAccountOrganizationRelPersistenceImpl { /** * Removes all the commerce account organization rels where organizationId = & # 63 ; from the database .
* @ param organizationId the organization ID */
@ Override public void removeByOrganizationId ( long organizationId ) { } } | for ( CommerceAccountOrganizationRel commerceAccountOrganizationRel : findByOrganizationId ( organizationId , QueryUtil . ALL_POS , QueryUtil . ALL_POS , null ) ) { remove ( commerceAccountOrganizationRel ) ; } |
public class Utils4J { /** * Returns a given string as URL and supports " classpath : " scheme . A < code > null < / code > argument returns < code > null < / code > .
* @ param url
* String to convert into an URL or < code > null < / code > .
* @ return URL or < code > null < / code > */
public static URL url ( final String url ) { } } | if ( url == null ) { return null ; } try { if ( url . startsWith ( "classpath:" ) ) { return new URL ( null , url , new ClasspathURLStreamHandler ( ) ) ; } return new URL ( url ) ; } catch ( final MalformedURLException ex ) { throw new IllegalArgumentException ( "Invalid URL: " + url , ex ) ; } |
public class DataLoader { /** * Clears the future with the specified key from the cache , if caching is enabled , so it will be re - fetched
* on the next load request .
* @ param key the key to remove
* @ return the data loader for fluent coding */
public DataLoader < K , V > clear ( K key ) { } } | Object cacheKey = getCacheKey ( key ) ; synchronized ( this ) { futureCache . delete ( cacheKey ) ; } return this ; |
public class Packages { /** * Get the table name . */
public String getTableNames ( boolean bAddQuotes ) { } } | return ( m_tableName == null ) ? Record . formatTableNames ( PACKAGES_FILE , bAddQuotes ) : super . getTableNames ( bAddQuotes ) ; |
public class HeapCache { /** * JSR107 bulk interface . The behaviour is compatible to the JSR107 TCK . We also need
* to be compatible to the exception handling policy , which says that the exception
* is to be thrown when most specific . So exceptions are only thrown , when the value
* which has produced an exception is requested from the map . */
public Map < K , V > getAll ( final Iterable < ? extends K > _inputKeys ) { } } | Map < K , ExaminationEntry < K , V > > map = new HashMap < K , ExaminationEntry < K , V > > ( ) ; for ( K k : _inputKeys ) { Entry < K , V > e = getEntryInternal ( k ) ; if ( e != null ) { map . put ( extractKeyObj ( e ) , ReadOnlyCacheEntry . of ( e ) ) ; } } return convertValueMap ( map ) ; |
public class ZKSegmentContainerMonitor { /** * The container assignment monitor .
* This method will fetch the current owned containers for this host and ensures that the local containers ' state
* reflects this . */
@ Synchronized private void checkAssignment ( ) { } } | long traceId = LoggerHelpers . traceEnter ( log , "checkAssignment" ) ; try { Exceptions . checkNotClosed ( closed . get ( ) , this ) ; // Fetch the list of containers that is supposed to be owned by this host .
Set < Integer > desiredList = getDesiredContainerList ( ) ; if ( desiredList != null ) { Collection < Integer > runningContainers = new HashSet < > ( this . handles . keySet ( ) ) ; Collection < Integer > containersPendingTasks = new HashSet < > ( this . pendingTasks ) ; // Filter out containers which have pending tasks so we don ' t initiate conflicting events on the same
// containers . Events for these containers will be tried on subsequent runs of this executor .
Collection < Integer > containersToBeStarted = CollectionHelpers . filterOut ( desiredList , runningContainers ) ; containersToBeStarted = CollectionHelpers . filterOut ( containersToBeStarted , containersPendingTasks ) ; Collection < Integer > containersToBeStopped = CollectionHelpers . filterOut ( runningContainers , desiredList ) ; containersToBeStopped = CollectionHelpers . filterOut ( containersToBeStopped , containersPendingTasks ) ; log . info ( "Container Changes: Desired = {}, Current = {}, PendingTasks = {}, ToStart = {}, ToStop = {}." , desiredList , runningContainers , containersPendingTasks , containersToBeStarted , containersToBeStopped ) ; // Initiate the start and stop tasks asynchronously .
containersToBeStarted . forEach ( this :: startContainer ) ; containersToBeStopped . forEach ( this :: stopContainer ) ; } else { log . warn ( "No segment container assignments found" ) ; } } catch ( Throwable e ) { // Need to catch all exceptions here since throwing any exception here will halt this scheduled job .
log . warn ( "Failed to monitor the segmentcontainer assignment: " , e ) ; } finally { LoggerHelpers . traceLeave ( log , "checkAssignment" , traceId ) ; } |
public class GeocodedAddress { /** * region > helpers */
private static GeocodeApiResponse . Result firstResult ( final GeocodeApiResponse apiResponse ) { } } | if ( apiResponse . getStatus ( ) != GeocodeApiResponse . Status . OK ) { return null ; } final List < GeocodeApiResponse . Result > results = apiResponse . getResults ( ) ; if ( results . isEmpty ( ) ) { return null ; } return results . get ( 0 ) ; |
public class Compound { /** * Maps a component Out field to an object ' s field . Both field have the
* same name .
* @ param from the component
* @ param from _ out the component ' s Out field .
* @ param o the object */
public void out2field ( Object from , String from_out , Object o ) { } } | out2field ( from , from_out , o , from_out ) ; |
public class ComponentAnnotationLoader { /** * Helper method that generate a { @ link RuntimeException } in case of a reflection error .
* @ param componentClass the component for which to return the interface types
* @ return the Types representing the interfaces directly implemented by the class or interface represented by this
* object
* @ throws RuntimeException in case of a reflection error such as
* { @ link java . lang . reflect . MalformedParameterizedTypeException } */
private Type [ ] getGenericInterfaces ( Class < ? > componentClass ) { } } | Type [ ] interfaceTypes ; try { interfaceTypes = componentClass . getGenericInterfaces ( ) ; } catch ( Exception e ) { throw new RuntimeException ( String . format ( "Failed to get interface for [%s]" , componentClass . getName ( ) ) , e ) ; } return interfaceTypes ; |
public class ActionsConfig { /** * Get all actions and their references .
* @ param node The current node to check ( must not be < code > null < / code > ) .
* @ return The actions found . */
private static List < ActionRef > getRefs ( Xml node ) { } } | final Collection < Xml > children = node . getChildren ( NODE_ACTION ) ; final List < ActionRef > actions = new ArrayList < > ( children . size ( ) ) ; for ( final Xml action : children ) { final String path = action . readString ( ATT_PATH ) ; final boolean cancel = action . readBoolean ( false , ATT_CANCEL ) ; actions . add ( new ActionRef ( path , cancel , getRefs ( action ) ) ) ; } return actions ; |
public class GenericsUtils { /** * Situation when parameterized type contains 0 arguments is not normal ( impossible normally , except inner
* classes ) , but may appear after { @ link ru . vyarus . java . generics . resolver . util . type . instance . InstanceType }
* resolution ( where parameterized type have to be used even for classes in order to store actual instance ) ,
* but , as we repackage type here , we don ' t need wrapper anymore .
* @ param type type to repackage
* @ param generics known generics
* @ param countPreservedVariables true to replace { @ link ExplicitTypeVariable } too
* @ return type without { @ link TypeVariable } ' s */
private static Type resolveParameterizedTypeVariables ( final ParameterizedType type , final Map < String , Type > generics , final boolean countPreservedVariables ) { } } | final boolean emptyContainerForClass = type . getActualTypeArguments ( ) . length == 0 && type . getOwnerType ( ) == null ; return emptyContainerForClass ? type . getRawType ( ) : new ParameterizedTypeImpl ( type . getRawType ( ) , resolveTypeVariables ( type . getActualTypeArguments ( ) , generics , countPreservedVariables ) , type . getOwnerType ( ) ) ; |
public class SimpleDBResponseMetadata { /** * Returns the SimpleDB box usage reported in a response ' s metadata . SimpleDB box usage
* indicates how much compute capacity was used to process your request .
* Box usage is useful when looking at how different queries perform on your data . You can use
* that information to tune your queries , and reduce your monthly SimpleDB usage charges .
* @ return The SimpleDB box usage reported for the associated request . */
public float getBoxUsage ( ) { } } | String boxUsage = metadata . get ( BOX_USAGE ) ; if ( boxUsage == null || boxUsage . trim ( ) . length ( ) == 0 ) return 0 ; return Float . parseFloat ( boxUsage ) ; |
public class UpdateConfigurationTemplateRequest { /** * A list of configuration options to remove from the configuration set .
* Constraint : You can remove only < code > UserDefined < / code > configuration options .
* @ return A list of configuration options to remove from the configuration set . < / p >
* Constraint : You can remove only < code > UserDefined < / code > configuration options . */
public java . util . List < OptionSpecification > getOptionsToRemove ( ) { } } | if ( optionsToRemove == null ) { optionsToRemove = new com . amazonaws . internal . SdkInternalList < OptionSpecification > ( ) ; } return optionsToRemove ; |
public class GenericDao { /** * 解析映射的实体类 , 获取主键名 、 表名 、 分片数 、 sequence配置
* @ param */
protected void analysisSequence ( Class < ENTITY > entityClass ) { } } | Sequence sequence = entityClass . getAnnotation ( Sequence . class ) ; if ( sequence != null ) { this . sequenceName = sequence . name ( ) ; sequenceGenerator . initialSequence ( sequenceName , sequence . size ( ) ) ; } |
public class IfcReferenceImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ SuppressWarnings ( "unchecked" ) @ Override public EList < Long > getListPositions ( ) { } } | return ( EList < Long > ) eGet ( Ifc4Package . Literals . IFC_REFERENCE__LIST_POSITIONS , true ) ; |
public class BitfinexCandlestickSymbol { /** * Construct from Bitfinex string
* @ param symbol
* @ return */
public static BitfinexCandlestickSymbol fromBitfinexString ( final String symbol ) { } } | if ( ! symbol . startsWith ( "trade:" ) ) { throw new IllegalArgumentException ( "Unable to parse: " + symbol ) ; } final String [ ] splitString = symbol . split ( ":" ) ; if ( splitString . length != 3 ) { throw new IllegalArgumentException ( "Unable to parse: " + symbol ) ; } final String timeframeString = splitString [ 1 ] ; final String symbolString = splitString [ 2 ] ; return BitfinexSymbols . candlesticks ( BitfinexCurrencyPair . fromSymbolString ( symbolString ) , BitfinexCandleTimeFrame . fromSymbolString ( timeframeString ) ) ; |
public class SourceStreamControl { /** * / * ( non - Javadoc )
* @ see com . ibm . ws . sib . processor . runtime . SIMPDeliveryStreamTransmitControllable # getTransmitMessagesIterator */
public SIMPIterator getTransmitMessagesIterator ( int maxMsgs ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "getTransmitMessagesIterator" ) ; // TODO : Method needs to throw SIMPRuntimInvalid to admin
SIMPIterator returnIterator = null ; Iterator < TickRange > messagesOnStream = _sourceStream . getAllMessageItemsOnStream ( true ) . iterator ( ) ; // now build a collection of TransmitMessageControllable
Collection < SIMPTransmitMessageControllable > transmitMessages = new LinkedList < SIMPTransmitMessageControllable > ( ) ; boolean allMsgs = ( maxMsgs == SIMPConstants . SIMPCONTROL_RETURN_ALL_MESSAGES ) ; int index = 0 ; while ( ( allMsgs || ( index < maxMsgs ) ) && messagesOnStream . hasNext ( ) ) { try { TickRange tr = messagesOnStream . next ( ) ; if ( tr . value == null ) transmitMessages . add ( new LinkTransmitMessageControl ( tr . itemStreamIndex , _sourceStream , _downControl ) ) ; else transmitMessages . add ( new LinkTransmitMessageControl ( ( ( SIMPMessage ) tr . value ) , _sourceStream ) ) ; index ++ ; } catch ( SIResourceException e ) { // No FFDC code needed
SibTr . exception ( tc , e ) ; } } returnIterator = new TransmitMessageControllableIterator ( transmitMessages . iterator ( ) ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "getTransmitMessagesIterator" , returnIterator ) ; return returnIterator ; |
public class EndpointGroupRegistry { /** * Returns the { @ link EndpointSelector } for the specified case - insensitive { @ code groupName } .
* @ return the { @ link EndpointSelector } , or { @ code null } if { @ code groupName } has not been registered yet . */
@ Nullable public static EndpointSelector getNodeSelector ( String groupName ) { } } | groupName = normalizeGroupName ( groupName ) ; return serverGroups . get ( groupName ) ; |
public class CollUtil { /** * 反序给定List , 会创建一个新的List , 原List数据不变
* @ param < T > 元素类型
* @ param list 被反转的List
* @ return 反转后的List
* @ since 4.0.6 */
public static < T > List < T > reverseNew ( List < T > list ) { } } | final List < T > list2 = ObjectUtil . clone ( list ) ; return reverse ( list2 ) ; |
public class AzureFirewallsInner { /** * Deletes the specified Azure Firewall .
* @ param resourceGroupName The name of the resource group .
* @ param azureFirewallName The name of the Azure Firewall .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws CloudException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */
public void delete ( String resourceGroupName , String azureFirewallName ) { } } | deleteWithServiceResponseAsync ( resourceGroupName , azureFirewallName ) . toBlocking ( ) . last ( ) . body ( ) ; |
public class CdnClient { /** * Get cache operation quota .
* @ param request The request containing all the options related to the statistics .
* @ return Details of statistics */
public GetCacheQuotaResponse getCacheQuota ( GetCacheQuotaRequest request ) { } } | InternalRequest internalRequest = this . createRequest ( request , HttpMethodName . GET , CACHE , "quota" ) ; return this . invokeHttpClient ( internalRequest , GetCacheQuotaResponse . class ) ; |
public class ContainerBase { /** * { @ inheritDoc }
* @ see org . jboss . shrinkwrap . api . container . LibraryContainer # addAsLibrary ( java . lang . String ) */
@ Override public T addAsLibrary ( String resourceName ) throws IllegalArgumentException { } } | Validate . notNull ( resourceName , "ResourceName must be specified" ) ; File file = fileFromResource ( resourceName ) ; return addAsLibrary ( file , new BasicPath ( resourceName ) ) ; |
public class StreamExecutionEnvironment { /** * Generic method to create an input data stream with { @ link org . apache . flink . api . common . io . InputFormat } .
* < p > The data stream is typed to the given TypeInformation . This method is intended for input formats
* where the return type cannot be determined by reflection analysis , and that do not implement the
* { @ link org . apache . flink . api . java . typeutils . ResultTypeQueryable } interface .
* < p > < b > NOTES ON CHECKPOINTING : < / b > In the case of a { @ link FileInputFormat } , the source
* ( which executes the { @ link ContinuousFileMonitoringFunction } ) monitors the path , creates the
* { @ link org . apache . flink . core . fs . FileInputSplit FileInputSplits } to be processed , forwards
* them to the downstream { @ link ContinuousFileReaderOperator } to read the actual data , and exits ,
* without waiting for the readers to finish reading . This implies that no more checkpoint
* barriers are going to be forwarded after the source exits , thus having no checkpoints .
* @ param inputFormat
* The input format used to create the data stream
* @ param typeInfo
* The information about the type of the output type
* @ param < OUT >
* The type of the returned data stream
* @ return The data stream that represents the data created by the input format */
@ PublicEvolving public < OUT > DataStreamSource < OUT > createInput ( InputFormat < OUT , ? > inputFormat , TypeInformation < OUT > typeInfo ) { } } | DataStreamSource < OUT > source ; if ( inputFormat instanceof FileInputFormat ) { @ SuppressWarnings ( "unchecked" ) FileInputFormat < OUT > format = ( FileInputFormat < OUT > ) inputFormat ; source = createFileInput ( format , typeInfo , "Custom File source" , FileProcessingMode . PROCESS_ONCE , - 1 ) ; } else { source = createInput ( inputFormat , typeInfo , "Custom Source" ) ; } return source ; |
public class FixedLengthDecodingState { /** * { @ inheritDoc } */
public DecodingState decode ( IoBuffer in , ProtocolDecoderOutput out ) throws Exception { } } | if ( buffer == null ) { if ( in . remaining ( ) >= length ) { int limit = in . limit ( ) ; in . limit ( in . position ( ) + length ) ; IoBuffer product = in . slice ( ) ; in . position ( in . position ( ) + length ) ; in . limit ( limit ) ; return finishDecode ( product , out ) ; } buffer = IoBuffer . allocate ( length ) ; buffer . put ( in ) ; return this ; } if ( in . remaining ( ) >= length - buffer . position ( ) ) { int limit = in . limit ( ) ; in . limit ( in . position ( ) + length - buffer . position ( ) ) ; buffer . put ( in ) ; in . limit ( limit ) ; IoBuffer product = this . buffer ; this . buffer = null ; return finishDecode ( product . flip ( ) , out ) ; } buffer . put ( in ) ; return this ; |
public class CmsResultItemWidget { /** * Initializes the title attribute of the subtitle line . < p >
* @ param subtitleTitle the value to set */
public void setSubtitleTitle ( final String subtitleTitle ) { } } | m_subtitle . setTitle ( subtitleTitle ) ; m_subtitle . setTitleGenerator ( new I_TitleGenerator ( ) { public String getTitle ( String originalText ) { return subtitleTitle ; } } ) ; |
public class InMemoryResumableFramesStore { /** * / * this method and saveFrame ( ) won ' t be called concurrently ,
* so non - atomic on volatile is safe */
private int releaseTailFrame ( ByteBuf content ) { } } | int frameSize = content . readableBytes ( ) ; cacheSize -= frameSize ; position += frameSize ; content . release ( ) ; return frameSize ; |
public class JSModule { /** * Removes any input with the given name . Returns whether any were removed . */
public boolean removeByName ( String name ) { } } | boolean found = false ; Iterator < CompilerInput > iter = inputs . iterator ( ) ; while ( iter . hasNext ( ) ) { CompilerInput file = iter . next ( ) ; if ( name . equals ( file . getName ( ) ) ) { iter . remove ( ) ; file . setModule ( null ) ; found = true ; } } return found ; |
public class InternalXtypeParser { /** * InternalXtype . g : 233:1 : entryRuleJvmUpperBoundAnded : ruleJvmUpperBoundAnded EOF ; */
public final void entryRuleJvmUpperBoundAnded ( ) throws RecognitionException { } } | try { // InternalXtype . g : 234:1 : ( ruleJvmUpperBoundAnded EOF )
// InternalXtype . g : 235:1 : ruleJvmUpperBoundAnded EOF
{ if ( state . backtracking == 0 ) { before ( grammarAccess . getJvmUpperBoundAndedRule ( ) ) ; } pushFollow ( FOLLOW_1 ) ; ruleJvmUpperBoundAnded ( ) ; state . _fsp -- ; if ( state . failed ) return ; if ( state . backtracking == 0 ) { after ( grammarAccess . getJvmUpperBoundAndedRule ( ) ) ; } match ( input , EOF , FOLLOW_2 ) ; if ( state . failed ) return ; } } catch ( RecognitionException re ) { reportError ( re ) ; recover ( input , re ) ; } finally { } return ; |
public class sslcertkey { /** * Use this API to fetch all the sslcertkey resources that are configured on netscaler . */
public static sslcertkey [ ] get ( nitro_service service ) throws Exception { } } | sslcertkey obj = new sslcertkey ( ) ; sslcertkey [ ] response = ( sslcertkey [ ] ) obj . get_resources ( service ) ; return response ; |
public class Leader { /** * Starts from joining leader itself .
* @ param peer should be as same as serverId of leader .
* @ throws Exception in case something goes wrong . */
@ Override public void join ( String peer ) throws Exception { } } | try { // Initializes the persistent variables .
List < String > peers = new ArrayList < String > ( ) ; peers . add ( this . serverId ) ; ClusterConfiguration cnf = new ClusterConfiguration ( new Zxid ( 0 , 0 ) , peers , this . serverId ) ; persistence . setLastSeenConfig ( cnf ) ; ByteBuffer cop = cnf . toByteBuffer ( ) ; Transaction txn = new Transaction ( cnf . getVersion ( ) , ProposalType . COP_VALUE , cop ) ; // Also we need to append the initial configuration to log .
persistence . getLog ( ) . append ( txn ) ; persistence . setProposedEpoch ( 0 ) ; persistence . setAckEpoch ( 0 ) ; /* - - Broadcasting phase - - */
// Initialize the vote for leader election .
this . election . specifyLeader ( this . serverId ) ; changePhase ( Phase . BROADCASTING ) ; broadcasting ( ) ; } catch ( InterruptedException e ) { LOG . debug ( "Participant is canceled by user." ) ; throw e ; } catch ( TimeoutException e ) { LOG . debug ( "Didn't hear message from peers for {} milliseconds. Going" + " back to leader election." , this . config . getTimeoutMs ( ) ) ; } catch ( BackToElectionException e ) { LOG . debug ( "Got GO_BACK message from queue, going back to electing." ) ; } catch ( LeftCluster e ) { LOG . debug ( "Exit running : {}" , e . getMessage ( ) ) ; throw e ; } catch ( Exception e ) { LOG . error ( "Caught exception" , e ) ; throw e ; } finally { changePhase ( Phase . FINALIZING ) ; } |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link String } { @ code > } */
@ XmlElementDecl ( namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/" , name = "renditionFilter" , scope = GetCheckedOutDocs . class ) public JAXBElement < String > createGetCheckedOutDocsRenditionFilter ( String value ) { } } | return new JAXBElement < String > ( _GetObjectOfLatestVersionRenditionFilter_QNAME , String . class , GetCheckedOutDocs . class , value ) ; |
public class RegionCommitmentClient { /** * Returns the specified commitment resource . Gets a list of available commitments by making a
* list ( ) request .
* < p > Sample code :
* < pre > < code >
* try ( RegionCommitmentClient regionCommitmentClient = RegionCommitmentClient . create ( ) ) {
* ProjectRegionCommitmentName commitment = ProjectRegionCommitmentName . of ( " [ PROJECT ] " , " [ REGION ] " , " [ COMMITMENT ] " ) ;
* Commitment response = regionCommitmentClient . getRegionCommitment ( commitment . toString ( ) ) ;
* < / code > < / pre >
* @ param commitment Name of the commitment to return .
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
@ BetaApi public final Commitment getRegionCommitment ( String commitment ) { } } | GetRegionCommitmentHttpRequest request = GetRegionCommitmentHttpRequest . newBuilder ( ) . setCommitment ( commitment ) . build ( ) ; return getRegionCommitment ( request ) ; |
public class ChecksumService { /** * Created a { @ link Checksum } of { @ link Checksum # type } with amount in the given currency .
* @ param amount
* Amount ( in cents ) which will be charged .
* @ param currency
* ISO 4217 formatted currency code .
* @ param returnUrl
* URL to redirect customers to after checkout has completed .
* @ param cancelUrl
* URL to redirect customers to after they have canceled the checkout . As a result , there will be no transaction .
* @ param description
* A short description for the transaction or < code > null < / code > .
* @ param items
* { @ link List } of { @ link ShoppingCartItem } s
* @ param billing
* Billing { @ link Address } for this transaction .
* @ param shipping
* Shipping { @ link Address } for this transaction .
* @ return { @ link Checksum } object . */
public Checksum createChecksumForPaypalWithItemsAndAddress ( Integer amount , String currency , String returnUrl , String cancelUrl , String description , List < ShoppingCartItem > items , Address shipping , Address billing ) { } } | return this . createChecksumForPaypalWithFeeAndItemsAndAddress ( amount , currency , returnUrl , cancelUrl , null , description , items , shipping , billing , null ) ; |
public class RolloutHelper { /** * Verify if the supplied amount of groups is in range
* @ param amountGroup
* amount of groups
* @ param quotaManagement
* to retrieve maximum number of groups allowed */
public static void verifyRolloutGroupParameter ( final int amountGroup , final QuotaManagement quotaManagement ) { } } | if ( amountGroup <= 0 ) { throw new ValidationException ( "The amount of groups cannot be lower than zero" ) ; } else if ( amountGroup > quotaManagement . getMaxRolloutGroupsPerRollout ( ) ) { throw new QuotaExceededException ( "The amount of groups cannot be greater than " + quotaManagement . getMaxRolloutGroupsPerRollout ( ) ) ; } |
public class ApiOvhTelephony { /** * List old phones archived as they were not returned after an RMA
* REST : GET / telephony / { billingAccount } / oldPhone
* @ param billingAccount [ required ] The name of your billingAccount */
public ArrayList < OvhPhone > billingAccount_oldPhone_GET ( String billingAccount ) throws IOException { } } | String qPath = "/telephony/{billingAccount}/oldPhone" ; StringBuilder sb = path ( qPath , billingAccount ) ; String resp = exec ( qPath , "GET" , sb . toString ( ) , null ) ; return convertTo ( resp , t16 ) ; |
public class HttpServerExchange { /** * Get the inbound request . If there is no request body , calling this method
* may cause the next request to immediately be processed . The { @ link StreamSourceChannel # close ( ) } or { @ link StreamSourceChannel # shutdownReads ( ) }
* method must be called at some point after the request is processed to prevent resource leakage and to allow
* the next request to proceed . Any unread content will be discarded .
* @ return the channel for the inbound request , or { @ code null } if another party already acquired the channel */
public StreamSourceChannel getRequestChannel ( ) { } } | if ( requestChannel != null ) { if ( anyAreSet ( state , FLAG_REQUEST_RESET ) ) { state &= ~ FLAG_REQUEST_RESET ; return requestChannel ; } return null ; } if ( anyAreSet ( state , FLAG_REQUEST_TERMINATED ) ) { return requestChannel = new ReadDispatchChannel ( new ConduitStreamSourceChannel ( Configurable . EMPTY , new EmptyStreamSourceConduit ( getIoThread ( ) ) ) ) ; } final ConduitWrapper < StreamSourceConduit > [ ] wrappers = this . requestWrappers ; final ConduitStreamSourceChannel sourceChannel = connection . getSourceChannel ( ) ; if ( wrappers != null ) { this . requestWrappers = null ; final WrapperConduitFactory < StreamSourceConduit > factory = new WrapperConduitFactory < > ( wrappers , requestWrapperCount , sourceChannel . getConduit ( ) , this ) ; sourceChannel . setConduit ( factory . create ( ) ) ; } return requestChannel = new ReadDispatchChannel ( sourceChannel ) ; |
public class SipParser { /** * Consume CR + LF
* @ param buffer
* @ return the number of bytes we consumed , which should be two
* if we indeed consumed CRLF or zero otherwise . */
public static int consumeCRLF ( final Buffer buffer ) throws SipParseException { } } | try { buffer . markReaderIndex ( ) ; final byte cr = buffer . readByte ( ) ; final byte lf = buffer . readByte ( ) ; if ( cr == CR && lf == LF ) { return 2 ; } } catch ( final IndexOutOfBoundsException e ) { // fall through
} catch ( final IOException e ) { throw new SipParseException ( buffer . getReaderIndex ( ) , UNABLE_TO_READ_FROM_STREAM , e ) ; } buffer . resetReaderIndex ( ) ; return 0 ; |
public class CaptionDescriptionPresetMarshaller { /** * Marshall the given parameter object . */
public void marshall ( CaptionDescriptionPreset captionDescriptionPreset , ProtocolMarshaller protocolMarshaller ) { } } | if ( captionDescriptionPreset == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( captionDescriptionPreset . getCustomLanguageCode ( ) , CUSTOMLANGUAGECODE_BINDING ) ; protocolMarshaller . marshall ( captionDescriptionPreset . getDestinationSettings ( ) , DESTINATIONSETTINGS_BINDING ) ; protocolMarshaller . marshall ( captionDescriptionPreset . getLanguageCode ( ) , LANGUAGECODE_BINDING ) ; protocolMarshaller . marshall ( captionDescriptionPreset . getLanguageDescription ( ) , LANGUAGEDESCRIPTION_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class RequestHelpers { /** * Sets the request Content - Type / Accept headers for JSON or SMILE encoding based on the
* given isBinaryTransportEnabled argument . */
public static Builder setContentTypeHeaders ( boolean isBinaryTransportEnabled , Builder requestBuilder ) { } } | if ( isBinaryTransportEnabled ) { return requestBuilder . setHeader ( CONTENT_TYPE , APPLICATION_JACKSON_SMILE ) . setHeader ( ACCEPT , APPLICATION_JACKSON_SMILE ) ; } return requestBuilder . setHeader ( CONTENT_TYPE , JSON_UTF_8 . toString ( ) ) . setHeader ( ACCEPT , JSON_UTF_8 . toString ( ) ) ; |
public class ClasspathFileReader { /** * Returns an input stream for reading the specified resource . This method
* functions similarly to
* < code > ClassLoader . getResourceAsStream < / code > . < B > Make sure you
* close the stream when you are done with it , as it allocates a
* file handle on the system , and leaving them open degrades
* performance or causes failures . < / B >
* @ param fileName the name of the resource to resolve
* @ return an input stream opened to the requested resource , or < code > null < / code >
* if the resource could not be found */
public InputStream getResourceAsStream ( String fileName ) { } } | try { File file = getFile ( fileName ) ; cache . put ( fileName , new CacheEntry ( file ) ) ; return new FileInputStream ( file ) ; } catch ( FileNotFoundException e ) { InputStream is = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( fileName ) ; if ( is != null ) { cache . put ( fileName , new CacheEntry ( ) ) ; } return is ; } |
public class BaseBigtableTableAdminClient { /** * Generates a consistency token for a Table , which can be used in CheckConsistency to check
* whether mutations to the table that finished before this call started have been replicated . The
* tokens will be available for 90 days .
* < p > Sample code :
* < pre > < code >
* try ( BaseBigtableTableAdminClient baseBigtableTableAdminClient = BaseBigtableTableAdminClient . create ( ) ) {
* TableName name = TableName . of ( " [ PROJECT ] " , " [ INSTANCE ] " , " [ TABLE ] " ) ;
* GenerateConsistencyTokenResponse response = baseBigtableTableAdminClient . generateConsistencyToken ( name . toString ( ) ) ;
* < / code > < / pre >
* @ param name The unique name of the Table for which to create a consistency token . Values are of
* the form ` projects / & lt ; project & gt ; / instances / & lt ; instance & gt ; / tables / & lt ; table & gt ; ` .
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
public final GenerateConsistencyTokenResponse generateConsistencyToken ( String name ) { } } | GenerateConsistencyTokenRequest request = GenerateConsistencyTokenRequest . newBuilder ( ) . setName ( name ) . build ( ) ; return generateConsistencyToken ( request ) ; |
public class Kinds { /** * A KindName representing the kind of a given class / interface type . */
public static KindName typeKindName ( Type t ) { } } | if ( t . hasTag ( TYPEVAR ) || t . hasTag ( CLASS ) && ( t . tsym . flags ( ) & COMPOUND ) != 0 ) return KindName . BOUND ; else if ( t . hasTag ( PACKAGE ) ) return KindName . PACKAGE ; else if ( ( t . tsym . flags_field & ANNOTATION ) != 0 ) return KindName . ANNOTATION ; else if ( ( t . tsym . flags_field & INTERFACE ) != 0 ) return KindName . INTERFACE ; else return KindName . CLASS ; |
public class AbstractAggregatorImpl { /** * / * ( non - Javadoc )
* @ see com . ibm . jaggr . service . IAggregator # getTransport ( ) */
@ Override public IHttpTransport getTransport ( ) { } } | IAggregatorExtension ext = getExtensions ( IHttpTransportExtensionPoint . ID ) . iterator ( ) . next ( ) ; return ( IHttpTransport ) ( ext != null ? ext . getInstance ( ) : null ) ; |
public class Rational { /** * Convert the given string to a BigDecimal or a constant if given , e . g . " pi " */
private BigDecimal parse ( String raw ) { } } | raw = raw . trim ( ) ; switch ( raw ) { case "pi" : return PI ; default : return new BigDecimal ( raw ) ; } |
public class PostgreSqlQueryUtils { /** * Returns all attributes persisted by PostgreSQL in entity table ( e . g . no compound attributes and
* attributes with an expression )
* @ return stream of persisted non - MREF attributes */
static Stream < Attribute > getTableAttributes ( EntityType entityType ) { } } | return getPersistedAttributes ( entityType ) . filter ( PostgreSqlQueryUtils :: isTableAttribute ) ; |
public class JobsInner { /** * Creates or updates a job .
* @ param resourceGroupName The name of the resource group that contains the resource . You can obtain this value from the Azure Resource Manager API or the portal .
* @ param serverName The name of the server .
* @ param jobAgentName The name of the job agent .
* @ param jobName The name of the job to get .
* @ param parameters The requested job state .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the JobInner object */
public Observable < JobInner > createOrUpdateAsync ( String resourceGroupName , String serverName , String jobAgentName , String jobName , JobInner parameters ) { } } | return createOrUpdateWithServiceResponseAsync ( resourceGroupName , serverName , jobAgentName , jobName , parameters ) . map ( new Func1 < ServiceResponse < JobInner > , JobInner > ( ) { @ Override public JobInner call ( ServiceResponse < JobInner > response ) { return response . body ( ) ; } } ) ; |
public class DocPath { /** * Return the inverse path for a package .
* For example , if the package is java . lang ,
* the inverse path is . . / . . . */
public static DocPath forRoot ( PackageDoc pd ) { } } | String name = ( pd == null ) ? "" : pd . name ( ) ; if ( name . isEmpty ( ) ) return empty ; return new DocPath ( name . replace ( '.' , '/' ) . replaceAll ( "[^/]+" , ".." ) ) ; |
public class BaseBigtableTableAdminClient { /** * Permanently deletes a specified table and all of its data .
* < p > Sample code :
* < pre > < code >
* try ( BaseBigtableTableAdminClient baseBigtableTableAdminClient = BaseBigtableTableAdminClient . create ( ) ) {
* TableName name = TableName . of ( " [ PROJECT ] " , " [ INSTANCE ] " , " [ TABLE ] " ) ;
* baseBigtableTableAdminClient . deleteTable ( name ) ;
* < / code > < / pre >
* @ param name The unique name of the table to be deleted . Values are of the form
* ` projects / & lt ; project & gt ; / instances / & lt ; instance & gt ; / tables / & lt ; table & gt ; ` .
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
public final void deleteTable ( TableName name ) { } } | DeleteTableRequest request = DeleteTableRequest . newBuilder ( ) . setName ( name == null ? null : name . toString ( ) ) . build ( ) ; deleteTable ( request ) ; |
public class PreferenceFragment { /** * Initializes the preference , which allows to specfify , whether dialogs should be shown
* fullscreen , or not . */
private void initializeFullscreenPreference ( ) { } } | Preference fullscreenPreference = findPreference ( getString ( R . string . fullscreen_preference_key ) ) ; fullscreenPreference . setOnPreferenceChangeListener ( createThemeChangeListener ( ) ) ; |
public class XMLStreamEventsSync { /** * Go to the next inner element having the given name . Return true if one is found , false if the closing tag of the parent is found . */
public boolean nextInnerElement ( ElementContext parent , String childName ) throws XMLException , IOException { } } | while ( nextInnerElement ( parent ) ) { if ( event . text . equals ( childName ) ) return true ; } return false ; |
public class QueueBuffer { /** * Changes visibility of a message in SQS . Does not return until a confirmation from SQS has
* been received .
* @ return */
public ChangeMessageVisibilityResult changeMessageVisibilitySync ( ChangeMessageVisibilityRequest request ) { } } | Future < ChangeMessageVisibilityResult > future = sendBuffer . changeMessageVisibility ( request , null ) ; return waitForFuture ( future ) ; |
public class CommerceTaxFixedRatePersistenceImpl { /** * Returns the last commerce tax fixed rate in the ordered set where CPTaxCategoryId = & # 63 ; .
* @ param CPTaxCategoryId the cp tax category ID
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the last matching commerce tax fixed rate , or < code > null < / code > if a matching commerce tax fixed rate could not be found */
@ Override public CommerceTaxFixedRate fetchByCPTaxCategoryId_Last ( long CPTaxCategoryId , OrderByComparator < CommerceTaxFixedRate > orderByComparator ) { } } | int count = countByCPTaxCategoryId ( CPTaxCategoryId ) ; if ( count == 0 ) { return null ; } List < CommerceTaxFixedRate > list = findByCPTaxCategoryId ( CPTaxCategoryId , count - 1 , count , orderByComparator ) ; if ( ! list . isEmpty ( ) ) { return list . get ( 0 ) ; } return null ; |
public class Bubble { /** * Sort the double array in ascending order using this algorithm .
* @ param doubleArray the array of double that we want to sort */
public static void sort ( double [ ] doubleArray ) { } } | boolean swapped = true ; while ( swapped ) { swapped = false ; for ( int i = 0 ; i < ( doubleArray . length - 1 ) ; i ++ ) { if ( doubleArray [ i ] > doubleArray [ i + 1 ] ) { TrivialSwap . swap ( doubleArray , i , i + 1 ) ; swapped = true ; } } } |
public class BpmnURLHandler { /** * Open the connection for the given URL .
* @ param url the url from which to open a connection .
* @ return a connection on the specified URL .
* @ throws IOException if an error occurs or if the URL is malformed . */
@ Override public URLConnection openConnection ( URL url ) throws IOException { } } | if ( url . getPath ( ) == null || url . getPath ( ) . trim ( ) . length ( ) == 0 ) { throw new MalformedURLException ( "Path can not be null or empty. Syntax: " + SYNTAX ) ; } bpmnXmlURL = new URL ( url . getPath ( ) ) ; logger . log ( Level . FINE , "BPMN xml URL is: [" + bpmnXmlURL + "]" ) ; return new Connection ( url ) ; |
public class mps_doc_image { /** * < pre >
* Converts API response of bulk operation into object and returns the object array in case of get request .
* < / pre > */
protected base_resource [ ] get_nitro_bulk_response ( nitro_service service , String response ) throws Exception { } } | mps_doc_image_responses result = ( mps_doc_image_responses ) service . get_payload_formatter ( ) . string_to_resource ( mps_doc_image_responses . class , response ) ; if ( result . errorcode != 0 ) { if ( result . errorcode == SESSION_NOT_EXISTS ) service . clear_session ( ) ; throw new nitro_exception ( result . message , result . errorcode , ( base_response [ ] ) result . mps_doc_image_response_array ) ; } mps_doc_image [ ] result_mps_doc_image = new mps_doc_image [ result . mps_doc_image_response_array . length ] ; for ( int i = 0 ; i < result . mps_doc_image_response_array . length ; i ++ ) { result_mps_doc_image [ i ] = result . mps_doc_image_response_array [ i ] . mps_doc_image [ 0 ] ; } return result_mps_doc_image ; |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < }
* { @ link CmisExtensionType } { @ code > } */
@ XmlElementDecl ( namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/" , name = "extension" , scope = GetObject . class ) public JAXBElement < CmisExtensionType > createGetObjectExtension ( CmisExtensionType value ) { } } | return new JAXBElement < CmisExtensionType > ( _GetPropertiesExtension_QNAME , CmisExtensionType . class , GetObject . class , value ) ; |
public class PackageMatcher { /** * Check if there is a pattern in the map that match the given package
* @ param categoriesByPackage The map of package patterns
* @ param pkg The package to check against
* @ return The entry with the corresponding match or null if no match */
public static Map . Entry < String , String > match ( Map < String , String > categoriesByPackage , String pkg ) { } } | if ( categoriesByPackage != null && pkg != null ) { for ( Map . Entry < String , String > e : categoriesByPackage . entrySet ( ) ) { if ( Minimatch . minimatch ( pkg . replaceAll ( "\\." , "/" ) , e . getKey ( ) . replaceAll ( "\\." , "/" ) ) ) { return e ; } } } return null ; |
public class TimeSeriesGenerator { /** * TODO : add pad _ sequences , make _ sampling _ table , skipgrams utils */
public static TimeSeriesGenerator fromJson ( String jsonFileName ) throws IOException , InvalidKerasConfigurationException { } } | String json = new String ( Files . readAllBytes ( Paths . get ( jsonFileName ) ) ) ; Map < String , Object > timeSeriesBaseConfig = parseJsonString ( json ) ; Map < String , Object > timeSeriesConfig ; if ( timeSeriesBaseConfig . containsKey ( "config" ) ) timeSeriesConfig = ( Map < String , Object > ) timeSeriesBaseConfig . get ( "config" ) ; else throw new InvalidKerasConfigurationException ( "No configuration found for Keras tokenizer" ) ; int length = ( int ) timeSeriesConfig . get ( "length" ) ; int samplingRate = ( int ) timeSeriesConfig . get ( "sampling_rate" ) ; int stride = ( int ) timeSeriesConfig . get ( "stride" ) ; int startIndex = ( int ) timeSeriesConfig . get ( "start_index" ) ; int endIndex = ( int ) timeSeriesConfig . get ( "end_index" ) ; int batchSize = ( int ) timeSeriesConfig . get ( "batch_size" ) ; boolean shuffle = ( boolean ) timeSeriesConfig . get ( "shuffle" ) ; boolean reverse = ( boolean ) timeSeriesConfig . get ( "reverse" ) ; Gson gson = new Gson ( ) ; List < List < Double > > dataList = gson . fromJson ( ( String ) timeSeriesConfig . get ( "data" ) , new TypeToken < List < List < Double > > > ( ) { } . getType ( ) ) ; List < List < Double > > targetsList = gson . fromJson ( ( String ) timeSeriesConfig . get ( "targets" ) , new TypeToken < List < List < Double > > > ( ) { } . getType ( ) ) ; int dataPoints = dataList . size ( ) ; int dataPointsPerRow = dataList . get ( 0 ) . size ( ) ; INDArray data = Nd4j . create ( dataPoints , dataPointsPerRow ) ; INDArray targets = Nd4j . create ( dataPoints , dataPointsPerRow ) ; for ( int i = 0 ; i < dataPoints ; i ++ ) { data . put ( i , Nd4j . create ( dataList . get ( i ) ) ) ; targets . put ( i , Nd4j . create ( targetsList . get ( i ) ) ) ; } TimeSeriesGenerator gen = new TimeSeriesGenerator ( data , targets , length , samplingRate , stride , startIndex , endIndex , shuffle , reverse , batchSize ) ; return gen ; |
public class DbUtils { /** * Commits a < code > Connection < / code > then closes it , avoid closing if null .
* @ param conn Connection to close .
* @ throws java . sql . SQLException if a database access error occurs */
public static void commitAndClose ( Connection conn ) throws SQLException { } } | if ( conn != null ) { try { conn . commit ( ) ; } finally { conn . close ( ) ; } } |
public class CounterContext { /** * Compares two shards , returns :
* - GREATER _ THAN if leftState overrides rightState
* - LESS _ THAN if rightState overrides leftState
* - EQUAL for two equal , non - local , shards
* - DISJOINT for any two local shards */
private Relationship compare ( ContextState leftState , ContextState rightState ) { } } | long leftClock = leftState . getClock ( ) ; long leftCount = leftState . getCount ( ) ; long rightClock = rightState . getClock ( ) ; long rightCount = rightState . getCount ( ) ; if ( leftState . isGlobal ( ) || rightState . isGlobal ( ) ) { if ( leftState . isGlobal ( ) && rightState . isGlobal ( ) ) { if ( leftClock == rightClock ) { // Can happen if an sstable gets lost and disk failure policy is set to ' best effort '
if ( leftCount != rightCount && CompactionManager . isCompactionManager . get ( ) ) { logger . warn ( "invalid global counter shard detected; ({}, {}, {}) and ({}, {}, {}) differ only in " + "count; will pick highest to self-heal on compaction" , leftState . getCounterId ( ) , leftClock , leftCount , rightState . getCounterId ( ) , rightClock , rightCount ) ; } if ( leftCount > rightCount ) return Relationship . GREATER_THAN ; else if ( leftCount == rightCount ) return Relationship . EQUAL ; else return Relationship . LESS_THAN ; } else { return leftClock > rightClock ? Relationship . GREATER_THAN : Relationship . LESS_THAN ; } } else // only one is global - keep that one
{ return leftState . isGlobal ( ) ? Relationship . GREATER_THAN : Relationship . LESS_THAN ; } } if ( leftState . isLocal ( ) || rightState . isLocal ( ) ) { // Local id and at least one is a local shard .
if ( leftState . isLocal ( ) && rightState . isLocal ( ) ) return Relationship . DISJOINT ; else // only one is local - keep that one
return leftState . isLocal ( ) ? Relationship . GREATER_THAN : Relationship . LESS_THAN ; } // both are remote shards
if ( leftClock == rightClock ) { // We should never see non - local shards w / same id + clock but different counts . However , if we do
// we should " heal " the problem by being deterministic in our selection of shard - and
// log the occurrence so that the operator will know something is wrong .
if ( leftCount != rightCount && CompactionManager . isCompactionManager . get ( ) ) { logger . warn ( "invalid remote counter shard detected; ({}, {}, {}) and ({}, {}, {}) differ only in " + "count; will pick highest to self-heal on compaction" , leftState . getCounterId ( ) , leftClock , leftCount , rightState . getCounterId ( ) , rightClock , rightCount ) ; } if ( leftCount > rightCount ) return Relationship . GREATER_THAN ; else if ( leftCount == rightCount ) return Relationship . EQUAL ; else return Relationship . LESS_THAN ; } else { if ( ( leftClock >= 0 && rightClock > 0 && leftClock >= rightClock ) || ( leftClock < 0 && ( rightClock > 0 || leftClock < rightClock ) ) ) return Relationship . GREATER_THAN ; else return Relationship . LESS_THAN ; } |
public class GraphsCompletionProposer { /** * Finds the context from the given text .
* @ param text
* @ return a context */
private Ctx findContext ( String text ) { } } | // Are we inside a comment ?
Ctx ctx = new Ctx ( ) ; int n ; for ( n = text . length ( ) - 1 ; n >= 0 ; n -- ) { char c = text . charAt ( n ) ; if ( isLineBreak ( c ) ) break ; if ( c == '#' ) { ctx . kind = CtxKind . COMMENT ; return ctx ; } } // Simplify the search : remove all the comments .
text = TextUtils . removeComments ( text ) ; // Keep on simplifying the search : remove complete components and facets
// Since instances can contain other instances ( recursivity ) , we must
// apply the pattern several times , until no more replacement is possible .
int before = - 1 ; int after = - 2 ; while ( before != after ) { before = text . length ( ) ; text = text . replaceAll ( "(?i)(?s)(facet\\s+)?[^{]*\\{[^{}]*\\}\r?\n" , "" ) ; after = text . length ( ) ; } // Remove white spaces at the beginning of the string .
text = text . replaceAll ( "^(\n|\r\n)+" , "" ) ; // Now , find our context .
// We go back until we find a ' { ' . Then , we keep rewinding
// until we find a line break .
String lastWord = null ; String lastLine = null ; StringBuilder sb = new StringBuilder ( ) ; boolean bracketFound = false ; for ( n = text . length ( ) - 1 ; n >= 0 ; n -- ) { char c = text . charAt ( n ) ; // White space ? We have a our last word .
if ( Character . isWhitespace ( c ) && lastWord == null ) { lastWord = sb . toString ( ) ; sb . setLength ( 0 ) ; sb . append ( c ) ; } // Same thing after a curly bracket
else if ( c == '{' ) bracketFound = true ; // If we find a closing bracket , then we are at the end of a declaration
else if ( c == '}' ) { ctx . kind = CtxKind . NOTHING ; break ; } // Line break ? That depends . . .
else if ( isLineBreak ( c ) ) { if ( bracketFound ) break ; if ( lastLine == null ) { lastLine = sb . toString ( ) ; sb . setLength ( 0 ) ; } } else { sb . insert ( 0 , c ) ; } } // Update the context
if ( lastLine == null ) lastLine = sb . toString ( ) ; ctx . lastWord = lastWord == null ? "" : lastWord ; ctx . property = lastLine ; // Time to analyze
if ( ctx . property . trim ( ) . endsWith ( ":" ) || ctx . property . trim ( ) . endsWith ( "," ) ) { ctx . kind = CtxKind . PROPERTY ; } else if ( Utils . isEmptyOrWhitespaces ( ctx . property ) ) { if ( bracketFound && ! Utils . isEmptyOrWhitespaces ( sb . toString ( ) ) ) ctx . kind = CtxKind . ATTRIBUTE ; } if ( sb . toString ( ) . matches ( "(?i)\\s*" + KEYWORD_FACET + "\\s+.*" ) ) ctx . facet = true ; return ctx ; |
public class ProxyDataSourceBuilder { /** * Add { @ link QueryExecutionListener } that performs given lambda on { @ link QueryExecutionListener # beforeQuery ( ExecutionInfo , List ) } .
* @ param callback a lambda function executed on { @ link QueryExecutionListener # beforeQuery ( ExecutionInfo , List ) }
* @ return builder
* @ since 1.4.3 */
public ProxyDataSourceBuilder beforeQuery ( final SingleQueryExecution callback ) { } } | QueryExecutionListener listener = new NoOpQueryExecutionListener ( ) { @ Override public void beforeQuery ( ExecutionInfo execInfo , List < QueryInfo > queryInfoList ) { callback . execute ( execInfo , queryInfoList ) ; } } ; this . queryExecutionListeners . add ( listener ) ; return this ; |
public class Configuration { /** * Get a configuration value if set as configuration or the default
* value if not
* @ param pKey the configuration key to lookup
* @ return the configuration value or the default value if no configuration
* was given . */
public String get ( ConfigKey pKey ) { } } | String value = globalConfig . get ( pKey ) ; if ( value == null ) { value = pKey . getDefaultValue ( ) ; } return value ; |
public class RegistrationManagerImpl { /** * { @ inheritDoc } */
@ Override public void updateServiceUri ( String serviceName , String providerAddress , String uri ) throws ServiceException { } } | ServiceInstanceUtils . validateManagerIsStarted ( isStarted . get ( ) ) ; ServiceInstanceUtils . validateServiceName ( serviceName ) ; ServiceInstanceUtils . validateAddress ( providerAddress ) ; ServiceInstanceUtils . validateURI ( uri ) ; getRegistrationService ( ) . updateServiceUri ( serviceName , providerAddress , uri ) ; |
public class ListGroupCertificateAuthoritiesResult { /** * A list of certificate authorities associated with the group .
* @ param groupCertificateAuthorities
* A list of certificate authorities associated with the group . */
public void setGroupCertificateAuthorities ( java . util . Collection < GroupCertificateAuthorityProperties > groupCertificateAuthorities ) { } } | if ( groupCertificateAuthorities == null ) { this . groupCertificateAuthorities = null ; return ; } this . groupCertificateAuthorities = new java . util . ArrayList < GroupCertificateAuthorityProperties > ( groupCertificateAuthorities ) ; |
public class DSLMapParser { /** * src / main / resources / org / drools / compiler / lang / dsl / DSLMap . g : 111:1 : statement : ( entry | EOL ! ) ; */
public final DSLMapParser . statement_return statement ( ) throws RecognitionException { } } | DSLMapParser . statement_return retval = new DSLMapParser . statement_return ( ) ; retval . start = input . LT ( 1 ) ; Object root_0 = null ; Token EOL3 = null ; ParserRuleReturnScope entry2 = null ; Object EOL3_tree = null ; try { // src / main / resources / org / drools / compiler / lang / dsl / DSLMap . g : 112:5 : ( entry | EOL ! )
int alt2 = 2 ; int LA2_0 = input . LA ( 1 ) ; if ( ( LA2_0 == LEFT_SQUARE ) ) { alt2 = 1 ; } else if ( ( LA2_0 == EOL ) ) { alt2 = 2 ; } else { if ( state . backtracking > 0 ) { state . failed = true ; return retval ; } NoViableAltException nvae = new NoViableAltException ( "" , 2 , 0 , input ) ; throw nvae ; } switch ( alt2 ) { case 1 : // src / main / resources / org / drools / compiler / lang / dsl / DSLMap . g : 112:7 : entry
{ root_0 = ( Object ) adaptor . nil ( ) ; pushFollow ( FOLLOW_entry_in_statement306 ) ; entry2 = entry ( ) ; state . _fsp -- ; if ( state . failed ) return retval ; if ( state . backtracking == 0 ) adaptor . addChild ( root_0 , entry2 . getTree ( ) ) ; } break ; case 2 : // src / main / resources / org / drools / compiler / lang / dsl / DSLMap . g : 113:7 : EOL !
{ root_0 = ( Object ) adaptor . nil ( ) ; EOL3 = ( Token ) match ( input , EOL , FOLLOW_EOL_in_statement314 ) ; if ( state . failed ) return retval ; } break ; } retval . stop = input . LT ( - 1 ) ; if ( state . backtracking == 0 ) { retval . tree = ( Object ) adaptor . rulePostProcessing ( root_0 ) ; adaptor . setTokenBoundaries ( retval . tree , retval . start , retval . stop ) ; } } catch ( RecognitionException re ) { reportError ( re ) ; recover ( input , re ) ; retval . tree = ( Object ) adaptor . errorNode ( input , retval . start , input . LT ( - 1 ) , re ) ; } finally { // do for sure before leaving
} return retval ; |
public class WaveFile { /** * Write 16 - bit audio */
public int writeSamples ( short [ ] data , int numSamples ) { } } | int numBytes = numSamples << 1 ; byte [ ] theData = new byte [ numBytes ] ; for ( int y = 0 , yc = 0 ; y < numBytes ; y += 2 ) { theData [ y ] = ( byte ) ( data [ yc ] & 0x00FF ) ; theData [ y + 1 ] = ( byte ) ( ( data [ yc ++ ] >>> 8 ) & 0x00FF ) ; } return write ( theData , numBytes ) ; |
public class StartSessionRequest { /** * Reserved for future use .
* @ param parameters
* Reserved for future use . */
public void setParameters ( java . util . Map < String , java . util . List < String > > parameters ) { } } | this . parameters = parameters ; |
public class Trie2Writable { /** * No error checking for illegal arguments .
* @ hide draft / provisional / internal are hidden on Android */
private int getDataBlock ( int c , boolean forLSCP ) { } } | int i2 , oldBlock , newBlock ; i2 = getIndex2Block ( c , forLSCP ) ; i2 += ( c >> UTRIE2_SHIFT_2 ) & UTRIE2_INDEX_2_MASK ; oldBlock = index2 [ i2 ] ; if ( isWritableBlock ( oldBlock ) ) { return oldBlock ; } /* allocate a new data block */
newBlock = allocDataBlock ( oldBlock ) ; setIndex2Entry ( i2 , newBlock ) ; return newBlock ; |
public class ValueLineChart { /** * Resets and clears the data object . */
@ Override public void clearChart ( ) { } } | mSeries . clear ( ) ; mStandardValues . clear ( ) ; mFocusedPoint = null ; mLastPoint = null ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.