signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class IntPipeline { /** * Adapt a { @ code Sink < Integer > to an { @ code IntConsumer } , ideally simply
* by casting . */
private static IntConsumer adapt ( Sink < Integer > sink ) { } } | if ( sink instanceof IntConsumer ) { return ( IntConsumer ) sink ; } else { // if ( Tripwire . ENABLED )
// Tripwire . trip ( AbstractPipeline . class ,
// " using IntStream . adapt ( Sink < Integer > s ) " ) ;
return sink :: accept ; } |
public class GlobalNamespace { /** * Determines whether a name reference in a particular scope is a global name reference .
* @ param name A variable or property name ( e . g . " a " or " a . b . c . d " )
* @ param s The scope in which the name is referenced
* @ return Whether the name reference is a global name reference */
private boolean isGlobalNameReference ( String name , Scope s ) { } } | String topVarName = getTopVarName ( name ) ; return isGlobalVarReference ( topVarName , s ) ; |
public class EncodingKit { /** * 字符串编码转换的实现方法
* @ param str
* 待转换编码的字符串
* @ param newCharset
* 目标编码
* @ return */
public static String changeCharset ( String str , String newCharset ) { } } | if ( str != null ) { // 用默认字符编码解码字符串 。
byte [ ] bs = str . getBytes ( ) ; // 用新的字符编码生成字符串
try { return new String ( bs , newCharset ) ; } catch ( UnsupportedEncodingException e ) { } } return "" ; |
public class MongoDBDialect { /** * not for embedded */
private Document findAssociation ( AssociationKey key , AssociationContext associationContext , AssociationStorageStrategy storageStrategy ) { } } | final Document associationKeyObject = associationKeyToObject ( key , storageStrategy ) ; MongoCollection < Document > associationCollection = getAssociationCollection ( key , storageStrategy , associationContext ) ; FindIterable < Document > fi = associationCollection . find ( associationKeyObject ) ; return fi != null ? ( fi . projection ( getProjection ( key , false ) ) . first ( ) ) : null ; |
public class ProbeAtCatchMethodAdapter { /** * Generate the code required to fire a probe out of an exception
* handler . */
private void onHandlerEntry ( ) { } } | if ( enabled ) { Type exceptionType = handlers . get ( handlerPendingInstruction ) ; // Clear the pending instruction flag
handlerPendingInstruction = null ; // Filter the interested down to this exception
Set < ProbeListener > filtered = new HashSet < ProbeListener > ( ) ; for ( ProbeListener listener : enabledListeners ) { ListenerConfiguration config = listener . getListenerConfiguration ( ) ; ProbeFilter filter = config . getTransformerData ( EXCEPTION_FILTER_KEY ) ; if ( filter . isBasicFilter ( ) && filter . basicClassNameMatches ( exceptionType . getClassName ( ) ) ) { filtered . add ( listener ) ; } else if ( filter . isAdvancedFilter ( ) ) { Class < ? > clazz = getOwningClass ( exceptionType . getInternalName ( ) ) ; if ( clazz != null && filter . matches ( clazz ) ) { filtered . add ( listener ) ; } } } if ( filtered . isEmpty ( ) ) { return ; } String key = createKey ( exceptionType ) ; ProbeImpl probe = getProbe ( key ) ; long probeId = probe . getIdentifier ( ) ; setProbeInProgress ( true ) ; visitInsn ( DUP ) ; // throwable throwable
visitLdcInsn ( Long . valueOf ( probeId ) ) ; // throwable throwable long1 long2
visitInsn ( DUP2_X1 ) ; // throwable long1 long2 throwable long1 long2
visitInsn ( POP2 ) ; // throwable long1 long2 throwable
if ( isStatic ( ) ) { visitInsn ( ACONST_NULL ) ; // throwable long1 long2 throwable this
} else { visitVarInsn ( ALOAD , 0 ) ; // throwable long1 long2 throwable this
} visitInsn ( SWAP ) ; // throwable long1 long2 this throwable
visitInsn ( ACONST_NULL ) ; // throwable long1 long2 this throwable null
visitInsn ( SWAP ) ; // throwable long1 long2 this null throwable
visitFireProbeInvocation ( ) ; // throwable
setProbeInProgress ( false ) ; setProbeListeners ( probe , filtered ) ; } |
public class SemanticSearchServiceHelper { /** * A helper function that gets identifiers of all the attributes from one EntityType */
public List < String > getAttributeIdentifiers ( EntityType sourceEntityType ) { } } | Entity entityTypeEntity = dataService . findOne ( ENTITY_TYPE_META_DATA , new QueryImpl < > ( ) . eq ( EntityTypeMetadata . ID , sourceEntityType . getId ( ) ) ) ; if ( entityTypeEntity == null ) throw new MolgenisDataAccessException ( "Could not find EntityTypeEntity by the name of " + sourceEntityType . getId ( ) ) ; List < String > attributeIdentifiers = new ArrayList < > ( ) ; recursivelyCollectAttributeIdentifiers ( entityTypeEntity . getEntities ( EntityTypeMetadata . ATTRIBUTES ) , attributeIdentifiers ) ; return attributeIdentifiers ; |
public class CellUtil { /** * 判断指定的单元格是否是合并单元格
* @ param sheet { @ link Sheet }
* @ param row 行号
* @ param column 列号
* @ return 是否是合并单元格 */
public static boolean isMergedRegion ( Sheet sheet , int row , int column ) { } } | final int sheetMergeCount = sheet . getNumMergedRegions ( ) ; CellRangeAddress ca ; for ( int i = 0 ; i < sheetMergeCount ; i ++ ) { ca = sheet . getMergedRegion ( i ) ; if ( row >= ca . getFirstRow ( ) && row <= ca . getLastRow ( ) && column >= ca . getFirstColumn ( ) && column <= ca . getLastColumn ( ) ) { return true ; } } return false ; |
public class DDPStateSingleton { /** * Saves resume token to Android ' s internal app storage
* @ param token resume token */
public void saveResumeToken ( String token ) { } } | SharedPreferences settings = mContext . getSharedPreferences ( PREF_DDPINFO , Context . MODE_PRIVATE ) ; SharedPreferences . Editor editor = settings . edit ( ) ; // REVIEW : should token be encrypted ?
editor . putString ( PREF_RESUMETOKEN , token ) ; editor . apply ( ) ; |
public class ModuleDeps { /** * Calls { @ link ModuleDepInfo # andWith ( ModuleDepInfo ) } on each of the
* entries in this list .
* @ param info
* the { @ link ModuleDepInfo } who ' s formula will be anded with the
* entries in the list .
* @ return this object . */
public ModuleDeps andWith ( ModuleDepInfo info ) { } } | for ( Map . Entry < String , ModuleDepInfo > entry : entrySet ( ) ) { entry . getValue ( ) . andWith ( info ) ; } return this ; |
public class Minimizer { /** * This method realizes the core of the actual minimization , the " split " procedure .
* A split separates in each block the states , if any , which have different transition characteristics wrt . a
* specified block , the splitter .
* This method does not perform actual splits , but instead it modifies the splitBlocks attribute to containing the
* blocks that could potentially be split . The information on the subsets into which a block is split is contained
* in the sub - blocks of the blocks in the result list .
* The actual splitting is performed by the method updateBlocks ( ) . */
private void split ( Block < S , L > splitter ) { } } | // STEP 1 : Collect the states that have outgoing edges
// pointing to states inside the currently considered blocks .
// Also , a list of transition labels occuring on these
// edges is created .
for ( State < S , L > state : splitter . getStates ( ) ) { for ( Edge < S , L > edge : state . getIncoming ( ) ) { TransitionLabel < S , L > transition = edge . getTransitionLabel ( ) ; State < S , L > newState = edge . getSource ( ) ; // Blocks that only contain a single state cannot
// be split any further , and thus are of no
// interest .
if ( newState . isSingletonBlock ( ) ) { continue ; // continue ;
} if ( transition . addToSet ( newState ) ) { letterList . add ( transition ) ; } } } // STEP 2 : Build the signatures . A signature of a state
// is a sequence of the transition labels of its outgoing
// edge that point into the considered split block .
// The iteration over the label list in the outer loop
// guarantees a consistent ordering of the transition labels .
for ( TransitionLabel < S , L > letter : letterList ) { for ( State < S , L > state : letter . getSet ( ) ) { if ( state . addToSignature ( letter ) ) { stateList . add ( state ) ; state . setSplitPoint ( false ) ; } } letter . clearSet ( ) ; } letterList . clear ( ) ; // STEP 3 : Discriminate the states . This is done by weak
// sorting the states . At the end of the weak sort , the finalList
// will contain the states in such an order that only states belonging
// to the same block having the same signature will be contiguous .
// First , initialize the buckets of each block . This is done
// for grouping the states by their corresponding block .
for ( State < S , L > state : stateList ) { Block < S , L > block = state . getBlock ( ) ; if ( block . addToBucket ( state ) ) { splitBlocks . add ( block ) ; } } stateList . clear ( ) ; for ( Block < S , L > block : splitBlocks ) { stateList . concat ( block . getBucket ( ) ) ; } // Now , the states are ordered according to their signatures
int i = 0 ; while ( ! stateList . isEmpty ( ) ) { for ( State < S , L > state : stateList ) { TransitionLabel < S , L > letter = state . getSignatureLetter ( i ) ; if ( letter == null ) { finalList . pushBack ( state ) ; } else if ( letter . addToBucket ( state ) ) { letterList . add ( letter ) ; } // If this state was the first to be added to the respective
// bucket , or it differs from the previous entry in the previous
// letter , it is a split point .
if ( state . getPrev ( ) == null ) { state . setSplitPoint ( true ) ; } else if ( i > 0 && state . getPrev ( ) . getSignatureLetter ( i - 1 ) != state . getSignatureLetter ( i - 1 ) ) { state . setSplitPoint ( true ) ; } } stateList . clear ( ) ; for ( TransitionLabel < S , L > letter : letterList ) { stateList . concat ( letter . getBucket ( ) ) ; } letterList . clear ( ) ; i ++ ; } Block < S , L > prevBlock = null ; State < S , L > prev = null ; for ( State < S , L > state : finalList ) { Block < S , L > currBlock = state . getBlock ( ) ; if ( currBlock != prevBlock ) { currBlock . createSubBlock ( ) ; prevBlock = currBlock ; } else if ( state . isSplitPoint ( ) ) { currBlock . createSubBlock ( ) ; } currBlock . addToSubBlock ( state ) ; if ( prev != null ) { prev . reset ( ) ; } prev = state ; } if ( prev != null ) { prev . reset ( ) ; } finalList . clear ( ) ; // Step 4 of the algorithm is done in the method
// updateBlocks ( ) |
public class CircularQueueCaptureQueriesListener { /** * Index 0 is oldest */
@ SuppressWarnings ( "UseBulkOperation" ) public List < Query > getCapturedQueries ( ) { } } | // Make a copy so that we aren ' t affected by changes to the list outside of the
// synchronized block
ArrayList < Query > retVal = new ArrayList < > ( CAPACITY ) ; myQueries . forEach ( retVal :: add ) ; return Collections . unmodifiableList ( retVal ) ; |
public class MalisisInventoryContainer { /** * Handles shift clicking a slot .
* @ param inventoryId the inventory id
* @ param slot the slot
* @ return the item stack */
private ItemStack handleShiftClick ( MalisisInventory inventory , MalisisSlot slot ) { } } | ItemStack itemStack = transferSlotOutOfInventory ( inventory , slot ) ; // replace what ' s left of the item back into the slot
slot . setItemStack ( itemStack ) ; slot . onSlotChanged ( ) ; return itemStack ; |
public class Connectors { /** * Sets the request path and query parameters , decoding to the requested charset .
* @ param exchange The exchange
* @ param encodedPath The encoded path
* @ param charset The charset */
public static void setExchangeRequestPath ( final HttpServerExchange exchange , final String encodedPath , final String charset , boolean decode , final boolean allowEncodedSlash , StringBuilder decodeBuffer , int maxParameters ) throws ParameterLimitException { } } | boolean requiresDecode = false ; for ( int i = 0 ; i < encodedPath . length ( ) ; ++ i ) { char c = encodedPath . charAt ( i ) ; if ( c == '?' ) { String part ; String encodedPart = encodedPath . substring ( 0 , i ) ; if ( requiresDecode ) { part = URLUtils . decode ( encodedPart , charset , allowEncodedSlash , false , decodeBuffer ) ; } else { part = encodedPart ; } exchange . setRequestPath ( part ) ; exchange . setRelativePath ( part ) ; exchange . setRequestURI ( encodedPart ) ; final String qs = encodedPath . substring ( i + 1 ) ; exchange . setQueryString ( qs ) ; URLUtils . parseQueryString ( qs , exchange , charset , decode , maxParameters ) ; return ; } else if ( c == ';' ) { String part ; String encodedPart = encodedPath . substring ( 0 , i ) ; if ( requiresDecode ) { part = URLUtils . decode ( encodedPart , charset , allowEncodedSlash , false , decodeBuffer ) ; } else { part = encodedPart ; } exchange . setRequestPath ( part ) ; exchange . setRelativePath ( part ) ; for ( int j = i ; j < encodedPath . length ( ) ; ++ j ) { if ( encodedPath . charAt ( j ) == '?' ) { exchange . setRequestURI ( encodedPath . substring ( 0 , j ) ) ; String pathParams = encodedPath . substring ( i + 1 , j ) ; URLUtils . parsePathParams ( pathParams , exchange , charset , decode , maxParameters ) ; String qs = encodedPath . substring ( j + 1 ) ; exchange . setQueryString ( qs ) ; URLUtils . parseQueryString ( qs , exchange , charset , decode , maxParameters ) ; return ; } } exchange . setRequestURI ( encodedPath ) ; URLUtils . parsePathParams ( encodedPath . substring ( i + 1 ) , exchange , charset , decode , maxParameters ) ; return ; } else if ( c == '%' || c == '+' ) { requiresDecode = decode ; } } String part ; if ( requiresDecode ) { part = URLUtils . decode ( encodedPath , charset , allowEncodedSlash , false , decodeBuffer ) ; } else { part = encodedPath ; } exchange . setRequestPath ( part ) ; exchange . setRelativePath ( part ) ; exchange . setRequestURI ( encodedPath ) ; |
public class TerminateRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( TerminateRequest terminateRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( terminateRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( terminateRequest . getWorkspaceId ( ) , WORKSPACEID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class Resty { /** * POST to a URI and parse the result as XML
* @ param anUri
* the URI to visit
* @ param requestContent
* the content to POST to the URI
* @ return
* @ throws IOException
* if uri is wrong or no connection could be made or for 10 zillion other reasons */
public XMLResource xml ( URI anUri , AbstractContent requestContent ) throws IOException { } } | return doPOSTOrPUT ( anUri , requestContent , createXMLResource ( ) ) ; |
public class ChronoZonedDateTimeImpl { @ Override public ChronoZonedDateTime < D > plus ( long amountToAdd , TemporalUnit unit ) { } } | if ( unit instanceof ChronoUnit ) { return with ( dateTime . plus ( amountToAdd , unit ) ) ; } return ChronoZonedDateTimeImpl . ensureValid ( getChronology ( ) , unit . addTo ( this , amountToAdd ) ) ; // / TODO : Generics replacement Risk ! |
public class StateMachineExample { /** * Main entry point for the program .
* @ param args The command line arguments . */
public static void main ( String [ ] args ) throws Exception { } } | // - - - - print some usage help - - - -
System . out . println ( "Usage with built-in data generator: StateMachineExample [--error-rate <probability-of-invalid-transition>] [--sleep <sleep-per-record-in-ms>]" ) ; System . out . println ( "Usage with Kafka: StateMachineExample --kafka-topic <topic> [--brokers <brokers>]" ) ; System . out . println ( "Options for both the above setups: " ) ; System . out . println ( "\t[--backend <file|rocks>]" ) ; System . out . println ( "\t[--checkpoint-dir <filepath>]" ) ; System . out . println ( "\t[--async-checkpoints <true|false>]" ) ; System . out . println ( "\t[--incremental-checkpoints <true|false>]" ) ; System . out . println ( "\t[--output <filepath> OR null for stdout]" ) ; System . out . println ( ) ; // - - - - determine whether to use the built - in source , or read from Kafka - - - -
final SourceFunction < Event > source ; final ParameterTool params = ParameterTool . fromArgs ( args ) ; if ( params . has ( "kafka-topic" ) ) { // set up the Kafka reader
String kafkaTopic = params . get ( "kafka-topic" ) ; String brokers = params . get ( "brokers" , "localhost:9092" ) ; System . out . printf ( "Reading from kafka topic %s @ %s\n" , kafkaTopic , brokers ) ; System . out . println ( ) ; Properties kafkaProps = new Properties ( ) ; kafkaProps . setProperty ( "bootstrap.servers" , brokers ) ; FlinkKafkaConsumer010 < Event > kafka = new FlinkKafkaConsumer010 < > ( kafkaTopic , new EventDeSerializer ( ) , kafkaProps ) ; kafka . setStartFromLatest ( ) ; kafka . setCommitOffsetsOnCheckpoints ( false ) ; source = kafka ; } else { double errorRate = params . getDouble ( "error-rate" , 0.0 ) ; int sleep = params . getInt ( "sleep" , 1 ) ; System . out . printf ( "Using standalone source with error rate %f and sleep delay %s millis\n" , errorRate , sleep ) ; System . out . println ( ) ; source = new EventsGeneratorSource ( errorRate , sleep ) ; } // - - - - main program - - - -
// create the environment to create streams and configure execution
final StreamExecutionEnvironment env = StreamExecutionEnvironment . getExecutionEnvironment ( ) ; env . enableCheckpointing ( 2000L ) ; final String stateBackend = params . get ( "backend" , "memory" ) ; if ( "file" . equals ( stateBackend ) ) { final String checkpointDir = params . get ( "checkpoint-dir" ) ; boolean asyncCheckpoints = params . getBoolean ( "async-checkpoints" , false ) ; env . setStateBackend ( new FsStateBackend ( checkpointDir , asyncCheckpoints ) ) ; } else if ( "rocks" . equals ( stateBackend ) ) { final String checkpointDir = params . get ( "checkpoint-dir" ) ; boolean incrementalCheckpoints = params . getBoolean ( "incremental-checkpoints" , false ) ; env . setStateBackend ( new RocksDBStateBackend ( checkpointDir , incrementalCheckpoints ) ) ; } final String outputFile = params . get ( "output" ) ; // make parameters available in the web interface
env . getConfig ( ) . setGlobalJobParameters ( params ) ; DataStream < Event > events = env . addSource ( source ) ; DataStream < Alert > alerts = events // partition on the address to make sure equal addresses
// end up in the same state machine flatMap function
. keyBy ( Event :: sourceAddress ) // the function that evaluates the state machine over the sequence of events
. flatMap ( new StateMachineMapper ( ) ) ; // output the alerts to std - out
if ( outputFile == null ) { alerts . print ( ) ; } else { alerts . writeAsText ( outputFile , FileSystem . WriteMode . OVERWRITE ) . setParallelism ( 1 ) ; } // trigger program execution
env . execute ( "State machine job" ) ; |
public class MessageBuilder { /** * Removes all mentions of the specified types and replaces them with the closest looking textual representation .
* < p > Use this over { @ link # stripMentions ( Guild , Message . MentionType . . . ) } if { @ link net . dv8tion . jda . core . entities . User User }
* mentions should be replaced with their { @ link net . dv8tion . jda . core . entities . User # getName ( ) } .
* @ param jda
* The JDA instance used to resolve the mentions .
* @ param types
* the { @ link net . dv8tion . jda . core . entities . Message . MentionType MentionTypes } that should be stripped
* @ return The MessageBuilder instance . Useful for chaining . */
public MessageBuilder stripMentions ( JDA jda , Message . MentionType ... types ) { } } | return this . stripMentions ( jda , null , types ) ; |
public class ClobStreamingProcess { /** * { @ inheritDoc } */
@ Override public void write ( Clob entity , OutputStream output , Long pos , Long length ) throws IOException { } } | Reader reader ; try { reader = entity . getCharacterStream ( pos , length ) ; } catch ( SQLException e ) { throw new IOException ( e ) ; } try { ReaderWriter . writeTo ( reader , new OutputStreamWriter ( output ) ) ; } finally { IOUtils . closeQuietly ( reader ) ; } |
public class MetaDataMergeStrategyResolver { /** * Returns a { @ link DescriptorMergeStrategy } for a given descriptor . The strategy chosen is the one defined
* in the descriptor document .
* @ param descriptorUrl the URL that identifies the descriptor
* @ param descriptorDom the XML DOM of the descriptor
* @ return the { @ link DescriptorMergeStrategy } for the descriptor , or null if the DOM is null or if there ' s no
* element in the DOM that defines the merge strategy to use .
* @ throws XmlException if the element value doesn ' t refer to an existing strategy */
public DescriptorMergeStrategy getStrategy ( String descriptorUrl , Document descriptorDom ) throws XmlException { } } | if ( descriptorDom != null ) { Node element = descriptorDom . selectSingleNode ( mergeStrategyElementXPathQuery ) ; if ( element != null ) { DescriptorMergeStrategy strategy = elementValueToStrategyMappings . get ( element . getText ( ) ) ; if ( strategy != null ) { return strategy ; } else { throw new XmlException ( "Element value \"" + element . getText ( ) + "\" doesn't refer to an " + "registered strategy" ) ; } } else { return null ; } } else { return null ; } |
public class LocalDateTime { /** * Returns a copy of this datetime minus the specified number of weeks .
* This LocalDateTime instance is immutable and unaffected by this method call .
* The following three lines are identical in effect :
* < pre >
* LocalDateTime subtracted = dt . minusWeeks ( 6 ) ;
* LocalDateTime subtracted = dt . minus ( Period . weeks ( 6 ) ) ;
* LocalDateTime subtracted = dt . withFieldAdded ( DurationFieldType . weeks ( ) , - 6 ) ;
* < / pre >
* @ param weeks the amount of weeks to subtract , may be negative
* @ return the new LocalDateTime minus the increased weeks */
public LocalDateTime minusWeeks ( int weeks ) { } } | if ( weeks == 0 ) { return this ; } long instant = getChronology ( ) . weeks ( ) . subtract ( getLocalMillis ( ) , weeks ) ; return withLocalMillis ( instant ) ; |
public class PlaceRenderer { /** * Render the PlaceViewModel information . */
@ Override protected void render ( ) { } } | PlaceViewModel place = getContent ( ) ; nameTextView . setText ( place . getName ( ) ) ; Picasso . with ( context ) . load ( place . getPhoto ( ) ) . placeholder ( R . drawable . maps_placeholder ) . into ( photoImageView ) ; |
public class UpdateCrawlerRequest { /** * A list of custom classifiers that the user has registered . By default , all built - in classifiers are included in a
* crawl , but these custom classifiers always override the default classifiers for a given classification .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setClassifiers ( java . util . Collection ) } or { @ link # withClassifiers ( java . util . Collection ) } if you want to
* override the existing values .
* @ param classifiers
* A list of custom classifiers that the user has registered . By default , all built - in classifiers are
* included in a crawl , but these custom classifiers always override the default classifiers for a given
* classification .
* @ return Returns a reference to this object so that method calls can be chained together . */
public UpdateCrawlerRequest withClassifiers ( String ... classifiers ) { } } | if ( this . classifiers == null ) { setClassifiers ( new java . util . ArrayList < String > ( classifiers . length ) ) ; } for ( String ele : classifiers ) { this . classifiers . add ( ele ) ; } return this ; |
public class ResultHierarchy { /** * Informs all registered { @ link ResultListener } that a result has changed .
* @ param current Result that has changed */
private void fireResultChanged ( Result current ) { } } | if ( LOG . isDebugging ( ) ) { LOG . debug ( "Result changed: " + current ) ; } for ( int i = listenerList . size ( ) ; -- i >= 0 ; ) { listenerList . get ( i ) . resultChanged ( current ) ; } |
public class DefaultModelImpl { /** * / * ( non - Javadoc )
* @ see org . soitoolkit . tools . generator . model . IModel # getJavaPackage ( ) */
public String getJavaPackage ( ) { } } | String javaPackage = getJavaGroupId ( ) ; if ( ! isGroupIdSuffixedWithArtifactId ( ) ) { javaPackage += "." + getJavaArtifactId ( ) ; } return javaPackage . toLowerCase ( ) ; |
public class EasyGeneralFeatureDetector { /** * Detect features inside the image . Excluding points in the exclude list .
* @ param input Image being processed .
* @ param exclude List of points that should not be returned . */
public void detect ( T input , QueueCorner exclude ) { } } | initializeDerivatives ( input ) ; if ( detector . getRequiresGradient ( ) || detector . getRequiresHessian ( ) ) gradient . process ( input , derivX , derivY ) ; if ( detector . getRequiresHessian ( ) ) hessian . process ( derivX , derivY , derivXX , derivYY , derivXY ) ; detector . setExcludeMaximum ( exclude ) ; detector . process ( input , derivX , derivY , derivXX , derivYY , derivXY ) ; |
public class GetDatabaseRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( GetDatabaseRequest getDatabaseRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( getDatabaseRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( getDatabaseRequest . getCatalogId ( ) , CATALOGID_BINDING ) ; protocolMarshaller . marshall ( getDatabaseRequest . getName ( ) , NAME_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class AmazonPinpointClient { /** * Delete an APNS sandbox channel .
* @ param deleteApnsSandboxChannelRequest
* @ return Result of the DeleteApnsSandboxChannel operation returned by the service .
* @ throws BadRequestException
* 400 response
* @ throws InternalServerErrorException
* 500 response
* @ throws ForbiddenException
* 403 response
* @ throws NotFoundException
* 404 response
* @ throws MethodNotAllowedException
* 405 response
* @ throws TooManyRequestsException
* 429 response
* @ sample AmazonPinpoint . DeleteApnsSandboxChannel
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / pinpoint - 2016-12-01 / DeleteApnsSandboxChannel "
* target = " _ top " > AWS API Documentation < / a > */
@ Override public DeleteApnsSandboxChannelResult deleteApnsSandboxChannel ( DeleteApnsSandboxChannelRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeDeleteApnsSandboxChannel ( request ) ; |
public class RespokeCall { /** * Process ICE candidates suggested by the remote endpoint . This is used internally to the SDK and should not be called directly by your client application .
* @ param candidates Array of candidates to evaluate */
public void iceCandidatesReceived ( JSONArray candidates ) { } } | if ( isActive ( ) ) { for ( int ii = 0 ; ii < candidates . length ( ) ; ii ++ ) { try { JSONObject eachCandidate = ( JSONObject ) candidates . get ( ii ) ; String mid = eachCandidate . getString ( "sdpMid" ) ; int sdpLineIndex = eachCandidate . getInt ( "sdpMLineIndex" ) ; String sdp = eachCandidate . getString ( "candidate" ) ; IceCandidate rtcCandidate = new IceCandidate ( mid , sdpLineIndex , sdp ) ; try { // Start critical block
queuedRemoteCandidatesSemaphore . acquire ( ) ; if ( null != queuedRemoteCandidates ) { queuedRemoteCandidates . add ( rtcCandidate ) ; } else { peerConnection . addIceCandidate ( rtcCandidate ) ; } // End critical block
queuedRemoteCandidatesSemaphore . release ( ) ; } catch ( InterruptedException e ) { Log . d ( TAG , "Error with remote candidates semaphore" ) ; } } catch ( JSONException e ) { Log . d ( TAG , "Error processing remote ice candidate data" ) ; } } } |
public class XidFactoryImpl { /** * Create a branch Xid .
* @ param globalId the global Xid
* @ param branch the branch number
* @ return the new Xid . */
public Xid createBranch ( Xid globalId , int branch ) { } } | byte [ ] branchId = baseId . clone ( ) ; branchId [ 0 ] = ( byte ) branch ; branchId [ 1 ] = ( byte ) ( branch >>> 8 ) ; branchId [ 2 ] = ( byte ) ( branch >>> 16 ) ; branchId [ 3 ] = ( byte ) ( branch >>> 24 ) ; insertLong ( start , branchId , 4 ) ; return new XidImpl ( globalId , branchId ) ; |
public class FleetData { /** * Information about the instances that could not be launched by the fleet . Valid only when < b > Type < / b > is set to
* < code > instant < / code > .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setErrors ( java . util . Collection ) } or { @ link # withErrors ( java . util . Collection ) } if you want to override the
* existing values .
* @ param errors
* Information about the instances that could not be launched by the fleet . Valid only when < b > Type < / b > is
* set to < code > instant < / code > .
* @ return Returns a reference to this object so that method calls can be chained together . */
public FleetData withErrors ( DescribeFleetError ... errors ) { } } | if ( this . errors == null ) { setErrors ( new com . amazonaws . internal . SdkInternalList < DescribeFleetError > ( errors . length ) ) ; } for ( DescribeFleetError ele : errors ) { this . errors . add ( ele ) ; } return this ; |
public class AbstractTreeMap { /** * Answers a Collection of the keys contained in this TreeMap . The set is backed by
* this TreeMap so changes to one are relected by the other . The Collection does
* not support adding .
* @ return a Collection of the keys */
public Collection keyCollection ( ) { } } | if ( keyCollection == null ) { keyCollection = new AbstractCollectionView ( ) { public long size ( ) throws ObjectManagerException { return AbstractTreeMap . this . size ( ) ; } public Iterator iterator ( ) throws ObjectManagerException { return makeTreeMapIterator ( new AbstractMapEntry . Type ( ) { public Object get ( AbstractMapEntry entry ) { return entry . key ; } } ) ; } } ; } return keyCollection ; |
public class PropertiesFile { /** * Strip out any reserved properties and then write properties object to a file .
* @ param outputFile The file that our properties object will be written to */
public void writePropertiesToFile ( File outputFile ) throws MojoExecutionException { } } | // NOSONAR
stripOutReservedProperties ( ) ; // TODO if jmeter . properties write properties that are required for plugin
if ( properties . isEmpty ( ) ) { return ; } try { try ( FileOutputStream writeOutFinalPropertiesFile = new FileOutputStream ( outputFile ) ) { properties . store ( writeOutFinalPropertiesFile , null ) ; writeOutFinalPropertiesFile . flush ( ) ; } } catch ( IOException e ) { throw new MojoExecutionException ( e . getMessage ( ) , e ) ; } |
public class TurfJoins { /** * Takes a { @ link FeatureCollection } of { @ link Point } and a { @ link FeatureCollection } of
* { @ link Polygon } and returns the points that fall within the polygons .
* @ param points input points .
* @ param polygons input polygons .
* @ return points that land within at least one polygon .
* @ since 1.3.0 */
public static FeatureCollection pointsWithinPolygon ( FeatureCollection points , FeatureCollection polygons ) { } } | ArrayList < Feature > features = new ArrayList < > ( ) ; for ( int i = 0 ; i < polygons . features ( ) . size ( ) ; i ++ ) { for ( int j = 0 ; j < points . features ( ) . size ( ) ; j ++ ) { Point point = ( Point ) points . features ( ) . get ( j ) . geometry ( ) ; boolean isInside = TurfJoins . inside ( point , ( Polygon ) polygons . features ( ) . get ( i ) . geometry ( ) ) ; if ( isInside ) { features . add ( Feature . fromGeometry ( point ) ) ; } } } return FeatureCollection . fromFeatures ( features ) ; |
public class WeightVectors { /** * Read a set of weight vector from a file
* @ param filePath A file containing the weight vectors
* @ return A set of weight vectors */
public static double [ ] [ ] readFromFile ( String filePath ) { } } | double [ ] [ ] weights ; Vector < double [ ] > listOfWeights = new Vector < > ( ) ; try { // Open the file
FileInputStream fis = new FileInputStream ( filePath ) ; InputStreamReader isr = new InputStreamReader ( fis ) ; BufferedReader br = new BufferedReader ( isr ) ; int numberOfObjectives = 0 ; int j ; String aux = br . readLine ( ) ; while ( aux != null ) { StringTokenizer st = new StringTokenizer ( aux ) ; j = 0 ; numberOfObjectives = st . countTokens ( ) ; double [ ] weight = new double [ numberOfObjectives ] ; while ( st . hasMoreTokens ( ) ) { weight [ j ] = new Double ( st . nextToken ( ) ) ; j ++ ; } listOfWeights . add ( weight ) ; aux = br . readLine ( ) ; } br . close ( ) ; weights = new double [ listOfWeights . size ( ) ] [ numberOfObjectives ] ; for ( int indexWeight = 0 ; indexWeight < listOfWeights . size ( ) ; indexWeight ++ ) { System . arraycopy ( listOfWeights . get ( indexWeight ) , 0 , weights [ indexWeight ] , 0 , numberOfObjectives ) ; } } catch ( Exception e ) { throw new JMetalException ( "readFromFile: failed when reading for file: " + filePath + "" , e ) ; } return weights ; |
public class DeepEquals { /** * Correctly handles floating point comparisions . < br >
* source : http : / / floating - point - gui . de / errors / comparison /
* @ param a first number
* @ param b second number
* @ param epsilon double tolerance value
* @ return true if a and b are close enough */
private static boolean nearlyEqual ( double a , double b , double epsilon ) { } } | final double absA = Math . abs ( a ) ; final double absB = Math . abs ( b ) ; final double diff = Math . abs ( a - b ) ; if ( a == b ) { // shortcut , handles infinities
return true ; } else if ( a == 0 || b == 0 || diff < Double . MIN_NORMAL ) { // a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < ( epsilon * Double . MIN_NORMAL ) ; } else { // use relative error
return diff / ( absA + absB ) < epsilon ; } |
public class ApiOvhOrder { /** * Get allowed durations for ' upgrade ' option
* REST : GET / order / license / virtuozzo / { serviceName } / upgrade
* @ param containerNumber [ required ] How much container is this license able to manage . . .
* @ param serviceName [ required ] The name of your Virtuozzo license */
public ArrayList < String > license_virtuozzo_serviceName_upgrade_GET ( String serviceName , OvhOrderableVirtuozzoContainerNumberEnum containerNumber ) throws IOException { } } | String qPath = "/order/license/virtuozzo/{serviceName}/upgrade" ; StringBuilder sb = path ( qPath , serviceName ) ; query ( sb , "containerNumber" , containerNumber ) ; String resp = exec ( qPath , "GET" , sb . toString ( ) , null ) ; return convertTo ( resp , t1 ) ; |
public class Stylesheet { /** * Get an " xsl : namespace - alias " property .
* @ see < a href = " http : / / www . w3 . org / TR / xslt # literal - result - element " > literal - result - element in XSLT Specification < / a >
* @ param i Index of NamespaceAlias element to get from the list
* @ return NamespaceAlias element at the given index in the list
* @ throws ArrayIndexOutOfBoundsException */
public NamespaceAlias getNamespaceAlias ( int i ) throws ArrayIndexOutOfBoundsException { } } | if ( null == m_prefix_aliases ) throw new ArrayIndexOutOfBoundsException ( ) ; return ( NamespaceAlias ) m_prefix_aliases . elementAt ( i ) ; |
public class SeaGlassLookAndFeel { /** * Initialize the default font .
* @ return the default font . */
protected Font initializeDefaultFont ( ) { } } | /* * Set the default font to Lucida Grande if available , else use Lucida
* Sans Unicode . Grande is a later font and a bit nicer looking , but it
* is a derivation of Sans Unicode , so they ' re compatible . */
if ( defaultFont == null ) { if ( PlatformUtils . isMac ( ) ) { defaultFont = new Font ( "Lucida Grande" , Font . PLAIN , 13 ) ; } if ( defaultFont == null ) { defaultFont = new Font ( "Dialog" , Font . PLAIN , 13 ) ; } if ( defaultFont == null ) { defaultFont = new Font ( "SansSerif" , Font . PLAIN , 13 ) ; } } return defaultFont ; |
public class SASLAuthentication { /** * Returns the registered SASLMechanism sorted by the level of preference .
* @ return the registered SASLMechanism sorted by the level of preference . */
public static Map < String , String > getRegisterdSASLMechanisms ( ) { } } | Map < String , String > answer = new LinkedHashMap < > ( ) ; synchronized ( REGISTERED_MECHANISMS ) { for ( SASLMechanism mechanism : REGISTERED_MECHANISMS ) { answer . put ( mechanism . getClass ( ) . getName ( ) , mechanism . toString ( ) ) ; } } return answer ; |
public class GetLifecyclePolicyRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( GetLifecyclePolicyRequest getLifecyclePolicyRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( getLifecyclePolicyRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( getLifecyclePolicyRequest . getPolicyId ( ) , POLICYID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class HCJSNodeDetector { /** * Check if the passed node is an inline JS node after unwrapping .
* @ param aNode
* The node to be checked - may be < code > null < / code > .
* @ return < code > true < / code > if the node implements { @ link HCScriptInline } . */
public static boolean isJSInlineNode ( @ Nullable final IHCNode aNode ) { } } | final IHCNode aUnwrappedNode = HCHelper . getUnwrappedNode ( aNode ) ; return isDirectJSInlineNode ( aUnwrappedNode ) ; |
public class DelaunayTriangulation { /** * assumes v is NOT an halfplane !
* returns the next triangle for find . */
private static Triangle findnext1 ( Vector3 p , Triangle v ) { } } | if ( ! v . abnext . halfplane && PointLineTest . pointLineTest ( v . a , v . b , p ) == PointLinePosition . RIGHT ) return v . abnext ; if ( ! v . bcnext . halfplane && PointLineTest . pointLineTest ( v . b , v . c , p ) == PointLinePosition . RIGHT ) return v . bcnext ; if ( ! v . canext . halfplane && PointLineTest . pointLineTest ( v . c , v . a , p ) == PointLinePosition . RIGHT ) return v . canext ; if ( PointLineTest . pointLineTest ( v . a , v . b , p ) == PointLinePosition . RIGHT ) return v . abnext ; if ( PointLineTest . pointLineTest ( v . b , v . c , p ) == PointLinePosition . RIGHT ) return v . bcnext ; if ( PointLineTest . pointLineTest ( v . c , v . a , p ) == PointLinePosition . RIGHT ) return v . canext ; return null ; |
public class Validate { /** * < p > Validate that the specified argument collection is neither { @ code null }
* nor a size of zero ( no elements ) ; otherwise throwing an exception
* with the specified message .
* < pre > Validate . notEmpty ( myCollection , " The collection must not be empty " ) ; < / pre >
* @ param < T > the collection type
* @ param collection the collection to check , validated not null by this method
* @ param message the { @ link String # format ( String , Object . . . ) } exception message if invalid , not null
* @ param values the optional values for the formatted exception message , null array not recommended
* @ return the validated collection ( never { @ code null } method for chaining )
* @ throws NullPointerException if the collection is { @ code null }
* @ throws IllegalArgumentException if the collection is empty
* @ see # notEmpty ( Object [ ] ) */
public static < T extends Collection < ? > > T notEmpty ( final T collection , final String message , final Object ... values ) { } } | if ( collection == null ) { throw new NullPointerException ( StringUtils . simpleFormat ( message , values ) ) ; } if ( collection . isEmpty ( ) ) { throw new IllegalArgumentException ( StringUtils . simpleFormat ( message , values ) ) ; } return collection ; |
public class WorkflowClient { /** * Retrieve all workflows for a given correlation id and name
* @ param name the name of the workflow
* @ param correlationId the correlation id
* @ param includeClosed specify if all workflows are to be returned or only running workflows
* @ param includeTasks specify if the tasks in the workflow need to be returned
* @ return list of workflows for the given correlation id and name */
public List < Workflow > getWorkflows ( String name , String correlationId , boolean includeClosed , boolean includeTasks ) { } } | Preconditions . checkArgument ( StringUtils . isNotBlank ( name ) , "name cannot be blank" ) ; Preconditions . checkArgument ( StringUtils . isNotBlank ( correlationId ) , "correlationId cannot be blank" ) ; Object [ ] params = new Object [ ] { "includeClosed" , includeClosed , "includeTasks" , includeTasks } ; List < Workflow > workflows = getForEntity ( "workflow/{name}/correlated/{correlationId}" , params , new GenericType < List < Workflow > > ( ) { } , name , correlationId ) ; workflows . forEach ( this :: populateWorkflowOutput ) ; return workflows ; |
public class LocalisationManager { /** * Method addMEToRemoteQueuePointGuessSet
* < p > Adds an ME to the remote guess set for queue points .
* Unit tests only
* @ return */
public void addMEToRemoteQueuePointGuessSet ( SIBUuid8 messagingEngineUuid ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "addMEToRemoteQueuePointGuessSet" ) ; synchronized ( _remoteQueuePointsGuessSet ) { _remoteQueuePointsGuessSet . add ( messagingEngineUuid ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "addMEToRemoteQueuePointGuessSet" ) ; |
public class Packet { /** * Builds the packet which just wraps the IoBuffer .
* @ param buffer
* @ return packet */
public static Packet build ( IoBuffer buffer ) { } } | if ( buffer . hasArray ( ) ) { return new Packet ( buffer . array ( ) ) ; } byte [ ] buf = new byte [ buffer . remaining ( ) ] ; buffer . get ( buf ) ; return new Packet ( buf ) ; |
public class MavenResolverSystemBaseImpl { /** * { @ inheritDoc }
* @ see org . jboss . shrinkwrap . resolver . api . ResolveStage # resolve ( java . util . Collection ) */
@ Override public STRATEGYSTAGETYPE resolve ( Collection < String > canonicalForms ) throws IllegalArgumentException , ResolutionException , CoordinateParseException { } } | return delegate . resolve ( canonicalForms ) ; |
public class druidGLexer { /** * $ ANTLR start " DOUBLE _ SUM " */
public final void mDOUBLE_SUM ( ) throws RecognitionException { } } | try { int _type = DOUBLE_SUM ; int _channel = DEFAULT_TOKEN_CHANNEL ; // druidG . g : 610:12 : ( ( ' DOUBLE _ SUM ' ) )
// druidG . g : 610:14 : ( ' DOUBLE _ SUM ' )
{ // druidG . g : 610:14 : ( ' DOUBLE _ SUM ' )
// druidG . g : 610:15 : ' DOUBLE _ SUM '
{ match ( "DOUBLE_SUM" ) ; } } state . type = _type ; state . channel = _channel ; } finally { // do for sure before leaving
} |
public class NaturalLanguageClassifier { /** * Classify multiple phrases .
* Returns label information for multiple phrases . The status must be ` Available ` before you can use the classifier to
* classify text .
* Note that classifying Japanese texts is a beta feature .
* @ param classifyCollectionOptions the { @ link ClassifyCollectionOptions } containing the options for the call
* @ return a { @ link ServiceCall } with a response type of { @ link ClassificationCollection } */
public ServiceCall < ClassificationCollection > classifyCollection ( ClassifyCollectionOptions classifyCollectionOptions ) { } } | Validator . notNull ( classifyCollectionOptions , "classifyCollectionOptions cannot be null" ) ; String [ ] pathSegments = { "v1/classifiers" , "classify_collection" } ; String [ ] pathParameters = { classifyCollectionOptions . classifierId ( ) } ; RequestBuilder builder = RequestBuilder . post ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments , pathParameters ) ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "natural_language_classifier" , "v1" , "classifyCollection" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; final JsonObject contentJson = new JsonObject ( ) ; contentJson . add ( "collection" , GsonSingleton . getGson ( ) . toJsonTree ( classifyCollectionOptions . collection ( ) ) ) ; builder . bodyJson ( contentJson ) ; return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( ClassificationCollection . class ) ) ; |
public class AlluxioMasterRestServiceHandler { /** * Gets Web UI workers page data .
* @ return the response object */
@ GET @ Path ( WEBUI_WORKERS ) @ ReturnType ( "alluxio.wire.MasterWebUIWorkers" ) public Response getWebUIWorkers ( ) { } } | return RestUtils . call ( ( ) -> { MasterWebUIWorkers response = new MasterWebUIWorkers ( ) ; response . setDebug ( ServerConfiguration . getBoolean ( PropertyKey . DEBUG ) ) ; List < WorkerInfo > workerInfos = mBlockMaster . getWorkerInfoList ( ) ; NodeInfo [ ] normalNodeInfos = WebUtils . generateOrderedNodeInfos ( workerInfos ) ; response . setNormalNodeInfos ( normalNodeInfos ) ; List < WorkerInfo > lostWorkerInfos = mBlockMaster . getLostWorkersInfoList ( ) ; NodeInfo [ ] failedNodeInfos = WebUtils . generateOrderedNodeInfos ( lostWorkerInfos ) ; response . setFailedNodeInfos ( failedNodeInfos ) ; return response ; } , ServerConfiguration . global ( ) ) ; |
public class JCalRawWriter { /** * Closes the current component array .
* @ throws IllegalStateException if there are no open components (
* { @ link # writeStartComponent ( String ) } must be called first )
* @ throws IOException if there ' s an I / O problem */
public void writeEndComponent ( ) throws IOException { } } | if ( stack . isEmpty ( ) ) { throw new IllegalStateException ( Messages . INSTANCE . getExceptionMessage ( 2 ) ) ; } Info cur = stack . removeLast ( ) ; if ( ! cur . wroteEndPropertiesArray ) { generator . writeEndArray ( ) ; } if ( ! cur . wroteStartSubComponentsArray ) { generator . writeStartArray ( ) ; } generator . writeEndArray ( ) ; // end sub - components array
generator . writeEndArray ( ) ; // end the array of this component
componentEnded = true ; |
public class CmsLockManager { /** * Returns a shared lock for the given excclusive lock and sibling . < p >
* @ param exclusiveLock the exclusive lock to use ( has to be set on a sibling of siblingName )
* @ param siblingName the siblings name
* @ return the shared lock */
private CmsLock internalSiblingLock ( CmsLock exclusiveLock , String siblingName ) { } } | CmsLock lock = null ; if ( ! exclusiveLock . getSystemLock ( ) . isUnlocked ( ) ) { lock = new CmsLock ( siblingName , exclusiveLock . getUserId ( ) , exclusiveLock . getProject ( ) , exclusiveLock . getSystemLock ( ) . getType ( ) ) ; } if ( ( lock == null ) || ! exclusiveLock . getEditionLock ( ) . isNullLock ( ) ) { CmsLockType type = CmsLockType . SHARED_EXCLUSIVE ; if ( ! getParentLock ( siblingName ) . isNullLock ( ) ) { type = CmsLockType . SHARED_INHERITED ; } if ( lock == null ) { lock = new CmsLock ( siblingName , exclusiveLock . getUserId ( ) , exclusiveLock . getProject ( ) , type ) ; } else { CmsLock editionLock = new CmsLock ( siblingName , exclusiveLock . getUserId ( ) , exclusiveLock . getProject ( ) , type ) ; lock . setRelatedLock ( editionLock ) ; } } return lock ; |
public class VariantCustom { /** * Inner method for correct scripting
* @ param msg the message that need to be modified
* @ param originalPair the original { @ code NameValuePair } being tested .
* @ param paramName the name of the parameter
* @ param value the value thta should be set for this parameter
* @ param escaped true if the parameter has been already escaped
* @ return the value set as parameter */
private String setParameter ( HttpMessage msg , NameValuePair originalPair , String paramName , String value , boolean escaped ) { } } | try { if ( script != null ) { currentParam = originalPair ; script . setParameter ( this , msg , paramName , value , escaped ) ; } } catch ( Exception e ) { // Catch Exception instead of ScriptException because script engine implementations might
// throw other exceptions on script errors ( e . g . jdk . nashorn . internal . runtime . ECMAException )
extension . handleScriptException ( wrapper , e ) ; } finally { currentParam = null ; } return value ; |
public class ScopeStack { /** * / * @ Nullable */
public String getName ( Object referenced ) { } } | if ( referenced == null ) throw new NullPointerException ( "referenced" ) ; if ( scopes . isEmpty ( ) ) return null ; int size = scopes . size ( ) ; int i = size - 1 ; while ( i >= 0 ) { Scope currentScope = scopes . get ( i -- ) ; for ( Variable v : currentScope . variables ( ) ) { if ( v . referenced . equals ( referenced ) ) return v . name ; } } return null ; |
public class MultiLineFileHeaderProvider { /** * / * @ NonNull */
@ Override public List < INode > getFileHeaderNodes ( Resource resource ) { } } | if ( resource instanceof XtextResource ) { IParseResult parseResult = ( ( XtextResource ) resource ) . getParseResult ( ) ; if ( parseResult != null ) { for ( ILeafNode leafNode : parseResult . getRootNode ( ) . getLeafNodes ( ) ) { EObject grammarElement = leafNode . getGrammarElement ( ) ; if ( grammarElement instanceof TerminalRule ) { String terminalRuleName = ( ( TerminalRule ) grammarElement ) . getName ( ) ; if ( ruleName . equalsIgnoreCase ( terminalRuleName ) ) { return singletonList ( ( INode ) leafNode ) ; } else if ( wsRuleName . equals ( terminalRuleName ) ) { continue ; } } break ; } } } return Collections . emptyList ( ) ; |
public class LObjIntSrtPredicateBuilder { /** * One of ways of creating builder . This is possibly the least verbose way where compiler should be able to guess the generic parameters . */
@ Nonnull public static < T > LObjIntSrtPredicate < T > objIntSrtPredicateFrom ( Consumer < LObjIntSrtPredicateBuilder < T > > buildingFunction ) { } } | LObjIntSrtPredicateBuilder builder = new LObjIntSrtPredicateBuilder ( ) ; buildingFunction . accept ( builder ) ; return builder . build ( ) ; |
public class CholeskyDecomposition { /** * Solve A * X = B
* @ param B A Matrix with as many rows as A and any number of columns .
* @ return X so that L * L ^ T * X = B
* @ exception IllegalArgumentException Matrix row dimensions must agree .
* @ exception RuntimeException Matrix is not symmetric positive definite . */
public double [ ] [ ] solve ( double [ ] [ ] B ) { } } | if ( B . length != L . length ) { throw new IllegalArgumentException ( ERR_MATRIX_DIMENSIONS ) ; } if ( ! isspd ) { throw new ArithmeticException ( ERR_MATRIX_NOT_SPD ) ; } // Work on a copy !
return solveLtransposed ( solveL ( copy ( B ) ) ) ; |
public class BlockReader { /** * Read a list of fixed sized blocks from the input stream .
* @ return List of MapRow instances representing the fixed size blocks */
public List < MapRow > read ( ) throws IOException { } } | List < MapRow > result = new ArrayList < MapRow > ( ) ; int fileCount = m_stream . readInt ( ) ; if ( fileCount != 0 ) { for ( int index = 0 ; index < fileCount ; index ++ ) { // We use a LinkedHashMap to preserve insertion order in iteration
// Useful when debugging the file format .
Map < String , Object > map = new LinkedHashMap < String , Object > ( ) ; readBlock ( map ) ; result . add ( new MapRow ( map ) ) ; } } return result ; |
public class PropertyDatabase { /** * Write property database to an OutputStream . The OutputStream is
* guaranteed to be closed , even if an exception is thrown .
* @ param out
* the OutputStream
* @ throws IOException */
public void write ( @ WillClose OutputStream out ) throws IOException { } } | BufferedWriter writer = null ; boolean missingClassWarningsSuppressed = AnalysisContext . currentAnalysisContext ( ) . setMissingClassWarningsSuppressed ( true ) ; try { writer = new BufferedWriter ( new OutputStreamWriter ( out , UTF8 . charset ) ) ; TreeSet < KeyType > sortedMethodSet = new TreeSet < > ( ) ; sortedMethodSet . addAll ( propertyMap . keySet ( ) ) ; for ( KeyType key : sortedMethodSet ) { if ( AnalysisContext . currentAnalysisContext ( ) . isApplicationClass ( key . getClassDescriptor ( ) ) ) { ValueType property = propertyMap . get ( key ) ; writeKey ( writer , key ) ; writer . write ( "|" ) ; writer . write ( encodeProperty ( property ) ) ; writer . write ( "\n" ) ; } } } finally { AnalysisContext . currentAnalysisContext ( ) . setMissingClassWarningsSuppressed ( missingClassWarningsSuppressed ) ; try { if ( writer != null ) { writer . close ( ) ; } } catch ( IOException e ) { // Ignore
} } |
public class ReplParser { /** * As faithful a clone of the overridden method as possible while still
* achieving the goal of allowing the parse of a stand - alone snippet .
* As a result , some variables are assigned and never used , tests are
* always true , loops don ' t , etc . This is to allow easy transition as the
* underlying method changes .
* @ return a snippet wrapped in a compilation unit */
@ Override public JCCompilationUnit parseCompilationUnit ( ) { } } | Token firstToken = token ; JCModifiers mods = null ; boolean seenImport = false ; boolean seenPackage = false ; ListBuffer < JCTree > defs = new ListBuffer < > ( ) ; if ( token . kind == MONKEYS_AT ) { mods = modifiersOpt ( ) ; } boolean firstTypeDecl = true ; while ( token . kind != EOF ) { if ( token . pos > 0 && token . pos <= endPosTable . errorEndPos ) { // error recovery
skip ( true , false , false , false ) ; if ( token . kind == EOF ) { break ; } } if ( mods == null && token . kind == IMPORT ) { seenImport = true ; defs . append ( importDeclaration ( ) ) ; } else { Comment docComment = token . comment ( CommentStyle . JAVADOC ) ; if ( firstTypeDecl && ! seenImport && ! seenPackage ) { docComment = firstToken . comment ( CommentStyle . JAVADOC ) ; } List < ? extends JCTree > udefs = replUnit ( mods , docComment ) ; // if ( def instanceof JCExpressionStatement )
// def = ( ( JCExpressionStatement ) def ) . expr ;
for ( JCTree def : udefs ) { defs . append ( def ) ; } mods = null ; firstTypeDecl = false ; } break ; // Remove to process more than one snippet
} List < JCTree > rdefs = defs . toList ( ) ; class ReplUnit extends JCCompilationUnit { public ReplUnit ( List < JCTree > defs ) { super ( defs ) ; } } JCCompilationUnit toplevel = new ReplUnit ( rdefs ) ; if ( rdefs . isEmpty ( ) ) { storeEnd ( toplevel , S . prevToken ( ) . endPos ) ; } toplevel . lineMap = S . getLineMap ( ) ; this . endPosTable . setParser ( null ) ; // remove reference to parser
toplevel . endPositions = this . endPosTable ; return toplevel ; |
public class FilteredAttributes { /** * Get the URI for the index - th attribute . */
public String getURI ( int index ) { } } | if ( index < 0 || index >= indexSet . size ( ) ) return null ; return attributes . getURI ( indexSet . get ( index ) ) ; |
public class ClassUtil { /** * Looks up the method on the specified object that has a signature that matches the supplied
* arguments array . This is very expensive , so you shouldn ' t be doing this for something that
* happens frequently .
* @ return the best matching method with the specified name that accepts the supplied
* arguments , or null if no method could be found .
* @ see MethodFinder */
public static Method getMethod ( String name , Object target , Object [ ] args ) { } } | Class < ? > tclass = target . getClass ( ) ; Method meth = null ; try { MethodFinder finder = new MethodFinder ( tclass ) ; meth = finder . findMethod ( name , args ) ; } catch ( NoSuchMethodException nsme ) { // nothing to do here but fall through and return null
log . info ( "No such method" , "name" , name , "tclass" , tclass . getName ( ) , "args" , args , "error" , nsme ) ; } catch ( SecurityException se ) { log . warning ( "Unable to look up method?" , "tclass" , tclass . getName ( ) , "mname" , name ) ; } return meth ; |
public class ProtoFieldInterpreter { /** * Returns a { @ link ProtoFieldInterpreter } that has the given type and delegates to the
* SoyValueConverter for interpretation . */
private static final ProtoFieldInterpreter enumTypeField ( final EnumDescriptor enumDescriptor ) { } } | return new ProtoFieldInterpreter ( ) { @ Override public SoyValue soyFromProto ( Object field ) { int value ; if ( field instanceof ProtocolMessageEnum ) { value = ( ( ProtocolMessageEnum ) field ) . getNumber ( ) ; } else { // The value will be an EnumValueDescriptor when fetched via reflection or a
// ProtocolMessageEnum otherwise . Who knows why .
value = ( ( EnumValueDescriptor ) field ) . getNumber ( ) ; } return IntegerData . forValue ( value ) ; } @ Override Object protoFromSoy ( SoyValue field ) { // The proto reflection api wants the EnumValueDescriptor , not the actual enum instance
int value = field . integerValue ( ) ; // in proto3 we preserve unknown enum values ( for consistency with jbcsrc ) , but for proto2
// we don ' t , and so if the field is unknown we will return null which will trigger an NPE
// again , for consistency with jbcsrc .
if ( enumDescriptor . getFile ( ) . getSyntax ( ) == Syntax . PROTO3 ) { return enumDescriptor . findValueByNumberCreatingIfUnknown ( value ) ; } return enumDescriptor . findValueByNumber ( value ) ; } } ; |
public class cachepolicy_lbvserver_binding { /** * Use this API to fetch cachepolicy _ lbvserver _ binding resources of given name . */
public static cachepolicy_lbvserver_binding [ ] get ( nitro_service service , String policyname ) throws Exception { } } | cachepolicy_lbvserver_binding obj = new cachepolicy_lbvserver_binding ( ) ; obj . set_policyname ( policyname ) ; cachepolicy_lbvserver_binding response [ ] = ( cachepolicy_lbvserver_binding [ ] ) obj . get_resources ( service ) ; return response ; |
public class AwsClientBuilder { /** * Request handlers are copied to a new list to avoid mutation , if no request handlers are
* provided to the builder we supply an empty list . */
private List < RequestHandler2 > resolveRequestHandlers ( ) { } } | return ( requestHandlers == null ) ? new ArrayList < RequestHandler2 > ( ) : new ArrayList < RequestHandler2 > ( requestHandlers ) ; |
public class SimplestMapViewer { /** * Creates a simple tile renderer layer with the AndroidUtil helper . */
@ Override protected void createLayers ( ) { } } | TileRendererLayer tileRendererLayer = AndroidUtil . createTileRendererLayer ( this . tileCaches . get ( 0 ) , this . mapView . getModel ( ) . mapViewPosition , getMapFile ( ) , getRenderTheme ( ) , false , true , false ) ; this . mapView . getLayerManager ( ) . getLayers ( ) . add ( tileRendererLayer ) ; |
public class Utils { /** * Convert timestamp in a long format to joda time
* @ param input timestamp
* @ param format timestamp format
* @ param timezone time zone of timestamp
* @ return joda time */
public static DateTime toDateTime ( long input , String format , String timezone ) { } } | return toDateTime ( Long . toString ( input ) , format , timezone ) ; |
public class CharacterEncoder { /** * Encode the buffer in < i > aBuffer < / i > and write the encoded
* result to the OutputStream < i > aStream < / i > . */
public void encode ( byte aBuffer [ ] , OutputStream aStream ) throws IOException { } } | ByteArrayInputStream inStream = new ByteArrayInputStream ( aBuffer ) ; encode ( inStream , aStream ) ; |
public class KeyUtil { /** * 生成私钥 , 仅用于非对称加密 < br >
* 采用PKCS # 8规范 , 此规范定义了私钥信息语法和加密私钥语法 < br >
* 算法见 : https : / / docs . oracle . com / javase / 7 / docs / technotes / guides / security / StandardNames . html # KeyFactory
* @ param algorithm 算法
* @ param key 密钥 , 必须为DER编码存储
* @ return 私钥 { @ link PrivateKey } */
public static PrivateKey generatePrivateKey ( String algorithm , byte [ ] key ) { } } | if ( null == key ) { return null ; } return generatePrivateKey ( algorithm , new PKCS8EncodedKeySpec ( key ) ) ; |
public class AlignedBox3d { /** * Set the min X .
* @ param x the min x . */
@ Override public void setMinX ( double x ) { } } | double o = this . maxxProperty . doubleValue ( ) ; if ( o < x ) { this . minxProperty . set ( o ) ; this . maxxProperty . set ( x ) ; } else { this . minxProperty . set ( x ) ; } |
public class StreamEx { /** * Merge series of adjacent elements which satisfy the given predicate using
* the merger function and return a new stream .
* This is a < a href = " package - summary . html # StreamOps " > quasi - intermediate < / a >
* partial reduction operation .
* This operation is equivalent to
* { @ code collapse ( collapsible , Collectors . reducing ( merger ) ) . map ( Optional : : get ) }
* , but more efficient .
* @ param collapsible a non - interfering , stateless predicate to apply to the
* pair of adjacent elements of the input stream which returns true
* for elements which are collapsible .
* @ param merger a non - interfering , stateless , associative function to merge
* two adjacent elements for which collapsible predicate returned
* true . Note that it can be applied to the results if previous
* merges .
* @ return the new stream
* @ since 0.3.1 */
public StreamEx < T > collapse ( BiPredicate < ? super T , ? super T > collapsible , BinaryOperator < T > merger ) { } } | return collapseInternal ( collapsible , Function . identity ( ) , merger , merger ) ; |
public class HttpInputStream { /** * Reset the stream .
* Turn chunking off and disable all filters .
* @ exception IllegalStateException The stream cannot be reset if
* there is some unread chunked input or a content length greater
* than zero remaining . */
public void resetStream ( ) throws IllegalStateException { } } | if ( ( _deChunker != null && _deChunker . _chunkSize > 0 ) || _realIn . getByteLimit ( ) > 0 ) throw new IllegalStateException ( "Unread input" ) ; if ( log . isTraceEnabled ( ) ) log . trace ( "resetStream()" ) ; in = _realIn ; if ( _deChunker != null ) _deChunker . resetStream ( ) ; _chunking = false ; _realIn . setByteLimit ( - 1 ) ; |
public class JvmEnumAnnotationValueImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public EList < JvmEnumerationLiteral > getValues ( ) { } } | if ( values == null ) { values = new EObjectResolvingEList < JvmEnumerationLiteral > ( JvmEnumerationLiteral . class , this , TypesPackage . JVM_ENUM_ANNOTATION_VALUE__VALUES ) ; } return values ; |
public class CmsDefaultXmlContentHandler { /** * Returns the is - invalidate - parent flag for the given xpath . < p >
* @ param xpath the path to get the check rule for
* @ return the configured is - invalidate - parent flag for the given xpath */
protected boolean isInvalidateParent ( String xpath ) { } } | if ( ! CmsXmlUtils . isDeepXpath ( xpath ) ) { return false ; } Boolean isInvalidateParent = null ; // look up the default from the configured mappings
isInvalidateParent = m_relationChecks . get ( xpath ) ; if ( isInvalidateParent == null ) { // no value found , try default xpath
String path = CmsXmlUtils . removeXpath ( xpath ) ; // look up the default value again without indexes
isInvalidateParent = m_relationChecks . get ( path ) ; } if ( isInvalidateParent == null ) { return false ; } return isInvalidateParent . booleanValue ( ) ; |
public class JaxbHelper { /** * Marshals the object as XML to a string .
* @ param obj
* Object to marshal .
* @ param jaxbContext
* Context to use .
* @ return XML String .
* @ throws MarshalObjectException
* Error writing the object .
* @ param < TYPE >
* Type of the object . */
public < TYPE > String write ( @ NotNull final TYPE obj , @ NotNull final JAXBContext jaxbContext ) throws MarshalObjectException { } } | Contract . requireArgNotNull ( "obj" , obj ) ; Contract . requireArgNotNull ( "jaxbContext" , jaxbContext ) ; final StringWriter writer = new StringWriter ( ) ; write ( obj , writer , jaxbContext ) ; return writer . toString ( ) ; |
public class IOUtil { /** * Copy the specified < code > scrFile < / code > if it ' s a file or its sub files / directories if it ' s a directory to the target < code > destDir < / code > with the specified < code > filter < / code >
* @ param srcFile
* @ param destDir
* @ param preserveFileDate
* @ param filter */
public static < E extends Exception > void copy ( File srcFile , File destDir , final boolean preserveFileDate , final Try . BiPredicate < ? super File , ? super File , E > filter ) throws UncheckedIOException , E { } } | if ( ! srcFile . exists ( ) ) { throw new IllegalArgumentException ( "The source file doesn't exist: " + srcFile . getAbsolutePath ( ) ) ; } if ( destDir . exists ( ) ) { if ( destDir . isFile ( ) ) { throw new IllegalArgumentException ( "The destination file must be directory: " + destDir . getAbsolutePath ( ) ) ; } } else { if ( ! destDir . mkdirs ( ) ) { throw new UncheckedIOException ( new IOException ( "Failed to create destination directory: " + destDir . getAbsolutePath ( ) ) ) ; } } if ( destDir . canWrite ( ) == false ) { throw new UncheckedIOException ( new IOException ( "Destination '" + destDir + "' cannot be written to" ) ) ; } String destCanonicalPath = null ; String srcCanonicalPath = null ; try { srcFile = srcFile . getCanonicalFile ( ) ; destDir = destDir . getCanonicalFile ( ) ; destCanonicalPath = destDir . getCanonicalPath ( ) ; srcCanonicalPath = srcFile . getCanonicalPath ( ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } if ( srcFile . isDirectory ( ) ) { if ( destCanonicalPath . startsWith ( srcCanonicalPath ) && ( destCanonicalPath . length ( ) == srcCanonicalPath . length ( ) || destCanonicalPath . charAt ( srcCanonicalPath . length ( ) ) == '/' || destCanonicalPath . charAt ( srcCanonicalPath . length ( ) ) == '\\' ) ) { throw new IllegalArgumentException ( "Failed to copy due to the target directory: " + destCanonicalPath + " is in or same as the source directory: " + srcCanonicalPath ) ; } try { doCopyDirectory ( srcFile , destDir , preserveFileDate , filter ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } } else { File destFile = null ; try { if ( destDir . getCanonicalPath ( ) . equals ( srcFile . getParentFile ( ) . getCanonicalPath ( ) ) ) { destFile = new File ( destDir , "Copy of " + srcFile . getName ( ) ) ; } else { destFile = new File ( destDir , srcFile . getName ( ) ) ; } } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } doCopyFile ( srcFile , destFile , preserveFileDate ) ; } |
public class DefaultSecurityContext { /** * Calculate UserInfo strings . */
private void userInfoInit ( ) { } } | boolean first = true ; userId = null ; userLocale = null ; userName = null ; userOrganization = null ; userDivision = null ; if ( null != authentications ) { for ( Authentication auth : authentications ) { userId = combine ( userId , auth . getUserId ( ) ) ; userName = combine ( userName , auth . getUserName ( ) ) ; if ( first ) { userLocale = auth . getUserLocale ( ) ; first = false ; } else { if ( null != auth . getUserLocale ( ) && ( null == userLocale || ! userLocale . equals ( auth . getUserLocale ( ) ) ) ) { userLocale = null ; } } userOrganization = combine ( userOrganization , auth . getUserOrganization ( ) ) ; userDivision = combine ( userDivision , auth . getUserDivision ( ) ) ; } } // now calculate the " id " for this context , this should be independent of the data order , so sort
Map < String , List < String > > idParts = new HashMap < String , List < String > > ( ) ; if ( null != authentications ) { for ( Authentication auth : authentications ) { List < String > auths = new ArrayList < String > ( ) ; for ( BaseAuthorization ba : auth . getAuthorizations ( ) ) { auths . add ( ba . getId ( ) ) ; } Collections . sort ( auths ) ; idParts . put ( auth . getSecurityServiceId ( ) , auths ) ; } } StringBuilder sb = new StringBuilder ( ) ; List < String > sortedKeys = new ArrayList < String > ( idParts . keySet ( ) ) ; Collections . sort ( sortedKeys ) ; for ( String key : sortedKeys ) { if ( sb . length ( ) > 0 ) { sb . append ( '|' ) ; } List < String > auths = idParts . get ( key ) ; first = true ; for ( String ak : auths ) { if ( first ) { first = false ; } else { sb . append ( '|' ) ; } sb . append ( ak ) ; } sb . append ( '@' ) ; sb . append ( key ) ; } id = sb . toString ( ) ; |
public class MetaDataResult { /** * Get the Quandl code associated with this metadata .
* @ return the quandl code ( DATASOURCE / CODE form ) , null if not present . */
public String getQuandlCode ( ) { } } | try { String dataSourceField = getString ( DATA_SOURCE_FIELD ) ; String codeField = getString ( CODE_FIELD ) ; // if either not present , will throw an exception .
return dataSourceField + "/" + codeField ; } catch ( RuntimeException ex ) { return null ; } |
public class LeaderState { /** * Ensures the local server is not the leader . */
private void stepDown ( ) { } } | if ( context . getLeader ( ) != null && context . getLeader ( ) . equals ( context . getCluster ( ) . member ( ) ) ) { context . setLeader ( 0 ) ; } |
public class HtmlTool { /** * Splits the given HTML content into partitions based on the given separator selector . The
* separators are either dropped or joined with before / after depending on the indicated
* separator strategy .
* Note that splitting algorithm tries to resolve nested elements so that returned partitions
* are self - contained HTML elements . The nesting is normally contained within the first
* applicable partition .
* @ param content
* HTML content to split
* @ param separatorCssSelector
* CSS selector for separators
* @ param separatorStrategy
* strategy to drop or keep separators
* @ return a list of HTML partitions split on separator locations . If no splitting occurs ,
* returns the original content as the single element of the list
* @ since 1.0 */
public List < String > split ( String content , String separatorCssSelector , JoinSeparator separatorStrategy ) { } } | Element body = parseContent ( content ) ; List < Element > separators = body . select ( separatorCssSelector ) ; if ( separators . size ( ) > 0 ) { List < List < Element > > partitions = split ( separators , separatorStrategy , body ) ; List < String > sectionHtml = new ArrayList < String > ( ) ; for ( List < Element > partition : partitions ) { sectionHtml . add ( outerHtml ( partition ) ) ; } return sectionHtml ; } else { // nothing to split
return Collections . singletonList ( content ) ; } |
public class FilterUtilities { /** * This function is used to create the HQL query where clause that is
* appended to the generic EJBQL ( as created in default EntityList objects )
* select statement . It takes the request parameters to get the tags that
* are to be included in the clause , groups them by category , and then take
* additional request parameters to define the boolean operations to use
* between tags in a category , and between categories .
* @ return the clause to append to the EJBQL select statement */
public static < T > CriteriaQuery < T > buildQuery ( final Filter filter , final IFilterQueryBuilder < T > filterQueryBuilder ) { } } | final CriteriaQuery < T > query = filterQueryBuilder . getBaseCriteriaQuery ( ) ; final Predicate condition = buildQueryConditions ( filter , filterQueryBuilder ) ; return condition == null ? query : query . where ( condition ) ; |
public class TransactionProcessor { /** * Ensures that family delete markers are present in the columns requested for any get operation .
* @ param get The original get request
* @ return The modified get request with the family delete qualifiers represented */
private Get projectFamilyDeletes ( Get get ) { } } | for ( Map . Entry < byte [ ] , NavigableSet < byte [ ] > > entry : get . getFamilyMap ( ) . entrySet ( ) ) { NavigableSet < byte [ ] > columns = entry . getValue ( ) ; // wildcard scans will automatically include the delete marker , so only need to add it when we have
// explicit columns listed
if ( columns != null && ! columns . isEmpty ( ) ) { get . addColumn ( entry . getKey ( ) , TxConstants . FAMILY_DELETE_QUALIFIER ) ; } } return get ; |
public class WhitelistingApi { /** * Upload a CSV file related to the Device Type .
* Upload a CSV file related to the Device Type .
* @ param dtid Device Type ID . ( required )
* @ param file Device Type ID . ( required )
* @ return UploadIdEnvelope
* @ throws ApiException If fail to call the API , e . g . server error or cannot deserialize the response body */
public UploadIdEnvelope uploadCSV ( String dtid , byte [ ] file ) throws ApiException { } } | ApiResponse < UploadIdEnvelope > resp = uploadCSVWithHttpInfo ( dtid , file ) ; return resp . getData ( ) ; |
public class CSSParserFactory { /** * Parses a media query from a string ( e . g . the ' media ' HTML attribute ) .
* @ param query The query string
* @ return List of media queries found . */
public List < MediaQuery > parseMediaQuery ( String query ) { } } | try { // input from string
CSSInputStream input = CSSInputStream . stringStream ( query ) ; input . setBase ( new URL ( "file://media/query/url" ) ) ; // this URL should not be used , just for safety
// create parser
CSSParser parser = createParserForInput ( input ) ; // visitor
CSSParserVisitorImpl visitor = new CSSParserVisitorImpl ( ) ; return visitor . visitMedia ( parser . media ( ) ) ; } catch ( IOException e ) { log . error ( "I/O error during media query parsing: {}" , e . getMessage ( ) ) ; return null ; } /* catch ( CSSException e ) {
log . warn ( " Malformed media query { } " , query ) ;
return null ; */
catch ( RecognitionException e ) { log . warn ( "Malformed media query {}" , query ) ; return null ; } |
public class InterconnectClient { /** * Creates a Interconnect in the specified project using the data included in the request .
* < p > Sample code :
* < pre > < code >
* try ( InterconnectClient interconnectClient = InterconnectClient . create ( ) ) {
* ProjectName project = ProjectName . of ( " [ PROJECT ] " ) ;
* Interconnect interconnectResource = Interconnect . newBuilder ( ) . build ( ) ;
* Operation response = interconnectClient . insertInterconnect ( project , interconnectResource ) ;
* < / code > < / pre >
* @ param project Project ID for this request .
* @ param interconnectResource Represents an Interconnects resource . The Interconnects resource is
* a dedicated connection between Google ' s network and your on - premises network . For more
* information , see the Dedicated overview page . ( = = resource _ for v1 . interconnects = = ) ( = =
* resource _ for beta . interconnects = = )
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
@ BetaApi public final Operation insertInterconnect ( ProjectName project , Interconnect interconnectResource ) { } } | InsertInterconnectHttpRequest request = InsertInterconnectHttpRequest . newBuilder ( ) . setProject ( project == null ? null : project . toString ( ) ) . setInterconnectResource ( interconnectResource ) . build ( ) ; return insertInterconnect ( request ) ; |
public class DirectoryBasedOverlayNotifier { /** * { @ inheritDoc } */
@ Override public synchronized boolean registerForNotifications ( ArtifactNotification targets , ArtifactListener callbackObject ) throws IllegalArgumentException { } } | verifyTargets ( targets ) ; // build the aggregate set of paths to monitor from the caller ' s args .
// addTarget will always add the listener , but will return false if the
// path is already in the monitor list . .
Set < String > pathsToMonitor = new HashSet < String > ( ) ; for ( String path : targets . getPaths ( ) ) { // do not remove the ! paths here . . as they must be passed onto the other containers .
ArtifactListenerSelector artifactSelectorCallback = new ArtifactListenerSelector ( callbackObject ) ; boolean addToMonitorList = addTarget ( path , artifactSelectorCallback ) ; if ( addToMonitorList ) { pathsToMonitor . add ( path ) ; } } // figure out the new minset of paths to monitor .
pathsToMonitor . addAll ( pathsMonitored ) ; collapsePaths ( pathsToMonitor ) ; // if we ' re already listening , we need to stop briefly to update the list . .
if ( listeningToContainers ) { overlayContainer . getArtifactNotifier ( ) . removeListener ( this ) ; overlaidContainer . getArtifactNotifier ( ) . removeListener ( this ) ; } pathsMonitored . clear ( ) ; pathsMonitored . addAll ( pathsToMonitor ) ; overlayContainer . getArtifactNotifier ( ) . registerForNotifications ( new DefaultArtifactNotification ( overlayContainer , pathsMonitored ) , this ) ; overlaidContainer . getArtifactNotifier ( ) . registerForNotifications ( new DefaultArtifactNotification ( overlaidContainer , pathsMonitored ) , this ) ; listeningToContainers = true ; return true ; |
public class PeriodType { /** * Gets a type that defines all standard fields except months .
* < ul >
* < li > years
* < li > weeks
* < li > days
* < li > hours
* < li > minutes
* < li > seconds
* < li > milliseconds
* < / ul >
* @ return the period type */
public static PeriodType yearWeekDayTime ( ) { } } | PeriodType type = cYWDTime ; if ( type == null ) { type = new PeriodType ( "YearWeekDayTime" , new DurationFieldType [ ] { DurationFieldType . years ( ) , DurationFieldType . weeks ( ) , DurationFieldType . days ( ) , DurationFieldType . hours ( ) , DurationFieldType . minutes ( ) , DurationFieldType . seconds ( ) , DurationFieldType . millis ( ) , } , new int [ ] { 0 , - 1 , 1 , 2 , 3 , 4 , 5 , 6 , } ) ; cYWDTime = type ; } return type ; |
public class GraphqlErrorBuilder { /** * This will set up the { @ link GraphQLError # getLocations ( ) } and { @ link graphql . GraphQLError # getPath ( ) } for you from the
* fetching environment .
* @ param dataFetchingEnvironment the data fetching environment
* @ return a builder of { @ link graphql . GraphQLError } s */
public static GraphqlErrorBuilder newError ( DataFetchingEnvironment dataFetchingEnvironment ) { } } | return new GraphqlErrorBuilder ( ) . location ( dataFetchingEnvironment . getField ( ) . getSourceLocation ( ) ) . path ( dataFetchingEnvironment . getExecutionStepInfo ( ) . getPath ( ) ) ; |
public class VcfStringToUserProfileConverter { /** * Convert from text from user profile */
@ Override public UserProfile convert ( String text ) { } } | if ( text == null || text . trim ( ) . length ( ) == 0 ) return null ; String [ ] lines = text . split ( "\\\n" ) ; BiConsumer < String , UserProfile > strategy = null ; UserProfile userProfile = null ; String lineUpper = null ; for ( String line : lines ) { // get first term
int index = line . indexOf ( ";" ) ; if ( index < 0 ) continue ; // skip line
String term = line . substring ( 0 , index ) ; strategy = strategies . get ( term . toLowerCase ( ) ) ; lineUpper = line . toUpperCase ( ) ; if ( strategy == null ) { // check for a different format
// N : Green ; Gregory ; ; ;
if ( lineUpper . startsWith ( "N:" ) ) strategy = strategies . get ( "n" ) ; else if ( lineUpper . startsWith ( "FN:" ) ) strategy = strategies . get ( "fn" ) ; else if ( lineUpper . contains ( "EMAIL;" ) ) strategy = strategies . get ( "email" ) ; else continue ; // skip
} if ( userProfile == null ) { userProfile = ClassPath . newInstance ( this . userProfileClass ) ; } strategy . accept ( line , userProfile ) ; } return userProfile ; |
public class TaskMethodFinder { /** * Determines the parameter injection of the initialization method . */
private Object lookUp ( Class < ? > type ) { } } | Jenkins j = Jenkins . getInstance ( ) ; assert j != null : "This method is only invoked after the Jenkins singleton instance has been set" ; if ( type == Jenkins . class || type == Hudson . class ) return j ; Injector i = j . getInjector ( ) ; if ( i != null ) return i . getInstance ( type ) ; throw new IllegalArgumentException ( "Unable to inject " + type ) ; |
public class PostalAddress { /** * < pre >
* Optional . Postal code of the address . Not all countries use or require
* postal codes to be present , but where they are used , they may trigger
* additional validation with other parts of the address ( e . g . state / zip
* validation in the U . S . A . ) .
* < / pre >
* < code > string postal _ code = 4 ; < / code > */
public java . lang . String getPostalCode ( ) { } } | java . lang . Object ref = postalCode_ ; if ( ref instanceof java . lang . String ) { return ( java . lang . String ) ref ; } else { com . google . protobuf . ByteString bs = ( com . google . protobuf . ByteString ) ref ; java . lang . String s = bs . toStringUtf8 ( ) ; postalCode_ = s ; return s ; } |
public class JettyServletWebServerFactory { /** * Create a configuration object that adds mime type mappings .
* @ return a configuration object for adding mime type mappings */
private Configuration getMimeTypeConfiguration ( ) { } } | return new AbstractConfiguration ( ) { @ Override public void configure ( WebAppContext context ) throws Exception { MimeTypes mimeTypes = context . getMimeTypes ( ) ; for ( MimeMappings . Mapping mapping : getMimeMappings ( ) ) { mimeTypes . addMimeMapping ( mapping . getExtension ( ) , mapping . getMimeType ( ) ) ; } } } ; |
public class Column { /** * Handle a browser event that took place within the column .
* @ param context the cell context
* @ param elem the parent Element
* @ param object the base object to be updated
* @ param event the native browser event */
public void onBrowserEvent ( Context context , Element elem , final T object , NativeEvent event ) { } } | final int index = context . getIndex ( ) ; ValueUpdater < C > valueUpdater = ( fieldUpdater == null ) ? null : ( ValueUpdater < C > ) value -> { fieldUpdater . update ( index , object , value ) ; } ; cell . onBrowserEvent ( context , elem , getValue ( object ) , event , valueUpdater ) ; |
public class BaseMessageManager { /** * Remove all the filters that have this as a listener .
* @ param listener Filters with this listener will be removed . */
public void freeListenersWithSource ( Object objSource ) { } } | if ( m_messageMap != null ) { for ( BaseMessageQueue messageQueue : m_messageMap . values ( ) ) { if ( messageQueue != null ) messageQueue . freeListenersWithSource ( objSource ) ; } } |
public class HttpHeaders { /** * Puts all headers of the { @ link HttpHeaders } object into this { @ link HttpHeaders } object .
* @ param headers { @ link HttpHeaders } from where the headers are taken
* @ since 1.10 */
public final void fromHttpHeaders ( HttpHeaders headers ) { } } | try { ParseHeaderState state = new ParseHeaderState ( this , null ) ; serializeHeaders ( headers , null , null , null , new HeaderParsingFakeLevelHttpRequest ( this , state ) ) ; state . finish ( ) ; } catch ( IOException ex ) { // Should never occur as we are dealing with a FakeLowLevelHttpRequest
throw Throwables . propagate ( ex ) ; } |
public class JavaEESecCDIExtension { /** * make sure that there is one HAM for each modules , and if there is a HAM in a module , make sure there is no login configuration in web . xml . */
private void verifyConfiguration ( ) throws DeploymentException { } } | Map < URL , ModuleMetaData > mmds = getModuleMetaDataMap ( ) ; if ( mmds != null ) { for ( Map . Entry < URL , ModuleMetaData > entry : mmds . entrySet ( ) ) { ModuleMetaData mmd = entry . getValue ( ) ; if ( mmd instanceof WebModuleMetaData ) { String j2eeModuleName = mmd . getJ2EEName ( ) . getModule ( ) ; Map < Class < ? > , Properties > authMechs = getAuthMechs ( j2eeModuleName ) ; if ( authMechs != null && ! authMechs . isEmpty ( ) ) { // make sure that only one HAM .
if ( authMechs . size ( ) != 1 ) { String appName = mmd . getJ2EEName ( ) . getApplication ( ) ; String authMechNames = getAuthMechNames ( authMechs ) ; Tr . error ( tc , "JAVAEESEC_CDI_ERROR_MULTIPLE_HTTPAUTHMECHS" , j2eeModuleName , appName , authMechNames ) ; String msg = Tr . formatMessage ( tc , "JAVAEESEC_CDI_ERROR_MULTIPLE_HTTPAUTHMECHS" , j2eeModuleName , appName , authMechNames ) ; throw new DeploymentException ( msg ) ; } SecurityMetadata smd = ( SecurityMetadata ) ( ( WebModuleMetaData ) mmd ) . getSecurityMetaData ( ) ; if ( smd != null ) { LoginConfiguration lc = smd . getLoginConfiguration ( ) ; if ( lc != null && ! lc . isAuthenticationMethodDefaulted ( ) ) { String appName = mmd . getJ2EEName ( ) . getApplication ( ) ; String msg = Tr . formatMessage ( tc , "JAVAEESEC_CDI_ERROR_LOGIN_CONFIG_EXISTS" , j2eeModuleName , appName ) ; Tr . error ( tc , "JAVAEESEC_CDI_ERROR_LOGIN_CONFIG_EXISTS" , j2eeModuleName , appName ) ; throw new DeploymentException ( msg ) ; } } } } } } |
public class ServicesHelper { /** * delete a service identified by its id , if force is true , the user does not have to confirm */
public void deleteService ( String id , boolean force ) { } } | try { if ( id == null || id . isEmpty ( ) ) { id = selectRunningService ( ) ; } final String idFinal = id ; int input = 'Y' ; if ( ! force ) { OutputStreamFormater . printValue ( String . format ( "Do you really want to delete the connector: %s (Y/n): " , id ) ) ; input = keyboard . read ( ) ; } if ( 'n' != ( char ) input && 'N' != ( char ) input ) { SecurityContext . executeWithSystemPermissions ( new Callable < Object > ( ) { @ Override public Object call ( ) throws Exception { serviceManager . delete ( idFinal ) ; return null ; } } ) ; OutputStreamFormater . printValue ( String . format ( "Service: %s successfully deleted" , id ) ) ; } } catch ( ExecutionException e ) { e . printStackTrace ( ) ; System . err . println ( "Could not delete service" ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; System . err . println ( "Unexpected Error" ) ; } |
public class TemplateDelegateNodeBuilder { /** * Returns the inferred ' partial ' name for a deltemplate . */
public static String partialDeltemplateTemplateName ( String delTemplateName , @ Nullable String delPackageName , String variant ) { } } | String delPackageTemplateAndVariantStr = ( delPackageName == null ? "" : delPackageName ) + "_" + delTemplateName . replace ( '.' , '_' ) + "_" + variant ; delPackageTemplateAndVariantStr = delPackageTemplateAndVariantStr . replace ( '.' , '_' ) ; // Generate the actual internal - use template name .
return ".__deltemplate_" + delPackageTemplateAndVariantStr ; |
public class ClassRef { /** * Checks if the ref needs to be done by fully qualified name . Why ? Because an other reference
* to a class with the same name but different package has been made already . */
private boolean requiresFullyQualifiedName ( ) { } } | String currentPackage = PackageScope . get ( ) ; if ( currentPackage != null ) { if ( definition != null && definition . getPackageName ( ) != null && definition . getFullyQualifiedName ( ) != null ) { String conflictingFQCN = getDefinition ( ) . getFullyQualifiedName ( ) . replace ( definition . getPackageName ( ) , currentPackage ) ; if ( ! conflictingFQCN . equals ( getFullyQualifiedName ( ) ) && DefinitionRepository . getRepository ( ) . getDefinition ( conflictingFQCN ) != null ) { return true ; } } } Map < String , String > referenceMap = DefinitionRepository . getRepository ( ) . getReferenceMap ( ) ; if ( referenceMap != null && referenceMap . containsKey ( definition . getName ( ) ) ) { String fqn = referenceMap . get ( definition . getName ( ) ) ; if ( ! getDefinition ( ) . getFullyQualifiedName ( ) . equals ( fqn ) ) { return true ; } } return false ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.