signature
stringlengths
43
39.1k
implementation
stringlengths
0
450k
public class SchedulerUtils { /** * Decode the JVM options * < br > 1 . strip \ " at the start and at the end * < br > 2 . replace " ( 61 ) " and " & amp ; equals ; " with " = " * < br > 3 . Revert from Base64 format * Note that ' = ' is escaped in two different ways . ' ( 61 ) ' is the new escaping . * ' & amp ; equals ; ' was the original replacement but it is not friendly to bash and * was causing issues . The original escaping is still left there for reference * and backward compatibility purposes ( to be removed after no topology needs * it ) * @ return decoded string */ public static String decodeJavaOpts ( String encodedJavaOpts ) { } }
String javaOptsBase64 = encodedJavaOpts . replaceAll ( "^\"+" , "" ) . replaceAll ( "\\s+$" , "" ) . replace ( "(61)" , "=" ) . replace ( "&equals;" , "=" ) ; return new String ( DatatypeConverter . parseBase64Binary ( javaOptsBase64 ) , StandardCharsets . UTF_8 ) ;
public class CompilerLogging { /** * Enable the given types of logging . Note that NONE will take precedence * over active logging flags and turn all logging off . Illegal logging * values will be silently ignored . * @ param loggerList * a comma - separated list of logging types to enable */ public static void activateLoggers ( String loggerList ) { } }
// Create an empty set . This will contain the list of all of the loggers // to activate . ( Note that NONE may be a logger ; in this case , all // logging will be deactivated . ) EnumSet < LoggingType > flags = EnumSet . noneOf ( LoggingType . class ) ; // Split on commas and remove white space . for ( String name : loggerList . split ( "\\s*,\\s*" ) ) { try { flags . add ( LoggingType . valueOf ( name . trim ( ) . toUpperCase ( ) ) ) ; } catch ( IllegalArgumentException consumed ) { } } // Loop over the flags , enabling each one . for ( LoggingType type : flags ) { type . activate ( ) ; }
public class Collator { /** * < strong > [ icu ] < / strong > Returns the name of the collator for the objectLocale , localized for the * default < code > DISPLAY < / code > locale . * @ param objectLocale the locale of the collator * @ return the display name * @ see android . icu . util . ULocale . Category # DISPLAY */ static public String getDisplayName ( ULocale objectLocale ) { } }
return getShim ( ) . getDisplayName ( objectLocale , ULocale . getDefault ( Category . DISPLAY ) ) ;
public class PageHelper { /** * Implicitly wait for an element . * Then , if the element cannot be found , refresh the page . * Try finding the element again , reiterating for maxRefreshes * times or until the element is found . * Finally , return the element . * @ param maxRefreshes max num of iterations of the loop * @ param locator the locator for the element we want to find * @ param driver * @ return the element identified by the given locator ; * null if the element is not found after the last iteration */ public static WebElement loopFindOrRefresh ( int maxRefreshes , By locator , WebDriver driver ) { } }
for ( int i = 0 ; i < maxRefreshes ; i ++ ) { WebElement element ; try { // implicitly wait element = driver . findElement ( locator ) ; // if no exception is thrown , then we can exit the loop return element ; } catch ( NoSuchElementException e ) { // if implicit wait times out , then refresh page and continue the loop logger . info ( "after implicit wait, element " + locator + " is still not present: refreshing page and trying again" ) ; Navigation . refreshPage ( driver ) ; } } return null ;
public class SimpleHostConnectionPool { /** * Internal method to wait for a connection from the available connection * pool . * @ param timeout * @ return * @ throws ConnectionException */ private Connection < CL > waitForConnection ( int timeout ) throws ConnectionException { } }
Connection < CL > connection = null ; long startTime = System . currentTimeMillis ( ) ; try { blockedThreads . incrementAndGet ( ) ; connection = availableConnections . poll ( timeout , TimeUnit . MILLISECONDS ) ; if ( connection != null ) return connection ; throw new PoolTimeoutException ( "Timed out waiting for connection" ) . setHost ( getHost ( ) ) . setLatency ( System . currentTimeMillis ( ) - startTime ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new InterruptedOperationException ( "Thread interrupted waiting for connection" ) . setHost ( getHost ( ) ) . setLatency ( System . currentTimeMillis ( ) - startTime ) ; } finally { blockedThreads . decrementAndGet ( ) ; }
public class ListUtils { /** * Divides the given object - list using the boundaries in < code > cuts < / code > . * < br > * Cuts are interpreted in an inclusive way , which means that a single cut * at position i divides the given list in 0 . . . i - 1 + i . . . n < br > * This method deals with both cut positions including and excluding start * and end - indexes < br > * @ param list * List to divide * @ param positions * Cut positions for divide operations * @ return A list of sublists of < code > list < / code > according to the given * cut positions * @ see # divideListPos ( List , Integer . . . ) */ public static List < List < Object > > divideObjectListPos ( List < Object > list , Integer ... positions ) { } }
return divideListPos ( list , positions ) ;
public class TeaServlet { /** * Process the user ' s http get request . Process the template that maps to * the URI that was hit . * @ param request the user ' s http request * @ param response the user ' s http response */ protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { } }
if ( processStatus ( request , response ) ) { return ; } if ( ! isRunning ( ) ) { int errorCode = mProperties . getInt ( "startup.codes.error" , 503 ) ; response . sendError ( errorCode ) ; return ; } if ( mUseSpiderableRequest ) { request = new SpiderableRequest ( request , mQuerySeparator , mParameterSeparator , mValueSeparator ) ; } // start transaction TeaServletTransaction tsTrans = getEngine ( ) . createTransaction ( request , response , true ) ; // load associated request / response ApplicationRequest appRequest = tsTrans . getRequest ( ) ; ApplicationResponse appResponse = tsTrans . getResponse ( ) ; // process template processTemplate ( appRequest , appResponse ) ; appResponse . finish ( ) ; // flush the output response . flushBuffer ( ) ;
public class ListViewColumn { /** * Returns all the registered { @ link ListViewColumn } descriptors . */ public static DescriptorExtensionList < ListViewColumn , Descriptor < ListViewColumn > > all ( ) { } }
return Jenkins . getInstance ( ) . < ListViewColumn , Descriptor < ListViewColumn > > getDescriptorList ( ListViewColumn . class ) ;
public class TarInputStream { /** * Reads bytes from the current tar archive entry . * This method is aware of the boundaries of the current * entry in the archive and will deal with them as if they * were this stream ' s start and EOF . * @ param buf The buffer into which to place bytes read . * @ param offset The offset at which to place bytes read . * @ param numToRead The number of bytes to read . * @ return The number of bytes read , or - 1 at EOF . * @ throws IOException on error */ public int read ( byte [ ] buf , int offset , int numToRead ) throws IOException { } }
int totalRead = 0 ; if ( this . entryOffset >= this . entrySize ) { return - 1 ; } if ( ( numToRead + this . entryOffset ) > this . entrySize ) { numToRead = ( int ) ( this . entrySize - this . entryOffset ) ; } if ( this . readBuf != null ) { int sz = ( numToRead > this . readBuf . length ) ? this . readBuf . length : numToRead ; System . arraycopy ( this . readBuf , 0 , buf , offset , sz ) ; if ( sz >= this . readBuf . length ) { this . readBuf = null ; } else { int newLen = this . readBuf . length - sz ; byte [ ] newBuf = new byte [ newLen ] ; System . arraycopy ( this . readBuf , sz , newBuf , 0 , newLen ) ; this . readBuf = newBuf ; } totalRead += sz ; numToRead -= sz ; offset += sz ; } while ( numToRead > 0 ) { byte [ ] rec = this . buffer . readRecord ( ) ; if ( rec == null ) { // Unexpected EOF ! throw new IOException ( "unexpected EOF with " + numToRead + " bytes unread" ) ; } int sz = numToRead ; int recLen = rec . length ; if ( recLen > sz ) { System . arraycopy ( rec , 0 , buf , offset , sz ) ; this . readBuf = new byte [ recLen - sz ] ; System . arraycopy ( rec , sz , this . readBuf , 0 , recLen - sz ) ; } else { sz = recLen ; System . arraycopy ( rec , 0 , buf , offset , recLen ) ; } totalRead += sz ; numToRead -= sz ; offset += sz ; } this . entryOffset += totalRead ; return totalRead ;
public class Expression { /** * A VoltDB extension to support indexed expressions */ public VoltXMLElement voltGetExpressionXML ( Session session , Table table ) throws HSQLParseException { } }
resolveTableColumns ( table ) ; Expression parent = null ; // As far as I can tell , this argument just gets passed around but never used ! ? resolveTypes ( session , parent ) ; return voltGetXML ( new SimpleColumnContext ( session , null , 0 ) , null ) ;
public class ImageArchiveUtil { /** * Search the manifest for an entry that has a repository and tag matching the provided pattern . * @ param repoTagPattern the repository and tag to search ( e . g . busybox : latest ) . * @ param manifest the manifest to be searched * @ return a pair containing the matched tag and the entry found , or null if no match . */ public static Pair < String , ImageArchiveManifestEntry > findEntryByRepoTagPattern ( String repoTagPattern , ImageArchiveManifest manifest ) throws PatternSyntaxException { } }
return findEntryByRepoTagPattern ( repoTagPattern == null ? null : Pattern . compile ( repoTagPattern ) , manifest ) ;
public class MediaUtils { /** * Generate an accessible temporary file URI to be used for camera captures * @ param ctx * @ return * @ throws IOException */ private static Uri createAccessibleTempFile ( Context ctx , String authority ) throws IOException { } }
File dir = new File ( ctx . getCacheDir ( ) , "camera" ) ; File tmp = createTempFile ( dir ) ; // Give permissions return FileProvider . getUriForFile ( ctx , authority , tmp ) ;
public class VirtualNetworkTapsInner { /** * Updates an VirtualNetworkTap tags . * @ param resourceGroupName The name of the resource group . * @ param tapName The name of the tap . * @ 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 * @ return the VirtualNetworkTapInner object if successful . */ public VirtualNetworkTapInner beginUpdateTags ( String resourceGroupName , String tapName ) { } }
return beginUpdateTagsWithServiceResponseAsync ( resourceGroupName , tapName ) . toBlocking ( ) . single ( ) . body ( ) ;
public class BaseXmlExporter { /** * Indicates whether or not the provided String contains only * characters that are valid according to the specification of * XML 1.0 that are defined here http : / / www . w3 . org / TR / xml / # charsets * @ param content the content to check * @ return < code > true < / code > if all the characters of the provided * String are valid regarding the XML specification , < code > false < / code > * otherwise */ protected static boolean hasValidCharsOnly ( String content ) { } }
if ( content == null ) return true ; for ( int i = 0 , length = content . length ( ) ; i < length ; i ++ ) { char c = content . charAt ( i ) ; if ( ( c == 0x9 ) || ( c == 0xA ) || ( c == 0xD ) || ( ( c >= 0x20 ) && ( c <= 0xD7FF ) ) || ( ( c >= 0xE000 ) && ( c <= 0xFFFD ) ) || ( ( c >= 0x10000 ) && ( c <= 0x10FFFF ) ) ) { // The character is valid continue ; } // The character is not valid return false ; } return true ;
public class Boxing { /** * Transforms a primitive array into an array of boxed values . * @ param src source array * @ param srcPos start position * @ param len length * @ return array */ public static Object [ ] boxAll ( Object src , int srcPos , int len ) { } }
switch ( tId ( src . getClass ( ) ) ) { case I_BOOLEAN : return box ( ( boolean [ ] ) src , srcPos , len ) ; case I_BYTE : return box ( ( byte [ ] ) src , srcPos , len ) ; case I_CHARACTER : return box ( ( char [ ] ) src , srcPos , len ) ; case I_DOUBLE : return box ( ( double [ ] ) src , srcPos , len ) ; case I_FLOAT : return box ( ( float [ ] ) src , srcPos , len ) ; case I_INTEGER : return box ( ( int [ ] ) src , srcPos , len ) ; case I_LONG : return box ( ( long [ ] ) src , srcPos , len ) ; case I_SHORT : return box ( ( short [ ] ) src , srcPos , len ) ; } throw new IllegalArgumentException ( "No primitive array: " + src ) ;
public class CorporationApi { /** * Get corporation standings Return corporation standings from agents , NPC * corporations , and factions - - - This route is cached for up to 3600 * seconds SSO Scope : esi - corporations . read _ standings . v1 * @ param corporationId * An EVE corporation ID ( required ) * @ param datasource * The server name you would like data from ( optional , default to * tranquility ) * @ param ifNoneMatch * ETag from a previous request . A 304 will be returned if this * matches the current ETag ( optional ) * @ param page * Which page of results to return ( optional , default to 1) * @ param token * Access token to use if unable to set a header ( optional ) * @ return ApiResponse & lt ; List & lt ; CorporationStandingsResponse & gt ; & gt ; * @ throws ApiException * If fail to call the API , e . g . server error or cannot * deserialize the response body */ public ApiResponse < List < CorporationStandingsResponse > > getCorporationsCorporationIdStandingsWithHttpInfo ( Integer corporationId , String datasource , String ifNoneMatch , Integer page , String token ) throws ApiException { } }
com . squareup . okhttp . Call call = getCorporationsCorporationIdStandingsValidateBeforeCall ( corporationId , datasource , ifNoneMatch , page , token , null ) ; Type localVarReturnType = new TypeToken < List < CorporationStandingsResponse > > ( ) { } . getType ( ) ; return apiClient . execute ( call , localVarReturnType ) ;
public class CmsObject { /** * Returns the list of all resource names that define the " view " of the given project . < p > * @ param project the project to get the project resources for * @ return the list of all resource names ( root paths ) , as < code > { @ link String } < / code > * objects that define the " view " of the given project * @ throws CmsException if something goes wrong */ public List < String > readProjectResources ( CmsProject project ) throws CmsException { } }
return m_securityManager . readProjectResources ( m_context , project ) ;
public class AmazonWorkLinkClient { /** * Removes a certificate authority ( CA ) . * @ param disassociateWebsiteCertificateAuthorityRequest * @ return Result of the DisassociateWebsiteCertificateAuthority operation returned by the service . * @ throws UnauthorizedException * You are not authorized to perform this action . * @ throws InternalServerErrorException * The service is temporarily unavailable . * @ throws InvalidRequestException * The request is not valid . * @ throws ResourceNotFoundException * The requested resource was not found . * @ throws TooManyRequestsException * The number of requests exceeds the limit . * @ sample AmazonWorkLink . DisassociateWebsiteCertificateAuthority * @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / worklink - 2018-09-25 / DisassociateWebsiteCertificateAuthority " * target = " _ top " > AWS API Documentation < / a > */ @ Override public DisassociateWebsiteCertificateAuthorityResult disassociateWebsiteCertificateAuthority ( DisassociateWebsiteCertificateAuthorityRequest request ) { } }
request = beforeClientExecution ( request ) ; return executeDisassociateWebsiteCertificateAuthority ( request ) ;
public class GenericResponses { /** * Creates a new { @ link GenericResponseBuilder } by performing a shallow copy of the existing * response . * @ param response the { @ link GenericResponse } to create a new builder from . * @ see Response . ResponseBuilder # fromResponse ( Response ) * @ return a new builder */ public static < T > GenericResponseBuilder < T > fromResponse ( GenericResponse < T > response ) { } }
GenericResponseBuilder < T > builder = genericResponseBuilderFactory . create ( response . getStatus ( ) , response . body ( ) ) ; for ( String headerName : response . getHeaders ( ) . keySet ( ) ) { List < Object > headerValues = response . getHeaders ( ) . get ( headerName ) ; for ( Object headerValue : headerValues ) { builder . header ( headerName , headerValue ) ; } } return builder ;
public class RenderUtils { /** * Render a generic object , emitting the corresponding HTML string to the supplied * { @ code Appendable } object . Works for null objects , RDF { @ code Value } s , { @ code Record } s , * { @ code BindingSet } s and { @ code Iterable } s of the former . * @ param object * the object to render . */ @ SuppressWarnings ( "unchecked" ) public static < T extends Appendable > T render ( final Object object , final T out ) throws IOException { } }
if ( object instanceof URI ) { render ( ( URI ) object , null , out ) ; } else if ( object instanceof Literal ) { final Literal literal = ( Literal ) object ; out . append ( "<span" ) ; if ( literal . getLanguage ( ) != null ) { out . append ( " title=\"@" ) . append ( literal . getLanguage ( ) ) . append ( "\"" ) ; } else if ( literal . getDatatype ( ) != null ) { out . append ( " title=\"&lt;" ) . append ( literal . getDatatype ( ) . stringValue ( ) ) . append ( "&gt;\"" ) ; } out . append ( ">" ) . append ( literal . stringValue ( ) ) . append ( "</span>" ) ; } else if ( object instanceof BNode ) { final BNode bnode = ( BNode ) object ; out . append ( "_:" ) . append ( bnode . getID ( ) ) ; } else if ( object instanceof Record ) { final Record record = ( Record ) object ; out . append ( "<table class=\"record table table-condensed\"><tbody>\n<tr><td>ID</td><td>" ) ; render ( record . getID ( ) , out ) ; out . append ( "</td></tr>\n" ) ; for ( final URI property : Ordering . from ( Data . getTotalComparator ( ) ) . sortedCopy ( record . getProperties ( ) ) ) { out . append ( "<tr><td>" ) ; render ( property , out ) ; out . append ( "</td><td>" ) ; final List < Object > values = record . get ( property ) ; if ( values . size ( ) == 1 ) { render ( values . get ( 0 ) , out ) ; } else { out . append ( "<div class=\"scroll\">" ) ; String separator = "" ; for ( final Object value : Ordering . from ( Data . getTotalComparator ( ) ) . sortedCopy ( record . get ( property ) ) ) { out . append ( separator ) ; render ( value , out ) ; separator = "<br/>" ; } out . append ( "</div>" ) ; } out . append ( "</td></tr>\n" ) ; } out . append ( "</tbody></table>" ) ; } else if ( object instanceof BindingSet ) { render ( ImmutableSet . of ( object ) ) ; } else if ( object instanceof Iterable < ? > ) { final Iterable < ? > iterable = ( Iterable < ? > ) object ; boolean isEmpty = true ; boolean isIterableOfSolutions = true ; for ( final Object element : iterable ) { isEmpty = false ; if ( ! ( element instanceof BindingSet ) ) { isIterableOfSolutions = false ; break ; } } if ( ! isEmpty ) { if ( ! isIterableOfSolutions ) { String separator = "" ; for ( final Object element : ( Iterable < ? > ) object ) { out . append ( separator ) ; render ( element , out ) ; separator = "<br/>" ; } } else { Joiner . on ( "" ) . appendTo ( out , renderSolutionTable ( null , ( Iterable < BindingSet > ) object ) . iterator ( ) ) ; } } } else if ( object != null ) { out . append ( object . toString ( ) ) ; } return out ;
public class CookieUtil { /** * 删除cookie < / br > * @ param name cookie名称 * @ param request http请求 * @ param response http响应 */ public static void deleteCookie ( String name , String domain , HttpServletResponse response ) { } }
if ( name == null || name . length ( ) == 0 ) { throw new IllegalArgumentException ( "cookie名称不能为空." ) ; } CookieUtil . setCookie ( name , "" , - 1 , false , domain , response ) ;
public class MentsuComp { /** * 刻子でも槓子でも役の判定に影響しない場合に利用します * 刻子と槓子をまとめて返します 。 * TODO : good name * @ return 刻子と槓子をまとめたリスト */ public List < Kotsu > getKotsuKantsu ( ) { } }
List < Kotsu > kotsuList = new ArrayList < > ( this . kotsuList ) ; for ( Kantsu kantsu : kantsuList ) { kotsuList . add ( new Kotsu ( kantsu . isOpen ( ) , kantsu . getTile ( ) ) ) ; } return kotsuList ;
public class Decoration { /** * Basic construction . With an error */ public static < T > Decoration < T > error ( Decorator < T > decorator , String error ) { } }
Validate . notNull ( decorator , "The decorator is required" ) ; Validate . notBlank ( error , "The decoration error is required" ) ; return new Decoration < > ( decorator , null , error ) ;
public class AbstractPropertyEditor { /** * Detects and sets the default methods for the property to which editor is associated . If property * has multiple cardinality , { @ link # setMethod } , { @ link # addMethod } , and { @ link # removeMethod } are * set , otherwise only the { @ link # setMethod } . * @ exception NoSuchMethodException if a method for the property does not exist */ private void detectMethods ( ) throws NoSuchMethodException { } }
String javaName = getJavaName ( property ) ; if ( multipleCardinality ) { this . addMethod = domain . getMethod ( "add" + javaName , range ) ; this . removeMethod = domain . getMethod ( "remove" + javaName , range ) ; } else { this . setMethod = domain . getMethod ( "set" + javaName , range ) ; }
public class ResourceUtil { /** * cast a String ( argument destination ) to a File Object , if destination is not a absolute , file * object will be relative to current position ( get from PageContext ) existing file is preferred but * dont must exist * @ param pc Page Context to the current position in filesystem * @ param destination relative or absolute path for file object * @ return file object from destination */ public static Resource toResourceNotExisting ( PageContext pc , String destination ) { } }
return toResourceNotExisting ( pc , destination , pc . getConfig ( ) . allowRealPath ( ) , false ) ;
public class OnlineLDAsvi { /** * Sets the number of topics that LDA will try to learn * @ param K the number of topics to learn */ public void setK ( final int K ) { } }
if ( K < 2 ) throw new IllegalArgumentException ( "At least 2 topics must be learned" ) ; this . K = K ; gammaLocal = new ThreadLocal < Vec > ( ) { @ Override protected Vec initialValue ( ) { return new DenseVector ( K ) ; } } ; logThetaLocal = new ThreadLocal < Vec > ( ) { @ Override protected Vec initialValue ( ) { return new DenseVector ( K ) ; } } ; expLogThetaLocal = new ThreadLocal < Vec > ( ) { @ Override protected Vec initialValue ( ) { return new DenseVector ( K ) ; } } ; lambda = null ;
public class Jmx { /** * Register a MBean to JMX server */ public static void register ( String name , Object instance ) { } }
try { Class < Object > mbeanInterface = guessMBeanInterface ( instance ) ; ManagementFactory . getPlatformMBeanServer ( ) . registerMBean ( new StandardMBean ( instance , mbeanInterface ) , new ObjectName ( name ) ) ; } catch ( MalformedObjectNameException | NotCompliantMBeanException | InstanceAlreadyExistsException | MBeanRegistrationException e ) { throw new IllegalStateException ( "Can not register MBean [" + name + "]" , e ) ; }
public class Verbs { /** * if 200 ok delay is enabled we need to answer only the calls * which are having any further call enabler verbs in their RCML . * @ return */ public static boolean isThisVerbCallEnabler ( Tag verb ) { } }
if ( Verbs . play . equals ( verb . name ( ) ) || Verbs . say . equals ( verb . name ( ) ) || Verbs . gather . equals ( verb . name ( ) ) || Verbs . record . equals ( verb . name ( ) ) || Verbs . redirect . equals ( verb . name ( ) ) ) return true ; return false ;
public class DrizzleResultSet { /** * Moves the cursor to the previous row in this < code > ResultSet < / code > object . * When a call to the < code > previous < / code > method returns < code > false < / code > , the cursor is positioned before the * first row . Any invocation of a < code > ResultSet < / code > method which requires a current row will result in a * < code > SQLException < / code > being thrown . * If an input stream is open for the current row , a call to the method < code > previous < / code > will implicitly close * it . A < code > ResultSet < / code > object ' s warning change is cleared when a new row is read . * @ return < code > true < / code > if the cursor is now positioned on a valid row ; < code > false < / code > if the cursor is * positioned before the first row * @ throws java . sql . SQLException if a database access error occurs ; this method is called on a closed result set or * the result set type is < code > TYPE _ FORWARD _ ONLY < / code > * @ throws java . sql . SQLFeatureNotSupportedException * if the JDBC driver does not support this method * @ since 1.2 */ public boolean previous ( ) throws SQLException { } }
if ( queryResult . getResultSetType ( ) != ResultSetType . SELECT ) { return false ; } final SelectQueryResult sqr = ( SelectQueryResult ) queryResult ; if ( sqr . getRows ( ) >= 0 ) { sqr . moveRowPointerTo ( sqr . getRowPointer ( ) - 1 ) ; return true ; } return false ;
public class ApnsClientBuilder { /** * Constructs a new { @ link ApnsClient } with the previously - set configuration . * @ return a new ApnsClient instance with the previously - set configuration * @ throws SSLException if an SSL context could not be created for the new client for any reason * @ throws IllegalStateException if this method is called without specifying an APNs server address , if this method * is called without providing TLS credentials or a signing key , or if this method is called with both TLS * credentials and a signing key * @ since 0.8 */ public ApnsClient build ( ) throws SSLException { } }
if ( this . apnsServerAddress == null ) { throw new IllegalStateException ( "No APNs server address specified." ) ; } if ( this . clientCertificate == null && this . privateKey == null && this . signingKey == null ) { throw new IllegalStateException ( "No client credentials specified; either TLS credentials (a " + "certificate/private key) or an APNs signing key must be provided before building a client." ) ; } else if ( ( this . clientCertificate != null || this . privateKey != null ) && this . signingKey != null ) { throw new IllegalStateException ( "Clients may not have both a signing key and TLS credentials." ) ; } final SslContext sslContext ; { final SslProvider sslProvider ; if ( OpenSsl . isAvailable ( ) ) { log . info ( "Native SSL provider is available; will use native provider." ) ; sslProvider = SslProvider . OPENSSL_REFCNT ; } else { log . info ( "Native SSL provider not available; will use JDK SSL provider." ) ; sslProvider = SslProvider . JDK ; } final SslContextBuilder sslContextBuilder = SslContextBuilder . forClient ( ) . sslProvider ( sslProvider ) . ciphers ( Http2SecurityUtil . CIPHERS , SupportedCipherSuiteFilter . INSTANCE ) ; if ( this . clientCertificate != null && this . privateKey != null ) { sslContextBuilder . keyManager ( this . privateKey , this . privateKeyPassword , this . clientCertificate ) ; } if ( this . trustedServerCertificatePemFile != null ) { sslContextBuilder . trustManager ( this . trustedServerCertificatePemFile ) ; } else if ( this . trustedServerCertificateInputStream != null ) { sslContextBuilder . trustManager ( this . trustedServerCertificateInputStream ) ; } else if ( this . trustedServerCertificates != null ) { sslContextBuilder . trustManager ( this . trustedServerCertificates ) ; } sslContext = sslContextBuilder . build ( ) ; } final ApnsClient client = new ApnsClient ( this . apnsServerAddress , sslContext , this . signingKey , this . proxyHandlerFactory , this . connectionTimeoutMillis , this . idlePingIntervalMillis , this . gracefulShutdownTimeoutMillis , this . concurrentConnections , this . metricsListener , this . frameLogger , this . eventLoopGroup ) ; if ( sslContext instanceof ReferenceCounted ) { ( ( ReferenceCounted ) sslContext ) . release ( ) ; } return client ;
public class NotifdEventConsumer { @ Override protected void checkDeviceConnection ( DeviceProxy device , String attribute , DeviceData deviceData , String event_name ) throws DevFailed { } }
String deviceName = device . name ( ) ; if ( ! device_channel_map . containsKey ( deviceName ) ) { connect ( device , attribute , event_name , deviceData ) ; if ( ! device_channel_map . containsKey ( deviceName ) ) { Except . throw_event_system_failed ( "API_NotificationServiceFailed" , "Failed to connect to event channel for device" , "EventConsumer.subscribe_event()" ) ; } }
public class MultiProcessCluster { /** * Gets the index of the primary master . * @ param timeoutMs maximum amount of time to wait , in milliseconds * @ return the index of the primary master */ public synchronized int getPrimaryMasterIndex ( int timeoutMs ) throws TimeoutException , InterruptedException { } }
final FileSystem fs = getFileSystemClient ( ) ; final MasterInquireClient inquireClient = getMasterInquireClient ( ) ; CommonUtils . waitFor ( "a primary master to be serving" , ( ) -> { try { // Make sure the leader is serving . fs . getStatus ( new AlluxioURI ( "/" ) ) ; return true ; } catch ( UnavailableException e ) { return false ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } , WaitForOptions . defaults ( ) . setTimeoutMs ( timeoutMs ) ) ; int primaryRpcPort ; try { primaryRpcPort = inquireClient . getPrimaryRpcAddress ( ) . getPort ( ) ; } catch ( UnavailableException e ) { throw new RuntimeException ( e ) ; } // Returns the master whose RPC port matches the primary RPC port . for ( int i = 0 ; i < mMasterAddresses . size ( ) ; i ++ ) { if ( mMasterAddresses . get ( i ) . getRpcPort ( ) == primaryRpcPort ) { return i ; } } throw new RuntimeException ( String . format ( "No master found with RPC port %d. Master addresses: %s" , primaryRpcPort , mMasterAddresses ) ) ;
public class DisconfCenterFile { /** * 配置文件的路径 */ public String getFileDir ( ) { } }
// 获取相对于classpath的路径 if ( targetDirPath != null ) { if ( targetDirPath . startsWith ( "/" ) ) { return OsUtil . pathJoin ( targetDirPath ) ; } return OsUtil . pathJoin ( ClassLoaderUtil . getClassPath ( ) , targetDirPath ) ; } return ClassLoaderUtil . getClassPath ( ) ;
public class WriteRequestCommand { /** * < pre > * Cancel , close and error will be handled by standard gRPC stream APIs . * < / pre > * < code > optional . alluxio . proto . dataserver . CreateUfsFileOptions create _ ufs _ file _ options = 6 ; < / code > */ public alluxio . proto . dataserver . Protocol . CreateUfsFileOptions getCreateUfsFileOptions ( ) { } }
return createUfsFileOptions_ == null ? alluxio . proto . dataserver . Protocol . CreateUfsFileOptions . getDefaultInstance ( ) : createUfsFileOptions_ ;
public class TIFFDirectory { /** * Returns an ordered array of ints indicating the tag * values . */ public int [ ] getTags ( ) { } }
int [ ] tags = new int [ fieldIndex . size ( ) ] ; Enumeration e = fieldIndex . keys ( ) ; int i = 0 ; while ( e . hasMoreElements ( ) ) { tags [ i ++ ] = ( ( Integer ) e . nextElement ( ) ) . intValue ( ) ; } return tags ;
public class SearchableInterceptor { /** * Installs a < code > Searchable < / code > into the given component . * @ param propertyName * the property name . * @ param component * the target component . */ @ Override public void processComponent ( String propertyName , JComponent component ) { } }
if ( component instanceof JComboBox ) { this . installSearchable ( ( JComboBox ) component ) ; } else if ( component instanceof JList ) { this . installSearchable ( ( JList ) component ) ; } else if ( component instanceof JTable ) { this . installSearchable ( ( JTable ) component ) ; } else if ( component instanceof JTextComponent ) { this . installSearchable ( ( JTextComponent ) component ) ; }
public class RunScriptProcess { /** * DoCommand Method . */ public int doCommand ( Script recScript , Map < String , Object > properties ) { } }
int iErrorCode = DBConstants . NORMAL_RETURN ; if ( recScript . getEditMode ( ) != DBConstants . EDIT_CURRENT ) return DBConstants . ERROR_RETURN ; if ( properties == null ) { // First time , climb the tree and set up the properties . properties = new Hashtable < String , Object > ( ) ; Script recTempScript = new Script ( this ) ; try { int iParentScriptID = ( int ) recScript . getField ( Script . PARENT_FOLDER_ID ) . getValue ( ) ; recTempScript . getField ( Script . ID ) . setValue ( iParentScriptID ) ; while ( ( iParentScriptID > 0 ) && ( recTempScript . seek ( null ) == true ) ) { if ( ! recTempScript . getField ( Script . PROPERTIES ) . isNull ( ) ) { // Execute this script Map < String , Object > propRecord = ( ( PropertiesField ) recTempScript . getField ( Script . PROPERTIES ) ) . getProperties ( ) ; propRecord . putAll ( properties ) ; // These properties override parent properties properties = propRecord ; } iParentScriptID = ( int ) recTempScript . getField ( Script . PARENT_FOLDER_ID ) . getValue ( ) ; recTempScript . addNew ( ) ; recTempScript . getField ( Script . ID ) . setValue ( iParentScriptID ) ; } } catch ( DBException ex ) { ex . printStackTrace ( ) ; } finally { recTempScript . free ( ) ; recTempScript = null ; } } if ( ! recScript . getField ( Script . PROPERTIES ) . isNull ( ) ) { // Execute this script Map < String , Object > propRecord = ( ( PropertiesField ) recScript . getField ( Script . PROPERTIES ) ) . getProperties ( ) ; properties = new Hashtable < String , Object > ( properties ) ; // Create a copy , so you don ' t mess up the original properties . putAll ( propRecord ) ; } String strCommand = recScript . getField ( Script . COMMAND ) . toString ( ) ; if ( Script . RUN . equalsIgnoreCase ( strCommand ) ) iErrorCode = this . doRunCommand ( recScript , properties ) ; else if ( Script . RUN_REMOTE . equalsIgnoreCase ( strCommand ) ) { BaseMessage message = new MapMessage ( new TrxMessageHeader ( MessageConstants . TRX_SEND_QUEUE , MessageConstants . INTRANET_QUEUE , properties ) , properties ) ; ( ( Application ) this . getTask ( ) . getApplication ( ) ) . getMessageManager ( ) . sendMessage ( message ) ; } else if ( Script . SEEK . equalsIgnoreCase ( strCommand ) ) iErrorCode = this . doSeekCommand ( recScript , properties ) ; else if ( Script . COPY_RECORDS . equalsIgnoreCase ( strCommand ) ) iErrorCode = this . doCopyRecordsCommand ( recScript , properties ) ; else if ( Script . COPY_FIELDS . equalsIgnoreCase ( strCommand ) ) iErrorCode = this . doCopyFieldsCommand ( recScript , properties ) ; else if ( Script . COPY_DATA . equalsIgnoreCase ( strCommand ) ) iErrorCode = this . doCopyDataCommand ( recScript , properties ) ; if ( iErrorCode != DONT_READ_SUB_SCRIPT ) if ( iErrorCode != DBConstants . NORMAL_RETURN ) return iErrorCode ; if ( iErrorCode != DONT_READ_SUB_SCRIPT ) iErrorCode = this . doSubScriptCommands ( recScript , properties ) ; else iErrorCode = DBConstants . NORMAL_RETURN ; return iErrorCode ;
public class ToStringBuilder { /** * < p > Append to the < code > toString < / code > an < code > Object < / code > * value . < / p > * @ param obj the value to add to the < code > toString < / code > * @ return this */ @ GwtIncompatible ( "incompatible method" ) public ToStringBuilder append ( final Object obj ) { } }
style . append ( buffer , null , obj , null ) ; return this ;
public class ContainerBase { /** * ( non - Javadoc ) * @ see org . jboss . shrinkwrap . api . container . ManifestContainer # addManifestResource ( java . lang . Package , * java . lang . String ) */ @ Override public T addAsManifestResource ( Package resourcePackage , String resourceName ) throws IllegalArgumentException { } }
Validate . notNull ( resourcePackage , "ResourcePackage must be specified" ) ; Validate . notNull ( resourceName , "ResourceName must be specified" ) ; String classloaderResourceName = AssetUtil . getClassLoaderResourceName ( resourcePackage , resourceName ) ; ArchivePath target = ArchivePaths . create ( classloaderResourceName ) ; return addAsManifestResource ( resourcePackage , resourceName , target ) ;
public class DTDValidatorBase { /** * Method for finding out the index of the attribute ( collected using * the attribute collector ; having DTD - derived info in same order ) * that is of type ID . DTD explicitly specifies that at most one * attribute can have this type for any element . * @ return Index of the attribute with type ID , in the current * element , if one exists : - 1 otherwise */ @ Override public int getIdAttrIndex ( ) { } }
// Let ' s figure out the index only when needed int ix = mIdAttrIndex ; if ( ix == - 2 ) { ix = - 1 ; if ( mCurrElem != null ) { DTDAttribute idAttr = mCurrElem . getIdAttribute ( ) ; if ( idAttr != null ) { DTDAttribute [ ] attrs = mAttrSpecs ; for ( int i = 0 , len = attrs . length ; i < len ; ++ i ) { if ( attrs [ i ] == idAttr ) { ix = i ; break ; } } } } mIdAttrIndex = ix ; } return ix ;
public class JenkinsServer { /** * Get the xml description of an existing job . * @ param jobName name of the job . * @ param folder { @ link FolderJob } * @ return the new job object * @ throws IOException in case of an error . */ public String getJobXml ( FolderJob folder , String jobName ) throws IOException { } }
return client . get ( UrlUtils . toJobBaseUrl ( folder , jobName ) + "/config.xml" ) ;
public class BatchScheduleActionCreateRequestMarshaller { /** * Marshall the given parameter object . */ public void marshall ( BatchScheduleActionCreateRequest batchScheduleActionCreateRequest , ProtocolMarshaller protocolMarshaller ) { } }
if ( batchScheduleActionCreateRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( batchScheduleActionCreateRequest . getScheduleActions ( ) , SCHEDULEACTIONS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; }
public class SkipHandler { /** * Check the skipCount and skippable exception lists to determine whether * the given Exception is skippable . */ private boolean isSkippable ( Exception e ) { } }
final String mName = "isSkippable" ; String exClassName = e . getClass ( ) . getName ( ) ; boolean retVal = containsSkippable ( _skipIncludeExceptions , e ) && ! containsSkippable ( _skipExcludeExceptions , e ) ; if ( logger . isLoggable ( Level . FINE ) ) logger . logp ( Level . FINE , className , mName , mName + ": " + retVal + ": " + exClassName ) ; return retVal ;
public class Helper { /** * Returns a formatted string containing the type of the exception , the * message and the stacktrace . * @ param ex * @ return */ public static String convertExceptionToMessage ( Throwable ex ) { } }
StringBuilder sb = new StringBuilder ( ) ; if ( ex != null ) { sb . append ( "Exception type: " ) . append ( ex . getClass ( ) . getName ( ) ) . append ( "\n" ) ; sb . append ( "Message: " ) . append ( ex . getLocalizedMessage ( ) ) . append ( "\n" ) ; sb . append ( "Stacktrace: \n" ) ; StackTraceElement [ ] st = ex . getStackTrace ( ) ; for ( int i = 0 ; i < st . length ; i ++ ) { sb . append ( st [ i ] . toString ( ) ) ; sb . append ( "\n" ) ; } } return sb . toString ( ) ;
public class ExcelModuleDemoToDoItems { @ Programmatic public ExcelModuleDemoToDoItem findByDescription ( final String description ) { } }
return container . firstMatch ( new QueryDefault < > ( ExcelModuleDemoToDoItem . class , "findByDescription" , "description" , description , "ownedBy" , currentUserName ( ) ) ) ;
public class Parameter { /** * { @ inheritDoc } * @ throws NullPointerException { @ inheritDoc } */ @ Override public < T extends Annotation > T [ ] getAnnotationsByType ( Class < T > annotationClass ) { } }
// Android - changed : Uses AnnotatedElements instead . return AnnotatedElements . getDirectOrIndirectAnnotationsByType ( this , annotationClass ) ;
public class HttpRequest { /** * Resets the value of the given parameter . * @ param parameter * the name of the parameter to reset . * @ return * the object itself , for method chaining . */ public HttpRequest withoutParameter ( String parameter ) { } }
if ( Strings . isValid ( parameter ) ) { for ( HttpParameter p : parameters ) { if ( parameter . equals ( p . getName ( ) ) ) { parameters . remove ( p ) ; } } } return this ;
public class KDTree { /** * Returns the index for the median , adjusted incase multiple features have the same value . * @ param data the dataset to get the median index of * @ param pivot the dimension to pivot on , and ensure the median index has a different value on the left side * @ return */ public int getMedianIndex ( final List < Integer > data , int pivot ) { } }
int medianIndex = data . size ( ) / 2 ; // What if more than one point have the samve value ? Keep incrementing until that dosn ' t happen while ( medianIndex < data . size ( ) - 1 && allVecs . get ( data . get ( medianIndex ) ) . get ( pivot ) == allVecs . get ( data . get ( medianIndex + 1 ) ) . get ( pivot ) ) medianIndex ++ ; return medianIndex ;
public class BreakpointsParam { /** * Sets whether the user should confirm the drop of the trapped message . * @ param confirmDrop { @ code true } if the user should confirm the drop , { @ code false } otherwise * @ see # isConfirmDropMessage ( ) * @ see org . zaproxy . zap . extension . brk . BreakPanelToolbarFactory # getBtnDrop ( ) */ public void setConfirmDropMessage ( boolean confirmDrop ) { } }
if ( confirmDropMessage != confirmDrop ) { this . confirmDropMessage = confirmDrop ; getConfig ( ) . setProperty ( PARAM_CONFIRM_DROP_MESSAGE_KEY , confirmDrop ) ; }
public class CameraConfigurationManager { /** * Reads , one time , values from the camera that are needed by the app . */ void initFromCameraParameters ( OpenCamera camera ) { } }
Camera . Parameters parameters = camera . getCamera ( ) . getParameters ( ) ; WindowManager manager = ( WindowManager ) context . getSystemService ( Context . WINDOW_SERVICE ) ; Display display = manager . getDefaultDisplay ( ) ; int displayRotation = display . getRotation ( ) ; int cwRotationFromNaturalToDisplay ; switch ( displayRotation ) { case Surface . ROTATION_0 : cwRotationFromNaturalToDisplay = 0 ; break ; case Surface . ROTATION_90 : cwRotationFromNaturalToDisplay = 90 ; break ; case Surface . ROTATION_180 : cwRotationFromNaturalToDisplay = 180 ; break ; case Surface . ROTATION_270 : cwRotationFromNaturalToDisplay = 270 ; break ; default : // Have seen this return incorrect values like - 90 if ( displayRotation % 90 == 0 ) { cwRotationFromNaturalToDisplay = ( 360 + displayRotation ) % 360 ; } else { throw new IllegalArgumentException ( "Bad rotation: " + displayRotation ) ; } } Log . i ( TAG , "Display at: " + cwRotationFromNaturalToDisplay ) ; int cwRotationFromNaturalToCamera = camera . getOrientation ( ) ; Log . i ( TAG , "Camera at: " + cwRotationFromNaturalToCamera ) ; // Still not 100 % sure about this . But acts like we need to flip this : if ( camera . getFacing ( ) == CameraFacing . FRONT ) { cwRotationFromNaturalToCamera = ( 360 - cwRotationFromNaturalToCamera ) % 360 ; Log . i ( TAG , "Front camera overriden to: " + cwRotationFromNaturalToCamera ) ; } /* SharedPreferences prefs = PreferenceManager . getDefaultSharedPreferences ( context ) ; String overrideRotationString ; if ( camera . getFacing ( ) = = CameraFacing . FRONT ) { overrideRotationString = prefs . getString ( PreferencesActivity . KEY _ FORCE _ CAMERA _ ORIENTATION _ FRONT , null ) ; } else { overrideRotationString = prefs . getString ( PreferencesActivity . KEY _ FORCE _ CAMERA _ ORIENTATION , null ) ; if ( overrideRotationString ! = null & & ! " - " . equals ( overrideRotationString ) ) { Log . i ( TAG , " Overriding camera manually to " + overrideRotationString ) ; cwRotationFromNaturalToCamera = Integer . parseInt ( overrideRotationString ) ; */ cwRotationFromDisplayToCamera = ( 360 + cwRotationFromNaturalToCamera - cwRotationFromNaturalToDisplay ) % 360 ; Log . i ( TAG , "Final display orientation: " + cwRotationFromDisplayToCamera ) ; if ( camera . getFacing ( ) == CameraFacing . FRONT ) { Log . i ( TAG , "Compensating rotation for front camera" ) ; cwNeededRotation = ( 360 - cwRotationFromDisplayToCamera ) % 360 ; } else { cwNeededRotation = cwRotationFromDisplayToCamera ; } Log . i ( TAG , "Clockwise rotation from display to camera: " + cwNeededRotation ) ; Point theScreenResolution = new Point ( ) ; display . getSize ( theScreenResolution ) ; screenResolution = theScreenResolution ; Log . i ( TAG , "Screen resolution in current orientation: " + screenResolution ) ; cameraResolution = CameraConfigurationUtils . findBestPreviewSizeValue ( parameters , screenResolution ) ; Log . i ( TAG , "Camera resolution: " + cameraResolution ) ; bestPreviewSize = CameraConfigurationUtils . findBestPreviewSizeValue ( parameters , screenResolution ) ; Log . i ( TAG , "Best available preview size: " + bestPreviewSize ) ; boolean isScreenPortrait = screenResolution . x < screenResolution . y ; boolean isPreviewSizePortrait = bestPreviewSize . x < bestPreviewSize . y ; if ( isScreenPortrait == isPreviewSizePortrait ) { previewSizeOnScreen = bestPreviewSize ; } else { previewSizeOnScreen = new Point ( bestPreviewSize . y , bestPreviewSize . x ) ; } Log . i ( TAG , "Preview size on screen: " + previewSizeOnScreen ) ;
public class OAuth2AuthorizationResource { /** * Validate an access _ token . * The Oauth2 specification does not specify how this should be done . Do similar to what Google does * @ param access _ token access token to validate . Be careful about using url safe tokens or use url encoding . * @ return http 200 if success and some basic info about the access _ token */ @ GET @ Path ( "tokeninfo" ) public Response validate ( @ QueryParam ( "access_token" ) String access_token ) { } }
checkNotNull ( access_token ) ; DConnection connection = connectionDao . findByAccessToken ( access_token ) ; LOGGER . debug ( "Connection {}" , connection ) ; if ( null == connection || hasAccessTokenExpired ( connection ) ) { throw new BadRequestRestException ( "Invalid access_token" ) ; } return Response . ok ( ImmutableMap . builder ( ) . put ( "user_id" , connection . getUserId ( ) ) . put ( "expires_in" , Seconds . secondsBetween ( DateTime . now ( ) , new DateTime ( connection . getExpireTime ( ) ) ) . getSeconds ( ) ) . build ( ) ) . build ( ) ;
public class ChannelQuery { /** * Executes the query and calls the listener with the result . * If the query was already executed , the listener is called * immediately with the result . * @ param listener - channel query listener */ public void execute ( ChannelQueryListener listener ) { } }
addChannelQueryListener ( listener ) ; // Make a local copy to avoid synchronization Result localResult = result ; // If the query was executed , just call the listener if ( localResult != null ) { listener . queryExecuted ( localResult ) ; } else { execute ( ) ; }
public class ContentRepository { /** * Logs into the repository as admin user . The session should be logged out after each test if the repository is * used as a { @ link org . junit . ClassRule } . * @ return a session with admin privileges * @ throws RepositoryException * if the login failed for any reason */ public Session getAdminSession ( ) throws RepositoryException { } }
if ( this . isActive ( this . adminSession ) ) { // perform a refresh to update the session to the latest repository version this . adminSession . refresh ( false ) ; } else { this . adminSession = this . repository . login ( new SimpleCredentials ( "admin" , "admin" . toCharArray ( ) ) ) ; } return this . adminSession ;
public class UpdateRecordsRequest { /** * A list of patch operations . * @ return A list of patch operations . */ public java . util . List < RecordPatch > getRecordPatches ( ) { } }
if ( recordPatches == null ) { recordPatches = new com . amazonaws . internal . SdkInternalList < RecordPatch > ( ) ; } return recordPatches ;
public class ConfigMgrImpl { /** * 通知Zookeeper , 失败时不回滚数据库 , 通过监控来解决分布式不一致问题 */ @ Override public void notifyZookeeper ( Long configId ) { } }
ConfListVo confListVo = getConfVo ( configId ) ; if ( confListVo . getTypeId ( ) . equals ( DisConfigTypeEnum . FILE . getType ( ) ) ) { zooKeeperDriver . notifyNodeUpdate ( confListVo . getAppName ( ) , confListVo . getEnvName ( ) , confListVo . getVersion ( ) , confListVo . getKey ( ) , GsonUtils . toJson ( confListVo . getValue ( ) ) , DisConfigTypeEnum . FILE ) ; } else { zooKeeperDriver . notifyNodeUpdate ( confListVo . getAppName ( ) , confListVo . getEnvName ( ) , confListVo . getVersion ( ) , confListVo . getKey ( ) , confListVo . getValue ( ) , DisConfigTypeEnum . ITEM ) ; }
public class DensityGrid { /** * Generates an Array List of neighbours for this density grid by varying each coordinate * by one in either direction . Does not test whether the generated neighbours are valid as * DensityGrid is not aware of the number of partitions in each dimension . * @ return an Array List of neighbours for this density grid */ public ArrayList < DensityGrid > getNeighbours ( ) { } }
ArrayList < DensityGrid > neighbours = new ArrayList < DensityGrid > ( ) ; DensityGrid h ; int [ ] hCoord = this . getCoordinates ( ) ; for ( int i = 0 ; i < this . dimensions ; i ++ ) { hCoord [ i ] = hCoord [ i ] - 1 ; h = new DensityGrid ( hCoord ) ; neighbours . add ( h ) ; hCoord [ i ] = hCoord [ i ] + 2 ; h = new DensityGrid ( hCoord ) ; neighbours . add ( h ) ; hCoord [ i ] = hCoord [ i ] - 1 ; } return neighbours ;
public class CommonOps_DDF2 { /** * Returns the absolute value of the element in the vector that has the smallest absolute value . < br > * < br > * Min { | a < sub > i < / sub > | } for all i < br > * @ param a A matrix . Not modified . * @ return The max element value of the vector . */ public static double elementMinAbs ( DMatrix2 a ) { } }
double min = Math . abs ( a . a1 ) ; double tmp = Math . abs ( a . a1 ) ; if ( tmp < min ) min = tmp ; tmp = Math . abs ( a . a2 ) ; if ( tmp < min ) min = tmp ; return min ;
public class PackedDecimal { /** * Subtrahiert den uebergebenen Operanden und liefert als Ergebnis eine neue * { @ link PackedDecimal } zurueck * @ param operand Operand * @ return Differenz */ public PackedDecimal subtract ( Bruch operand ) { } }
AbstractNumber result = toBruch ( ) . subtract ( operand ) ; return PackedDecimal . valueOf ( result ) ;
public class WSCallbackHandlerFactoryImpl { /** * { @ inheritDoc } */ @ Override public CallbackHandler getCallbackHandler ( String realmName , X509Certificate [ ] certChain ) { } }
AuthenticationData authenticationData = new WSAuthenticationData ( ) ; authenticationData . set ( AuthenticationData . REALM , realmName ) ; authenticationData . set ( AuthenticationData . CERTCHAIN , certChain ) ; return new AuthenticationDataCallbackHandler ( authenticationData ) ;
public class BoxComment { /** * Replies to this comment with another message . * @ param message the message for the reply . * @ return info about the newly created reply comment . */ public BoxComment . Info reply ( String message ) { } }
JsonObject itemJSON = new JsonObject ( ) ; itemJSON . add ( "type" , "comment" ) ; itemJSON . add ( "id" , this . getID ( ) ) ; JsonObject requestJSON = new JsonObject ( ) ; requestJSON . add ( "item" , itemJSON ) ; if ( BoxComment . messageContainsMention ( message ) ) { requestJSON . add ( "tagged_message" , message ) ; } else { requestJSON . add ( "message" , message ) ; } URL url = ADD_COMMENT_URL_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( this . getAPI ( ) , url , "POST" ) ; request . setBody ( requestJSON . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxComment addedComment = new BoxComment ( this . getAPI ( ) , responseJSON . get ( "id" ) . asString ( ) ) ; return addedComment . new Info ( responseJSON ) ;
public class RollingResourceAppender { /** * Implements the usual roll over behavior . * If < code > MaxBackupIndex < / code > is positive , then files { < code > File . 1 < / code > , . . . , * < code > File . MaxBackupIndex - 1 < / code > } are renamed to { < code > File . 2 < / code > , . . . , * < code > File . MaxBackupIndex < / code > } . Moreover , < code > File < / code > is renamed < code > File . 1 < / code > and * closed . A new < code > File < / code > is created to receive further log output . * If < code > MaxBackupIndex < / code > is equal to zero , then the < code > File < / code > is truncated with no * backup files created . */ public void rollOver ( ) { } }
Resource target ; Resource file ; if ( qw != null ) { long size = ( ( CountingQuietWriter ) qw ) . getCount ( ) ; LogLog . debug ( "rolling over count=" + size ) ; // if operation fails , do not roll again until // maxFileSize more bytes are written nextRollover = size + maxFileSize ; } LogLog . debug ( "maxBackupIndex=" + maxBackupIndex ) ; boolean renameSucceeded = true ; Resource parent = res . getParentResource ( ) ; // If maxBackups < = 0 , then there is no file renaming to be done . if ( maxBackupIndex > 0 ) { // Delete the oldest file , to keep Windows happy . file = parent . getRealResource ( res . getName ( ) + "." + maxBackupIndex + ".bak" ) ; if ( file . exists ( ) ) renameSucceeded = file . delete ( ) ; // Map { ( maxBackupIndex - 1 ) , . . . , 2 , 1 } to { maxBackupIndex , . . . , 3 , 2} for ( int i = maxBackupIndex - 1 ; i >= 1 && renameSucceeded ; i -- ) { file = parent . getRealResource ( res . getName ( ) + "." + i + ".bak" ) ; if ( file . exists ( ) ) { target = parent . getRealResource ( res . getName ( ) + "." + ( i + 1 ) + ".bak" ) ; LogLog . debug ( "Renaming file " + file + " to " + target ) ; renameSucceeded = file . renameTo ( target ) ; } } if ( renameSucceeded ) { // Rename fileName to fileName . 1 target = parent . getRealResource ( res . getName ( ) + ".1.bak" ) ; this . closeFile ( ) ; // keep windows happy . file = res ; LogLog . debug ( "Renaming file " + file + " to " + target ) ; renameSucceeded = file . renameTo ( target ) ; // if file rename failed , reopen file with append = true if ( ! renameSucceeded ) { try { this . setFile ( true ) ; } catch ( IOException e ) { LogLog . error ( "setFile(" + res + ", true) call failed." , e ) ; } } } } // if all renames were successful , then if ( renameSucceeded ) { try { // This will also close the file . This is OK since multiple // close operations are safe . this . setFile ( false ) ; nextRollover = 0 ; } catch ( IOException e ) { LogLog . error ( "setFile(" + res + ", false) call failed." , e ) ; } }
public class V1OperationModel { /** * { @ inheritDoc } */ @ Override public InputsModel getInputs ( ) { } }
if ( _inputs == null ) { _inputs = ( InputsModel ) getFirstChildModel ( INPUTS ) ; } return _inputs ;
public class PropertyChangeSupport { /** * Remove a PropertyChangeListener for a specific property . * @ param propertyName The name of the property that was listened on . * @ param listener The PropertyChangeListener to be removed */ public void removePropertyChangeListener ( String propertyName , PropertyChangeListener listener ) { } }
if ( children == null ) { return ; } PropertyChangeSupport child = ( PropertyChangeSupport ) children . get ( propertyName ) ; if ( child == null ) { return ; } child . removePropertyChangeListener ( listener ) ;
public class CacheFilter { /** * { @ inheritDoc } */ @ Override public void init ( FilterConfig filterConfig ) throws ServletException { } }
try { expiration = Long . valueOf ( filterConfig . getInitParameter ( CacheConfigParameter . EXPIRATION . getName ( ) ) ) ; } catch ( NumberFormatException e ) { throw new ServletException ( new StringBuilder ( "The initialization parameter " ) . append ( CacheConfigParameter . EXPIRATION . getName ( ) ) . append ( " is invalid or is missing for the filter " ) . append ( filterConfig . getFilterName ( ) ) . append ( "." ) . toString ( ) ) ; } cacheability = Boolean . valueOf ( filterConfig . getInitParameter ( CacheConfigParameter . PRIVATE . getName ( ) ) ) ? Cacheability . PRIVATE : Cacheability . PUBLIC ; mustRevalidate = Boolean . valueOf ( filterConfig . getInitParameter ( CacheConfigParameter . MUST_REVALIDATE . getName ( ) ) ) ; vary = filterConfig . getInitParameter ( CacheConfigParameter . VARY . getName ( ) ) ;
public class StringExpression { /** * Create a { @ code this . substring ( beginIndex ) } expression * @ param beginIndex inclusive start index * @ return this . substring ( beginIndex ) * @ see java . lang . String # substring ( int ) */ public StringExpression substring ( int beginIndex ) { } }
return Expressions . stringOperation ( Ops . SUBSTR_1ARG , mixin , ConstantImpl . create ( beginIndex ) ) ;
public class FileLock { /** * Finds a oldest expired lock file ( using modification timestamp ) , then takes * ownership of the lock file * Impt : Assumes access to lockFilesDir has been externally synchronized such that * only one thread accessing the same thread * @ param fs * @ param lockFilesDir * @ param locktimeoutSec * @ return */ public static FileLock acquireOldestExpiredLock ( FileSystem fs , Path lockFilesDir , int locktimeoutSec , String spoutId ) throws IOException { } }
// list files long now = System . currentTimeMillis ( ) ; long olderThan = now - ( locktimeoutSec * 1000 ) ; Collection < Path > listing = HdfsUtils . listFilesByModificationTime ( fs , lockFilesDir , olderThan ) ; // locate expired lock files ( if any ) . Try to take ownership ( oldest lock first ) for ( Path file : listing ) { if ( file . getName ( ) . equalsIgnoreCase ( DirLock . DIR_LOCK_FILE ) ) { continue ; } LogEntry lastEntry = getLastEntryIfStale ( fs , file , olderThan ) ; if ( lastEntry != null ) { FileLock lock = FileLock . takeOwnership ( fs , file , lastEntry , spoutId ) ; if ( lock != null ) { return lock ; } } } if ( listing . isEmpty ( ) ) { LOG . debug ( "No abandoned lock files found by Spout {}" , spoutId ) ; } return null ;
public class InvalidExitUtil { /** * Check the process exit value . */ public static void checkExit ( ProcessAttributes attributes , ProcessResult result ) { } }
Set < Integer > allowedExitValues = attributes . getAllowedExitValues ( ) ; if ( allowedExitValues != null && ! allowedExitValues . contains ( result . getExitValue ( ) ) ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Unexpected exit value: " ) . append ( result . getExitValue ( ) ) ; sb . append ( ", allowed exit values: " ) . append ( allowedExitValues ) ; addExceptionMessageSuffix ( attributes , sb , result . hasOutput ( ) ? result . getOutput ( ) : null ) ; throw new InvalidExitValueException ( sb . toString ( ) , result ) ; }
public class DateUtils { /** * 字符串转换为日期java . util . Date * @ param dateString * 字符串 */ public static Date stringToDate ( String dateString ) { } }
if ( ! "" . equals ( dateString ) && dateString != null ) { // ISO _ DATE _ FORMAT = " yyyyMMdd " ; if ( dateString . trim ( ) . length ( ) == 8 ) { return stringToDate ( dateString , ISO_DATE_FORMAT , LENIENT_DATE ) ; } else if ( dateString . trim ( ) . length ( ) == 10 ) { // ISO _ EXPANDED _ DATE _ FORMAT = " yyyy - MM - dd " ; return stringToDate ( dateString , ISO_EXPANDED_DATE_FORMAT , LENIENT_DATE ) ; } else if ( dateString . trim ( ) . length ( ) == 19 ) { // DATETIME _ PATTERN = " yyyy - MM - dd hh : mm : ss " ; return stringToDate ( dateString , DATETIME_PATTERN , LENIENT_DATE ) ; } else if ( dateString . trim ( ) . length ( ) == 11 ) { // CHINESE _ EXPANDED _ DATE _ FORMAT = " yyyy年MM月dd日 " ; return stringToDate ( dateString , CHINESE_EXPANDED_DATE_FORMAT , LENIENT_DATE ) ; } } return null ;
public class CmsLruCache { /** * Removes all cached objects in this cache . < p > */ public synchronized void clear ( ) { } }
// remove all objects from the linked list from the tail to the head : I_CmsLruCacheObject currentObject = m_listTail ; while ( currentObject != null ) { currentObject = currentObject . getNextLruObject ( ) ; removeTail ( ) ; } // reset the data structure m_objectCosts = 0 ; m_objectCount = 0 ; m_listHead = null ; m_listTail = null ;
public class GenericPortletFilterBean { /** * { @ inheritDoc } * Calls { @ link # doCommonFilter ( PortletRequest , PortletResponse , FilterChain ) } */ @ Override public void doFilter ( RenderRequest request , RenderResponse response , FilterChain chain ) throws IOException , PortletException { } }
doCommonFilter ( request , response , chain ) ;
public class Tuple3i { /** * { @ inheritDoc } */ @ Override public void clamp ( double min , double max , T t ) { } }
clamp ( ( int ) min , ( int ) max , t ) ;
public class SqlSelectBuilder { /** * Generate SQL . * @ param method * the method * @ param methodBuilder * the method builder * @ param replaceProjectedColumns * the replace projected columns * @ return the splitted sql */ static SplittedSql generateSQL ( final SQLiteModelMethod method , MethodSpec . Builder methodBuilder , final boolean replaceProjectedColumns ) { } }
JQLChecker jqlChecker = JQLChecker . getInstance ( ) ; final SplittedSql splittedSql = new SplittedSql ( ) ; String sql = convertJQL2SQL ( method , false ) ; // parameters extracted from JQL converted in SQL splittedSql . sqlBasic = jqlChecker . replaceVariableStatements ( method , sql , new JQLReplaceVariableStatementListenerImpl ( ) { @ Override public String onWhere ( String statement ) { splittedSql . sqlWhereStatement = statement ; return "" ; } @ Override public String onOrderBy ( String statement ) { splittedSql . sqlOrderByStatement = statement ; return "" ; } @ Override public String onOffset ( String statement ) { splittedSql . sqlOffsetStatement = statement ; return "" ; } @ Override public String onLimit ( String statement ) { splittedSql . sqlLimitStatement = statement ; return "" ; } @ Override public String onHaving ( String statement ) { splittedSql . sqlHavingStatement = statement ; return "" ; } @ Override public String onGroup ( String statement ) { splittedSql . sqlGroupStatement = statement ; return "" ; } @ Override public String onProjectedColumns ( String statement ) { if ( replaceProjectedColumns ) return "%s" ; else return null ; } } ) ; return splittedSql ;
public class CmsPublishDialog { /** * Shows the publish dialog . < p > * @ param result the publish data * @ param handler the dialog close handler ( may be null ) * @ param refreshAction the action to execute on a context menu triggered refresh * @ param editorHandler the content editor handler ( may be null ) */ public static void showPublishDialog ( CmsPublishData result , CloseHandler < PopupPanel > handler , Runnable refreshAction , I_CmsContentEditorHandler editorHandler ) { } }
CmsPublishDialog publishDialog = new CmsPublishDialog ( result , refreshAction , editorHandler ) ; if ( handler != null ) { publishDialog . addCloseHandler ( handler ) ; } publishDialog . centerHorizontally ( 50 ) ; // replace current notification widget by overlay publishDialog . catchNotifications ( ) ;
public class SessionFactory { /** * Creates a { @ link Session } , adds the event handlers to the session and * then connects it to the remote jetserver . This way events will not be * lost on connect . * @ param eventHandlers * The handlers to be added to listen to session . * @ return The session instance created and connected to remote jetserver . * @ throws InterruptedException * @ throws Exception */ public Session createAndConnectSession ( EventHandler ... eventHandlers ) throws InterruptedException , Exception { } }
Session session = createSession ( ) ; connectSession ( session , eventHandlers ) ; return session ;
public class StartupServletContextListener { /** * loads the faces init plugins per reflection and Service loader * in a jdk6 environment * @ return false in case of a failed attempt or no listeners found * which then will cause the jdk5 context . xml code to trigger */ private boolean loadFacesInitPluginsJDK6 ( ) { } }
String [ ] pluginEntries = null ; try { Class serviceLoader = ClassUtils . getContextClassLoader ( ) . loadClass ( "java.util.ServiceLoader" ) ; Method m = serviceLoader . getDeclaredMethod ( "load" , Class . class , ClassLoader . class ) ; Object loader = m . invoke ( serviceLoader , StartupListener . class , ClassUtils . getContextClassLoader ( ) ) ; m = loader . getClass ( ) . getDeclaredMethod ( "iterator" ) ; Iterator < StartupListener > it = ( Iterator < StartupListener > ) m . invoke ( loader ) ; List < StartupListener > listeners = new LinkedList < StartupListener > ( ) ; if ( ! it . hasNext ( ) ) { return false ; } while ( it . hasNext ( ) ) { listeners . add ( it . next ( ) ) ; } // StartupListener [ ] listeners1 = listeners . toArray ( new StartupListener [ listeners . size ( ) ] ) ; _servletContext . setAttribute ( FACES_INIT_PLUGINS , listeners ) ; return true ; } catch ( ClassNotFoundException e ) { } catch ( NoSuchMethodException e ) { log . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } catch ( InvocationTargetException e ) { log . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { log . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } return false ;
public class ZoneTransferIn { /** * Instantiates a ZoneTransferIn object to do an AXFR ( full zone transfer ) . * @ param zone The zone to transfer . * @ param host The host from which to transfer the zone . * @ param port The port to connect to on the server , or 0 for the default . * @ param key The TSIG key used to authenticate the transfer , or null . * @ return The ZoneTransferIn object . * @ throws UnknownHostException The host does not exist . */ public static ZoneTransferIn newAXFR ( Name zone , String host , int port , TSIG key ) throws UnknownHostException { } }
if ( port == 0 ) port = SimpleResolver . DEFAULT_PORT ; return newAXFR ( zone , new InetSocketAddress ( host , port ) , key ) ;
public class AccessLogMarshaller { /** * Marshall the given parameter object . */ public void marshall ( AccessLog accessLog , ProtocolMarshaller protocolMarshaller ) { } }
if ( accessLog == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( accessLog . getFile ( ) , FILE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; }
public class Actions { /** * Performs a modifier key press after focusing on an element . Equivalent to : * < i > Actions . click ( element ) . sendKeys ( theKey ) ; < / i > * @ see # keyDown ( CharSequence ) * @ param key Either { @ link Keys # SHIFT } , { @ link Keys # ALT } or { @ link Keys # CONTROL } . If the * provided key is none of those , { @ link IllegalArgumentException } is thrown . * @ param target WebElement to perform the action * @ return A self reference . */ public Actions keyDown ( WebElement target , CharSequence key ) { } }
if ( isBuildingActions ( ) ) { action . addAction ( new KeyDownAction ( jsonKeyboard , jsonMouse , ( Locatable ) target , asKeys ( key ) ) ) ; } return focusInTicks ( target ) . addKeyAction ( key , codepoint -> tick ( defaultKeyboard . createKeyDown ( codepoint ) ) ) ;
public class BoundsOnBinomialProportions { /** * Computes upper bound of approximate Clopper - Pearson confidence interval for a binomial * proportion . * < p > Implementation Notes : < br > * The approximateUpperBoundOnP is defined with respect to the left tail of the binomial * distribution . < / p > * < ul > * < li > We want to solve for the < i > p < / i > for which sum < sub > < i > j , 0 , k < / i > < / sub > bino ( < i > j ; n , p < / i > ) * = delta . < / li > * < li > Define < i > x < / i > = 1 - < i > p < / i > . < / li > * < li > We want to solve for the < i > x < / i > for which I < sub > < i > x ( n - k , k + 1 ) < / i > < / sub > = delta . < / li > * < li > We specify delta via numStdDevs through the right tail of the standard normal * distribution . < / li > * < li > Bigger values of numStdDevs correspond to smaller values of delta . < / li > * < li > return < i > p < / i > = 1 - < i > x < / i > . < / li > * < / ul > * @ param n is the number of trials . Must be non - negative . * @ param k is the number of successes . Must be non - negative , and cannot exceed < i > n < / i > . * @ param numStdDevs the number of standard deviations defining the confidence interval * @ return the upper bound of the approximate Clopper - Pearson confidence interval for the * unknown success probability . */ public static double approximateUpperBoundOnP ( final long n , final long k , final double numStdDevs ) { } }
checkInputs ( n , k ) ; if ( n == 0 ) { return 1.0 ; } // the coin was never flipped , so we know nothing else if ( k == n ) { return 1.0 ; } else if ( k == ( n - 1 ) ) { return ( exactUpperBoundOnPForKequalsNminusOne ( n , deltaOfNumStdevs ( numStdDevs ) ) ) ; } else if ( k == 0 ) { return ( exactUpperBoundOnPForKequalsZero ( n , deltaOfNumStdevs ( numStdDevs ) ) ) ; } else { final double x = abramowitzStegunFormula26p5p22 ( n - k , k + 1 , numStdDevs ) ; return ( 1.0 - x ) ; // which is p }
public class VerticalRecordsProcessor { /** * セルの入力規則の範囲を修正する 。 * @ param sheet * @ param recordOperation */ private void correctDataValidation ( final Sheet sheet , final RecordOperation recordOperation ) { } }
if ( recordOperation . isNotExecuteRecordOperation ( ) ) { return ; } // TODO : セルの結合も考慮する // 操作をしていないセルの範囲の取得 final CellRangeAddress notOperateRange = new CellRangeAddress ( recordOperation . getTopLeftPoisitoin ( ) . y , recordOperation . getBottomRightPosition ( ) . y , recordOperation . getTopLeftPoisitoin ( ) . x , recordOperation . getBottomRightPosition ( ) . x - recordOperation . getCountInsertRecord ( ) ) ; final List < ? extends DataValidation > list = sheet . getDataValidations ( ) ; for ( DataValidation validation : list ) { final CellRangeAddressList region = validation . getRegions ( ) . copy ( ) ; boolean changedRange = false ; for ( CellRangeAddress range : region . getCellRangeAddresses ( ) ) { if ( notOperateRange . isInRange ( range . getFirstRow ( ) , range . getFirstColumn ( ) ) ) { // 自身のセルの範囲の場合は 、 行の範囲を広げる range . setLastColumn ( recordOperation . getBottomRightPosition ( ) . x ) ; changedRange = true ; } else if ( notOperateRange . getLastColumn ( ) < range . getFirstColumn ( ) ) { /* * VerticalRecordsの場合は 、 挿入 ・ 削除はないので 、 自身以外の範囲は修正しない 。 */ } } // 修正した規則を 、 再度シートに追加する if ( changedRange ) { boolean updated = POIUtils . updateDataValidationRegion ( sheet , validation . getRegions ( ) , region ) ; assert updated == true ; } }
public class OJBSearchFilter { /** * Change the search filter to one that specifies an element to * match or not match one of a list of values . * The old search filter is deleted . * @ param elementName is the name of the element to be matched * @ param values is a vector of possible matches * @ param oper is the IN or NOT _ IN operator to indicate how to matche */ public void matchList ( String elementName , Vector values , int oper ) { } }
// Delete the old search criteria criteria = new Criteria ( ) ; if ( oper != NOT_IN ) { for ( int i = 0 ; i < values . size ( ) ; i ++ ) { Criteria tempCrit = new Criteria ( ) ; tempCrit . addEqualTo ( elementName , values . elementAt ( i ) ) ; criteria . addOrCriteria ( tempCrit ) ; } } else { for ( int i = 0 ; i < values . size ( ) ; i ++ ) { criteria . addNotEqualTo ( elementName , values . elementAt ( i ) ) ; } }
public class DocumentRootImpl { /** * < ! - - begin - user - doc - - > * < ! - - end - user - doc - - > * @ generated */ public void setPackageName ( String newPackageName ) { } }
String oldPackageName = packageName ; packageName = newPackageName ; if ( eNotificationRequired ( ) ) eNotify ( new ENotificationImpl ( this , Notification . SET , DroolsPackage . DOCUMENT_ROOT__PACKAGE_NAME , oldPackageName , packageName ) ) ;
public class Association { /** * Adds the given row to this association , using the given row key . * The row must not be null , use the { @ link org . hibernate . ogm . model . spi . Association # remove ( org . hibernate . ogm . model . key . spi . RowKey ) } * operation instead . * @ param key the key to store the row under * @ param value the association row to store */ public void put ( RowKey key , Tuple value ) { } }
// instead of setting it to null , core must use remove Contracts . assertNotNull ( value , "association.put value" ) ; currentState . put ( key , new AssociationOperation ( key , value , PUT ) ) ;
public class StreamCharBuffer { /** * Writes the buffer content to a target java . io . Writer * @ param target Writer * @ param flushTarget calls target . flush ( ) before finishing * @ param emptyAfter empties the buffer if true * @ throws IOException */ public void writeTo ( Writer target , boolean flushTarget , boolean emptyAfter ) throws IOException { } }
if ( target instanceof GrailsWrappedWriter ) { GrailsWrappedWriter wrappedWriter = ( ( GrailsWrappedWriter ) target ) ; if ( wrappedWriter . isAllowUnwrappingOut ( ) ) { target = wrappedWriter . unwrap ( ) ; } } if ( target == writer ) { throw new IllegalArgumentException ( "Cannot write buffer to itself." ) ; } if ( ! emptyAfter && target instanceof StreamCharBufferWriter ) { ( ( StreamCharBufferWriter ) target ) . write ( this , null ) ; return ; } else if ( writeToEncodedAppender ( this , target , writer . getEncodedAppender ( ) , true ) ) { if ( emptyAfter ) { emptyAfterReading ( ) ; } if ( flushTarget ) { target . flush ( ) ; } return ; } writeToImpl ( target , flushTarget , emptyAfter ) ;
public class EntityInfo { /** * 根据Entity对象获取Entity的表名 * @ param bean Entity对象 * @ return String */ public String getTable ( T bean ) { } }
if ( tableStrategy == null ) return table ; String t = tableStrategy . getTable ( table , bean ) ; return t == null || t . isEmpty ( ) ? table : t ;
public class SqlStrUtils { /** * Example : < br > * < code > new String [ ] { " id " , " code " , " name " } equals SqlStrUtils . getSelectColumns ( " select id , code , name from user " ) < / code > */ public static String [ ] getSelectColumns ( String sql ) { } }
Asserts . notBlank ( sql ) ; sql = sql . trim ( ) ; if ( sql . startsWith ( "select " ) || sql . startsWith ( "SELECT " ) ) { sql = sql . substring ( 7 ) . trim ( ) ; int idxFrom = sql . indexOf ( " from " ) ; if ( idxFrom == - 1 ) idxFrom = sql . indexOf ( " FROM " ) ; if ( idxFrom == - 1 ) throw new IllegalArgumentException ( "Bad sql, no from " ) ; sql = sql . substring ( 0 , idxFrom ) . trim ( ) ; String [ ] columns = sql . split ( "," ) ; for ( int i = 0 ; i < columns . length ; i ++ ) { columns [ i ] = columns [ i ] . trim ( ) ; } return columns ; } else { throw new IllegalArgumentException ( "Not a select sql" ) ; }
public class GetKeywords { /** * Runs the example . * @ param adWordsServices the services factory . * @ param session the session . * @ param adGroupId the ID of the ad group to use to find keywords . * @ throws ApiException if the API request failed with one or more service errors . * @ throws RemoteException if the API request failed due to other errors . */ public static void runExample ( AdWordsServicesInterface adWordsServices , AdWordsSession session , Long adGroupId ) throws RemoteException { } }
// Get the AdGroupCriterionService . AdGroupCriterionServiceInterface adGroupCriterionService = adWordsServices . get ( session , AdGroupCriterionServiceInterface . class ) ; int offset = 0 ; boolean morePages = true ; // Create selector . SelectorBuilder builder = new SelectorBuilder ( ) ; Selector selector = builder . fields ( AdGroupCriterionField . Id , AdGroupCriterionField . CriteriaType , AdGroupCriterionField . KeywordMatchType , AdGroupCriterionField . KeywordText ) . orderAscBy ( AdGroupCriterionField . KeywordText ) . offset ( offset ) . limit ( PAGE_SIZE ) . in ( AdGroupCriterionField . AdGroupId , adGroupId . toString ( ) ) . in ( AdGroupCriterionField . CriteriaType , "KEYWORD" ) . build ( ) ; while ( morePages ) { // Get all ad group criteria . AdGroupCriterionPage page = adGroupCriterionService . get ( selector ) ; // Display ad group criteria . if ( page . getEntries ( ) != null && page . getEntries ( ) . length > 0 ) { // Display results . Arrays . stream ( page . getEntries ( ) ) . map ( adGroupCriterionResult -> ( Keyword ) adGroupCriterionResult . getCriterion ( ) ) . forEach ( keyword -> System . out . printf ( "Keyword with text '%s', match type '%s', criteria type '%s'," + " and ID %d was found.%n" , keyword . getText ( ) , keyword . getMatchType ( ) , keyword . getType ( ) , keyword . getId ( ) ) ) ; } else { System . out . println ( "No ad group criteria were found." ) ; } offset += PAGE_SIZE ; selector = builder . increaseOffsetBy ( PAGE_SIZE ) . build ( ) ; morePages = offset < page . getTotalNumEntries ( ) ; }
public class PhoneInfoResponse { /** * Map a Token instance to its Java ' s Map representation . * @ return a Java ' s Map with the description of this object . */ public Map < String , String > toMap ( ) { } }
Map < String , String > map = new HashMap < > ( ) ; map . put ( "message" , this . getMessage ( ) ) ; map . put ( "success" , this . getSuccess ( ) ) ; map . put ( "is_ported" , this . getIsPorted ( ) ) ; map . put ( "provider" , this . getProvider ( ) ) ; map . put ( "type" , this . getType ( ) ) ; return map ;
public class VersionHandler { /** * { @ inheritDoc } * @ param serverManager * @ param request */ @ Override public Object doHandleRequest ( MBeanServerExecutor serverManager , JmxVersionRequest request ) throws InstanceNotFoundException , AttributeNotFoundException , ReflectionException , MBeanException , IOException { } }
JSONObject ret = new JSONObject ( ) ; ret . put ( "agent" , Version . getAgentVersion ( ) ) ; ret . put ( "protocol" , Version . getProtocolVersion ( ) ) ; if ( serverHandle != null ) { ret . put ( "info" , serverHandle . toJSONObject ( serverManager ) ) ; } ret . put ( "config" , configToJSONObject ( ) ) ; return ret ;
public class ConfigurationSectionContainer { /** * Add a new configuration section to the container . * @ throws IllegalArgumentException if same type is already present and a singleton * @ return always { @ code true } */ public boolean add ( ConfigurationSection section ) { } }
if ( section instanceof SingletonConfigurationSection ) { if ( getSection ( section . getClass ( ) ) != null ) { throw new IllegalArgumentException ( "Section of same type already inserted: " + section . getClass ( ) . getName ( ) ) ; } } return sections . add ( section ) ;
public class FnJodaTimeUtils { /** * It creates an { @ link Interval } from the input { @ link Date } elements . * The { @ link Interval } will be created with the given { @ link DateTimeZone } * @ param dateTimeZone the the time zone ( { @ link DateTimeZone } ) to be used * @ return the { @ link Interval } created from the input and arguments */ public static final Function < Collection < ? extends Date > , Interval > dateFieldCollectionToInterval ( DateTimeZone dateTimeZone ) { } }
return FnInterval . dateFieldCollectionToInterval ( dateTimeZone ) ;
public class ConfigurationItem { /** * A list of CloudTrail event IDs . * A populated field indicates that the current configuration was initiated by the events recorded in the CloudTrail * log . For more information about CloudTrail , see < a * href = " https : / / docs . aws . amazon . com / awscloudtrail / latest / userguide / what _ is _ cloud _ trail _ top _ level . html " > What Is AWS * CloudTrail < / a > . * An empty field indicates that the current configuration was not initiated by any event . * < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use * { @ link # setRelatedEvents ( java . util . Collection ) } or { @ link # withRelatedEvents ( java . util . Collection ) } if you want * to override the existing values . * @ param relatedEvents * A list of CloudTrail event IDs . < / p > * A populated field indicates that the current configuration was initiated by the events recorded in the * CloudTrail log . For more information about CloudTrail , see < a * href = " https : / / docs . aws . amazon . com / awscloudtrail / latest / userguide / what _ is _ cloud _ trail _ top _ level . html " > What * Is AWS CloudTrail < / a > . * An empty field indicates that the current configuration was not initiated by any event . * @ return Returns a reference to this object so that method calls can be chained together . */ public ConfigurationItem withRelatedEvents ( String ... relatedEvents ) { } }
if ( this . relatedEvents == null ) { setRelatedEvents ( new com . amazonaws . internal . SdkInternalList < String > ( relatedEvents . length ) ) ; } for ( String ele : relatedEvents ) { this . relatedEvents . add ( ele ) ; } return this ;
public class BigtableVeneerSettingsFactory { /** * Creates { @ link RetrySettings } for non - streaming idempotent method . */ private static RetrySettings buildIdempotentRetrySettings ( RetrySettings retrySettings , BigtableOptions options ) { } }
RetryOptions retryOptions = options . getRetryOptions ( ) ; CallOptionsConfig callOptions = options . getCallOptionsConfig ( ) ; RetrySettings . Builder retryBuilder = retrySettings . toBuilder ( ) ; if ( retryOptions . allowRetriesWithoutTimestamp ( ) ) { throw new UnsupportedOperationException ( "Retries without Timestamp does not support yet." ) ; } // if useTimeout is false , then RPC ' s are defaults to 6 minutes . Duration rpcTimeout = ofMillis ( callOptions . isUseTimeout ( ) ? callOptions . getShortRpcTimeoutMs ( ) : RPC_DEADLINE_MS ) ; retryBuilder . setInitialRetryDelay ( ofMillis ( retryOptions . getInitialBackoffMillis ( ) ) ) . setRetryDelayMultiplier ( retryOptions . getBackoffMultiplier ( ) ) . setMaxRetryDelay ( ofMillis ( MAX_RETRY_TIMEOUT_MS ) ) . setInitialRpcTimeout ( rpcTimeout ) . setMaxRpcTimeout ( rpcTimeout ) . setMaxAttempts ( 0 ) . setTotalTimeout ( ofMillis ( retryOptions . getMaxElapsedBackoffMillis ( ) ) ) ; return retryBuilder . build ( ) ;
public class DynamoDBReflector { /** * Returns the set of getter methods which are relevant when marshalling or * unmarshalling an object . */ Collection < Method > getRelevantGetters ( Class < ? > clazz ) { } }
synchronized ( getterCache ) { if ( ! getterCache . containsKey ( clazz ) ) { List < Method > relevantGetters = findRelevantGetters ( clazz ) ; getterCache . put ( clazz , relevantGetters ) ; } return getterCache . get ( clazz ) ; }
public class LObjSrtFunctionBuilder { /** * One of ways of creating builder . This might be the only way ( considering all _ functional _ builders ) that might be utilize to specify generic params only once . */ @ Nonnull public static < T , R > LObjSrtFunctionBuilder < T , R > objSrtFunction ( Consumer < LObjSrtFunction < T , R > > consumer ) { } }
return new LObjSrtFunctionBuilder ( consumer ) ;
public class event { /** * < pre > * Performs generic data validation for the operation to be performed * < / pre > */ protected void validate ( String operationType ) throws Exception { } }
super . validate ( operationType ) ; MPSString id_validator = new MPSString ( ) ; id_validator . setConstraintIsReq ( MPSConstants . DELETE_CONSTRAINT , true ) ; id_validator . setConstraintIsReq ( MPSConstants . MODIFY_CONSTRAINT , true ) ; id_validator . validate ( operationType , id , "\"id\"" ) ; MPSString category_validator = new MPSString ( ) ; category_validator . setConstraintMaxStrLen ( MPSConstants . GENERIC_CONSTRAINT , 1024 ) ; category_validator . setConstraintMinStrLen ( MPSConstants . GENERIC_CONSTRAINT , 1 ) ; category_validator . validate ( operationType , category , "\"category\"" ) ; MPSString entity_validator = new MPSString ( ) ; entity_validator . setConstraintMaxStrLen ( MPSConstants . GENERIC_CONSTRAINT , 1024 ) ; entity_validator . setConstraintMinStrLen ( MPSConstants . GENERIC_CONSTRAINT , 1 ) ; entity_validator . validate ( operationType , entity , "\"entity\"" ) ; MPSString severity_validator = new MPSString ( ) ; severity_validator . setConstraintMaxStrLen ( MPSConstants . GENERIC_CONSTRAINT , 32 ) ; severity_validator . setConstraintMinStrLen ( MPSConstants . GENERIC_CONSTRAINT , 1 ) ; severity_validator . validate ( operationType , severity , "\"severity\"" ) ; MPSString source_validator = new MPSString ( ) ; source_validator . setConstraintMaxStrLen ( MPSConstants . GENERIC_CONSTRAINT , 128 ) ; source_validator . setConstraintMinStrLen ( MPSConstants . GENERIC_CONSTRAINT , 1 ) ; source_validator . validate ( operationType , source , "\"source\"" ) ; MPSString failureobj_validator = new MPSString ( ) ; failureobj_validator . setConstraintCharSetRegEx ( MPSConstants . GENERIC_CONSTRAINT , "[ a-zA-Z0-9_#.:@=-]+" ) ; failureobj_validator . setConstraintMaxStrLen ( MPSConstants . GENERIC_CONSTRAINT , 128 ) ; failureobj_validator . setConstraintMinStrLen ( MPSConstants . GENERIC_CONSTRAINT , 1 ) ; failureobj_validator . validate ( operationType , failureobj , "\"failureobj\"" ) ; MPSInt source_event_id_validator = new MPSInt ( ) ; source_event_id_validator . validate ( operationType , source_event_id , "\"source_event_id\"" ) ; MPSInt timestamp_validator = new MPSInt ( ) ; timestamp_validator . validate ( operationType , timestamp , "\"timestamp\"" ) ; MPSString message_validator = new MPSString ( ) ; message_validator . setConstraintMaxStrLen ( MPSConstants . GENERIC_CONSTRAINT , 4096 ) ; message_validator . validate ( operationType , message , "\"message\"" ) ; MPSString operation_type_validator = new MPSString ( ) ; operation_type_validator . setConstraintCharSetRegEx ( MPSConstants . GENERIC_CONSTRAINT , "[ a-zA-Z0-9_#.:@=-]+" ) ; operation_type_validator . setConstraintMaxStrLen ( MPSConstants . GENERIC_CONSTRAINT , 32 ) ; operation_type_validator . setConstraintMinStrLen ( MPSConstants . GENERIC_CONSTRAINT , 1 ) ; operation_type_validator . validate ( operationType , operation_type , "\"operation_type\"" ) ; MPSInt trap_id_validator = new MPSInt ( ) ; trap_id_validator . validate ( operationType , trap_id , "\"trap_id\"" ) ; MPSString history_validator = new MPSString ( ) ; history_validator . setConstraintCharSetRegEx ( MPSConstants . GENERIC_CONSTRAINT , "[ a-zA-Z0-9_#.:@=-]+" ) ; history_validator . validate ( operationType , history , "\"history\"" ) ;
public class OperationRunnerImpl { /** * Ensures that the quorum is present if the quorum is configured and the operation service is quorum aware . * @ param op the operation for which the quorum must be checked for presence * @ throws QuorumException if the operation requires a quorum and the quorum is not present */ private void ensureQuorumPresent ( Operation op ) { } }
QuorumServiceImpl quorumService = operationService . nodeEngine . getQuorumService ( ) ; quorumService . ensureQuorumPresent ( op ) ;
public class CmsResourceUtil { /** * Returns the path of the current resource , taking into account just the site mode . < p > * @ return the full path */ public String getFullPath ( ) { } }
String path = m_resource . getRootPath ( ) ; if ( ( m_siteMode != SITE_MODE_ROOT ) && ( m_cms != null ) ) { String site = getSite ( ) ; if ( path . startsWith ( site ) ) { path = path . substring ( site . length ( ) ) ; } } return path ;
public class Loader { /** * CSVLoader implementation of the Loader * @ param reader A Reader opened to the CSV file * @ param columns List of columns in the CSV * @ param dimensions List of dimensions to index * @ param timestampDimension Timestamp dimension * @ return A new CSVLoader to the CSV file specified by the reader */ public static Loader csv ( Reader reader , List < String > columns , List < String > dimensions , String timestampDimension ) { } }
return new CSVLoader ( reader , columns , dimensions , timestampDimension ) ;
public class CommonsInstanceDiscovery { /** * helper that fetches the Instances for each application from DiscoveryClient . * @ param serviceId Id of the service whose instances should be returned * @ return List of instances * @ throws Exception - retrieving and marshalling service instances may result in an * Exception */ protected List < Instance > getInstancesForApp ( String serviceId ) throws Exception { } }
List < Instance > instances = new ArrayList < > ( ) ; log . info ( "Fetching instances for app: " + serviceId ) ; List < ServiceInstance > serviceInstances = discoveryClient . getInstances ( serviceId ) ; if ( serviceInstances == null || serviceInstances . isEmpty ( ) ) { log . warn ( "DiscoveryClient returned null or empty for service: " + serviceId ) ; return instances ; } try { log . info ( "Received instance list for service: " + serviceId + ", size=" + serviceInstances . size ( ) ) ; for ( ServiceInstance serviceInstance : serviceInstances ) { Instance instance = marshall ( serviceInstance ) ; if ( instance != null ) { instances . add ( instance ) ; } } } catch ( Exception e ) { log . warn ( "Failed to retrieve instances from DiscoveryClient" , e ) ; } return instances ;