idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
149,500
public static DMatrixRMaj insideSpan ( DMatrixRMaj [ ] span , double min , double max , Random rand ) { DMatrixRMaj A = new DMatrixRMaj ( span . length , 1 ) ; DMatrixRMaj B = new DMatrixRMaj ( span [ 0 ] . getNumElements ( ) , 1 ) ; for ( int i = 0 ; i < span . length ; i ++ ) { B . set ( span [ i ] ) ; double val = r...
Creates a random vector that is inside the specified span .
149,501
public static DMatrixRMaj diagonal ( int N , double min , double max , Random rand ) { return diagonal ( N , N , min , max , rand ) ; }
Creates a random diagonal matrix where the diagonal elements are selected from a uniform distribution that goes from min to max .
149,502
public static DMatrixRMaj diagonal ( int numRows , int numCols , double min , double max , Random rand ) { if ( max < min ) throw new IllegalArgumentException ( "The max must be >= the min" ) ; DMatrixRMaj ret = new DMatrixRMaj ( numRows , numCols ) ; int N = Math . min ( numRows , numCols ) ; double r = max - min ; fo...
Creates a random matrix where all elements are zero but diagonal elements . Diagonal elements randomly drawn from a uniform distribution from min to max inclusive .
149,503
public static DMatrixRMaj symmetricWithEigenvalues ( int num , Random rand , double ... eigenvalues ) { DMatrixRMaj V = RandomMatrices_DDRM . orthogonal ( num , num , rand ) ; DMatrixRMaj D = CommonOps_DDRM . diag ( eigenvalues ) ; DMatrixRMaj temp = new DMatrixRMaj ( num , num ) ; CommonOps_DDRM . mult ( V , D , temp ...
Creates a new random symmetric matrix that will have the specified real eigenvalues .
149,504
public static BMatrixRMaj randomBinary ( int numRow , int numCol , Random rand ) { BMatrixRMaj mat = new BMatrixRMaj ( numRow , numCol ) ; setRandomB ( mat , rand ) ; return mat ; }
Returns new boolean matrix with true or false values selected with equal probability .
149,505
public static DMatrixRMaj symmetric ( int length , double min , double max , Random rand ) { DMatrixRMaj A = new DMatrixRMaj ( length , length ) ; symmetric ( A , min , max , rand ) ; return A ; }
Creates a random symmetric matrix whose values are selected from an uniform distribution from min to max inclusive .
149,506
public static void symmetric ( DMatrixRMaj A , double min , double max , Random rand ) { if ( A . numRows != A . numCols ) throw new IllegalArgumentException ( "A must be a square matrix" ) ; double range = max - min ; int length = A . numRows ; for ( int i = 0 ; i < length ; i ++ ) { for ( int j = i ; j < length ; j +...
Sets the provided square matrix to be a random symmetric matrix whose values are selected from an uniform distribution from min to max inclusive .
149,507
public static DMatrixRMaj triangularUpper ( int dimen , int hessenberg , double min , double max , Random rand ) { if ( hessenberg < 0 ) throw new RuntimeException ( "hessenberg must be more than or equal to 0" ) ; double range = max - min ; DMatrixRMaj A = new DMatrixRMaj ( dimen , dimen ) ; for ( int i = 0 ; i < dime...
Creates an upper triangular matrix whose values are selected from a uniform distribution . If hessenberg is greater than zero then a hessenberg matrix of the specified degree is created instead .
149,508
public double computeLikelihoodP ( ) { double ret = 1.0 ; for ( int i = 0 ; i < r . numRows ; i ++ ) { double a = r . get ( i , 0 ) ; ret *= Math . exp ( - a * a / 2.0 ) ; } return ret ; }
Computes the likelihood of the random draw
149,509
public boolean decompose ( DMatrixRMaj orig ) { if ( orig . numCols != orig . numRows ) throw new IllegalArgumentException ( "Matrix must be square." ) ; if ( orig . numCols <= 0 ) return false ; int N = orig . numRows ; if ( ! decomp . decompose ( orig ) ) return false ; if ( diag == null || diag . length < N ) { diag...
Decomposes the matrix using the QR algorithm . Care was taken to minimize unnecessary memory copying and cache skipping .
149,510
private boolean computeEigenValues ( ) { diagSaved = helper . copyDiag ( diagSaved ) ; offSaved = helper . copyOff ( offSaved ) ; vector . setQ ( null ) ; vector . setFastEigenvalues ( true ) ; if ( ! vector . process ( - 1 , null , null ) ) return false ; values = helper . copyEigenvalues ( values ) ; return true ; }
Computes eigenvalues only
149,511
protected void solveL ( double [ ] vv ) { int ii = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int ip = indx [ i ] ; double sumReal = vv [ ip * 2 ] ; double sumImg = vv [ ip * 2 + 1 ] ; vv [ ip * 2 ] = vv [ i * 2 ] ; vv [ ip * 2 + 1 ] = vv [ i * 2 + 1 ] ; if ( ii != 0 ) { int index = i * stride + ( ii - 1 ) * 2 ; for ( int ...
Solve the using the lower triangular matrix in LU . Diagonal elements are assumed to be 1
149,512
public boolean decompose ( DMatrixRMaj mat , int indexStart , int n ) { double m [ ] = mat . data ; double el_ii ; double div_el_ii = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { double sum = m [ indexStart + i * mat . numCols + j ] ; int iEl = i * n ; int jEl = j * n ; int end = iEl + i ; ...
Decomposes a submatrix . The results are written to the submatrix and to its internal matrix L .
149,513
public static List < int [ ] > createList ( int N ) { int data [ ] = new int [ N ] ; for ( int i = 0 ; i < data . length ; i ++ ) { data [ i ] = - 1 ; } List < int [ ] > ret = new ArrayList < int [ ] > ( ) ; createList ( data , 0 , - 1 , ret ) ; return ret ; }
Creates a list of all permutations for a set with N elements .
149,514
private static void createList ( int data [ ] , int k , int level , List < int [ ] > ret ) { data [ k ] = level ; if ( level < data . length - 1 ) { for ( int i = 0 ; i < data . length ; i ++ ) { if ( data [ i ] == - 1 ) { createList ( data , i , level + 1 , ret ) ; } } } else { int [ ] copy = new int [ data . length ]...
Internal function that uses recursion to create the list
149,515
public int [ ] next ( ) { boolean hasNewPerm = false ; escape : while ( level >= 0 ) { for ( int i = iter [ level ] ; i < data . length ; i = iter [ level ] ) { iter [ level ] ++ ; if ( data [ i ] == - 1 ) { level ++ ; data [ i ] = level - 1 ; if ( level >= data . length ) { hasNewPerm = true ; System . arraycopy ( dat...
Creates the next permutation in the sequence .
149,516
public static DMatrixSparseTriplet uniform ( int numRows , int numCols , int nz_total , double min , double max , Random rand ) { int N = numCols * numRows ; if ( N < 0 ) throw new IllegalArgumentException ( "matrix size is too large" ) ; nz_total = Math . min ( N , nz_total ) ; int selected [ ] = new int [ N ] ; for (...
Randomly generates matrix with the specified number of matrix elements filled with values from min to max .
149,517
public static boolean decomposeQR_block_col ( final int blockLength , final DSubmatrixD1 Y , final double gamma [ ] ) { int width = Y . col1 - Y . col0 ; int height = Y . row1 - Y . row0 ; int min = Math . min ( width , height ) ; for ( int i = 0 ; i < min ; i ++ ) { if ( ! computeHouseHolderCol ( blockLength , Y , gam...
Performs a standard QR decomposition on the specified submatrix that is one block wide .
149,518
public static void divideElementsCol ( final int blockLength , final DSubmatrixD1 Y , final int col , final double val ) { final int width = Math . min ( blockLength , Y . col1 - Y . col0 ) ; final double dataY [ ] = Y . original . data ; for ( int i = Y . row0 ; i < Y . row1 ; i += blockLength ) { int height = Math . ...
Divides the elements at the specified column by val . Takes in account leading zeros and one .
149,519
public static void multAdd_zeros ( final int blockLength , final DSubmatrixD1 Y , final DSubmatrixD1 B , final DSubmatrixD1 C ) { int widthY = Y . col1 - Y . col0 ; for ( int i = Y . row0 ; i < Y . row1 ; i += blockLength ) { int heightY = Math . min ( blockLength , Y . row1 - i ) ; for ( int j = B . col0 ; j < B . col...
Special multiplication that takes in account the zeros and one in Y which is the matrix that stores the householder vectors .
149,520
public static ManagerFunctions . InputN createMultTransA ( ) { return ( inputs , manager ) -> { if ( inputs . size ( ) != 2 ) throw new RuntimeException ( "Two inputs required" ) ; final Variable varA = inputs . get ( 0 ) ; final Variable varB = inputs . get ( 1 ) ; Operation . Info ret = new Operation . Info ( ) ; if ...
Create the function . Be sure to handle all possible input types and combinations correctly and provide meaningful error messages . The output matrix should be resized to fit the inputs .
149,521
public static DMatrixRMaj copyChangeRow ( int order [ ] , DMatrixRMaj src , DMatrixRMaj dst ) { if ( dst == null ) { dst = new DMatrixRMaj ( src . numRows , src . numCols ) ; } else if ( src . numRows != dst . numRows || src . numCols != dst . numCols ) { throw new IllegalArgumentException ( "src and dst must have the ...
Creates a copy of a matrix but swaps the rows as specified by the order array .
149,522
public static DMatrixRMaj copyTriangle ( DMatrixRMaj src , DMatrixRMaj dst , boolean upper ) { if ( dst == null ) { dst = new DMatrixRMaj ( src . numRows , src . numCols ) ; } else if ( src . numRows != dst . numRows || src . numCols != dst . numCols ) { throw new IllegalArgumentException ( "src and dst must have the s...
Copies just the upper or lower triangular portion of a matrix .
149,523
public static DMatrixRMaj [ ] splitIntoVectors ( DMatrix1Row A , boolean column ) { int w = column ? A . numCols : A . numRows ; int M = column ? A . numRows : 1 ; int N = column ? 1 : A . numCols ; int o = Math . max ( M , N ) ; DMatrixRMaj [ ] ret = new DMatrixRMaj [ w ] ; for ( int i = 0 ; i < w ; i ++ ) { DMatrixRM...
Takes a matrix and splits it into a set of row or column vectors .
149,524
public static double diagProd ( DMatrix1Row T ) { double prod = 1.0 ; int N = Math . min ( T . numRows , T . numCols ) ; for ( int i = 0 ; i < N ; i ++ ) { prod *= T . unsafe_get ( i , i ) ; } return prod ; }
Computes the product of the diagonal elements . For a diagonal or triangular matrix this is the determinant .
149,525
public static double elementSumSq ( DMatrixD1 m ) { double maxAbs = CommonOps_DDRM . elementMaxAbs ( m ) ; if ( maxAbs == 0 ) return 0 ; double total = 0 ; int N = m . getNumElements ( ) ; for ( int i = 0 ; i < N ; i ++ ) { double d = m . data [ i ] / maxAbs ; total += d * d ; } return maxAbs * total * maxAbs ; }
Sums up the square of each element in the matrix . This is equivalent to the Frobenius norm squared .
149,526
public void init ( double diag [ ] , double off [ ] , int numCols ) { reset ( numCols ) ; this . diag = diag ; this . off = off ; }
Sets up and declares internal data structures .
149,527
public void reset ( int N ) { this . N = N ; this . diag = null ; this . off = null ; if ( splits . length < N ) { splits = new int [ N ] ; } numSplits = 0 ; x1 = 0 ; x2 = N - 1 ; steps = numExceptional = lastExceptional = 0 ; this . Q = null ; }
Sets the size of the matrix being decomposed declares new memory if needed and sets all helper functions to their initial value .
149,528
protected boolean isZero ( int index ) { double bottom = Math . abs ( diag [ index ] ) + Math . abs ( diag [ index + 1 ] ) ; return ( Math . abs ( off [ index ] ) <= bottom * UtilEjml . EPS ) ; }
Checks to see if the specified off diagonal element is zero using a relative metric .
149,529
protected void createBulge ( int x1 , double p , boolean byAngle ) { double a11 = diag [ x1 ] ; double a22 = diag [ x1 + 1 ] ; double a12 = off [ x1 ] ; double a23 = off [ x1 + 1 ] ; if ( byAngle ) { c = Math . cos ( p ) ; s = Math . sin ( p ) ; c2 = c * c ; s2 = s * s ; cs = c * s ; } else { computeRotation ( a11 - p ...
Performs a similar transform on A - pI
149,530
protected void eigenvalue2by2 ( int x1 ) { double a = diag [ x1 ] ; double b = off [ x1 ] ; double c = diag [ x1 + 1 ] ; double absA = Math . abs ( a ) ; double absB = Math . abs ( b ) ; double absC = Math . abs ( c ) ; double scale = absA > absB ? absA : absB ; if ( absC > scale ) scale = absC ; if ( scale == 0 ) { of...
Computes the eigenvalue of the 2 by 2 matrix .
149,531
public void solve ( DMatrixRMaj B , DMatrixRMaj X ) { X . reshape ( blockA . numCols , B . numCols ) ; blockB . reshape ( B . numRows , B . numCols , false ) ; blockX . reshape ( X . numRows , X . numCols , false ) ; MatrixOps_DDRB . convert ( B , blockB ) ; alg . solve ( blockB , blockX ) ; MatrixOps_DDRB . convert ( ...
Converts B and X into block matrices and calls the block matrix solve routine .
149,532
public void invert ( DMatrixRMaj A_inv ) { blockB . reshape ( A_inv . numRows , A_inv . numCols , false ) ; alg . invert ( blockB ) ; MatrixOps_DDRB . convert ( blockB , A_inv ) ; }
Creates a block matrix the same size as A_inv inverts the matrix and copies the results back onto A_inv .
149,533
public void printMinors ( int matrix [ ] , int N , PrintStream stream ) { this . N = N ; this . stream = stream ; int index = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ , index ++ ) { stream . print ( " double m" + i + "" + j + " = " ) ; if ( ( i + j ) % 2 == 1 ) stream . print ( "-(...
Put the core auto - code algorithm here so an external class can call it
149,534
public boolean setA ( DMatrixRBlock A ) { if ( A . numRows < A . numCols ) throw new IllegalArgumentException ( "Number of rows must be more than or equal to the number of columns. " + "Can't solve an underdetermined system." ) ; if ( ! decomposer . decompose ( A ) ) return false ; this . QR = decomposer . getQR ( ) ;...
Computes the QR decomposition of A and store the results in A .
149,535
public void invert ( DMatrixRBlock A_inv ) { int M = Math . min ( QR . numRows , QR . numCols ) ; if ( A_inv . numRows != M || A_inv . numCols != M ) throw new IllegalArgumentException ( "A_inv must be square an have dimension " + M ) ; MatrixOps_DDRB . setIdentity ( A_inv ) ; decomposer . applyQTran ( A_inv ) ; Triang...
Invert by solving for against an identity matrix .
149,536
public void perform ( ) { for ( int i = 0 ; i < operations . size ( ) ; i ++ ) { operations . get ( i ) . process ( ) ; } }
Executes the sequence of operations
149,537
public void setExpectedMaxSize ( int numRows , int numCols ) { super . setExpectedMaxSize ( numRows , numCols ) ; if ( numRows < blockWidth ) B = new DMatrixRMaj ( 0 , 0 ) ; else B = new DMatrixRMaj ( blockWidth , maxWidth ) ; chol = new CholeskyBlockHelper_DDRM ( blockWidth ) ; }
Declares additional internal data structures .
149,538
public static DMatrixSparseCSC convert ( DMatrixSparseTriplet src , DMatrixSparseCSC dst , int hist [ ] ) { if ( dst == null ) dst = new DMatrixSparseCSC ( src . numRows , src . numCols , src . nz_length ) ; else dst . reshape ( src . numRows , src . numCols , src . nz_length ) ; if ( hist == null ) hist = new int [ sr...
Converts SMatrixTriplet_64 into a SMatrixCC_64 .
149,539
protected void setupPivotInfo ( ) { for ( int col = 0 ; col < numCols ; col ++ ) { pivots [ col ] = col ; double c [ ] = dataQR [ col ] ; double norm = 0 ; for ( int row = 0 ; row < numRows ; row ++ ) { double element = c [ row ] ; norm += element * element ; } normsCol [ col ] = norm ; } }
Sets the initial pivot ordering and compute the F - norm squared for each column
149,540
protected void updateNorms ( int j ) { boolean foundNegative = false ; for ( int col = j ; col < numCols ; col ++ ) { double e = dataQR [ col ] [ j - 1 ] ; double v = normsCol [ col ] -= e * e ; if ( v < 0 ) { foundNegative = true ; break ; } } if ( foundNegative ) { for ( int col = j ; col < numCols ; col ++ ) { doubl...
Performs an efficient update of each columns norm
149,541
protected void swapColumns ( int j ) { int largestIndex = j ; double largestNorm = normsCol [ j ] ; for ( int col = j + 1 ; col < numCols ; col ++ ) { double n = normsCol [ col ] ; if ( n > largestNorm ) { largestNorm = n ; largestIndex = col ; } } double [ ] tempC = dataQR [ j ] ; dataQR [ j ] = dataQR [ largestIndex ...
Finds the column with the largest normal and makes that the first column
149,542
public String getHiveExecutionEngine ( ) { String executionEngine = hiveConfSystemOverride . get ( HiveConf . ConfVars . HIVE_EXECUTION_ENGINE . varname ) ; return executionEngine == null ? HiveConf . ConfVars . HIVE_EXECUTION_ENGINE . getDefaultValue ( ) : executionEngine ; }
Get the configured hive . execution . engine . If not set it will default to the default value of HiveConf
149,543
public void override ( HiveRunnerConfig hiveRunnerConfig ) { config . putAll ( hiveRunnerConfig . config ) ; hiveConfSystemOverride . putAll ( hiveRunnerConfig . hiveConfSystemOverride ) ; }
Copy values from the inserted config to this config . Note that if properties has not been explicitly set the defaults will apply .
149,544
public static Optional < Field > getField ( Class < ? > type , final String fieldName ) { Optional < Field > field = Iterables . tryFind ( newArrayList ( type . getDeclaredFields ( ) ) , havingFieldName ( fieldName ) ) ; if ( ! field . isPresent ( ) && type . getSuperclass ( ) != null ) { field = getField ( type . getS...
Finds the first Field with given field name in the Class and in its super classes .
149,545
public void init ( Map < String , String > testConfig , Map < String , String > hiveVars ) { context . init ( ) ; HiveConf hiveConf = context . getHiveConf ( ) ; for ( Map . Entry < String , String > property : testConfig . entrySet ( ) ) { hiveConf . set ( property . getKey ( ) , property . getValue ( ) ) ; } try { hi...
Will start the HiveServer .
149,546
public InsertIntoTable addRowsFromDelimited ( File file , String delimiter , Object nullValue ) { builder . addRowsFromDelimited ( file , delimiter , nullValue ) ; return this ; }
Adds all rows from the TSV file specified using the provided delimiter and null value .
149,547
public InsertIntoTable addRowsFrom ( File file , FileParser fileParser ) { builder . addRowsFrom ( file , fileParser ) ; return this ; }
Adds all rows from the file specified using the provided parser .
149,548
public InsertIntoTable set ( String name , Object value ) { builder . set ( name , value ) ; return this ; }
Set the given column name to the given value .
149,549
public HiveShellContainer evaluateStatement ( List < ? extends Script > scripts , Object target , TemporaryFolder temporaryFolder , Statement base ) throws Throwable { container = null ; FileUtil . setPermission ( temporaryFolder . getRoot ( ) , FsPermission . getDirDefault ( ) ) ; try { LOGGER . info ( "Setting up {} ...
Drives the unit test .
149,550
private HiveShellContainer createHiveServerContainer ( final List < ? extends Script > scripts , final Object testCase , TemporaryFolder baseDir ) throws IOException { HiveServerContext context = new StandaloneHiveServerContext ( baseDir , config ) ; final HiveServerContainer hiveTestHarness = new HiveServerContainer (...
Traverses the test case annotations . Will inject a HiveShell in the test case that envelopes the HiveServer .
149,551
public static Command newInsert ( Object object , String outIdentifier ) { return getCommandFactoryProvider ( ) . newInsert ( object , outIdentifier ) ; }
Inserts a new instance but references via the outIdentifier which is returned as part of the ExecutionResults
149,552
public static Command newInsert ( Object object , String outIdentifier , boolean returnObject , String entryPoint ) { return getCommandFactoryProvider ( ) . newInsert ( object , outIdentifier , returnObject , entryPoint ) ; }
Inserts a new instance but references via the outIdentifier which is returned as part of the ExecutionResults The outIdentifier can be null . The entryPoint which can also be null specifies the entrypoint the object is inserted into .
149,553
public static Command newInsertElements ( Collection objects , String outIdentifier , boolean returnObject , String entryPoint ) { return getCommandFactoryProvider ( ) . newInsertElements ( objects , outIdentifier , returnObject , entryPoint ) ; }
Iterate and insert each of the elements of the Collection .
149,554
public static Command newSetGlobal ( String identifier , Object object ) { return getCommandFactoryProvider ( ) . newSetGlobal ( identifier , object ) ; }
Sets the global . Does not add the global to the ExecutionResults .
149,555
public static Command newGetGlobal ( String identifier , String outIdentifier ) { return getCommandFactoryProvider ( ) . newGetGlobal ( identifier , outIdentifier ) ; }
Gets the global and adds it ot the BatchExecutionresults using the alternative outIdentifier .
149,556
public static Command newStartProcess ( String processId , Map < String , Object > parameters ) { return getCommandFactoryProvider ( ) . newStartProcess ( processId , parameters ) ; }
Start a process using the given parameters .
149,557
public static Command newQuery ( String identifier , String name ) { return getCommandFactoryProvider ( ) . newQuery ( identifier , name ) ; }
Executes a query . The query results will be added to the ExecutionResults using the given identifier .
149,558
public static Command newQuery ( String identifier , String name , Object [ ] arguments ) { return getCommandFactoryProvider ( ) . newQuery ( identifier , name , arguments ) ; }
Executes a query using the given parameters . The query results will be added to the ExecutionResults using the given identifier .
149,559
public static KnowledgeBuilderConfiguration newKnowledgeBuilderConfiguration ( Properties properties , ClassLoader ... classLoaders ) { return FactoryServiceHolder . factoryService . newKnowledgeBuilderConfiguration ( properties , classLoaders ) ; }
Create a KnowledgeBuilderConfiguration on which properties can be set . Use the given properties file and ClassLoader - either of which can be null .
149,560
public static synchronized void unregister ( final String serviceName , final Callable < Class < ? > > factory ) { if ( serviceName == null ) { throw new IllegalArgumentException ( "serviceName cannot be null" ) ; } if ( factories != null ) { List < Callable < Class < ? > > > l = factories . get ( serviceName ) ; if ( ...
Removes the given service provider factory from the set of providers for the service .
149,561
public static synchronized void register ( final String serviceName , final Callable < Class < ? > > factory ) { if ( serviceName == null ) { throw new IllegalArgumentException ( "serviceName cannot be null" ) ; } if ( factory != null ) { if ( factories == null ) { factories = new HashMap < String , List < Callable < C...
Adds the given service provider factory to the set of providers for the service .
149,562
public static synchronized Class < ? > locate ( final String serviceName ) { if ( serviceName == null ) { throw new IllegalArgumentException ( "serviceName cannot be null" ) ; } if ( factories != null ) { List < Callable < Class < ? > > > l = factories . get ( serviceName ) ; if ( l != null && ! l . isEmpty ( ) ) { Cal...
Finds the preferred provider for the given service . The preferred provider is the last one added to the set of providers .
149,563
public static synchronized List < Class < ? > > locateAll ( final String serviceName ) { if ( serviceName == null ) { throw new IllegalArgumentException ( "serviceName cannot be null" ) ; } List < Class < ? > > classes = new ArrayList < Class < ? > > ( ) ; if ( factories != null ) { List < Callable < Class < ? > > > l ...
Finds all providers for the given service .
149,564
public static KieRuntimeLogger newFileLogger ( KieRuntimeEventManager session , String fileName ) { return getKnowledgeRuntimeLoggerProvider ( ) . newFileLogger ( session , fileName ) ; }
Creates a file logger in the current thread . The file is in XML format suitable for interpretation by Eclipse s Drools Audit View or other tools . Note that while events are written as they happen the file will not be flushed until it is closed or the underlying file buffer is filled . If you need real time logging th...
149,565
public static String toXml ( DeploymentDescriptor descriptor ) { try { Marshaller marshaller = getContext ( ) . createMarshaller ( ) ; marshaller . setProperty ( Marshaller . JAXB_FORMATTED_OUTPUT , Boolean . TRUE ) ; marshaller . setProperty ( Marshaller . JAXB_SCHEMA_LOCATION , "http://www.jboss.org/jbpm deployment-d...
Serializes descriptor instance to XML
149,566
public static List < ObjectModelResolver > getResolvers ( ) { if ( resolvers == null ) { synchronized ( serviceLoader ) { if ( resolvers == null ) { List < ObjectModelResolver > foundResolvers = new ArrayList < ObjectModelResolver > ( ) ; for ( ObjectModelResolver resolver : serviceLoader ) { foundResolvers . add ( res...
Returns all found resolvers
149,567
public static ObjectModelResolver get ( String resolverId ) { List < ObjectModelResolver > resolvers = getResolvers ( ) ; for ( ObjectModelResolver resolver : resolvers ) { if ( resolver . accept ( resolverId ) ) { return resolver ; } } return null ; }
Returns first resolver that accepts the given resolverId . In case none is found null is returned .
149,568
void reset ( ) { if ( ! hasStopped ) { throw new IllegalStateException ( "cannot reset a non stopped queue poller" ) ; } hasStopped = false ; run = true ; lastLoop = null ; loop = new Semaphore ( 0 ) ; }
Will make the thread ready to run once again after it has stopped .
149,569
void releaseResources ( JobInstance ji ) { this . peremption . remove ( ji . getId ( ) ) ; this . actualNbThread . decrementAndGet ( ) ; for ( ResourceManagerBase rm : this . resourceManagers ) { rm . releaseResource ( ji ) ; } if ( ! this . strictPollingPeriod ) { loop . release ( 1 ) ; } this . engine . signalEndOfRu...
Called when a payload thread has ended . This also notifies the poller to poll once again .
149,570
public static JqmEngineOperations startEngine ( String name , JqmEngineHandler handler ) { JqmEngine e = new JqmEngine ( ) ; e . start ( name , handler ) ; return e ; }
Creates and start an engine representing the node named as the given parameter .
149,571
public Response toResponse ( ErrorDto e ) { return Response . status ( e . httpStatus ) . entity ( e ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; }
private HttpServletResponse headers ;
149,572
public static JqmClient getClient ( String name , Properties p , boolean cached ) { Properties p2 = null ; if ( binder == null ) { bind ( ) ; } if ( p == null ) { p2 = props ; } else { p2 = new Properties ( props ) ; p2 . putAll ( p ) ; } return binder . getClientFactory ( ) . getClient ( name , p2 , cached ) ; }
Return a new client that may be cached or not . Given properties are always use when not cached and only used at creation time for cached clients .
149,573
public static ScheduledJob create ( String cronExpression ) { ScheduledJob res = new ScheduledJob ( ) ; res . cronExpression = cronExpression ; return res ; }
Fluent API builder .
149,574
static void export ( String path , String queueName , DbConn cnx ) throws JqmXmlException { if ( queueName == null ) { throw new IllegalArgumentException ( "queue name cannot be null" ) ; } if ( cnx == null ) { throw new IllegalArgumentException ( "database connection cannot be null" ) ; } Queue q = CommonXml . findQue...
Exports a single queue to an XML file .
149,575
static void createMessage ( String textMessage , JobInstance jobInstance , DbConn cnx ) { cnx . runUpdate ( "message_insert" , jobInstance . getId ( ) , textMessage ) ; }
Create a text message that will be stored in the database . Must be called inside a transaction .
149,576
static int createDeliverable ( String path , String originalFileName , String fileFamily , Integer jobId , DbConn cnx ) { QueryResult qr = cnx . runUpdate ( "deliverable_insert" , fileFamily , path , jobId , originalFileName , UUID . randomUUID ( ) . toString ( ) ) ; return qr . getGeneratedId ( ) ; }
Create a Deliverable inside the database that will track a file created by a JobInstance Must be called from inside a transaction
149,577
static void initSingleParam ( String key , String initValue , DbConn cnx ) { try { cnx . runSelectSingle ( "globalprm_select_by_key" , 2 , String . class , key ) ; return ; } catch ( NoResultException e ) { GlobalParameter . create ( cnx , key , initValue ) ; } catch ( NonUniqueResultException e ) { } }
Checks if a parameter exists . If it exists it is left untouched . If it doesn t it is created . Only works for parameters which key is unique . Must be called from within an open transaction .
149,578
static void setSingleParam ( String key , String value , DbConn cnx ) { QueryResult r = cnx . runUpdate ( "globalprm_update_value_by_key" , value , key ) ; if ( r . nbUpdated == 0 ) { cnx . runUpdate ( "globalprm_insert" , key , value ) ; } cnx . commit ( ) ; }
Checks if a parameter exists . If it exists it is updated . If it doesn t it is created . Only works for parameters which key is unique . Will create a transaction on the given entity manager .
149,579
public void close ( ) { if ( transac_open ) { try { this . _cnx . rollback ( ) ; } catch ( Exception e ) { } } for ( Statement s : toClose ) { closeQuietly ( s ) ; } toClose . clear ( ) ; closeQuietly ( _cnx ) ; _cnx = null ; }
Close all JDBC objects related to this connection .
149,580
void killAll ( ) { for ( RjiRegistration reg : this . instancesById . values ( ) . toArray ( new RjiRegistration [ ] { } ) ) { reg . rji . handleInstruction ( Instruction . KILL ) ; } }
Send a kill signal to all running instances and return as soon as the signal is sent .
149,581
public void setJobQueue ( int jobId , Queue queue ) { JqmClientFactory . getClient ( ) . setJobQueue ( jobId , queue ) ; }
No need to expose . Client side work .
149,582
public List < JobInstance > getJobs ( Query query ) { return JqmClientFactory . getClient ( ) . getJobs ( query ) ; }
Not exposed directly - the Query object passed as parameter actually contains results ...
149,583
public void stop ( ) { synchronized ( killHook ) { jqmlogger . info ( "JQM engine " + this . node . getName ( ) + " has received a stop order" ) ; try { if ( ! Runtime . getRuntime ( ) . removeShutdownHook ( killHook ) ) { jqmlogger . error ( "The engine could not unregister its shutdown hook" ) ; } } catch ( IllegalSt...
Gracefully stop the engine
149,584
private void purgeDeadJobInstances ( DbConn cnx , Node node ) { for ( JobInstance ji : JobInstance . select ( cnx , "ji_select_by_node" , node . getId ( ) ) ) { try { cnx . runSelectSingle ( "history_select_state_by_id" , String . class , ji . getId ( ) ) ; } catch ( NoResultException e ) { History . create ( cnx , ji ...
To be called at node startup - it purges all job instances associated to this node .
149,585
private URL [ ] getClasspath ( JobInstance ji , JobRunnerCallback cb ) throws JqmPayloadException { switch ( ji . getJD ( ) . getPathType ( ) ) { case MAVEN : return mavenResolver . resolve ( ji ) ; case MEMORY : return new URL [ 0 ] ; case FS : default : return fsResolver . getLibraries ( ji . getNode ( ) , ji . getJD...
Returns all the URL that should be inside the classpath . This includes the jar itself if any .
149,586
public static int forceCleanup ( Thread t ) { int i = 0 ; for ( Map . Entry < ConnectionPool , Set < ConnPair > > e : conns . entrySet ( ) ) { for ( ConnPair c : e . getValue ( ) ) { if ( c . thread . equals ( t ) ) { try { c . conn . getHandler ( ) . invoke ( c . conn , Connection . class . getMethod ( "close" ) , nul...
Called by the engine to trigger the cleanup at the end of a payload thread .
149,587
public static GlobalParameter create ( DbConn cnx , String key , String value ) { QueryResult r = cnx . runUpdate ( "globalprm_insert" , key , value ) ; GlobalParameter res = new GlobalParameter ( ) ; res . id = r . getGeneratedId ( ) ; res . key = key ; res . value = value ; return res ; }
Create a new GP entry in the database . No commit performed .
149,588
public static String getParameter ( DbConn cnx , String key , String defaultValue ) { try { return cnx . runSelectSingle ( "globalprm_select_by_key" , 3 , String . class , key ) ; } catch ( NoResultException e ) { return defaultValue ; } }
Retrieve the value of a single - valued parameter .
149,589
static JndiContext createJndiContext ( ) throws NamingException { try { if ( ! NamingManager . hasInitialContextFactoryBuilder ( ) ) { JndiContext ctx = new JndiContext ( ) ; NamingManager . setInitialContextFactoryBuilder ( ctx ) ; return ctx ; } else { return ( JndiContext ) NamingManager . getInitialContext ( null )...
Will create a JNDI Context and register it as the initial context factory builder
149,590
private static ClassLoader getParentCl ( ) { try { Method m = ClassLoader . class . getMethod ( "getPlatformClassLoader" ) ; return ( ClassLoader ) m . invoke ( null ) ; } catch ( NoSuchMethodException e ) { return null ; } catch ( Exception e ) { throw new JqmInitError ( "Could not fetch Platform Class Loader" , e ) ;...
A helper - in Java 9 the extension CL was renamed to platform CL and hosts all the JDK classes . Before 9 it was useless and we used bootstrap CL instead .
149,591
public static Properties loadProperties ( String [ ] filesToLoad ) { Properties p = new Properties ( ) ; InputStream fis = null ; for ( String path : filesToLoad ) { try { fis = Db . class . getClassLoader ( ) . getResourceAsStream ( path ) ; if ( fis != null ) { p . load ( fis ) ; jqmlogger . info ( "A jqm.properties ...
Helper method to load a property file from class path .
149,592
private void init ( boolean upgrade ) { initAdapter ( ) ; initQueries ( ) ; if ( upgrade ) { dbUpgrade ( ) ; } boolean versionValid = false ; while ( ! versionValid ) { try { checkSchemaVersion ( ) ; versionValid = true ; } catch ( Exception e ) { String msg = e . getLocalizedMessage ( ) ; if ( e . getCause ( ) != null...
Main database initialization . To be called only when _ds is a valid DataSource .
149,593
private void dbUpgrade ( ) { DbConn cnx = this . getConn ( ) ; Map < String , Object > rs = null ; int db_schema_version = 0 ; try { rs = cnx . runSelectSingleRow ( "version_select_latest" ) ; db_schema_version = ( Integer ) rs . get ( "VERSION_D1" ) ; } catch ( Exception e ) { } cnx . rollback ( ) ; if ( SCHEMA_VERSIO...
Updates the database . Never call this during normal operations upgrade is a user - controlled operation .
149,594
private void initAdapter ( ) { Connection tmp = null ; DatabaseMetaData meta = null ; try { tmp = _ds . getConnection ( ) ; meta = tmp . getMetaData ( ) ; product = meta . getDatabaseProductName ( ) . toLowerCase ( ) ; } catch ( SQLException e ) { throw new DatabaseException ( "Cannot connect to the database" , e ) ; }...
Creates the adapter for the target database .
149,595
public DbConn getConn ( ) { Connection cnx = null ; try { Thread . interrupted ( ) ; cnx = _ds . getConnection ( ) ; if ( cnx . getAutoCommit ( ) ) { cnx . setAutoCommit ( false ) ; cnx . rollback ( ) ; } if ( cnx . getTransactionIsolation ( ) != Connection . TRANSACTION_READ_COMMITTED ) { cnx . setTransactionIsolation...
A connection to the database . Should be short - lived . No transaction active by default .
149,596
String getQuery ( String key ) { String res = this . adapter . getSqlText ( key ) ; if ( res == null ) { throw new DatabaseException ( "Query " + key + " does not exist" ) ; } return res ; }
Gets the interpolated text of a query from cache . If key does not exist an exception is thrown .
149,597
public RuntimeParameter addParameter ( String key , String value ) { RuntimeParameter jp = new RuntimeParameter ( ) ; jp . setJi ( this . getId ( ) ) ; jp . setKey ( key ) ; jp . setValue ( value ) ; return jp ; }
Helper method to add a parameter without having to create it explicitely . The created parameter should be persisted afterwards .
149,598
void endOfRunDb ( ) { DbConn cnx = null ; try { cnx = Helpers . getNewDbSession ( ) ; History . create ( cnx , this . ji , this . resultStatus , endDate ) ; jqmlogger . trace ( "An History was just created for job instance " + this . ji . getId ( ) ) ; cnx . runUpdate ( "ji_delete_by_id" , this . ji . getId ( ) ) ; cnx...
Part of the endOfRun process that needs the database . May be deferred if the database is not available .
149,599
private Integer highlanderMode ( JobDef jd , DbConn cnx ) { if ( ! jd . isHighlander ( ) ) { return null ; } try { Integer existing = cnx . runSelectSingle ( "ji_select_existing_highlander" , Integer . class , jd . getId ( ) ) ; return existing ; } catch ( NoResultException ex ) { } ResultSet rs = cnx . runSelect ( tru...
Helper . Current transaction is committed in some cases .