idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
40,100
private void checkBestDistance ( KdTree . Node node , FastQueue < KdTreeResult > neighbors ) { double distSq = distance . distance ( ( P ) node . point , target ) ; if ( distSq <= mostDistantNeighborSq ) { if ( neighbors . size ( ) < searchN ) { KdTreeResult r = neighbors . grow ( ) ; r . distance = distSq ; r . node = node ; if ( neighbors . size ( ) == searchN ) { mostDistantNeighborSq = - 1 ; for ( int i = 0 ; i < searchN ; i ++ ) { r = neighbors . get ( i ) ; if ( r . distance > mostDistantNeighborSq ) { mostDistantNeighborSq = r . distance ; mostDistantNeighborIndex = i ; } } } } else { for ( int i = 0 ; i < searchN ; i ++ ) { KdTreeResult r = neighbors . get ( i ) ; if ( r . distance > mostDistantNeighborSq ) { throw new RuntimeException ( "Most distant isn't the most distant" ) ; } } KdTreeResult r = neighbors . get ( mostDistantNeighborIndex ) ; r . node = node ; r . distance = distSq ; mostDistantNeighborSq = - 1 ; for ( int i = 0 ; i < searchN ; i ++ ) { r = neighbors . get ( i ) ; if ( r . distance > mostDistantNeighborSq ) { mostDistantNeighborSq = r . distance ; mostDistantNeighborIndex = i ; } } } } }
See if the node being considered is a new nearest - neighbor
40,101
protected double expectation ( ) { double sumChiSq = 0 ; for ( int i = 0 ; i < info . size ( ) ; i ++ ) { PointInfo p = info . get ( i ) ; double bestLikelihood = 0 ; double bestChiSq = Double . MAX_VALUE ; double total = 0 ; for ( int j = 0 ; j < mixture . size ; j ++ ) { GaussianLikelihoodManager . Likelihood g = likelihoodManager . getLikelihood ( j ) ; double likelihood = g . likelihood ( p . point ) ; total += p . weights . data [ j ] = likelihood ; if ( likelihood > bestLikelihood ) { bestLikelihood = likelihood ; bestChiSq = g . getChisq ( ) ; } } if ( total > 0 ) { for ( int j = 0 ; j < mixture . size ; j ++ ) { p . weights . data [ j ] /= total ; } } sumChiSq += bestChiSq ; } return sumChiSq ; }
For each point compute the responsibility for each Gaussian
40,102
protected void maximization ( ) { for ( int i = 0 ; i < mixture . size ; i ++ ) { mixture . get ( i ) . zero ( ) ; } for ( int i = 0 ; i < info . size ; i ++ ) { PointInfo p = info . get ( i ) ; for ( int j = 0 ; j < mixture . size ; j ++ ) { mixture . get ( j ) . addMean ( p . point , p . weights . get ( j ) ) ; } } for ( int i = 0 ; i < mixture . size ; i ++ ) { GaussianGmm_F64 g = mixture . get ( i ) ; if ( g . weight > 0 ) CommonOps_DDRM . divide ( g . mean , g . weight ) ; } for ( int i = 0 ; i < info . size ; i ++ ) { PointInfo pp = info . get ( i ) ; double [ ] p = pp . point ; for ( int j = 0 ; j < mixture . size ; j ++ ) { GaussianGmm_F64 g = mixture . get ( j ) ; for ( int k = 0 ; k < p . length ; k ++ ) { dx [ k ] = p [ k ] - g . mean . data [ k ] ; } mixture . get ( j ) . addCovariance ( dx , pp . weights . get ( j ) ) ; } } double totalMixtureWeight = 0 ; for ( int i = 0 ; i < mixture . size ; i ++ ) { GaussianGmm_F64 g = mixture . get ( i ) ; if ( g . weight > 0 ) { CommonOps_DDRM . divide ( g . covariance , g . weight ) ; totalMixtureWeight += g . weight ; } } for ( int i = 0 ; i < mixture . size ; i ++ ) { mixture . get ( i ) . weight /= totalMixtureWeight ; } }
Using points responsibility information to recompute the Gaussians and their weights maximizing the likelihood of the mixture .
40,103
public boolean process ( int offset , int length , double ... data ) { if ( data . length < 3 ) throw new IllegalArgumentException ( "At least three points" ) ; A . reshape ( data . length , 3 ) ; y . reshape ( data . length , 1 ) ; int indexDst = 0 ; int indexSrc = offset ; for ( int i = 0 ; i < length ; i ++ ) { double d = data [ indexSrc ++ ] ; A . data [ indexDst ++ ] = i * i ; A . data [ indexDst ++ ] = i ; A . data [ indexDst ++ ] = 1 ; y . data [ i ] = d ; } if ( ! solver . setA ( A ) ) return false ; solver . solve ( y , x ) ; return true ; }
Computes polynomial coefficients for the given data .
40,104
public double innerVectorHessian ( DMatrixRMaj v ) { int M = A . getNumRows ( ) ; double sum = 0 ; sum += innerProduct ( v . data , 0 , A , v . data , 0 ) ; sum += 2 * innerProduct ( v . data , 0 , B , v . data , M ) ; sum += innerProduct ( v . data , M , D , v . data , M ) ; return sum ; }
Vector matrix inner product of Hessian in block format .
40,105
public void computeGradient ( S jacLeft , S jacRight , DMatrixRMaj residuals , DMatrixRMaj gradient ) { x1 . reshape ( jacLeft . getNumCols ( ) , 1 ) ; x2 . reshape ( jacRight . getNumCols ( ) , 1 ) ; multTransA ( jacLeft , residuals , x1 ) ; multTransA ( jacRight , residuals , x2 ) ; CommonOps_DDRM . insert ( x1 , gradient , 0 , 0 ) ; CommonOps_DDRM . insert ( x2 , gradient , x1 . numRows , 0 ) ; }
Computes the gradient using Schur complement
40,106
private Node buildFromPoints ( int lower , int upper ) { if ( upper == lower ) { return null ; } final Node node = new Node ( ) ; node . index = lower ; if ( upper - lower > 1 ) { int i = random . nextInt ( upper - lower - 1 ) + lower ; listSwap ( items , lower , i ) ; listSwap ( indexes , lower , i ) ; int median = ( upper + lower + 1 ) / 2 ; nthElement ( lower + 1 , upper , median , items [ lower ] ) ; node . threshold = distance ( items [ lower ] , items [ median ] ) ; node . index = lower ; node . left = buildFromPoints ( lower + 1 , median ) ; node . right = buildFromPoints ( median , upper ) ; } return node ; }
Builds the tree from a set of points by recursively partitioning them according to a random pivot .
40,107
private void nthElement ( int left , int right , int n , double [ ] origin ) { int npos = partitionItems ( left , right , n , origin ) ; if ( npos < n ) nthElement ( npos + 1 , right , n , origin ) ; if ( npos > n ) nthElement ( left , npos , n , origin ) ; }
Ensures that the n - th element is in a correct position in the list based on the distance from origin .
40,108
private int partitionItems ( int left , int right , int pivot , double [ ] origin ) { double pivotDistance = distance ( origin , items [ pivot ] ) ; listSwap ( items , pivot , right - 1 ) ; listSwap ( indexes , pivot , right - 1 ) ; int storeIndex = left ; for ( int i = left ; i < right - 1 ; i ++ ) { if ( distance ( origin , items [ i ] ) <= pivotDistance ) { listSwap ( items , i , storeIndex ) ; listSwap ( indexes , i , storeIndex ) ; storeIndex ++ ; } } listSwap ( items , storeIndex , right - 1 ) ; listSwap ( indexes , storeIndex , right - 1 ) ; return storeIndex ; }
Partition the points based on their distance to origin around the selected pivot .
40,109
private < E > void listSwap ( E [ ] list , int a , int b ) { final E tmp = list [ a ] ; list [ a ] = list [ b ] ; list [ b ] = tmp ; }
Swaps two items in the given list .
40,110
private static double distance ( double [ ] p1 , double [ ] p2 ) { switch ( p1 . length ) { case 2 : return Math . sqrt ( ( p1 [ 0 ] - p2 [ 0 ] ) * ( p1 [ 0 ] - p2 [ 0 ] ) + ( p1 [ 1 ] - p2 [ 1 ] ) * ( p1 [ 1 ] - p2 [ 1 ] ) ) ; case 3 : return Math . sqrt ( ( p1 [ 0 ] - p2 [ 0 ] ) * ( p1 [ 0 ] - p2 [ 0 ] ) + ( p1 [ 1 ] - p2 [ 1 ] ) * ( p1 [ 1 ] - p2 [ 1 ] ) + ( p1 [ 2 ] - p2 [ 2 ] ) * ( p1 [ 2 ] - p2 [ 2 ] ) ) ; default : { double dist = 0 ; for ( int i = p1 . length - 1 ; i >= 0 ; i -- ) { final double d = ( p1 [ i ] - p2 [ i ] ) ; dist += d * d ; } return Math . sqrt ( dist ) ; } } }
Compute the Euclidean distance between p1 and p2 .
40,111
private PriorityQueue < HeapItem > search ( final double [ ] target , double maxDistance , final int k ) { PriorityQueue < HeapItem > heap = new PriorityQueue < HeapItem > ( ) ; if ( root == null ) { return heap ; } double tau = maxDistance ; final FastQueue < Node > nodes = new FastQueue < Node > ( 20 , Node . class , false ) ; nodes . add ( root ) ; while ( nodes . size ( ) > 0 ) { final Node node = nodes . removeTail ( ) ; final double dist = distance ( items [ node . index ] , target ) ; if ( dist <= tau ) { if ( heap . size ( ) == k ) { heap . poll ( ) ; } heap . add ( new HeapItem ( node . index , dist ) ) ; if ( heap . size ( ) == k ) { tau = heap . element ( ) . dist ; } } if ( node . left != null && dist - tau <= node . threshold ) { nodes . add ( node . left ) ; } if ( node . right != null && dist + tau >= node . threshold ) { nodes . add ( node . right ) ; } } return heap ; }
Recursively search for the k nearest neighbors to target .
40,112
private boolean searchNearest ( final double [ ] target , double maxDistance , NnData < double [ ] > result ) { if ( root == null ) { return false ; } double tau = maxDistance ; final FastQueue < Node > nodes = new FastQueue < Node > ( 20 , Node . class , false ) ; nodes . add ( root ) ; result . distance = Double . POSITIVE_INFINITY ; boolean found = false ; while ( nodes . size ( ) > 0 ) { final Node node = nodes . getTail ( ) ; nodes . removeTail ( ) ; final double dist = distance ( items [ node . index ] , target ) ; if ( dist <= tau && dist < result . distance ) { result . distance = dist ; result . index = indexes . data [ node . index ] ; result . point = items [ node . index ] ; tau = dist ; found = true ; } if ( node . left != null && dist - tau <= node . threshold ) { nodes . add ( node . left ) ; } if ( node . right != null && dist + tau >= node . threshold ) { nodes . add ( node . right ) ; } } return found ; }
Equivalent to the above search method to find one nearest neighbor . It is faster as it does not need to allocate and use the heap data structure .
40,113
public KdTree . Node findNeighbor ( P target ) { if ( tree . root == null ) return null ; this . target = target ; this . closest = null ; this . bestDistanceSq = maxDistanceSq ; stepClosest ( tree . root ) ; return closest ; }
Finds the node which is closest to target
40,114
public void process ( Polynomial poly ) { sturm . initialize ( poly ) ; if ( searchRadius <= 0 ) numRoots = sturm . countRealRoots ( Double . NEGATIVE_INFINITY , Double . POSITIVE_INFINITY ) ; else numRoots = sturm . countRealRoots ( - searchRadius , searchRadius ) ; if ( numRoots == 0 ) return ; if ( searchRadius <= 0 ) handleAllRoots ( ) ; else { boundEachRoot ( - searchRadius , searchRadius , 0 , numRoots ) ; } for ( int i = 0 ; i < numRoots ; i ++ ) { roots [ i ] = PolynomialOps . refineRoot ( poly , roots [ i ] , maxRefineIterations ) ; } }
Find real roots for the specified polynomial .
40,115
private void handleAllRoots ( ) { int totalFound = 0 ; double r = 1 ; int iter = 0 ; while ( iter ++ < maxBoundIterations && ( totalFound = sturm . countRealRoots ( - r , r ) ) <= 0 ) { r = 2 * r * r ; } if ( Double . isInfinite ( r ) ) throw new RuntimeException ( "r is infinite" ) ; if ( iter >= maxBoundIterations ) throw new RuntimeException ( "Too many iterations when searching center region" ) ; boundEachRoot ( - r , r , 0 , totalFound ) ; int target ; if ( totalFound < numRoots && ( target = sturm . countRealRoots ( Double . NEGATIVE_INFINITY , - r ) ) > 0 ) { double upper = - r ; double width = r ; iter = 0 ; while ( iter < maxBoundIterations && target > 0 ) { int N = sturm . countRealRoots ( upper - width , upper ) ; if ( N != 0 ) { boundEachRoot ( upper - width , upper , totalFound , N ) ; target -= N ; totalFound += N ; } upper -= width ; width = 2 * width * width ; } if ( iter >= maxBoundIterations ) throw new RuntimeException ( "Too many iterations when searching lower region" ) ; } if ( totalFound < numRoots && ( target = sturm . countRealRoots ( r , Double . POSITIVE_INFINITY ) ) > 0 ) { double lower = r ; double width = r ; iter = 0 ; while ( iter < maxBoundIterations && target > 0 ) { int N = sturm . countRealRoots ( lower , lower + width ) ; if ( N != 0 ) { boundEachRoot ( lower , lower + width , totalFound , N ) ; target -= N ; totalFound += N ; } lower += width ; width = 2 * width * width ; } if ( iter >= maxBoundIterations ) throw new RuntimeException ( "Too many iterations when searching upper region" ) ; } }
Search for all real roots . First find a region about 0 which contains at least one root . Then search above and below .
40,116
private void bisectionRoot ( double l , double u , int index ) { int iter = 0 ; while ( u - l > boundTolerance * Math . abs ( l ) && iter ++ < maxBoundIterations ) { double m = ( l + u ) / 2.0 ; int numRoots = sturm . countRealRoots ( m , u ) ; if ( numRoots == 1 ) { l = m ; } else { u = m ; } } roots [ index ] = ( l + u ) / 2.0 ; }
Searches for a single real root inside the range . Only one root is assumed to be inside
40,117
private void boundEachRoot ( double l , double u , int startIndex , int numRoots ) { int iter = 0 ; double allUpper = u ; int root = 0 ; int lastFound = 0 ; double lastUpper = u ; while ( root < numRoots && iter ++ < maxBoundIterations ) { double m = ( l + u ) / 2.0 ; int found = sturm . countRealRoots ( l , m ) ; if ( found == 0 ) { l = m ; } else if ( found == 1 ) { bisectionRoot ( l , m , startIndex + root ++ ) ; l = m ; u = lastUpper = allUpper ; lastFound = 0 ; iter = 0 ; } else { lastFound = found ; lastUpper = u = m ; } if ( l == u ) throw new RuntimeException ( "Lower and upper bounds are the same" ) ; if ( iter >= maxBoundIterations ) { for ( int i = 0 ; i < lastFound ; i ++ ) roots [ startIndex + root ++ ] = m ; l = lastUpper ; u = lastUpper = allUpper ; lastFound = 0 ; iter = 0 ; } } if ( iter >= maxBoundIterations ) throw new RuntimeException ( "Too many iterations finding upper and lower bounds" ) ; }
Finds a crude upper and lower bound for each root that includes only one root .
40,118
public boolean iterate ( ) { boolean converged ; switch ( mode ) { case COMPUTE_DERIVATIVES : totalFullSteps ++ ; converged = updateDerivates ( ) ; if ( ! converged ) { totalSelectSteps ++ ; converged = computeStep ( ) ; } break ; case DETERMINE_STEP : totalSelectSteps ++ ; converged = computeStep ( ) ; break ; case CONVERGED : return true ; default : throw new RuntimeException ( "BUG! mode=" + mode ) ; } if ( converged ) { mode = Mode . CONVERGED ; return true ; } else { return false ; } }
Performs one iteration
40,119
public void computeHessianScaling ( DMatrixRMaj scaling ) { double max = 0 ; for ( int i = 0 ; i < scaling . numRows ; i ++ ) { double v = scaling . data [ i ] = sqrt ( abs ( scaling . data [ i ] ) ) ; if ( v > max ) max = v ; } max *= 1e-12 ; for ( int i = 0 ; i < scaling . numRows ; i ++ ) { scaling . data [ i ] += max ; } }
Applies the standard formula for computing scaling . This is broken off into its own function so that it easily invoked if the function above is overridden
40,120
public double computePredictedReduction ( DMatrixRMaj p ) { return - CommonOps_DDRM . dot ( gradient , p ) - 0.5 * hessian . innerVectorHessian ( p ) ; }
Computes predicted reduction for step p
40,121
public void setTo ( int [ ] array , int offset , int length ) { resize ( length ) ; System . arraycopy ( array , offset , data , 0 , length ) ; }
Sets this array to be equal to the array segment
40,122
public void insert ( int index , int value ) { if ( size == data . length ) { int temp [ ] = new int [ size * 2 ] ; System . arraycopy ( data , 0 , temp , 0 , index ) ; temp [ index ] = value ; System . arraycopy ( data , index , temp , index + 1 , size - index ) ; this . data = temp ; size ++ ; } else { size ++ ; for ( int i = size - 1 ; i > index ; i -- ) { data [ i ] = data [ i - 1 ] ; } data [ index ] = value ; } }
Inserts the value at the specified index and shifts all the other values down .
40,123
public void removeHead ( int total ) { for ( int j = total ; j < size ; j ++ ) { data [ j - total ] = data [ j ] ; } size -= total ; }
Removes the first total elements from the queue . Element total will be the new start of the queue
40,124
private void init ( List < T > list ) { this . list = list ; indexes = new int [ list . size ( ) ] ; counters = new int [ list . size ( ) ] ; for ( int i = 0 ; i < indexes . length ; i ++ ) { counters [ i ] = indexes [ i ] = i ; } total = 1 ; for ( int i = 2 ; i <= indexes . length ; i ++ ) { total *= i ; } permutation = 0 ; }
Initializes the permutation for a new list
40,125
public boolean next ( ) { if ( indexes . length <= 1 || permutation >= total - 1 ) return false ; int N = indexes . length - 2 ; int k = N ; swap ( k , counters [ k ] ++ ) ; while ( counters [ k ] == indexes . length ) { k -= 1 ; swap ( k , counters [ k ] ++ ) ; } swap ( counters [ k ] , k ) ; while ( k < indexes . length - 1 ) { k ++ ; counters [ k ] = k ; } permutation ++ ; return true ; }
This will permute the list once
40,126
public boolean previous ( ) { if ( indexes . length <= 1 || permutation <= 0 ) return false ; int N = indexes . length - 2 ; int k = N ; while ( counters [ k ] <= k ) { k -- ; } swap ( counters [ k ] , k ) ; counters [ k ] -- ; swap ( k , counters [ k ] ) ; int foo = k + 1 ; while ( counters [ k + 1 ] == k + 1 && k < indexes . length - 2 ) { k ++ ; swap ( k , indexes . length - 1 ) ; } for ( int i = foo ; i < indexes . length - 1 ; i ++ ) { counters [ i ] = indexes . length - 1 ; } permutation -- ; return true ; }
This will undo a permutation .
40,127
public List < T > getPermutation ( List < T > storage ) { if ( storage == null ) storage = new ArrayList < T > ( ) ; else storage . clear ( ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { storage . add ( get ( i ) ) ; } return storage ; }
Returns a list containing the current permutation .
40,128
public Sms recipient ( Recipient ... recipients ) { this . recipients . addAll ( Arrays . asList ( recipients ) ) ; return this ; }
Add a recipient for the message
40,129
public Sms from ( String name , String phoneNumber ) { return from ( name , new PhoneNumber ( phoneNumber ) ) ; }
Set the sender using the phone number as string .
40,130
public Sms to ( PhoneNumber ... numbers ) { for ( PhoneNumber number : numbers ) { to ( ( String ) null , number ) ; } return this ; }
Add a recipient specifying the phone number .
40,131
public Sms to ( String ... numbers ) { for ( String num : numbers ) { to ( new Recipient ( num ) ) ; } return this ; }
Add a recipient specifying the phone number as string .
40,132
public Sms to ( String name , PhoneNumber number ) { to ( new Recipient ( name , number ) ) ; return this ; }
Add a recipient specifying the name and the phone number .
40,133
public static Recipient [ ] toRecipient ( PhoneNumber [ ] to ) { Recipient [ ] addresses = new Recipient [ to . length ] ; int i = 0 ; for ( PhoneNumber t : to ) { addresses [ i ++ ] = new Recipient ( t ) ; } return addresses ; }
Converts a list of phone numbers to a list of recipients .
40,134
public static Recipient [ ] toRecipient ( String [ ] to ) { Recipient [ ] addresses = new Recipient [ to . length ] ; int i = 0 ; for ( String t : to ) { addresses [ i ++ ] = new Recipient ( t ) ; } return addresses ; }
Converts a list of string to a list of recipients .
40,135
public SendGridBuilder username ( String ... username ) { for ( String u : username ) { if ( u != null ) { usernames . add ( u ) ; } } return this ; }
Set username for SendGrid HTTP API .
40,136
public SendGridBuilder password ( String ... password ) { for ( String p : password ) { if ( p != null ) { passwords . add ( p ) ; } } return this ; }
Set password for SendGrid HTTP API .
40,137
public static boolean isInvalid ( Object bean ) { if ( bean == null ) { return false ; } return isPrimitiveOrWrapper ( bean . getClass ( ) ) || INVALID_TYPES . contains ( bean . getClass ( ) ) || isInstanceOfInvalid ( bean . getClass ( ) ) ; }
Check if the bean type can be wrapped or not .
40,138
public Email recipient ( Recipient ... recipients ) { this . recipients . addAll ( Arrays . asList ( recipients ) ) ; return this ; }
Add a recipient of the mail .
40,139
public Email to ( EmailAddress ... to ) { for ( EmailAddress t : to ) { recipient ( t , RecipientType . TO ) ; } return this ; }
Add a to recipient address .
40,140
public Email cc ( EmailAddress ... cc ) { for ( EmailAddress c : cc ) { recipient ( c , RecipientType . CC ) ; } return this ; }
Add a cc recipient address .
40,141
public Email bcc ( EmailAddress ... bcc ) { for ( EmailAddress b : bcc ) { recipient ( b , RecipientType . BCC ) ; } return this ; }
Add a bcc recipient address .
40,142
public < T extends Builder < ? extends MessageSender > > T sender ( Class < T > builderClass ) { return senderBuilderHelper . register ( builderClass ) ; }
Registers and configures sender through a dedicated builder .
40,143
public static boolean isInlineModeAllowed ( Element img , InlineMode mode ) { if ( ! img . attr ( INLINED_ATTR ) . isEmpty ( ) ) { return false ; } if ( ! img . attr ( INLINE_MODE_ATTR ) . isEmpty ( ) && ! img . attr ( INLINE_MODE_ATTR ) . equals ( mode . mode ( ) ) ) { return false ; } return true ; }
Checks if inlining mode is allowed on the provided element .
40,144
public CharsetBuilder convert ( String nioCharsetName , String cloudhopperCharset ) { mappings . add ( new CharsetMapping ( nioCharsetName , cloudhopperCharset ) ) ; return this ; }
Registers a charset conversion . Conversion is required by Cloudhopper in order to use a charset supported by the SMPP protocol .
40,145
public ResourceResolver getSupportingResolver ( String path ) { LOG . debug ( "Finding resolver for resource {}..." , path ) ; for ( ResourceResolver resolver : resolvers ) { if ( resolver . supports ( path ) ) { LOG . debug ( "{} can handle resource {}" , resolver , path ) ; return resolver ; } } LOG . debug ( "No resolver can handle path '{}'" , path ) ; return null ; }
Find the first supporting resolver .
40,146
public List < ResourceResolver > buildResolvers ( ) { List < ResourceResolver > resolvers = new ArrayList < > ( ) ; resolvers . addAll ( customResolvers ) ; List < ResolverHelper > helpers = new ArrayList < > ( ) ; if ( classPath != null ) { helpers . add ( new ResolverHelper ( classPath . getLookups ( ) , classPath ) ) ; } if ( file != null ) { helpers . add ( new ResolverHelper ( file . getLookups ( ) , file ) ) ; } if ( string != null ) { helpers . add ( new ResolverHelper ( string . getLookups ( ) , string ) ) ; } Collections . sort ( helpers , new PrefixComparator ( ) ) ; for ( ResolverHelper helper : helpers ) { helper . register ( resolvers ) ; } return resolvers ; }
Build the list of resource resolvers .
40,147
public CloudhopperBuilder port ( String ... port ) { for ( String p : port ) { if ( port != null ) { ports . add ( p ) ; } } return this ; }
Set the SMPP server port .
40,148
public CloudhopperBuilder interfaceVersion ( String ... version ) { for ( String v : version ) { if ( v != null ) { interfaceVersions . add ( v ) ; } } return this ; }
Set the SMPP protocol version .
40,149
public void addContentHandler ( Class < ? extends Content > clazz , JavaMailContentHandler handler ) { map . put ( clazz , handler ) ; }
Register a new content handler .
40,150
public void configure ( ) { Collections . sort ( configurers , new PriorityComparator ( ) ) ; for ( PrioritizedConfigurer configurer : configurers ) { configurer . getConfigurer ( ) . configure ( this ) ; } }
Apply all registered configurers on this builder instance .
40,151
public MessagingService build ( ) { LOG . info ( "Using service that calls all registered senders" ) ; List < ConditionalSender > senders = buildSenders ( ) ; LOG . debug ( "Registered senders: {}" , senders ) ; MessagingService service = new EverySupportingMessagingService ( senders ) ; if ( wrapUncaught ) { service = new WrapExceptionMessagingService ( service ) ; } return service ; }
Builds the messaging service . The messaging service relies on the generated senders . Each sender is able to manage one or multiple messages . The default implementation of the messaging service is to ask each sender if it is able to handle the message and if it the case then use this sender to really send the message . This implementation doesn t stop when the message is handled by a sender to possibly let another send the message through another channel .
40,152
public void addResourceHandler ( Class < ? extends NamedResource > clazz , JavaMailAttachmentResourceHandler handler ) { map . put ( clazz , handler ) ; }
Register a new attachment resource handler .
40,153
public boolean exists ( String className ) { if ( this . classLoader != null ) { if ( exists ( className , this . classLoader ) ) { LOG . debug ( "class {} found using class specific class loader" , className ) ; return true ; } return false ; } if ( existsWithDefaultClassLoader ( className ) ) { LOG . debug ( "class {} found using default class loader" , className ) ; return true ; } if ( exists ( className , Thread . currentThread ( ) . getContextClassLoader ( ) ) ) { LOG . debug ( "class {} found using class loader of current thread" , className ) ; return true ; } if ( exists ( className , getClass ( ) . getClassLoader ( ) ) ) { LOG . debug ( "class {} found using class loader of current class" , className ) ; return true ; } return false ; }
Test if the class name is defined in the classpath .
40,154
public EqualsBuilder append ( Object objectFieldValue , Object otherFieldValue ) { if ( equals && ! same ) { delegate . append ( objectFieldValue , otherFieldValue ) ; } return this ; }
Test if two Objects are equal using their equals method .
40,155
public final FluentCondition < T > and ( Condition < T > ... conditions ) { List < Condition < T > > merged = new ArrayList < > ( ) ; merged . add ( delegate ) ; for ( Condition < T > condition : conditions ) { merged . add ( condition ) ; } return Conditions . and ( merged ) ; }
Create a logical AND operator between current condition and conditions provided in parameters .
40,156
public FixedDelayBuilder < RetryBuilder < P > > fixedDelay ( ) { if ( fixedDelay == null ) { fixedDelay = new FixedDelayBuilder < > ( this , environmentBuilder ) ; } return fixedDelay ; }
Retry several times with a fixed delay between each try until the maximum attempts is reached .
40,157
public UsernamePasswordAuthenticatorBuilder username ( String ... username ) { for ( String u : username ) { if ( u != null && ! u . isEmpty ( ) ) { usernames . add ( u ) ; } } return this ; }
Set the username to use for the authentication .
40,158
public UsernamePasswordAuthenticatorBuilder password ( String ... password ) { for ( String p : password ) { if ( p != null && ! p . isEmpty ( ) ) { passwords . add ( p ) ; } } return this ; }
Set the password to use for the authentication .
40,159
public FixedDelayBuilder < P > maxRetries ( String ... maxRetries ) { for ( String m : maxRetries ) { if ( m != null ) { maxRetriesProps . add ( m ) ; } } return this ; }
Set the maximum number of attempts .
40,160
private void handleResponse ( Sms message , Response response ) throws IOException , JsonProcessingException , MessageNotSentException { if ( response . getStatus ( ) . isSuccess ( ) ) { JsonNode json = mapper . readTree ( response . getBody ( ) ) ; int ovhStatus = json . get ( "status" ) . asInt ( ) ; if ( ovhStatus >= OK_STATUS ) { LOG . error ( "SMS failed to be sent through OVH" ) ; LOG . debug ( "Sent SMS: {}" , message ) ; LOG . debug ( "Response status {}" , response . getStatus ( ) ) ; LOG . debug ( "Response body {}" , response . getBody ( ) ) ; throw new MessageNotSentException ( "SMS couldn't be sent through OVH: " + json . get ( "message" ) . asText ( ) , message ) ; } else { LOG . info ( "SMS successfully sent through OVH" ) ; LOG . debug ( "Sent SMS: {}" , message ) ; LOG . debug ( "Response: {}" , response . getBody ( ) ) ; } } else { LOG . error ( "Response status {}" , response . getStatus ( ) ) ; LOG . error ( "Response body {}" , response . getBody ( ) ) ; throw new MessageNotSentException ( "SMS couldn't be sent. Response status is " + response . getStatus ( ) , message ) ; } }
Handle OVH response . If status provided in response is less than 200 then the message has been sent . Otherwise the message has not been sent .
40,161
private static List < String > convert ( List < Recipient > recipients ) throws PhoneNumberException { List < String > tos = new ArrayList < > ( recipients . size ( ) ) ; for ( Recipient recipient : recipients ) { tos . add ( toInternational ( recipient . getPhoneNumber ( ) ) ) ; } return tos ; }
Convert the list of SMS recipients to international phone numbers usable by OVH .
40,162
public OvhSmsBuilder url ( String ... url ) { for ( String u : url ) { if ( u != null ) { urls . add ( u ) ; } } return this ; }
Set the URL of the OVH SMS HTTP API .
40,163
public OvhSmsBuilder account ( String ... account ) { for ( String a : account ) { if ( a != null ) { accounts . add ( a ) ; } } return this ; }
Set the OVH account identifier .
40,164
public OvhSmsBuilder login ( String ... login ) { for ( String l : login ) { if ( l != null ) { logins . add ( l ) ; } } return this ; }
Set the OVH username .
40,165
public OvhSmsBuilder password ( String ... password ) { for ( String p : password ) { if ( p != null ) { passwords . add ( p ) ; } } return this ; }
Set the OVH password .
40,166
public SendGridContentHandler register ( final Class < ? extends Content > clazz , final SendGridContentHandler handler ) { if ( handler == null ) { throw new IllegalArgumentException ( "[handler] cannot be null" ) ; } if ( clazz == null ) { throw new IllegalArgumentException ( "[clazz] cannot be null" ) ; } LOG . debug ( "Registering content handler {} for content type {}" , handler , clazz ) ; return handlers . put ( clazz , handler ) ; }
Registers a handler for a given content type .
40,167
public FreemarkerConfigurationBuilder < MYSELF > configuration ( ) { if ( configurationBuilder == null ) { configurationBuilder = new FreemarkerConfigurationBuilder < > ( myself , environmentBuilder ) ; } return configurationBuilder ; }
Fluent configurer for Freemarker configuration .
40,168
private MimeMessage createMimeMessage ( ) { Session session = Session . getInstance ( properties , authenticator ) ; return new MimeMessage ( session ) ; }
Initialize the session and create the mime message .
40,169
private void setFrom ( Email email , MimeMessage mimeMsg ) throws MessagingException , AddressException , UnsupportedEncodingException { if ( email . getFrom ( ) == null ) { throw new IllegalArgumentException ( "The sender address has not been set" ) ; } mimeMsg . setFrom ( toInternetAddress ( email . getFrom ( ) ) ) ; }
Set the sender address on the mime message .
40,170
private void setRecipients ( Email email , MimeMessage mimeMsg ) throws MessagingException , AddressException , UnsupportedEncodingException { for ( Recipient recipient : email . getRecipients ( ) ) { mimeMsg . addRecipient ( convert ( recipient . getType ( ) ) , toInternetAddress ( recipient . getAddress ( ) ) ) ; } }
Set the recipients addresses on the mime message .
40,171
private void setMimeContent ( Email email , MimeMessage mimeMsg ) throws MessagingException , ContentHandlerException , AttachmentResourceHandlerException { LOG . debug ( "Add message content for email {}" , email ) ; MimeMultipart rootContainer = new MimeMultipart ( "mixed" ) ; MimeMultipart relatedContainer = new MimeMultipart ( "related" ) ; MimeBodyPart relatedPart = new MimeBodyPart ( ) ; relatedPart . setContent ( relatedContainer ) ; contentHandler . setContent ( mimeMsg , relatedContainer , email , email . getContent ( ) ) ; for ( Attachment attachment : email . getAttachments ( ) ) { Multipart container = ContentDisposition . ATTACHMENT . equals ( attachment . getDisposition ( ) ) ? rootContainer : relatedContainer ; addAttachment ( container , attachment ) ; } if ( email . getAttachments ( ) . isEmpty ( ) ) { rootContainer = relatedContainer ; if ( relatedContainer . getCount ( ) == 1 ) { rootContainer . setSubType ( "mixed" ) ; } else { rootContainer . setSubType ( "alternative" ) ; } } else { rootContainer . addBodyPart ( relatedPart ) ; } mimeMsg . setContent ( rootContainer ) ; }
Set the content on the mime message .
40,172
private void addAttachment ( Multipart multipart , Attachment attachment ) throws AttachmentResourceHandlerException { MimeBodyPart part = new MimeBodyPart ( ) ; try { part . setFileName ( attachment . getResource ( ) . getName ( ) ) ; part . setDisposition ( attachment . getDisposition ( ) ) ; part . setDescription ( attachment . getDescription ( ) ) ; part . setContentID ( attachment . getContentId ( ) ) ; attachmentHandler . setData ( part , attachment . getResource ( ) , attachment ) ; multipart . addBodyPart ( part ) ; } catch ( MessagingException e ) { throw new AttachmentResourceHandlerException ( "Failed to attach " + attachment . getResource ( ) . getName ( ) , attachment , e ) ; } }
Add an attachment on the mime message .
40,173
public final MultiImplementationSender < M > addImplementation ( Condition < Message > condition , MessageSender implementation ) { implementations . add ( new Implementation ( condition , implementation ) ) ; return this ; }
Register a new possible implementation with the associated condition . The implementation is added at the end so any other possible implementation will be used before this one if the associated condition allow it .
40,174
public JavaMailBuilder port ( String ... port ) { for ( String p : port ) { if ( p != null ) { ports . add ( p ) ; } } return this ; }
Set the mail server port .
40,175
public JavaMailBuilder charset ( String ... charsets ) { for ( String c : charsets ) { if ( c != null ) { this . charsets . add ( c ) ; } } return this ; }
Set charset to use for email body .
40,176
private void internStyles ( Document doc , List < ExternalCss > cssContents ) { Elements els = doc . select ( CSS_LINKS_SELECTOR ) ; for ( Element e : els ) { if ( ! TRUE_VALUE . equals ( e . attr ( SKIP_INLINE ) ) ) { String path = e . attr ( HREF_ATTR ) ; Element style = new Element ( Tag . valueOf ( STYLE_TAG ) , "" ) ; style . appendChild ( new DataNode ( getCss ( cssContents , path ) , "" ) ) ; e . replaceWith ( style ) ; } } }
Replace link tags with style tags in order to keep the same inclusion order
40,177
private static List < Parameter > convert ( Map < String , Object > map ) { Set < Entry < String , Object > > entries = map . entrySet ( ) ; List < Parameter > parameters = new ArrayList < > ( entries . size ( ) ) ; for ( Entry < String , Object > entry : entries ) { if ( entry . getValue ( ) != null ) { parameters . add ( new Parameter ( entry . getKey ( ) , entry . getValue ( ) . toString ( ) ) ) ; } } return parameters ; }
Convert the map into a list of parameters
40,178
public final SimpleContext addValue ( String variable , Object value ) { variables . put ( variable , value ) ; return this ; }
Add a new variable entry .
40,179
public static void ignoreSslIssues ( final HttpObjectConfig . Execution execution ) { execution . setSslContext ( acceptingSslContext ( ) ) ; execution . setHostnameVerifier ( ANY_HOSTNAME ) ; }
Configuration helper used to ignore any SSL certificate - related issues by configuring an SSLContext that allows everything .
40,180
public UriBuilder setPath ( final String str ) { final String [ ] parts ; if ( str . startsWith ( "/" ) ) { parts = new String [ ] { str } ; } else { final String base = getPath ( ) . toString ( ) ; parts = new String [ ] { base , base . endsWith ( "/" ) ? "" : "/" , str } ; } return setPath ( new GStringImpl ( EMPTY , parts ) ) ; }
Sets the path part of the URI .
40,181
public URI toURI ( ) throws URISyntaxException { final String scheme = traverse ( this , UriBuilder :: getParent , UriBuilder :: getScheme , Traverser :: notNull ) ; final Integer port = traverse ( this , UriBuilder :: getParent , UriBuilder :: getPort , notValue ( DEFAULT_PORT ) ) ; final String host = traverse ( this , UriBuilder :: getParent , UriBuilder :: getHost , Traverser :: notNull ) ; final GString path = traverse ( this , UriBuilder :: getParent , UriBuilder :: getPath , Traverser :: notNull ) ; final String query = populateQueryString ( traverse ( this , UriBuilder :: getParent , UriBuilder :: getQuery , Traverser :: nonEmptyMap ) ) ; final String fragment = traverse ( this , UriBuilder :: getParent , UriBuilder :: getFragment , Traverser :: notNull ) ; final String userInfo = traverse ( this , UriBuilder :: getParent , UriBuilder :: getUserInfo , Traverser :: notNull ) ; final Boolean useRaw = traverse ( this , UriBuilder :: getParent , UriBuilder :: getUseRawValues , Traverser :: notNull ) ; if ( useRaw != null && useRaw ) { return toRawURI ( scheme , port , host , path , query , fragment , userInfo ) ; } else { return new URI ( scheme , userInfo , host , ( port == null ? - 1 : port ) , ( ( path == null ) ? null : path . toString ( ) ) , query , fragment ) ; } }
Converts the parts of the UriBuilder to the URI object instance .
40,182
private static Map < String , Collection < String > > extractQueryMap ( final String queryString ) { final Map < String , Collection < String > > map = new HashMap < > ( ) ; for ( final String nvp : queryString . split ( "&" ) ) { final String [ ] pair = nvp . split ( "=" ) ; map . computeIfAbsent ( pair [ 0 ] , k -> { List < String > list = new LinkedList < > ( ) ; list . add ( pair [ 1 ] ) ; return list ; } ) ; } return map ; }
does not do any encoding
40,183
public MultipartContent part ( String fieldName , String value ) { return part ( fieldName , null , ContentTypes . TEXT . getAt ( 0 ) , value ) ; }
Configures a field part with the given field name and value .
40,184
public static HttpBuilder configure ( final Function < HttpObjectConfig , ? extends HttpBuilder > factory , @ DelegatesTo ( HttpObjectConfig . class ) final Closure closure ) { HttpObjectConfig impl = new HttpObjectConfigImpl ( ) ; closure . setDelegate ( impl ) ; closure . setResolveStrategy ( Closure . DELEGATE_FIRST ) ; closure . call ( ) ; return factory . apply ( impl ) ; }
Creates an HttpBuilder configured with the provided configuration closure using the defaultFactory as the client factory .
40,185
public static HttpBuilder configure ( final Function < HttpObjectConfig , ? extends HttpBuilder > factory , final Consumer < HttpObjectConfig > configuration ) { HttpObjectConfig impl = new HttpObjectConfigImpl ( ) ; configuration . accept ( impl ) ; return factory . apply ( impl ) ; }
Creates an HttpBuilder using the provided client factory function configured with the provided configuration function .
40,186
public < T > T get ( final Class < T > type , @ DelegatesTo ( HttpConfig . class ) final Closure closure ) { return type . cast ( interceptors . get ( HttpVerb . GET ) . apply ( configureRequest ( type , HttpVerb . GET , closure ) , this :: doGet ) ) ; }
Executes a GET request on the configured URI with additional configuration provided by the configuration closure . The result will be cast to the specified type .
40,187
public < T > T get ( final Class < T > type , final Consumer < HttpConfig > configuration ) { return type . cast ( interceptors . get ( HttpVerb . GET ) . apply ( configureRequest ( type , HttpVerb . GET , configuration ) , this :: doGet ) ) ; }
Executes a GET request on the configured URI with additional configuration provided by the configuration function . The result will be cast to the specified type .
40,188
public < T > T head ( final Class < T > type , final Consumer < HttpConfig > configuration ) { return type . cast ( interceptors . get ( HttpVerb . HEAD ) . apply ( configureRequest ( type , HttpVerb . HEAD , configuration ) , this :: doHead ) ) ; }
Executes a HEAD request on the configured URI with additional configuration provided by the configuration function . The result will be cast to the specified type .
40,189
public < T > T post ( final Class < T > type , @ DelegatesTo ( HttpConfig . class ) final Closure closure ) { return type . cast ( interceptors . get ( HttpVerb . POST ) . apply ( configureRequest ( type , HttpVerb . POST , closure ) , this :: doPost ) ) ; }
Executes an POST request on the configured URI with additional configuration provided by the configuration closure . The result will be cast to the specified type .
40,190
public < T > T post ( final Class < T > type , final Consumer < HttpConfig > configuration ) { return type . cast ( interceptors . get ( HttpVerb . POST ) . apply ( configureRequest ( type , HttpVerb . POST , configuration ) , this :: doPost ) ) ; }
Executes a POST request on the configured URI with additional configuration provided by the configuration function . The result will be cast to the specified type .
40,191
public < T > T put ( final Class < T > type , @ DelegatesTo ( HttpConfig . class ) final Closure closure ) { return type . cast ( interceptors . get ( HttpVerb . PUT ) . apply ( configureRequest ( type , HttpVerb . PUT , closure ) , this :: doPut ) ) ; }
Executes an PUT request on the configured URI with additional configuration provided by the configuration closure . The result will be cast to the specified type .
40,192
public < T > T put ( final Class < T > type , final Consumer < HttpConfig > configuration ) { return type . cast ( interceptors . get ( HttpVerb . PUT ) . apply ( configureRequest ( type , HttpVerb . PUT , configuration ) , this :: doPut ) ) ; }
Executes a PUT request on the configured URI with additional configuration provided by the configuration function . The result will be cast to the specified type .
40,193
public < T > T delete ( final Class < T > type , @ DelegatesTo ( HttpConfig . class ) final Closure closure ) { return type . cast ( interceptors . get ( HttpVerb . DELETE ) . apply ( configureRequest ( type , HttpVerb . DELETE , closure ) , this :: doDelete ) ) ; }
Executes an DELETE request on the configured URI with additional configuration provided by the configuration closure . The result will be cast to the specified type .
40,194
public < T > T delete ( final Class < T > type , final Consumer < HttpConfig > configuration ) { return type . cast ( interceptors . get ( HttpVerb . DELETE ) . apply ( configureRequest ( type , HttpVerb . DELETE , configuration ) , this :: doDelete ) ) ; }
Executes a DELETE request on the configured URI with additional configuration provided by the configuration function . The result will be cast to the specified type .
40,195
public < T > T patch ( final Class < T > type , @ DelegatesTo ( HttpConfig . class ) final Closure closure ) { return type . cast ( interceptors . get ( HttpVerb . PATCH ) . apply ( configureRequest ( type , HttpVerb . PATCH , closure ) , this :: doPatch ) ) ; }
Executes a PATCH request on the configured URI with additional configuration provided by the configuration closure . The result will be cast to the specified type .
40,196
public < T > T patch ( final Class < T > type , final Consumer < HttpConfig > configuration ) { return type . cast ( interceptors . get ( HttpVerb . PATCH ) . apply ( configureRequest ( type , HttpVerb . PATCH , configuration ) , this :: doPatch ) ) ; }
Executes a PATCH request on the configured URI with additional configuration provided by the configuration function . The result will be cast to the specified type .
40,197
public < T > T options ( final Class < T > type , final Consumer < HttpConfig > configuration ) { return type . cast ( interceptors . get ( HttpVerb . OPTIONS ) . apply ( configureRequest ( type , HttpVerb . OPTIONS , configuration ) , this :: doOptions ) ) ; }
Executes a OPTIONS request on the configured URI with additional configuration provided by the configuration function . The result will be cast to the specified type .
40,198
public < T > T trace ( final Class < T > type , @ DelegatesTo ( HttpConfig . class ) final Closure closure ) { return type . cast ( interceptors . get ( HttpVerb . TRACE ) . apply ( configureRequest ( type , HttpVerb . TRACE , closure ) , this :: doTrace ) ) ; }
Executes a TRACE request on the configured URI with additional configuration provided by the configuration closure . The result will be cast to the specified type .
40,199
public < T > T trace ( final Class < T > type , final Consumer < HttpConfig > configuration ) { return type . cast ( interceptors . get ( HttpVerb . TRACE ) . apply ( configureRequest ( type , HttpVerb . TRACE , configuration ) , this :: doTrace ) ) ; }
Executes a TRACE request on the configured URI with additional configuration provided by the configuration function . The result will be cast to the specified type .